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

feat: integrate standard memo to Bitcoin inbound and E2E tests #3025

Merged
merged 13 commits into from
Oct 25, 2024

Conversation

ws4charlie
Copy link
Contributor

@ws4charlie ws4charlie commented Oct 21, 2024

Description

Complete:

  • add standard memo support for Bitcoin inbound.
  • add E2E tests for deposit, deposit_and_call, deposit_and_call_revert, etc.
  • fix the incorrect receiver address (which is currently a btc address) with actual receiver parsed from memo.
  • unit tests
  • feature is disabled for Bitcoin mainnet

Closes: #2880
Closes: #2149

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 support for stateful precompiled contracts and a staking precompiled contract.
    • Introduced a common importable zetacored RPC package.
    • Enhanced Bitcoin inscription support on testnet.
    • New functionality for handling Bitcoin inbound events, including compliance checks and memo decoding.
  • Bug Fixes

    • Resolved issues with operator voting on discarded keygen ballots and improved outbound tracker functionality.
  • Tests

    • Expanded testing coverage with new end-to-end tests for Bitcoin deposits and stateful precompiled contracts.
    • Added tests for handling various Bitcoin transaction scenarios, including donations and standard memo deposits.
  • Documentation

    • Updated changelog to reflect all new features, refactoring, and fixes.

@ws4charlie ws4charlie added zetaclient Issues related to ZetaClient chain:bitcoin Bitcoin chain related labels Oct 22, 2024
Copy link

codecov bot commented Oct 22, 2024

Codecov Report

Attention: Patch coverage is 93.80531% with 14 lines in your changes missing coverage. Please review.

Project coverage is 64.47%. Comparing base (a6f1e44) to head (d0e7b08).
Report is 1 commits behind head on develop.

Files with missing lines Patch % Lines
zetaclient/chains/bitcoin/observer/event.go 95.68% 5 Missing and 1 partial ⚠️
zetaclient/chains/bitcoin/observer/inbound.go 83.87% 5 Missing ⚠️
zetaclient/chains/evm/observer/v2_inbound.go 0.00% 2 Missing ⚠️
pkg/memo/memo.go 93.33% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           develop    #3025      +/-   ##
===========================================
+ Coverage    64.13%   64.47%   +0.33%     
===========================================
  Files          411      412       +1     
  Lines        28837    28976     +139     
===========================================
+ Hits         18496    18681     +185     
+ Misses        9559     9512      -47     
- Partials       782      783       +1     
Files with missing lines Coverage Δ
pkg/memo/fields_v0.go 97.05% <100.00%> (-0.12%) ⬇️
x/crosschain/types/message_vote_inbound.go 100.00% <100.00%> (ø)
zetaclient/chains/bitcoin/observer/witness.go 69.02% <100.00%> (ø)
zetaclient/chains/bitcoin/tx_script.go 89.20% <100.00%> (+0.99%) ⬆️
pkg/memo/memo.go 92.85% <93.33%> (+0.70%) ⬆️
zetaclient/chains/evm/observer/v2_inbound.go 0.00% <0.00%> (ø)
zetaclient/chains/bitcoin/observer/inbound.go 29.70% <83.87%> (+9.87%) ⬆️
zetaclient/chains/bitcoin/observer/event.go 95.68% <95.68%> (ø)

Copy link

!!!WARNING!!!
nosec detected in the following files: tests/simulation/sim/sim_state.go

Be very careful about using #nosec in code. It can be a quick way to suppress security warnings and move forward with development, it should be employed with caution. Suppressing warnings with #nosec can hide potentially serious vulnerabilities. Only use #nosec when you're absolutely certain that the security issue is either a false positive or has been mitigated in another way.

Only suppress a single rule (or a specific set of rules) within a section of code, while continuing to scan for other problems. To do this, you can list the rule(s) to be suppressed within the #nosec annotation, e.g: /* #nosec G401 */ or //#nosec G201 G202 G203
Broad #nosec annotations should be avoided, as they can hide other vulnerabilities. The CI will block you from merging this PR until you remove #nosec annotations that do not target specific rules.

Pay extra attention to the way #nosec is being used in the files listed above.

@github-actions github-actions bot added the nosec label Oct 22, 2024
@ws4charlie ws4charlie marked this pull request as ready for review October 22, 2024 17:42
Copy link
Contributor

coderabbitai bot commented Oct 22, 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
📝 Walkthrough

Walkthrough

The pull request introduces significant updates across various components, primarily enhancing Bitcoin deposit functionalities and testing. Key changes include the addition of new test cases, refactoring of existing functions, and the introduction of new methods for handling Bitcoin inbound events. The modifications also address specific issues related to the outbound receiver address for Bitcoin deposits and establish a new standard for parsing inbound data. Overall, the changes improve code quality, expand testing coverage, and enhance the functionality of Bitcoin-related operations.

Changes

File Path Change Summary
changelog.md Updated to reflect new features, refactoring, tests, fixes, CI improvements, and documentation enhancements. Notable additions include support for stateful precompiled contracts and a staking precompiled contract. Refactoring includes fixing lint errors and modifying function signatures.
cmd/zetae2e/local/local.go Added new test cases for Bitcoin deposits and renamed an existing test case.
e2e/e2etests/e2etests.go Removed outdated Bitcoin test constants and added new ones for enhanced functionality.
e2e/e2etests/test_bitcoin_deposit.go Updated method signature for Bitcoin deposit function to include an additional parameter.
e2e/e2etests/test_bitcoin_deposit_and_call_revert.go Introduced a new test function to validate Bitcoin deposit behavior with invalid memos.
e2e/e2etests/test_bitcoin_deposit_refund.go Removed test function for Bitcoin deposit refund.
e2e/e2etests/test_bitcoin_donation.go Added a new test function for validating Bitcoin donation process.
e2e/e2etests/test_bitcoin_std_deposit.go Introduced a new test function for Bitcoin deposits with standard memos.
e2e/e2etests/test_bitcoin_std_deposit_and_call.go Added a new test function for deposit and call functionality using standard memos.
e2e/e2etests/test_bitcoin_std_deposit_and_call_revert.go Introduced a new test function for handling reverts in deposit and call operations.
e2e/e2etests/test_bitcoin_std_deposit_and_call_revert_other_address.go Added a new test function for handling reverts to other addresses.
e2e/e2etests/test_stress_btc_deposit.go Updated method signature for stress test function to include an additional parameter.
e2e/runner/bitcoin.go Enhanced E2ERunner methods for Bitcoin transactions, including new deposit methods and improved error handling.
e2e/utils/zetacore.go Introduced a new function for waiting on reverted cross-chain transactions.
pkg/memo/fields.go Updated method signature for unpacking memo fields.
pkg/memo/fields_v0.go Modified unpacking method to remove operation code validation.
pkg/memo/fields_v0_test.go Adjusted test cases to reflect changes in unpacking logic.
pkg/memo/memo.go Updated error handling in the DecodeFromBytes function for memos.
pkg/memo/memo_test.go Enhanced test cases for encoding and decoding memos with new validation checks.
tests/simulation/sim/sim_state.go Added a comment to mitigate a security warning related to reading the genesis file.
testutil/helpers.go Introduced a new helper function for converting hex strings to byte slices.
testutil/sample/crypto.go Added a function to generate sample Bitcoin P2WPKH addresses.
x/crosschain/types/message_vote_inbound.go Introduced a new function for setting revert options in inbound vote messages.
x/crosschain/types/message_vote_inbound_test.go Added tests for new revert options functionality in inbound vote messages.
zetaclient/chains/bitcoin/observer/event.go Introduced functionality for handling Bitcoin inbound events, including compliance checks.
zetaclient/chains/bitcoin/observer/event_test.go Added unit tests for Bitcoin inbound event handling.
zetaclient/chains/bitcoin/observer/inbound.go Significant restructuring of inbound event handling logic, including renaming and refactoring methods.
zetaclient/chains/bitcoin/observer/inbound_test.go Added tests for the updated inbound event processing methods.
zetaclient/chains/bitcoin/observer/witness.go Simplified function call for extracting OP_RETURN data.
zetaclient/chains/bitcoin/tx_script.go Updated the DecodeOpReturnMemo function to simplify its signature and enhance error handling.
zetaclient/chains/bitcoin/tx_script_test.go Refactored tests for DecodeOpReturnMemo to improve organization and clarity.
zetaclient/chains/evm/observer/v2_inbound.go Enhanced methods for handling deposits and calls in the EVM context, including new event processing logic.
zetaclient/zetacore/constant.go Added a constant for gas limit used in inbound call options.

Assessment against linked issues

Objective Addressed Explanation
Define a standard for parsing Bitcoin inbound data (#2880)
Fix the outbound receiver address for Bitcoin deposits (#2149)

Possibly related PRs

Suggested labels

E2E

Suggested reviewers

  • kingpinXD
  • swift1337
  • skosito
  • fbac
  • brewmaster012
  • lumtis

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.

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

🧹 Outside diff range and nitpick comments (40)
pkg/memo/fields.go (1)

Line range hint 1-16: Consider enhancing interface documentation.

The interface would benefit from additional documentation explaining:

  1. The rationale behind the asymmetric parameter usage
  2. The relationship between the methods
  3. The expected flow of operations (Pack → Unpack → Validate)

Add comprehensive documentation:

 // Fields is the interface for memo fields
+// The interface provides methods for encoding and decoding memo fields with different
+// validation stages. While packing and validation require an operation code (opCode),
+// unpacking is performed independently of the operation type, with validation occurring
+// as a separate step.
 type Fields interface {
e2e/e2etests/test_bitcoin_deposit.go (2)

Line range hint 1-24: Enhance test coverage for new memo functionality.

Given that this PR introduces standard memo support and addresses receiver address issues, consider adding the following test improvements:

  1. Add explicit validation of the receiver address in the test
  2. Add test cases for both standard and legacy memo formats
  3. Include validation for the correct memo parsing

Here's a suggested enhancement:

 func TestBitcoinDeposit(r *runner.E2ERunner, args []string) {
     require.Len(r, args, 1)
 
     depositAmount := parseFloat(r, args[0])
 
     r.SetBtcAddress(r.Name, false)
     txHash := r.DepositBTCWithAmount(depositAmount, nil)
 
     // wait for the cctx to be mined
     cctx := utils.WaitCctxMinedByInboundHash(r.Ctx, txHash.String(), r.CctxClient, r.Logger, r.CctxTimeout)
     r.Logger.CCTX(*cctx, "deposit")
     utils.RequireCCTXStatus(r, cctx, crosschaintypes.CctxStatus_OutboundMined)
+    
+    // Validate receiver address
+    require.Equal(r, r.GetAddress(r.Name).String(), cctx.GetReceiver(),
+        "receiver address should match the intended recipient")
 }
+
+// TestBitcoinDepositWithStandardMemo tests deposit with the new standard memo format
+func TestBitcoinDepositWithStandardMemo(r *runner.E2ERunner, args []string) {
+    // Add test implementation for standard memo
+}
+
+// TestBitcoinDepositWithLegacyMemo tests deposit with the legacy memo format
+func TestBitcoinDepositWithLegacyMemo(r *runner.E2ERunner, args []string) {
+    // Add test implementation for legacy memo
+}

Line range hint 20-23: Consider adding error case validation.

The test currently only validates the happy path where the transaction is mined successfully. Consider adding test cases for error scenarios, such as:

  1. Invalid memo format
  2. Incorrect receiver address format
  3. Transaction revert scenarios

Would you like me to provide example test cases for these scenarios?

e2e/e2etests/test_bitcoin_donation.go (2)

14-14: Add function documentation.

Consider adding a documentation comment that describes the test's purpose, parameters, and expected behavior. This will help other developers understand the test's objectives and requirements.

+// TestBitcoinDonation validates that Bitcoin transactions with donation messages
+// are processed correctly but do not create cross-chain context data.
+// Args:
+//   - args[0]: donation amount in BTC
 func TestBitcoinDonation(r *runner.E2ERunner, args []string) {

36-37: Enhance error context for transaction failure.

Consider adding more context to the error when the transaction fails to help with debugging.

 txHash, err := r.SendToTSSFromDeployerWithMemo(amountTotal, utxos, memo)
-require.NoError(r, err)
+require.NoError(r, err, "failed to send donation transaction: %v", err)
e2e/e2etests/test_bitcoin_std_deposit_and_call_revert.go (1)

13-25: Add function documentation and improve error handling.

The test function would benefit from:

  1. A detailed documentation comment explaining its purpose, parameters, and test scenario
  2. Constants for expected argument count
  3. Explicit error handling for amount parsing

Consider applying these improvements:

+// TestBitcoinStdMemoDepositAndCallRevert tests the Bitcoin deposit and call revert functionality
+// using standard memo format. It verifies that when calling a non-existing contract,
+// the transaction is properly reverted and funds are refunded.
+// Args:
+//   - args[0]: amount of BTC to send
 func TestBitcoinStdMemoDepositAndCallRevert(r *runner.E2ERunner, args []string) {
+    const expectedArgCount = 1
-    require.Len(r, args, 1)
+    require.Len(r, args, expectedArgCount, "expected %d argument (amount)", expectedArgCount)
e2e/e2etests/test_stress_btc_deposit.go (3)

33-33: Document the purpose of the nil memo parameter.

The nil parameter represents an optional memo, but its purpose and implications aren't clear from the code. Consider adding a comment explaining why no memo is used in the stress test.


Line range hint 14-62: Enhance test coverage for memo scenarios.

The stress test currently only tests basic deposits without memos. Consider expanding the test to cover:

  1. Deposits with standard memos
  2. Validation of receiver addresses
  3. Different revert options

Here's a suggested enhancement:

 func TestStressBTCDeposit(r *runner.E2ERunner, args []string) {
-    require.Len(r, args, 2)
+    require.Len(r, args, 3)

     depositAmount := parseFloat(r, args[0])
     numDeposits := parseInt(r, args[1])
+    testMemo := args[2] == "true" // Optional flag to test with memos
 
     r.SetBtcAddress(r.Name, false)
 
     r.Logger.Print("starting stress test of %d deposits", numDeposits)
 
     var eg errgroup.Group
 
     for i := 0; i < numDeposits; i++ {
         i := i
-        txHash := r.DepositBTCWithAmount(depositAmount, nil)
+        var memo *memo.InboundMemo
+        if testMemo {
+            // Test different memo scenarios in round-robin fashion
+            switch i % 3 {
+            case 0:
+                memo = memo.NewStandardMemo(r.GetAddress())
+            case 1:
+                memo = memo.NewStandardMemoWithRevert(r.GetAddress(), r.GetAddress())
+            case 2:
+                memo = memo.NewDepositAndCallMemo(r.GetAddress(), []byte("test"))
+            }
+        }
+        txHash := r.DepositBTCWithAmount(depositAmount, memo)
         r.Logger.Print("index %d: starting deposit, tx hash: %s", i, txHash.String())

Line range hint 63-85: Enhance deposit monitoring to validate receiver addresses.

The monitorBTCDeposit function could be enhanced to validate that the receiver address in the CCTX matches the intended receiver from the memo (when present).

Here's a suggested enhancement:

 func monitorBTCDeposit(r *runner.E2ERunner, hash *chainhash.Hash, index int, startTime time.Time) error {
     cctx := utils.WaitCctxMinedByInboundHash(r.Ctx, hash.String(), r.CctxClient, r.Logger, r.ReceiptTimeout)
     if cctx.CctxStatus.Status != crosschaintypes.CctxStatus_OutboundMined {
         return fmt.Errorf(
             "index %d: deposit cctx failed with status %s, message %s, cctx index %s",
             index,
             cctx.CctxStatus.Status,
             cctx.CctxStatus.StatusMessage,
             cctx.Index,
         )
     }
+    // Validate receiver address if memo was used
+    if len(cctx.InboundTxParams.Memo) > 0 {
+        parsedMemo, err := memo.ParseInboundMemo(cctx.InboundTxParams.Memo)
+        if err != nil {
+            return fmt.Errorf("index %d: failed to parse memo: %v", index, err)
+        }
+        if parsedMemo.Receiver != cctx.OutboundTxParams.Receiver {
+            return fmt.Errorf(
+                "index %d: receiver mismatch, memo: %s, cctx: %s",
+                index,
+                parsedMemo.Receiver,
+                cctx.OutboundTxParams.Receiver,
+            )
+        }
+    }
     timeToComplete := time.Since(startTime)
     r.Logger.Print("index %d: deposit cctx success in %s", index, timeToComplete.String())
     return nil
 }
e2e/e2etests/test_bitcoin_deposit_and_call_revert.go (2)

23-25: Consider improving the argument handling and documentation.

  1. Replace the magic number with a named constant for better maintainability
  2. Add documentation explaining why DefaultDepositorFee is added to the amount
+const (
+    expectedArgCount = 1
+    argAmountIndex  = 0
+)

-require.Len(r, args, 1)
-amount := parseFloat(r, args[0])
+require.Len(r, args, expectedArgCount, "Expected amount argument")
+// Parse amount and add depositor fee to cover transaction costs
+amount := parseFloat(r, args[argAmountIndex])

13-51: Consider extracting common Bitcoin test setup.

The test setup logic (Bitcoin address configuration, mining setup, UTXO validation) appears to be common across Bitcoin tests. Consider extracting this into a shared setup helper to improve maintainability and reduce duplication.

Example structure:

func SetupBitcoinTest(r *runner.E2ERunner) func() {
    r.SetBtcAddress(r.Name, false)
    stop := r.MineBlocksIfLocalBitcoin()
    
    utxos, err := r.ListDeployerUTXOs()
    require.NoError(r, err)
    require.NotEmpty(r, utxos)
    
    return stop
}
e2e/e2etests/test_bitcoin_std_deposit_and_call_revert_other_address.go (2)

14-14: Add function documentation.

Consider adding a documentation comment that explains:

  • The purpose of this E2E test
  • Expected args format and their purpose
  • Expected behavior when the test passes

Example:

// TestBitcoinStdMemoDepositAndCallRevertOtherAddress tests the Bitcoin deposit and call
// functionality when targeting a non-existing contract address. It verifies that
// the transaction is properly reverted and funds are sent to the specified revert address.
//
// Args:
//   - args[0]: Amount of BTC to send in the deposit transaction

24-25: Improve args validation.

The current length check doesn't provide context about the expected argument. Consider adding a more descriptive error message.

-require.Len(r, args, 1)
+require.Len(r, args, 1, "expected 1 argument: BTC amount to send")
zetaclient/zetacore/constant.go (1)

27-29: Consider removing explicit type for consistency.

The constant declaration is well-placed and documented. However, for consistency with other constants in this file, consider removing the explicit uint64 type specification as Go will implicitly type the constant correctly.

-PostVoteInboundCallOptionsGasLimit uint64 = 1_500_000
+PostVoteInboundCallOptionsGasLimit = 1_500_000
e2e/e2etests/test_bitcoin_std_deposit.go (1)

30-39: Use constants for memo configuration values.

Magic numbers in the memo configuration should be replaced with named constants for better maintainability and documentation.

+const (
+    memoVersion     = 0
+    memoEncodingFmt = memo.EncodingFmtCompactShort
+)

 memo := &memo.InboundMemo{
     Header: memo.Header{
-        Version:     0,
+        Version:     memoVersion,
-        EncodingFmt: memo.EncodingFmtCompactShort,
+        EncodingFmt: memoEncodingFmt,
         OpCode:      memo.OpCodeDeposit,
     },
pkg/memo/memo.go (1)

54-54: Enhance function documentation for clarity.

The current documentation could be more explicit about error conditions and validation behavior. Consider expanding it to detail specific scenarios where nil is returned versus when errors are returned.

-// Returns nil memo if given data can't be decoded as a memo.
+// Returns:
+//   - (nil, error) if header decoding fails or version is invalid
+//   - (nil, error) if field unpacking or validation fails
+//   - (*InboundMemo, nil) on successful decode and validation
x/crosschain/types/message_vote_inbound.go (1)

Based on the analysis of the codebase, I can now provide a final response:

MaxMessageLength should be moved to chain-specific parameters for better flexibility

The current implementation uses a hardcoded MaxMessageLength constant (10240 bytes) that is only used in message validation. Given that:

  1. The constant is only referenced in validation and tests
  2. The crosschain module lacks a parameter management system
  3. Different chains may have different requirements for message sizes
  4. The PR introduces new memo support with potential for larger data structures

Recommended approach:

  • Create a new parameter system in the crosschain module similar to other modules (emissions, observer)
  • Move MaxMessageLength to chain-specific parameters
  • Allow different limits for standard memos vs inscriptions
  • Add proper parameter validation and update mechanisms
🔗 Analysis chain

Line range hint 15-20: Consider addressing MaxMessageLength TODO in light of new memo support.

Given that this PR introduces standard memo support and the PR objectives mention new inscription support allowing for larger inbound data structures, it might be worth addressing the TODO comment about parameterizing MaxMessageLength. This would provide more flexibility for different chain requirements.

Let's check if this constant is referenced elsewhere:

Consider:

  1. Making this a chain-specific parameter
  2. Moving it to a configuration that can be adjusted per network
  3. Adding different limits for different types of messages (standard vs inscription)

Let me gather more context about the usage and validation of this constant.

The first command will show how MaxMessageLength is being used in context, while the second will help identify if there's an existing parameter system for similar limits. This will help determine if we should integrate with an existing parameter system or propose a new one.


Let me check if there's an existing parameter system in the crosschain module that we could leverage.

This will help determine if there's an existing parameter system we can integrate with for managing the message length limits.


Let me check one final aspect - whether there's a params.proto file in the crosschain module that we could extend.

This will help determine if there's an existing parameter management infrastructure in the crosschain module that we can leverage for the message length limit.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for MaxMessageLength usage across the codebase
rg "MaxMessageLength" --type go

Length of output: 400


Script:

#!/bin/bash
# Get more context around the MaxMessageLength usage in the test and validation
rg "MaxMessageLength" -B 2 -A 2 --type go

# Check if there are any parameters or configuration related files
fd "params|config" --type f --extension go | xargs rg "Length|Size|Limit" -B 1 -A 1

Length of output: 19879


Script:

#!/bin/bash
# Check for parameter-related files in the crosschain module
fd "params|config" --type f --extension go --search-path x/crosschain | xargs rg "Params|Config" -B 1 -A 1

# Look for any existing chain-specific configurations
ast-grep --pattern 'type Params struct {
  $$$
}'

Length of output: 8557


Script:

#!/bin/bash
# Look for params.proto in the crosschain module
fd "params.proto" --type f --search-path x/crosschain

# Check if there's any existing parameter management code
rg "ParamSet|GetParams|SetParams" --type go --search-path x/crosschain

Length of output: 570

testutil/sample/crypto.go (1)

63-73: Add documentation and parameter validation.

While the implementation is correct, consider these improvements for better maintainability:

  1. Add godoc explaining the P2WPKH address format and network parameter requirements
  2. Add validation for nil network params

Apply this diff:

 // BtcAddressP2WPKH returns a sample btc P2WPKH address
+//
+// P2WPKH (Pay-to-Witness-Public-Key-Hash) is a native SegWit address format
+// that provides better efficiency and lower fees compared to legacy addresses.
+//
+// Parameters:
+//   - t: testing context for assertions
+//   - net: Bitcoin network parameters (e.g., chaincfg.MainNetParams, chaincfg.TestNet3Params)
+//     must not be nil
 func BtcAddressP2WPKH(t *testing.T, net *chaincfg.Params) string {
+	require.NotNil(t, net, "network parameters must not be nil")
+
 	privateKey, err := btcec.NewPrivateKey()
 	require.NoError(t, err)
zetaclient/chains/bitcoin/observer/witness.go (3)

Line range hint 16-54: Enhance error handling and logging structure for better observability.

Consider improving the error handling and logging structure in GetBtcEventWithWitness to facilitate better debugging and monitoring:

 func GetBtcEventWithWitness(
   client interfaces.BTCRPCClient,
   tx btcjson.TxRawResult,
   tssAddress string,
   blockNumber uint64,
   logger zerolog.Logger,
   netParams *chaincfg.Params,
   depositorFee float64,
 ) (*BTCInboundEvent, error) {
   if len(tx.Vout) < 1 {
-    logger.Debug().Msgf("no output %s", tx.Txid)
+    logger.Debug().
+      Str("txid", tx.Txid).
+      Msg("transaction has no outputs")
     return nil, nil
   }
   if len(tx.Vin) == 0 {
-    logger.Debug().Msgf("no input found for inbound: %s", tx.Txid)
+    logger.Debug().
+      Str("txid", tx.Txid).
+      Msg("no input found for inbound transaction")
     return nil, nil
   }

   if err := isValidRecipient(tx.Vout[0].ScriptPubKey.Hex, tssAddress, netParams); err != nil {
-    logger.Debug().Msgf("irrelevant recipient %s for tx %s, err: %s", tx.Vout[0].ScriptPubKey.Hex, tx.Txid, err)
+    logger.Debug().
+      Str("txid", tx.Txid).
+      Str("script", tx.Vout[0].ScriptPubKey.Hex).
+      Err(err).
+      Msg("irrelevant recipient for transaction")
     return nil, nil
   }

Line range hint 133-142: Improve error handling and function structure in tryExtractOpRet.

The function could benefit from a more consistent error handling pattern and better readability.

 func tryExtractOpRet(tx btcjson.TxRawResult, logger zerolog.Logger) []byte {
   if len(tx.Vout) < 2 {
-    logger.Debug().Msgf("txn %s has fewer than 2 outputs, not target OP_RETURN txn", tx.Txid)
+    logger.Debug().
+      Str("txid", tx.Txid).
+      Int("outputs", len(tx.Vout)).
+      Msg("insufficient outputs for OP_RETURN transaction")
     return nil
   }

   memo, found, err := bitcoin.DecodeOpReturnMemo(tx.Vout[1].ScriptPubKey.Hex)
   if err != nil {
-    logger.Error().Err(err).Msgf("tryExtractOpRet: error decoding OP_RETURN memo: %s", tx.Vout[1].ScriptPubKey.Hex)
+    logger.Error().
+      Err(err).
+      Str("txid", tx.Txid).
+      Str("script", tx.Vout[1].ScriptPubKey.Hex).
+      Msg("failed to decode OP_RETURN memo")
     return nil
   }

-  if found {
-    return memo
-  }
-  return nil
+  return memo if found else nil

Line range hint 71-89: Enhance documentation for Bitcoin-specific logic in ParseScriptFromWitness.

The function handles complex Bitcoin witness parsing logic that would benefit from more detailed documentation, especially regarding the BIP341 implementation.

+// ParseScriptFromWitness attempts to parse the script from witness data according to BIP341.
+// The function handles the following cases:
+// 1. Empty witness data
+// 2. Annex detection and removal (0x50 byte at the start of last element)
+// 3. Script path spending validation
+//
+// Parameters:
+// - witness: Array of hex-encoded witness elements
+// - logger: Logger instance for debug information
+//
+// Returns:
+// - []byte: Decoded script if found, nil otherwise
 func ParseScriptFromWitness(witness []string, logger zerolog.Logger) []byte {
pkg/memo/fields_v0.go (1)

Line range hint 171-173: Consider optimizing abort address handling.

The conversion of abortAddress to string via Hex() after unpacking could be optimized since it was originally a string in the RevertOptions.

Consider maintaining the original string format:

-var abortAddress common.Address
-if zetabits.IsBitSet(dataFlags, bitPosAbortAddress) {
-    codec.AddArguments(ArgAbortAddress(&abortAddress))
+if zetabits.IsBitSet(dataFlags, bitPosAbortAddress) {
+    var tmpAddr common.Address
+    codec.AddArguments(ArgAbortAddress(&tmpAddr))
+    f.RevertOptions.AbortAddress = tmpAddr.Hex()
}
-
-// convert abort address to string
-if !crypto.IsEmptyAddress(abortAddress) {
-    f.RevertOptions.AbortAddress = abortAddress.Hex()
-}
pkg/memo/memo_test.go (1)

158-158: Consider a more descriptive field name.

The field name invalidField could be more explicit about its purpose. Consider renaming it to expectMemoOnValidationFailure or returnMemoOnInvalidField to better convey its role in the test cases.

pkg/memo/fields_v0_test.go (1)

Line range hint 1-400: Consider adding test cases for Bitcoin-specific scenarios.

Given that this PR focuses on Bitcoin inbound transactions and standard memo functionality, consider adding test cases that specifically validate:

  1. Bitcoin address handling in receiver and revert addresses
  2. Memo size constraints for Bitcoin transactions
  3. Edge cases around inscription data structures

Here's a suggested test case to add:

{
    name:      "bitcoin address validation",
    encodeFmt: memo.EncodingFmtABI,
    dataFlags: flagsAllFieldsSet,
    data: ABIPack(t,
        memo.ArgReceiver(fAddress),
        memo.ArgPayload(fBytes),
        memo.ArgRevertAddress("bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh"), // Bitcoin address
        memo.ArgAbortAddress(fAddress),
        memo.ArgRevertMessage(fBytes)),
    errMsg: "invalid address format for Bitcoin network",
},
x/crosschain/types/message_vote_inbound_test.go (2)

45-82: Enhance test coverage with edge cases and negative scenarios

The test case is well-structured and covers the basic functionality of RevertOptions. Consider adding the following test scenarios to make it more robust:

  1. Edge cases:
    • Maximum gas limit
    • Empty revert message
    • Invalid addresses
  2. Negative scenarios:
    • Zero gas limit
    • Invalid hex addresses

Here's a suggested addition to strengthen the test coverage:

t.Run("handles edge cases for revert options", func(t *testing.T) {
    tests := []struct {
        name    string
        options types.RevertOptions
        wantErr bool
    }{
        {
            name: "max gas limit",
            options: types.RevertOptions{
                RevertAddress:  sample.EthAddress().Hex(),
                RevertGasLimit: math.NewUintFromString("115792089237316195423570985008687907853269984665640564039457584007913129639935"),
            },
        },
        {
            name: "invalid address format",
            options: types.RevertOptions{
                RevertAddress: "invalid",
            },
            wantErr: true,
        },
    }
    
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            msg := types.NewMsgVoteInbound(
                // ... other required fields ...
                types.WithRevertOptions(tt.options),
            )
            err := msg.ValidateBasic()
            if tt.wantErr {
                require.Error(t, err)
                return
            }
            require.NoError(t, err)
        })
    }
})

Line range hint 1-1: Add package documentation for test coverage

Consider adding a package comment to document the test coverage strategy and important test scenarios. This helps maintainers understand the test organization and identify gaps in coverage.

Add the following documentation at the beginning of the file:

/*
Package types_test provides comprehensive testing for MsgVoteInbound message handling.

Test coverage includes:
- Basic validation
- Revert options handling
- Cross-chain call options
- Message digest computation
- Signer validation
- Protocol versioning
*/
package types_test
cmd/zetae2e/local/local.go (1)

Modularization recommendation validated: File requires immediate structural improvements

Based on the analysis:

  • The file is significantly large (515 lines) with multiple test routines
  • There are 10 distinct test routines covering different aspects (Bitcoin, Ethereum, Solana, etc.)
  • An existing TODO comment explicitly acknowledges the need for simplification
  • No similar modularized test files exist yet, indicating this would be a pioneering improvement

Recommended modularization approach:

  • Create a dedicated testcases directory under cmd/zetae2e/local/
  • Split test routines into focused files (e.g., bitcoin_tests.go, ethereum_tests.go)
  • Maintain a common test configuration and utilities in a shared package

This restructuring will:

  • Reduce cognitive load (current file is 515 lines)
  • Enable parallel development of test suites
  • Improve maintainability and test isolation
  • Set a precedent for future test organization
🔗 Analysis chain

Line range hint 102-102: Consider expediting the modularization of test routines.

The TODO comment correctly identifies the need to simplify this file. Given the addition of new test cases and growing complexity, consider prioritizing the modularization effort to:

  • Improve maintainability by separating test routines into dedicated files
  • Enhance readability by reducing file size
  • Make it easier to add new test cases in the future

Let's analyze the current file size and complexity:


Let me gather more context about the test routines and their complexity before making the final recommendation.

This will help us understand:

  1. The complexity of each test routine
  2. Any existing modularization plans
  3. Similar test file organization patterns in the codebase
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Analyze file complexity to support modularization recommendation

# Check file size and number of functions
echo "File size and function count:"
wc -l cmd/zetae2e/local/local.go
rg -c "^func" cmd/zetae2e/local/local.go

# List all test routines that could be moved to separate files
echo -e "\nTest routines that could be modularized:"
rg "TestRoutine" cmd/zetae2e/local/local.go

Length of output: 1088


Script:

#!/bin/bash
# Description: Analyze test routine implementations and their complexity

# Find the implementation of test routines
echo "Test routine implementations:"
ast-grep --pattern 'func $_TestRoutine($$$) {
  $$$
}'

# Check TODO comments related to modularization
echo -e "\nTODO comments about modularization:"
rg -i "todo.*modular|todo.*simplif|todo.*refactor" cmd/zetae2e/local/local.go

# Check if there are similar test files in the codebase
echo -e "\nSimilar test files:"
fd -e go -e test.go zetae2e

Length of output: 456

zetaclient/chains/bitcoin/tx_script_test.go (1)

370-411: LGTM! Well-structured table-driven tests for error cases.

The table-driven tests provide comprehensive coverage of error scenarios with clear test names and expected error messages.

Consider adding a constant for the common hex prefix "6a" (OP_RETURN) to improve maintainability:

+const (
+    opReturn = "6a"
+)
+
 tests := []struct {
     name      string
     scriptHex string
     errMsg    string
 }{
     {
         name:      "should return error on invalid hex",
-        scriptHex: "6a14xy",
+        scriptHex: opReturn + "14xy",
         errMsg:    "error decoding script hex",
     },
     // ... rest of the test cases
 }
e2e/e2etests/e2etests.go (1)

75-91: Consider adding documentation comments for new test constants.

While the constant names are descriptive, adding documentation comments would improve maintainability by explicitly stating the purpose and expected behavior of each new test, especially for the standard memo-related tests.

Apply this diff to add documentation:

+// Bitcoin deposit tests with standard memo support
 TestBitcoinStdMemoDepositName                          = "bitcoin_std_memo_deposit"
 TestBitcoinStdMemoDepositAndCallName                   = "bitcoin_std_memo_deposit_and_call"
 TestBitcoinStdMemoDepositAndCallRevertName             = "bitcoin_std_memo_deposit_and_call_revert"
 TestBitcoinStdMemoDepositAndCallRevertOtherAddressName = "bitcoin_std_memo_deposit_and_call_revert_other_address"
changelog.md (1)

24-24: Enhance the changelog entry with more details.

The current entry "standard memo for Bitcoin inbound" could be more descriptive to better communicate the impact and scope of the change.

Consider expanding the entry to:

-* [3025](https://github.com/zeta-chain/node/pull/3025) - standard memo for Bitcoin inbound
+* [3025](https://github.com/zeta-chain/node/pull/3025) - add support for standard memo format in Bitcoin inbound transactions, enabling explicit function calls and receiver address specification
zetaclient/chains/bitcoin/observer/event.go (2)

139-140: Increase test coverage for error handling in legacy memo decoding

Lines 139-140 handle the error case when decoding a legacy memo fails. Currently, this branch is not covered by tests.

Consider adding unit tests that provide invalid legacy memo bytes to DecodeEventMemoBytes. This will ensure that the error handling logic is verified and robust against malformed input.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 139-140: zetaclient/chains/bitcoin/observer/event.go#L139-L140
Added lines #L139 - L140 were not covered by tests


173-173: Ensure all code paths are tested in CheckEventProcessability

Line 173 contains the default return statement of true, which is executed if none of the switch cases match. This line is not covered by tests.

After handling the unexpected InboundProcessability values with a default case as suggested, update the tests to cover this new branch. This will improve the test coverage and ensure that all possible code paths are verified.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 173-173: zetaclient/chains/bitcoin/observer/event.go#L173
Added line #L173 was not covered by tests

e2e/utils/zetacore.go (1)

207-225: Enhance Function Documentation

The WaitCctxRevertedByInboundHash function lacks descriptive documentation. Providing clear comments will improve maintainability and help other developers understand its purpose and usage.

Consider adding a detailed comment:

// WaitCctxRevertedByInboundHash waits until a cross-chain transaction (CCTX) with the specified inbound hash
// is reverted. It utilizes a match function to filter CCTXs based on defined criteria and returns the first
// matching CCTX found within the context's deadline.
zetaclient/chains/bitcoin/observer/event_test.go (3)

27-42: Enhance Documentation for createTestBtcEvent Function

Consider providing more detailed documentation for the createTestBtcEvent function. Including parameter descriptions and explaining the purpose of each field in the returned BTCInboundEvent struct will improve code readability and assist future maintainers.


137-228: Improve Test Data Clarity by Generating MemoBytes Programmatically

The test cases in Test_DecodeEventMemoBytes utilize hard-coded hex strings for MemoBytes (e.g., lines 143, 163, 179, etc.). Generating these memo bytes programmatically or adding comments that explain the composition of these hex strings can enhance the readability and maintainability of the tests. This approach makes it easier for others to understand and modify the test cases as needed.


344-346: Add Nil Check for vote Before Assertion

In Test_NewInboundVoteV1, after obtaining vote from ob.NewInboundVoteV1(event, amountSats) (line 344), consider adding a nil check before proceeding to the assertion on line 345. This ensures that a nil vote does not cause a panic, improving the robustness of the test.

zetaclient/chains/bitcoin/observer/inbound.go (1)

140-144: Increase Unit Test Coverage for New Code

The newly added code lines are not covered by unit tests. To ensure reliability and prevent future regressions, consider adding unit tests for these sections.

Also applies to: 282-282, 379-379

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 140-140: zetaclient/chains/bitcoin/observer/inbound.go#L140
Added line #L140 was not covered by tests


[warning] 142-142: zetaclient/chains/bitcoin/observer/inbound.go#L142
Added line #L142 was not covered by tests


[warning] 144-144: zetaclient/chains/bitcoin/observer/inbound.go#L144
Added line #L144 was not covered by tests

zetaclient/chains/evm/observer/v2_inbound.go (3)

Line range hint 185-210: Add Unit Tests for newDepositAndCallInboundVote Function

The newDepositAndCallInboundVote function is a critical addition for handling deposit and call events. To ensure correctness and prevent future regressions, it's advisable to add unit tests that cover various scenarios, including different asset types and event payloads.

Would you like assistance in generating unit tests for this function?

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 195-195: zetaclient/chains/evm/observer/v2_inbound.go#L195
Added line #L195 was not covered by tests


Line range hint 242-282: Refactor Observation Methods to Reduce Code Duplication

The ObserveGatewayDepositAndCall method shares significant similarities with ObserveGatewayDeposit and ObserveGatewayCall. Extracting common logic into shared helper functions or utilizing interfaces can improve maintainability and reduce code duplication.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 195-195: zetaclient/chains/evm/observer/v2_inbound.go#L195
Added line #L195 was not covered by tests


Line range hint 284-320: Consolidate Event Parsing Functions for Maintainability

The parseAndValidateDepositAndCallEvents function closely resembles parseAndValidateDepositEvents and parseAndValidateCallEvents. Refactoring these methods to share common code can reduce redundancy and simplify future updates or bug fixes.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 195-195: zetaclient/chains/evm/observer/v2_inbound.go#L195
Added line #L195 was not covered by tests

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 0f8a4c2 and 55091d8.

📒 Files selected for processing (33)
  • changelog.md (1 hunks)
  • cmd/zetae2e/local/local.go (1 hunks)
  • e2e/e2etests/e2etests.go (2 hunks)
  • e2e/e2etests/test_bitcoin_deposit.go (1 hunks)
  • e2e/e2etests/test_bitcoin_deposit_and_call_revert.go (1 hunks)
  • e2e/e2etests/test_bitcoin_deposit_refund.go (0 hunks)
  • e2e/e2etests/test_bitcoin_donation.go (1 hunks)
  • e2e/e2etests/test_bitcoin_std_deposit.go (1 hunks)
  • e2e/e2etests/test_bitcoin_std_deposit_and_call.go (1 hunks)
  • e2e/e2etests/test_bitcoin_std_deposit_and_call_revert.go (1 hunks)
  • e2e/e2etests/test_bitcoin_std_deposit_and_call_revert_other_address.go (1 hunks)
  • e2e/e2etests/test_stress_btc_deposit.go (1 hunks)
  • e2e/runner/bitcoin.go (6 hunks)
  • e2e/utils/zetacore.go (1 hunks)
  • pkg/memo/fields.go (1 hunks)
  • pkg/memo/fields_v0.go (1 hunks)
  • pkg/memo/fields_v0_test.go (1 hunks)
  • pkg/memo/memo.go (2 hunks)
  • pkg/memo/memo_test.go (3 hunks)
  • tests/simulation/sim/sim_state.go (1 hunks)
  • testutil/helpers.go (2 hunks)
  • testutil/sample/crypto.go (2 hunks)
  • x/crosschain/types/message_vote_inbound.go (1 hunks)
  • x/crosschain/types/message_vote_inbound_test.go (1 hunks)
  • zetaclient/chains/bitcoin/observer/event.go (1 hunks)
  • zetaclient/chains/bitcoin/observer/event_test.go (1 hunks)
  • zetaclient/chains/bitcoin/observer/inbound.go (5 hunks)
  • zetaclient/chains/bitcoin/observer/inbound_test.go (2 hunks)
  • zetaclient/chains/bitcoin/observer/witness.go (1 hunks)
  • zetaclient/chains/bitcoin/tx_script.go (1 hunks)
  • zetaclient/chains/bitcoin/tx_script_test.go (1 hunks)
  • zetaclient/chains/evm/observer/v2_inbound.go (2 hunks)
  • zetaclient/zetacore/constant.go (1 hunks)
💤 Files with no reviewable changes (1)
  • e2e/e2etests/test_bitcoin_deposit_refund.go
🧰 Additional context used
📓 Path-based instructions (31)
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.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.go (1)

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

e2e/e2etests/test_bitcoin_donation.go (1)

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

e2e/e2etests/test_bitcoin_std_deposit.go (1)

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

e2e/e2etests/test_bitcoin_std_deposit_and_call.go (1)

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

e2e/e2etests/test_bitcoin_std_deposit_and_call_revert.go (1)

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

e2e/e2etests/test_bitcoin_std_deposit_and_call_revert_other_address.go (1)

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

e2e/e2etests/test_stress_btc_deposit.go (1)

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

e2e/runner/bitcoin.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.

pkg/memo/fields.go (1)

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

pkg/memo/fields_v0.go (1)

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

pkg/memo/fields_v0_test.go (1)

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

pkg/memo/memo.go (1)

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

pkg/memo/memo_test.go (1)

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

tests/simulation/sim/sim_state.go (1)

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

testutil/helpers.go (1)

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

testutil/sample/crypto.go (1)

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

x/crosschain/types/message_vote_inbound.go (1)

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

x/crosschain/types/message_vote_inbound_test.go (1)

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

zetaclient/chains/bitcoin/observer/event.go (1)

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

zetaclient/chains/bitcoin/observer/event_test.go (1)

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

zetaclient/chains/bitcoin/observer/inbound.go (1)

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

zetaclient/chains/bitcoin/observer/inbound_test.go (1)

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

zetaclient/chains/bitcoin/observer/witness.go (1)

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

zetaclient/chains/bitcoin/tx_script.go (1)

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

zetaclient/chains/bitcoin/tx_script_test.go (1)

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

zetaclient/chains/evm/observer/v2_inbound.go (1)

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

zetaclient/zetacore/constant.go (1)

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

📓 Learnings (2)
zetaclient/chains/bitcoin/observer/event.go (4)
Learnt from: ws4charlie
PR: zeta-chain/node#2899
File: zetaclient/chains/bitcoin/observer/inbound.go:37-38
Timestamp: 2024-09-19T18:22:35.964Z
Learning: In `BTCInboundEvent`, it's acceptable to use `float64` for monetary values (`Value` and `DepositorFee`) because precision is ensured through conversion to integer when building the vote message.
Learnt from: ws4charlie
PR: zeta-chain/node#2899
File: zetaclient/chains/bitcoin/observer/inbound.go:37-38
Timestamp: 2024-10-08T15:34:48.217Z
Learning: In `BTCInboundEvent`, it's acceptable to use `float64` for monetary values (`Value` and `DepositorFee`) because precision is ensured through conversion to integer when building the vote message.
Learnt from: ws4charlie
PR: zeta-chain/node#2899
File: zetaclient/chains/bitcoin/observer/inbound.go:37-38
Timestamp: 2024-10-08T15:34:48.217Z
Learning: In `BTCInboundEvent`, it's acceptable to use `float64` for monetary values (`Value` and `DepositorFee`) because precision is ensured through conversion to integer when building the vote message.
Learnt from: ws4charlie
PR: zeta-chain/node#2899
File: zetaclient/chains/bitcoin/observer/inbound.go:37-38
Timestamp: 2024-10-08T15:34:47.578Z
Learning: In `BTCInboundEvent`, it's acceptable to use `float64` for monetary values (`Value` and `DepositorFee`) because precision is ensured through conversion to integer when building the vote message.
zetaclient/chains/bitcoin/observer/inbound.go (8)
Learnt from: ws4charlie
PR: zeta-chain/node#2899
File: zetaclient/chains/bitcoin/observer/inbound.go:131-132
Timestamp: 2024-10-08T15:34:47.578Z
Learning: ObserveInbound coverage will be improved in future refactor.
Learnt from: ws4charlie
PR: zeta-chain/node#2899
File: zetaclient/chains/bitcoin/observer/inbound.go:131-132
Timestamp: 2024-10-08T15:34:48.217Z
Learning: ObserveInbound coverage will be improved in future refactor.
Learnt from: ws4charlie
PR: zeta-chain/node#2899
File: zetaclient/chains/bitcoin/observer/inbound.go:131-132
Timestamp: 2024-10-08T15:34:48.217Z
Learning: ObserveInbound coverage will be improved in future refactor.
Learnt from: ws4charlie
PR: zeta-chain/node#2899
File: zetaclient/chains/bitcoin/observer/inbound.go:131-132
Timestamp: 2024-09-19T18:25:57.534Z
Learning: ObserveInbound coverage will be improved in future refactor.
Learnt from: ws4charlie
PR: zeta-chain/node#2899
File: zetaclient/chains/bitcoin/observer/inbound.go:37-38
Timestamp: 2024-10-08T15:34:47.578Z
Learning: In `BTCInboundEvent`, it's acceptable to use `float64` for monetary values (`Value` and `DepositorFee`) because precision is ensured through conversion to integer when building the vote message.
Learnt from: ws4charlie
PR: zeta-chain/node#2899
File: zetaclient/chains/bitcoin/observer/inbound.go:37-38
Timestamp: 2024-09-19T18:22:35.964Z
Learning: In `BTCInboundEvent`, it's acceptable to use `float64` for monetary values (`Value` and `DepositorFee`) because precision is ensured through conversion to integer when building the vote message.
Learnt from: ws4charlie
PR: zeta-chain/node#2899
File: zetaclient/chains/bitcoin/observer/inbound.go:37-38
Timestamp: 2024-10-08T15:34:48.217Z
Learning: In `BTCInboundEvent`, it's acceptable to use `float64` for monetary values (`Value` and `DepositorFee`) because precision is ensured through conversion to integer when building the vote message.
Learnt from: ws4charlie
PR: zeta-chain/node#2899
File: zetaclient/chains/bitcoin/observer/inbound.go:37-38
Timestamp: 2024-10-08T15:34:48.217Z
Learning: In `BTCInboundEvent`, it's acceptable to use `float64` for monetary values (`Value` and `DepositorFee`) because precision is ensured through conversion to integer when building the vote message.
🪛 GitHub Check: codecov/patch
tests/simulation/sim/sim_state.go

[warning] 251-251: tests/simulation/sim/sim_state.go#L251
Added line #L251 was not covered by tests

zetaclient/chains/bitcoin/observer/event.go

[warning] 139-140: zetaclient/chains/bitcoin/observer/event.go#L139-L140
Added lines #L139 - L140 were not covered by tests


[warning] 173-173: zetaclient/chains/bitcoin/observer/event.go#L173
Added line #L173 was not covered by tests

zetaclient/chains/bitcoin/observer/inbound.go

[warning] 140-140: zetaclient/chains/bitcoin/observer/inbound.go#L140
Added line #L140 was not covered by tests


[warning] 142-142: zetaclient/chains/bitcoin/observer/inbound.go#L142
Added line #L142 was not covered by tests


[warning] 144-144: zetaclient/chains/bitcoin/observer/inbound.go#L144
Added line #L144 was not covered by tests


[warning] 282-282: zetaclient/chains/bitcoin/observer/inbound.go#L282
Added line #L282 was not covered by tests


[warning] 379-379: zetaclient/chains/bitcoin/observer/inbound.go#L379
Added line #L379 was not covered by tests

zetaclient/chains/bitcoin/tx_script.go

[warning] 204-204: zetaclient/chains/bitcoin/tx_script.go#L204
Added line #L204 was not covered by tests

zetaclient/chains/evm/observer/v2_inbound.go

[warning] 195-195: zetaclient/chains/evm/observer/v2_inbound.go#L195
Added line #L195 was not covered by tests


[warning] 331-331: zetaclient/chains/evm/observer/v2_inbound.go#L331
Added line #L331 was not covered by tests

🔇 Additional comments (34)
pkg/memo/fields.go (1)

9-9: Verify the asymmetric handling of opCode parameter.

The Unpack method no longer requires opCode while Pack and Validate methods still use it. This asymmetry might indicate:

  1. OpCode validation is handled elsewhere in the call chain
  2. OpCode is not needed during unpacking
  3. Potential inconsistency in the interface design

Let's verify the usage pattern:

✅ Verification successful

Let me search for more specific information about the memo package implementation to understand the asymmetry better.


Let me search for the actual implementation details of the Unpack method to understand how it handles the opCode parameter.


The asymmetric handling of opCode is intentionally designed and correct.

The code analysis reveals a well-structured design where:

  1. Pack requires opCode to encode the memo fields with the correct operation type
  2. Validate needs opCode to enforce operation-specific rules (e.g., payload restrictions for OpCodeDeposit)
  3. Unpack doesn't need opCode because:
    • Operation type is already encoded in the memo header
    • Validation of operation-specific rules happens during Pack/Validate

This asymmetry aligns with the single responsibility principle:

  • Encoding (Pack): Needs full context to create the memo
  • Validation: Enforces operation-specific rules
  • Decoding (Unpack): Simply extracts data using the format specified in the header
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for Unpack method implementations and their callers
echo "Searching for Unpack implementations:"
ast-grep --pattern 'func ($x *$t) Unpack($$$) $$$'

echo -e "\nSearching for Unpack method calls:"
rg -A 2 '\.Unpack\(' 

Length of output: 43134


Script:

#!/bin/bash
# Search for the complete interface definition and its implementations
echo "Searching for memo Fields interface definition:"
rg -A 10 "type Fields interface" pkg/memo/

echo -e "\nSearching for Fields implementations:"
ast-grep --pattern 'type $x struct {
  $$$
}'  pkg/memo/

echo -e "\nSearching for Pack method implementations:"
ast-grep --pattern 'func ($x *$t) Pack($$$) $$$' pkg/memo/

Length of output: 1060


Script:

#!/bin/bash
# Search for Unpack implementations and related code
echo "Searching for Unpack implementations:"
rg -A 5 "func.*Unpack.*\(" pkg/memo/

echo -e "\nSearching for opCode usage in memo package:"
rg "opCode" pkg/memo/

echo -e "\nSearching for files in memo package:"
fd . pkg/memo/

Length of output: 4563

e2e/e2etests/test_bitcoin_deposit.go (1)

18-18: Verify the signature change impact across the codebase.

The updated call to DepositBTCWithAmount with a nil parameter appears to be part of the new standard memo integration. Let's verify this change is consistent across the codebase.

✅ Verification successful

Based on the results, I can now generate a final response as we have sufficient information about the signature changes and their usage across the codebase.

Signature change is consistently implemented across the codebase

The verification shows that:

  • The DepositBTCWithAmount function in e2e/runner/bitcoin.go correctly accepts two parameters: amount float64 and memo *memo.InboundMemo
  • All calls to this function across the codebase have been updated to use the new signature:
    • Standard deposit tests pass memo object: test_bitcoin_std_deposit.go, test_bitcoin_std_deposit_and_call.go
    • Basic deposit tests pass nil for memo: test_bitcoin_deposit.go, test_stress_btc_deposit.go
    • Revert scenario tests properly utilize the memo parameter: test_bitcoin_std_deposit_and_call_revert.go, test_bitcoin_std_deposit_and_call_revert_other_address.go
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining calls to the old signature
# and verify the implementation of the new signature

# Search for all calls to DepositBTCWithAmount
rg -A 2 "DepositBTCWithAmount\(" 

# Search for the implementation to verify parameter handling
ast-grep --pattern 'func $_($$) DepositBTCWithAmount($_, $_) {
  $$$
}'

Length of output: 1751

testutil/helpers.go (1)

4-11: LGTM: Import organization follows Go conventions

The imports are properly organized with standard library imports grouped separately from external dependencies.

e2e/e2etests/test_bitcoin_std_deposit_and_call_revert.go (1)

1-11: LGTM! Clean and well-organized imports.

The imports are properly organized with standard library packages separated from project-specific ones.

e2e/e2etests/test_bitcoin_std_deposit_and_call_revert_other_address.go (1)

46-46: Verify error handling for deposit transaction.

Consider adding test cases to verify error scenarios, such as:

  • Invalid amount
  • Malformed memo
  • Network issues
zetaclient/zetacore/constant.go (1)

27-29: Verify gas limit value usage and sufficiency.

The gas limit of 1,500,000 appears reasonable as it:

  • Matches PostGasPriceGasLimit
  • Is higher than basic operations (200,000)
  • Is lower than complex EVM interactions (4,000,000 - 7,000,000)

Let's verify its usage and adequacy:

✅ Verification successful

Based on the search results, I can now generate a final response as we have sufficient information about the gas limit usage and context.

Gas limit value of 1,500,000 is appropriately configured

The constant PostVoteInboundCallOptionsGasLimit is:

  • Used specifically in inbound vote processing (v2_inbound.go)
  • Well-positioned within the range of other gas limits in the codebase:
    • Higher than basic operations (21,000 for simple transfers)
    • Lower than complex operations (test cases show up to 1,000,000)
  • Consistent with the codebase's gas management patterns, where gas limits are explicitly set and validated
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage and context of the new gas limit constant

# Test 1: Find where this constant is used
echo "Searching for PostVoteInboundCallOptionsGasLimit usage:"
rg "PostVoteInboundCallOptionsGasLimit"

# Test 2: Look for similar gas consumption patterns in call options
echo -e "\nSearching for gas consumption patterns in call options:"
rg -i "call.*options.*gas"

Length of output: 8504

e2e/e2etests/test_bitcoin_std_deposit.go (1)

44-47: Enhance CCTX verification.

Consider adding more comprehensive checks for the CCTX:

  • Verify the receiver address matches the memo
  • Validate the amount in the CCTX
  • Check for any fees deducted
pkg/memo/memo.go (2)

67-71: LGTM! Clean error handling with good context.

The separation of unpacking and validation concerns improves code maintainability.


Line range hint 54-80: Verify memo decoding usage in Bitcoin inbound processing.

Given this change affects Bitcoin inbound data processing, let's verify all callers handle nil memo returns correctly.

✅ Verification successful

Let me gather more context about how the nil memo is handled in the Bitcoin observer.


Let me try one more verification to get the complete Bitcoin observer implementation.


Based on the context we've gathered, I can now provide a final response about the memo decoding usage in Bitcoin processing.

✓ Bitcoin observer correctly handles nil memo returns

The verification shows that the Bitcoin observer implementation in zetaclient/chains/bitcoin/observer/event.go properly handles the nil memo case through a switch statement pattern:

memoStd, err = memo.DecodeFromBytes(event.MemoBytes)

switch {
case memoStd != nil:
    // Handles valid memo with additional validation

The code structure ensures that nil memos are safely handled by falling through the switch statement, while valid memos undergo proper validation including:

  • Checking for improper data in valid memos
  • Validating operation codes (specifically blocking OpCodeCall)
  • Verifying revert address validity
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for DecodeFromBytes usage in Bitcoin inbound processing
rg -A 5 "DecodeFromBytes\(" | grep -B 5 -A 5 "bitcoin"

Length of output: 656


Script:

#!/bin/bash
# Get more context around the Bitcoin observer's memo handling
ast-grep --pattern 'memoStd, err = memo.DecodeFromBytes($_)' -A 20

Length of output: 1779


Script:

#!/bin/bash
# Check the full Bitcoin observer event processing implementation
rg -l "bitcoin.*observer.*event" | xargs cat

Length of output: 46


Script:

#!/bin/bash
# Get the Bitcoin observer implementation using a more specific pattern
rg -A 10 "type.*BitcoinObserver" 

Length of output: 34


Script:

#!/bin/bash
# Find and show the event handling function
ast-grep --pattern 'func ($_ *BitcoinObserver) $_($_, $_, $_) error {
  $$$
}'

Length of output: 80

x/crosschain/types/message_vote_inbound.go (1)

25-30: LGTM: Clean implementation of revert options setter.

The implementation follows the established pattern of option setters in the codebase and maintains good consistency with similar functions like WithZEVMRevertOptions and WithEVMRevertOptions.

testutil/sample/crypto.go (1)

10-12: LGTM: Clean import organization.

The new Bitcoin-related imports are properly organized and necessary for the added functionality.

zetaclient/chains/bitcoin/observer/witness.go (1)

Line range hint 133-142: Verify consistent memo handling across the codebase.

Let's ensure that the memo extraction logic is consistently implemented across all Bitcoin-related files.

✅ Verification successful

Based on the verification results, I can now generate the final response as the scripts have provided comprehensive information about memo handling across the codebase.

Memo handling implementation is consistent and well-structured across Bitcoin-related files

The verification confirms that:

  • The DecodeOpReturnMemo function signature is consistently used across all implementations
  • Error handling patterns are uniform across the codebase
  • The memo extraction logic in tryExtractOpRet follows the established pattern
  • Test coverage exists for both successful and error cases

The rationale for this verification:

  1. No instances of old/deprecated DecodeOpReturnMemo signatures were found
  2. The implementation in tx_script.go serves as the single source of truth for memo decoding
  3. All usages (witness.go, inbound.go) follow the same pattern of handling the (memo, found, error) tuple
  4. Comprehensive test coverage in tx_script_test.go validates both success and error scenarios
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify consistent memo handling implementation
# Expected results: All Bitcoin-related files should use the updated DecodeOpReturnMemo signature

# Check for any remaining uses of old DecodeOpReturnMemo signature
echo "Checking for old DecodeOpReturnMemo usage patterns..."
rg -p "DecodeOpReturnMemo.*tx.*Txid" --type go

# Check for consistent memo extraction patterns
echo "Checking for memo extraction patterns..."
rg -p "tryExtractOpRet|DecodeOpReturnMemo" --type go -A 3

Length of output: 2727

pkg/memo/fields_v0.go (2)

Line range hint 66-91: Validation logic is robust and well-structured.

The validation method effectively enforces:

  • Address validation for both receiver and abort addresses
  • Payload restrictions for deposit operations
  • Semantic correctness of revert message usage

57-63: Document validation requirements after Unpack signature change.

The removal of validation from Unpack requires careful handling to ensure validation is performed at the appropriate point in the call chain. Consider adding documentation to clarify when validation should be performed.

Let's verify all callers properly handle validation:

✅ Verification successful

Let me search for more specific information about the validation flow.


Validation is properly handled after Unpack signature change

The code analysis reveals that validation is still properly enforced in the call chain:

  1. Unpack is called in memo.go:DecodeFromBytes()
  2. Validation is explicitly performed right after unpacking:
err = memo.FieldsV0.Validate(memo.OpCode, memo.Header.DataFlags)

The separation of validation from Unpack follows the single responsibility principle while maintaining security through explicit validation calls. The change improves code organization without compromising validation requirements.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for Unpack calls to ensure they're paired with Validate
rg -A 5 "Unpack\(" 

Length of output: 90098


Script:

#!/bin/bash
# Search for Validate calls and memo package usage
rg -A 5 "Validate\(" pkg/memo/
rg -A 5 "FieldsV0" pkg/memo/

Length of output: 15988

pkg/memo/memo_test.go (2)

255-256: LGTM! Clear and specific error message.

The error message clearly indicates the specific failure point in unpacking FieldsV0, which helps in debugging and understanding test failures.


280-286: LGTM! Well-structured error handling.

The error handling logic clearly distinguishes between validation failures and decoding failures, with appropriate assertions for each case. The comments effectively explain the expected behavior.

pkg/memo/fields_v0_test.go (1)

216-216: Verify test coverage for operation-specific field validation.

While removing opCode from Unpack simplifies the API, we should ensure that operation-specific field validation is still covered elsewhere in the test suite. This is particularly important given the PR's focus on standardizing Bitcoin inbound data and handling different operation types (deposit, depositAndCall).

Let's verify the test coverage:

✅ Verification successful

Let me gather more information about the field validation and operation code handling to make a conclusive verification.


Let me gather one final piece of information to understand how operation validation is handled in the new structure.


Operation-specific validation remains robust despite API change

The removal of opCode from the Unpack method is a valid architectural change as the verification shows:

  • Operation-specific validation is properly handled in the separate Validate method, which still takes opCode as a parameter
  • The Validate method contains explicit checks for different operations (e.g., preventing payload for deposit operations)
  • Test coverage for field validation is maintained through comprehensive test cases in Test_V0_Validate
  • The separation of unpacking and validation concerns actually improves the code design by making the validation rules more explicit and centralized
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if operation-specific field validation is covered in other test files
# Look for test functions that validate fields based on operation type

# Search for test functions that handle operation validation
rg -g '*.go' -A 5 'func.*Test.*Operation|func.*Test.*OpCode'

# Search for field validation with different operation codes
ast-grep --pattern 'fields.Validate($opCode, $_)'

Length of output: 1215


Script:

#!/bin/bash
# Search for field validation tests and operation code handling
# Look for test cases and validation logic in the memo package

# Check for field validation tests
rg -g 'pkg/memo/*.go' -B 2 -A 5 'func.*Test.*Fields|func.*Test.*Validate'

# Look for operation code related constants and types
rg -g 'pkg/memo/*.go' "type.*Op|const.*Op"

# Search for validation logic in the fields implementation
ast-grep --pattern 'func ($receiver) Validate($$$) {
  $$$
}'

Length of output: 2035


Script:

#!/bin/bash
# Check the implementation of field validation and operation handling

# Look for the Unpack implementation and its validation logic
ast-grep --pattern 'func ($receiver) Unpack($$$) error {
  $$$
}'

# Check for any operation-specific validation in the V0 fields
rg -g 'pkg/memo/fields_v0.go' -B 2 -A 10 'func.*Validate|func.*Unpack'

Length of output: 1398

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

303-308: LGTM: Well-structured test coverage for Bitcoin standard memo functionality.

The new test cases provide comprehensive coverage for the standard memo functionality, including basic deposits, deposit-and-call operations, and revert scenarios. The test names are clear and follow the established naming convention.

zetaclient/chains/bitcoin/tx_script_test.go (3)

343-349: LGTM! Test case properly updated for the new function signature.

The test case correctly validates the OP_RETURN memo decoding functionality with the updated function signature.


353-358: LGTM! Non-OP_RETURN test case properly handles the signature change.

The test case maintains good error handling and validation logic while adapting to the new function signature.


359-367: LGTM! Good addition of edge case test.

The new test case for short scripts enhances the test coverage by validating an important edge case.

e2e/e2etests/e2etests.go (1)

498-541: Verify implementation of referenced test functions.

Let's ensure that all the new test functions referenced in the registrations are implemented in the codebase.

✅ Verification successful

Let me try a different search strategy using rg to locate these function implementations, as they might be in different files or have different patterns.


All test functions are properly implemented

The verification confirms that all test functions referenced in the registrations are implemented in their respective files:

  • TestBitcoinDepositAndCallRevert in test_bitcoin_deposit_and_call_revert.go
  • TestBitcoinDonation in test_bitcoin_donation.go
  • TestBitcoinStdMemoDeposit in test_bitcoin_std_deposit.go
  • TestBitcoinStdMemoDepositAndCall in test_bitcoin_std_deposit_and_call.go
  • TestBitcoinStdMemoDepositAndCallRevert in test_bitcoin_std_deposit_and_call_revert.go
  • TestBitcoinStdMemoDepositAndCallRevertOtherAddress in test_bitcoin_std_deposit_and_call_revert_other_address.go
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that all referenced test functions are implemented.

# Test functions to verify
functions=(
  "TestBitcoinDepositAndCallRevert"
  "TestBitcoinDonation"
  "TestBitcoinStdMemoDeposit"
  "TestBitcoinStdMemoDepositAndCall"
  "TestBitcoinStdMemoDepositAndCallRevert"
  "TestBitcoinStdMemoDepositAndCallRevertOtherAddress"
)

# Search for function implementations
for func in "${functions[@]}"; do
  echo "Searching for function: $func"
  ast-grep --pattern "func $func($$$) $$$"
done

Length of output: 1621


Script:

#!/bin/bash
# Search for function implementations using ripgrep
# Using -A 1 to show one line after the match for better context

for func in "TestBitcoinDepositAndCallRevert" "TestBitcoinDonation" "TestBitcoinStdMemoDeposit" "TestBitcoinStdMemoDepositAndCall" "TestBitcoinStdMemoDepositAndCallRevert" "TestBitcoinStdMemoDepositAndCallRevertOtherAddress"; do
  echo "=== Searching for function: $func ==="
  rg "func $func" -A 1
done

# Also search for the function names in case they're referenced differently
echo "=== Searching for any references to these functions ==="
rg "TestBitcoin(Deposit|Donation|StdMemo)" --type go

Length of output: 8728

zetaclient/chains/bitcoin/observer/event.go (4)

38-63: Struct BTCInboundEvent is well-defined

The BTCInboundEvent struct encapsulates all necessary fields for representing an inbound Bitcoin transaction event. The use of fields like FromAddress, ToAddress, Value, and MemoBytes provides clarity and completeness.


66-89: CheckProcessability function logic is sound

The method CheckProcessability systematically checks for compliance violations, donation identification, and correctly categorizes the inbound event's processability. The logic is clear and adheres to the compliance requirements.


145-147: Validate the receiver address before assignment

The check for an empty receiver address is appropriate. Ensuring that receiver is not empty before assigning to event.ToAddress prevents potential issues downstream.


200-233: 🛠️ Refactor suggestion

Consider updating the protocol contract version

The function NewInboundVoteMemoStd is currently creating a message with ProtocolContractVersion_V1, even though it's intended for standard memos, which might be associated with a newer protocol version.

Update the ProtocolContractVersion to reflect the appropriate version:

 crosschaintypes.NewMsgVoteInbound(
     // Existing parameters
-    crosschaintypes.ProtocolContractVersion_V1,
+    crosschaintypes.ProtocolContractVersion_V2,
     false, // Update if relevant for v2
 )

Also, consider updating the TODO comment and renaming the function to EventToInboundVoteV2 when addressing Issue #2711.

Likely invalid or redundant comment.

e2e/utils/zetacore.go (1)

209-212: 🛠️ Refactor suggestion

Ensure Consistent Parameter Ordering

The parameter t require.TestingT is placed after the context in WaitCctxRevertedByInboundHash. For consistency and readability, consider placing the testing parameter after the context to align with common Go conventions and the rest of the codebase.

You may adjust the function signature as follows:

 func WaitCctxRevertedByInboundHash(
 	ctx context.Context,
+	t require.TestingT,
 	hash string,
 	c CCTXClient,
-	t require.TestingT,
 ) crosschaintypes.CrossChainTx {

Likely invalid or redundant comment.

zetaclient/chains/bitcoin/tx_script.go (2)

178-180: Confirm the handling of non-OP_RETURN scripts.

The function returns nil, false, nil when the script is not an OP_RETURN script. Please ensure that this behavior aligns with the expectations of the callers and that they correctly handle the absence of memo data without misinterpreting it as an error.


169-211: The DecodeOpReturnMemo function demonstrates robust error handling and clear logic.

The implementation correctly decodes OP_RETURN scripts, accounts for different data length representations, and provides informative error messages, enhancing maintainability and readability.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 204-204: zetaclient/chains/bitcoin/tx_script.go#L204
Added line #L204 was not covered by tests

e2e/runner/bitcoin.go (5)

24-24: Import of memo package is appropriate

The addition of the "github.com/zeta-chain/node/pkg/memo" import is necessary for handling memo functionality in the updated methods.


Line range hint 81-111: Modification of DepositBTCWithAmount method supports memos

The updated signature of DepositBTCWithAmount, accepting a *memo.InboundMemo, effectively enables handling both standard and legacy memos based on the memo parameter. The conditional logic is clear and correctly directs the flow to the appropriate deposit method.


178-184: Legacy memo handling in DepositBTCWithLegacyMemo is accurate

The DepositBTCWithLegacyMemo function correctly uses the deployer's EVM address bytes as the memo for legacy deposits, aligning with the expected behavior for legacy memo processing.


188-201: Standard memo implementation in DepositBTCWithStandardMemo is correct

The function DepositBTCWithStandardMemo properly encodes the InboundMemo to bytes and utilizes it in the deposit process. Error handling is appropriate with require.NoError(r, err) ensuring any encoding issues are caught.


405-410: Ensure correct parsing of the receiver address from transaction output

The method accurately extracts the second output (TxOut[1]) to retrieve the receiver's address, adhering to the expected transaction structure. Error handling after decoding the script is correctly implemented.

testutil/helpers.go Show resolved Hide resolved
e2e/e2etests/test_bitcoin_donation.go Show resolved Hide resolved
e2e/e2etests/test_bitcoin_donation.go Show resolved Hide resolved
e2e/e2etests/test_bitcoin_donation.go Outdated Show resolved Hide resolved
e2e/e2etests/test_bitcoin_std_deposit_and_call_revert.go Outdated Show resolved Hide resolved
zetaclient/chains/evm/observer/v2_inbound.go Show resolved Hide resolved
zetaclient/chains/evm/observer/v2_inbound.go Show resolved Hide resolved
zetaclient/chains/bitcoin/observer/inbound_test.go Outdated Show resolved Hide resolved
e2e/runner/bitcoin.go Outdated Show resolved Hide resolved
e2e/runner/bitcoin.go Show resolved Hide resolved
Copy link
Member

@lumtis lumtis left a comment

Choose a reason for hiding this comment

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

Need some improvements in event.go

e2e/e2etests/test_bitcoin_donation.go Outdated Show resolved Hide resolved
pkg/memo/memo.go Outdated Show resolved Hide resolved
pkg/memo/memo.go Outdated Show resolved Hide resolved
zetaclient/chains/bitcoin/observer/event.go Outdated Show resolved Hide resolved
zetaclient/chains/bitcoin/observer/event.go Outdated Show resolved Hide resolved
zetaclient/chains/bitcoin/observer/event.go Outdated Show resolved Hide resolved
zetaclient/chains/bitcoin/observer/event.go Outdated Show resolved Hide resolved
zetaclient/chains/bitcoin/observer/event.go Outdated Show resolved Hide resolved
zetaclient/chains/bitcoin/observer/event.go Outdated Show resolved Hide resolved
zetaclient/zetacore/constant.go Show resolved Hide resolved
e2e/utils/zetacore.go Outdated Show resolved Hide resolved
@lumtis lumtis added the UPGRADE_LIGHT_TESTS Run make start-upgrade-test-light label Oct 24, 2024
@lumtis
Copy link
Member

lumtis commented Oct 24, 2024

Tested by disabling the mainnet condition (like mainnet is used for E2E tests), this looks good

bitcoin    | ⏳running - deposit Bitcoin into ZEVM
bitcoin    | ✅ completed in 6.038452044s - deposit Bitcoin into ZEVM
bitcoin    | ⏳running - deposit Bitcoin into ZEVM and call a contract
bitcoin    | ✅ completed in 4.033241877s - deposit Bitcoin into ZEVM and call a contract
bitcoin    | ⏳running - deposit Bitcoin into ZEVM; expect refund
bitcoin    | ✅ completed in 20.782137884s - deposit Bitcoin into ZEVM; expect refund

Copy link
Contributor

@skosito skosito 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, just couple minor comments

e2e/runner/bitcoin.go Outdated Show resolved Hide resolved
e2e/runner/bitcoin.go Show resolved Hide resolved
e2e/runner/bitcoin.go Show resolved Hide resolved
e2e/runner/bitcoin.go Show resolved Hide resolved
pkg/memo/fields_v0.go Show resolved Hide resolved
zetaclient/chains/bitcoin/observer/event.go Show resolved Hide resolved
pkg/memo/memo.go Show resolved Hide resolved
x/crosschain/types/message_vote_inbound.go Show resolved Hide resolved
zetaclient/chains/bitcoin/observer/event.go Outdated Show resolved Hide resolved
zetaclient/chains/bitcoin/observer/event.go Show resolved Hide resolved
zetaclient/chains/bitcoin/observer/event.go Show resolved Hide resolved
zetaclient/chains/bitcoin/observer/event.go Show resolved Hide resolved
zetaclient/chains/bitcoin/tx_script.go Show resolved Hide resolved
@ws4charlie
Copy link
Contributor Author

@fbac

Why would DonationMessage gets removed, on which step?
It's skipped in here

Is there anycase where isStandardMemo == false and err != nil? I'm failing here to see why we shouldn't simply check for errors just after DecodeFromBytes.
No. When isStandardMemo == false, we simply overwrite the err by whatever returned from DecodeLegacyMemoHex

@ws4charlie ws4charlie added this pull request to the merge queue Oct 25, 2024
@fbac fbac self-requested a review October 25, 2024 18:05
Merged via the queue into develop with commit 467d691 Oct 25, 2024
35 checks passed
@ws4charlie ws4charlie deleted the feat-btc-revert-address branch October 25, 2024 18:08
@@ -22,6 +22,13 @@ const MaxMessageLength = 10240
// InboundVoteOption is a function that sets some option on the inbound vote message
type InboundVoteOption func(*MsgVoteInbound)

// WithMemoRevertOptions sets the revert options for inbound vote message

Choose a reason for hiding this comment

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

The function comment referring to the WithMemoRevertOptions function is outdated, the function is called WithRevertOptions.

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 nosec UPGRADE_LIGHT_TESTS Run make start-upgrade-test-light zetaclient Issues related to ZetaClient
Projects
None yet
6 participants