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: skip solana unsupported transaction version #3206

Merged
merged 8 commits into from
Nov 25, 2024

Conversation

ws4charlie
Copy link
Contributor

@ws4charlie ws4charlie commented Nov 22, 2024

Description

There are two types of Solana transactions in Solana network: legacy and 0. Current zetaclient implementation can only pull legacy inbound transaction and returns error on version 0. This will blocks inbound observation if user send a deposit tx to gateway using version 0.

The fix:

  • Allow version 0 in the RPC query getTransaction.
  • Skip any unsupported transaction type, so inbound won't be impact if Solana protocol adds new transaction type at some point in the future.

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

Release Notes

  • New Features

    • Introduced a new "Unreleased" section in the changelog for better organization of upcoming changes.
    • Added functionality to handle unsupported Solana transaction versions, preventing disruptions in transaction processing.
  • Bug Fixes

    • Enhanced error handling for unsupported transaction versions, ensuring smoother transaction retrieval.
  • Tests

    • Added a new live test to verify transaction retrieval based on version support, improving test coverage for RPC functionality.

Copy link
Contributor

coderabbitai bot commented Nov 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

Walkthrough

This pull request introduces several updates across multiple files, focusing on enhancing transaction handling for the Solana blockchain. Key changes include the addition of a new section in the changelog for better organization of unreleased features, updates to dependency versions in go.mod, and significant modifications to transaction retrieval methods in inbound.go and rpc.go. A new function for retrieving transactions with a maximum version is implemented, along with improved error handling. Additionally, a new test function is added to validate these changes, ensuring robust transaction processing.

Changes

File Change Summary
changelog.md Added "Unreleased" section categorizing changes into Features, Tests, Refactor, and Fixes; included a fix for unsupported Solana transaction versions.
go.mod Updated dependency versions: github.com/gagliardetto/solana-go from v1.10.0 to v1.12.0, go.mongodb.org/mongo-driver from v1.11.0 to v1.12.2.
zetaclient/chains/solana/observer/inbound.go Modified ObserveInbound method to use solanarpc.GetTransactionWithMaxVersion, added nil check for transaction results, and adjusted logging statements.
zetaclient/chains/solana/rpc/rpc.go Introduced constant ErrorCodeUnsupportedTransactionVersion and added GetTransactionWithMaxVersion function with improved error handling.
zetaclient/chains/solana/rpc/rpc_live_test.go Added LiveTest_GetTransactionWithVersion function to test transaction retrieval based on version support.

Possibly related PRs

Suggested labels

no-changelog, chain:solana, SOLANA_TESTS, breaking:cli

Suggested reviewers

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

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 22, 2024 21:42
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (4)
zetaclient/chains/solana/rpc/rpc_live_test.go (1)

26-54: Enhance test documentation and coverage

The test function would benefit from:

  1. A function-level documentation explaining the test purpose and scenarios
  2. Constants for test values
  3. Additional assertions on transaction properties

Consider refactoring like this:

+// LiveTest_GetTransactionWithVersion tests the behavior of GetTransactionWithMaxVersion
+// for both supported and unsupported transaction versions using a known version "0"
+// transaction from devnet.
 func LiveTest_GetTransactionWithVersion(t *testing.T) {
+    const (
+        // Known version "0" transaction from devnet
+        testTxSignature = "Wqgj7hAaUUSfLzieN912G7GxyGHijzBZgY135NtuFtPRjevK8DnYjWwQZy7LAKFQZu582wsjuab2QP27VMUJzAi"
+    )
     
     // create a Solana devnet RPC client
     client := solanarpc.New(solanarpc.DevNet_RPC)
-    txSig := solana.MustSignatureFromBase58(
-        "Wqgj7hAaUUSfLzieN912G7GxyGHijzBZgY135NtuFtPRjevK8DnYjWwQZy7LAKFQZu582wsjuab2QP27VMUJzAi",
-    )
+    txSig := solana.MustSignatureFromBase58(testTxSignature)

     t.Run("should get the transaction if the version is supported", func(t *testing.T) {
         ctx := context.Background()
         txResult, err := rpc.GetTransactionWithMaxVersion(
             ctx,
             client,
             txSig,
             &solanarpc.MaxSupportedTransactionVersion0,
         )
         require.NoError(t, err)
         require.NotNil(t, txResult)
+        // Verify transaction properties
+        require.Equal(t, uint8(0), txResult.Version)
+        require.NotNil(t, txResult.Transaction)
     })
zetaclient/chains/solana/rpc/rpc.go (1)

130-147: Enhance function documentation and error handling.

While the implementation is solid, consider the following improvements:

  1. Add comprehensive function documentation explaining:

    • The purpose of maxTxVersion parameter
    • The nil return behavior for unsupported versions
    • The error handling strategy
  2. Consider more precise error handling to avoid masking other potential JSON-RPC errors.

Here's a suggested improvement:

-// GetTransactionWithMaxVersion fetches a transaction with the given signature and max version.
+// GetTransactionWithMaxVersion fetches a transaction with the given signature and max version.
+// Parameters:
+//   - ctx: Context for the RPC call
+//   - client: Solana RPC client interface
+//   - signature: Transaction signature to fetch
+//   - maxTxVersion: Maximum supported transaction version. If nil, no version constraint is applied.
+//
+// Returns:
+//   - (*rpc.GetTransactionResult, nil) for successful retrieval
+//   - (nil, nil) for transactions with unsupported versions
+//   - (nil, error) for other errors
 func GetTransactionWithMaxVersion(
     ctx context.Context,
     client interfaces.SolanaRPCClient,
     signature solana.Signature,
     maxTxVersion *uint64,
 ) (*rpc.GetTransactionResult, error) {
     txResult, err := client.GetTransaction(ctx, signature, &rpc.GetTransactionOpts{
         MaxSupportedTransactionVersion: maxTxVersion,
     })
 
-    // skip unsupported transaction version error
-    if err != nil && strings.Contains(err.Error(), ErrorCodeUnsupportedTransactionVersion) {
+    // Handle specific case of unsupported transaction version
+    if err != nil && isUnsupportedVersionError(err) {
         return nil, nil
     }
 
     return txResult, err
 }
+
+// isUnsupportedVersionError checks if the error is specifically about unsupported transaction version
+func isUnsupportedVersionError(err error) bool {
+    return err != nil && strings.Contains(err.Error(), ErrorCodeUnsupportedTransactionVersion)
}
zetaclient/chains/solana/observer/inbound.go (2)

103-104: Consider making transaction version configurable

While using rpc.MaxSupportedTransactionVersion0 works for the current use case, consider making this configurable to facilitate future version support without code changes.

-maxTxVersion := rpc.MaxSupportedTransactionVersion0
+maxTxVersion := ob.ChainParams().MaxSupportedTransactionVersion

110-119: Enhance error handling and logging

The error handling structure could be simplified while improving logging for better observability.

-switch {
-case txResult == nil:
-  ob.Logger().Inbound.Warn().Msgf("ObserveInbound: skip unsupported transaction sig %s", sigString)
-default:
-  // filter inbound events and vote
-  err = ob.FilterInboundEventsAndVote(ctx, txResult)
-  if err != nil {
-    // we have to re-scan this signature on next ticker
-    return errors.Wrapf(err, "error FilterInboundEventAndVote for chain %d sig %s", chainID, sigString)
-  }
+if txResult == nil {
+  ob.Logger().Inbound.Warn().
+    Str("signature", sigString).
+    Msg("ObserveInbound: skipping unsupported transaction")
+  return nil
+}
+
+// filter inbound events and vote
+if err := ob.FilterInboundEventsAndVote(ctx, txResult); err != nil {
+  // we have to re-scan this signature on next ticker
+  return errors.Wrapf(err, "error FilterInboundEventAndVote for chain %d sig %s", chainID, sigString)
}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between cda3398 and 093c023.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (5)
  • changelog.md (1 hunks)
  • go.mod (2 hunks)
  • zetaclient/chains/solana/observer/inbound.go (1 hunks)
  • zetaclient/chains/solana/rpc/rpc.go (3 hunks)
  • zetaclient/chains/solana/rpc/rpc_live_test.go (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • changelog.md
🧰 Additional context used
📓 Path-based instructions (3)
zetaclient/chains/solana/observer/inbound.go (1)

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

zetaclient/chains/solana/rpc/rpc.go (1)

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

zetaclient/chains/solana/rpc/rpc_live_test.go (1)

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

🔇 Additional comments (6)
zetaclient/chains/solana/rpc/rpc_live_test.go (2)

20-20: LGTM: Test integration is clean and consistent

The new test function is properly integrated into the live test suite, maintaining consistency with existing patterns.


30-34: Consider making the test more resilient to devnet resets

The hardcoded transaction signature from devnet could become invalid if the devnet is reset. Consider:

  1. Adding a comment explaining why this specific transaction was chosen
  2. Having a fallback mechanism or documenting the process to update the test data
✅ Verification successful

Transaction is still valid and accessible on devnet

The hardcoded transaction signature is currently valid and accessible on devnet. The transaction represents a good test case as it:

  • Has version "0"
  • Contains successful execution status
  • Includes compute budget instructions
  • Demonstrates a deposit operation with inner instructions

The test's choice of this specific transaction is well-justified for testing version handling.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify if the transaction still exists on devnet
curl -X POST -H "Content-Type: application/json" -d '{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "getTransaction",
  "params": [
    "Wqgj7hAaUUSfLzieN912G7GxyGHijzBZgY135NtuFtPRjevK8DnYjWwQZy7LAKFQZu582wsjuab2QP27VMUJzAi",
    {"encoding": "json", "maxSupportedTransactionVersion": 0}
  ]
}' https://api.devnet.solana.com

Length of output: 2943

zetaclient/chains/solana/rpc/rpc.go (2)

5-5: LGTM! Well-documented constant with proper source reference.

The error code constant is properly defined and documented with a link to the Solana source code, following Go naming conventions.

Also applies to: 22-25


130-147: Verify implementation meets PR objectives.

The implementation aligns well with the PR objectives:

  1. Handles version "0" transactions through the maxTxVersion parameter
  2. Gracefully skips unsupported transaction versions as required

Let's verify the error handling behavior:

✅ Verification successful

Implementation correctly handles unsupported transaction versions

The verification confirms the implementation aligns with the PR objectives and follows consistent error handling patterns:

  1. The error code ErrorCodeUnsupportedTransactionVersion = "-32015" is properly defined and referenced
  2. The changelog entry (PR fix: skip solana unsupported transaction version #3206) explicitly confirms the intention to skip unsupported transaction versions
  3. The error handling pattern is clean and follows best practices by checking both for nil error and specific error code
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consistent error handling across the codebase

# Look for other places where we handle transaction version errors
rg -A 2 "ErrorCodeUnsupportedTransactionVersion|unsupported.*version|version.*unsupported" 

# Check for similar error handling patterns
ast-grep --pattern 'if $err != nil && strings.Contains($err.Error(), $_)'

Length of output: 1190

go.mod (2)

285-285: Review security improvements in mongo-driver v1.12.2

The update to go.mongodb.org/mongo-driver v1.12.2 is a minor version bump that might include security fixes.

✅ Verification successful

No security-related changes found in mongo-driver v1.12.2

Based on the release notes, version 1.12.2 focuses on performance improvements in marshaling and compression, along with bug fixes in Client Side Encryption and transaction handling. No security-related changes or vulnerabilities were addressed in this release.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for security improvements in mongo-driver v1.12.2

# Get the changelog or release notes
gh api repos/mongodb/mongo-go-driver/releases/tags/v1.12.2 --jq .body

# Check for any security-related commits
gh api repos/mongodb/mongo-go-driver/commits --jq '.[] | select(.commit.message | test("security|CVE|vulnerability"; "i")) | .commit.message'

Length of output: 1957


29-29: Verify compatibility with solana-go v1.12.0

The update to github.com/gagliardetto/solana-go v1.12.0 aligns with the PR's objective to support version "0" Solana transactions.

✅ Verification successful

Update to solana-go v1.12.0 appears safe to proceed

Based on the changelog and codebase analysis:

  • No breaking changes to transaction-related APIs were introduced in v1.12.0
  • Changes are primarily bug fixes and feature additions
  • Existing transaction handling code in the codebase remains compatible

Notable improvements that benefit this update:

  • Memory leak fix in WebSocket client
  • Pointer dereference fixes
  • Added version support in TokenBalance type
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for breaking changes in solana-go v1.12.0

# Get the changelog or release notes
gh api repos/gagliardetto/solana-go/releases/tags/v1.12.0 --jq .body

# Search for any usage of potentially changed APIs
rg -l "solana-go" | xargs rg "GetTransaction|ParseTransaction"

Length of output: 12733

zetaclient/chains/solana/observer/inbound.go Outdated Show resolved Hide resolved
zetaclient/chains/solana/rpc/rpc.go Outdated Show resolved Hide resolved
zetaclient/chains/solana/rpc/rpc.go Outdated Show resolved Hide resolved
@ws4charlie ws4charlie added SOLANA_TESTS Run make start-solana-test zetaclient Issues related to ZetaClient labels Nov 23, 2024
Copy link

codecov bot commented Nov 23, 2024

Codecov Report

Attention: Patch coverage is 11.11111% with 32 lines in your changes missing coverage. Please review.

Project coverage is 62.38%. Comparing base (fffbcab) to head (5539108).
Report is 1 commits behind head on develop.

Files with missing lines Patch % Lines
zetaclient/chains/solana/observer/inbound.go 0.00% 20 Missing ⚠️
zetaclient/chains/solana/rpc/rpc.go 0.00% 12 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           develop    #3206      +/-   ##
===========================================
- Coverage    62.43%   62.38%   -0.06%     
===========================================
  Files          428      427       -1     
  Lines        30404    30416      +12     
===========================================
- Hits         18982    18974       -8     
- Misses       10576    10596      +20     
  Partials       846      846              
Files with missing lines Coverage Δ
zetaclient/chains/solana/signer/signer.go 23.48% <100.00%> (+0.31%) ⬆️
zetaclient/keys/relayer_key.go 90.00% <100.00%> (ø)
zetaclient/chains/solana/rpc/rpc.go 0.00% <0.00%> (ø)
zetaclient/chains/solana/observer/inbound.go 31.25% <0.00%> (-1.25%) ⬇️

zetaclient/chains/solana/rpc/rpc.go Outdated Show resolved Hide resolved
zetaclient/chains/solana/rpc/rpc.go Outdated Show resolved Hide resolved
zetaclient/chains/solana/rpc/rpc_live_test.go Outdated Show resolved Hide resolved
zetaclient/chains/solana/observer/inbound.go Outdated Show resolved Hide resolved
Copy link

gitguardian bot commented Nov 25, 2024

⚠️ GitGuardian has uncovered 1 secret following the scan of your pull request.

Please consider investigating the findings and remediating the incidents. Failure to do so may lead to compromising the associated services or software components.

🔎 Detected hardcoded secret in your pull request
GitGuardian id GitGuardian status Secret Commit Filename
14567965 Triggered Generic Password 5539108 cmd/zetaclientd/start.go View secret
🛠 Guidelines to remediate hardcoded secrets
  1. Understand the implications of revoking this secret by investigating where it is used in your code.
  2. Replace and store your secret safely. Learn here the best practices.
  3. Revoke and rotate this secret.
  4. If possible, rewrite git history. Rewriting git history is not a trivial act. You might completely break other contributing developers' workflow and you risk accidentally deleting legitimate data.

To avoid such incidents in the future consider


🦉 GitGuardian detects secrets in your source code to help developers and security teams secure the modern development process. You are seeing this because you or someone else with access to this repository has authorized GitGuardian to scan your pull request.

@ws4charlie ws4charlie added this pull request to the merge queue Nov 25, 2024
Merged via the queue into develop with commit 771317f Nov 25, 2024
40 of 41 checks passed
@ws4charlie ws4charlie deleted the fix-solana-unsupported-tx-version-0 branch November 25, 2024 20:56
gartnera pushed a commit that referenced this pull request Nov 26, 2024
* fix solana testnet unsupported version 0

* add changelog entry

* correct variable name; explicitly return a 'skip' flag to be more redable

* fix unit test

* Simplify RPC API

* Comment test case

* clean up commented test

---------

Co-authored-by: Dmitry S <[email protected]>
gartnera added a commit that referenced this pull request Nov 27, 2024
* fix solana testnet unsupported version 0

* add changelog entry

* correct variable name; explicitly return a 'skip' flag to be more redable

* fix unit test

* Simplify RPC API

* Comment test case

* clean up commented test

---------

Co-authored-by: Charlie Chen <[email protected]>
Co-authored-by: Dmitry S <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
SOLANA_TESTS Run make start-solana-test zetaclient Issues related to ZetaClient
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants