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: avoid panic in inscription parsing #3155

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from

Conversation

ws4charlie
Copy link
Contributor

@ws4charlie ws4charlie commented Nov 14, 2024

Description

This PR is to avoid potential panic in method checkInscriptionEnvelope.

func checkInscriptionEnvelope(t *txscript.ScriptTokenizer) error {
    if !t.Next() || t.Opcode() != txscript.OP_DATA_32 {
        // calling 't.Opcode()' will panic on the line below if t.Next() returns false, because the opcode inside is a null pointer
	return fmt.Errorf("cannot obtain public key bytes op %d or err %s", t.Opcode(), t.Err())
    }

    if !t.Next() || t.Opcode() != txscript.OP_CHECKSIG {
       // same panic could happen here
	return fmt.Errorf("cannot parse OP_CHECKSIG, op %d or err %s", t.Opcode(), t.Err())
    }

    return nil
}

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

    • Whitelist functionality for SPL tokens on Solana.
    • Enhanced build reproducibility.
    • Integrated SPL deposits and withdrawals.
  • Bug Fixes

    • Resolved issues with emissions module message registration.
    • Improved peer discovery mechanism.
    • Prevented out-of-gas errors during omnichain calls.
    • Fixed potential panic in Bitcoin inscription parsing.
  • Refactor

    • Streamlined zetaclientd CLI.
    • Removed unnecessary components and simplified configurations.
  • Tests

    • Added new tests for concurrent withdrawals and deposits.
    • Enhanced Bitcoin script decoding tests for better error handling.

Copy link
Contributor

coderabbitai bot commented Nov 14, 2024

📝 Walkthrough

Walkthrough

This pull request introduces a series of updates to the ZetaChain node, including new features such as the ability to whitelist SPL tokens on Solana and enhancements to build reproducibility. It also integrates SPL deposits and withdrawals and improves testing with new scenarios for concurrent transactions and Bitcoin end-to-end tests. Significant refactoring is present, including the removal of the HSM signer and simplification of configurations. Additionally, various fixes address issues related to emissions, peer discovery, and error handling in Bitcoin inscription parsing.

Changes

File Path Change Summary
changelog.md - Added features for whitelisting SPL tokens, improving build reproducibility, and integrating SPL deposits/withdrawals.
- Enhanced tests for concurrent withdrawals and deposits, and split Bitcoin E2E tests.
- Refactored by removing HSM signer, improving zetaclientd CLI, and simplifying configurations.
- Fixed issues with emissions registration, peer discovery, CCTX blocking, and Bitcoin inscription parsing.
zetaclient/chains/bitcoin/tx_script.go - Simplified error messages in checkInscriptionEnvelope for missing opcodes.
zetaclient/chains/bitcoin/tx_script_test.go - Added new test cases and refined existing ones for Bitcoin script decoding, focusing on error handling and consistency in test data processing.

Possibly related PRs

Suggested labels

no-changelog

Suggested reviewers

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

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 golangci-lint

level=error msg="Running error: context loading failed: failed to load packages: failed to load packages: failed to load with go/packages: context deadline exceeded"
level=error msg="Timeout exceeded: try increasing it by passing --timeout option"


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

codecov bot commented Nov 14, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 62.64%. Comparing base (d6ed9aa) to head (46a6cdc).

Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff            @@
##           develop    #3155   +/-   ##
========================================
  Coverage    62.64%   62.64%           
========================================
  Files          424      424           
  Lines        30115    30115           
========================================
  Hits         18866    18866           
  Misses       10408    10408           
  Partials       841      841           
Files with missing lines Coverage Δ
zetaclient/chains/bitcoin/tx_script.go 89.20% <100.00%> (ø)

@ws4charlie ws4charlie added chain:bitcoin Bitcoin chain related audit Fixes for issues found in audit labels Nov 14, 2024
@ws4charlie ws4charlie marked this pull request as ready for review November 14, 2024 15:55
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: 2

🧹 Outside diff range and nitpick comments (8)
changelog.md (1)

28-28: Enhance the fix description for better clarity.

The changelog entry correctly documents the fix for PR #3155, but could be more descriptive about the specific panic scenario being addressed.

Consider expanding the description to:

-* [3155](https://github.com/zeta-chain/node/pull/3155) - fix potential panic in the Bitcoin inscription parsing
+* [3155](https://github.com/zeta-chain/node/pull/3155) - fix potential panic in Bitcoin inscription parsing by adding null pointer checks in checkInscriptionEnvelope
zetaclient/chains/bitcoin/tx_script_test.go (7)

Line range hint 625-631: Use require.NoError instead of require.Nil for error assertions

In Go tests, it's idiomatic to use require.NoError(t, err) when checking for the absence of an error. This provides clearer output if the test fails.

Apply this diff to improve the error assertion:

-	require.Nil(t, err)
+	require.NoError(t, err)

Line range hint 625-638: Externalize large hexadecimal strings for better readability

Embedding large hexadecimal strings directly in the test code reduces readability and can make maintenance more challenging. Consider moving these strings to external test data files or constants.


Line range hint 639-646: Use require.NoError instead of require.Nil for error assertions

Consistent with Go testing best practices, replace require.Nil(t, err) with require.NoError(t, err) for clearer test output.

Apply this diff:

-	require.Nil(t, err)
+	require.NoError(t, err)

Line range hint 639-650: Externalize large hexadecimal strings for better readability

Similar to the previous suggestion, consider moving the hexadecimal strings to external files or constants to enhance readability and maintainability.


672-675: Correct the opcode value in the comment for accuracy

The comment incorrectly states that OP_CODESEPARATOR has the opcode 0xac, which is actually the opcode for OP_CHECKSIG. The correct opcode for OP_CODESEPARATOR is 0xab. Updating this will improve clarity.

Apply this diff to correct the comment:

-	// require OP_CHECKSIG (0xac) but OP_CODESEPARATOR (0xac) is found
+	// require OP_CHECKSIG (0xac) but OP_CODESEPARATOR (0xab) is found

683-691: Use require.NoError instead of require.Nil for error assertions

Replace require.Nil(t, err) with require.NoError(t, err) for consistency and clearer test failure messages.

Apply this diff:

-	require.Nil(t, err)
+	require.NoError(t, err)

693-701: Use require.NoError instead of require.Nil for error assertions

Maintain consistency in error checking by using require.NoError(t, err).

Apply this diff:

-	require.Nil(t, err)
+	require.NoError(t, err)
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d6ed9aa and 46a6cdc.

📒 Files selected for processing (3)
  • changelog.md (1 hunks)
  • zetaclient/chains/bitcoin/tx_script.go (1 hunks)
  • zetaclient/chains/bitcoin/tx_script_test.go (3 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
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.

🔇 Additional comments (1)
zetaclient/chains/bitcoin/tx_script.go (1)

Line range hint 339-348: Consider adding validation for public key data

The function checks for the correct opcodes but doesn't validate the public key data itself.

Consider adding validation for the public key data:

 func checkInscriptionEnvelope(t *txscript.ScriptTokenizer) error {
 	if !t.Next() || t.Opcode() != txscript.OP_DATA_32 {
 		if err := t.Err(); err != nil {
 			return fmt.Errorf("failed to parse public key: %w", err)
 		}
 		return fmt.Errorf("expected OP_DATA_32 for public key, got %v", t.Opcode())
 	}
+
+	// Validate public key data
+	pubKey := t.Data()
+	if len(pubKey) != 32 {
+		return fmt.Errorf("invalid public key length: got %d, want 32", len(pubKey))
+	}

 	if !t.Next() || t.Opcode() != txscript.OP_CHECKSIG {
 		if err := t.Err(); err != nil {
 			return fmt.Errorf("failed to parse OP_CHECKSIG: %w", err)
 		}
 		return fmt.Errorf("expected OP_CHECKSIG, got %v", t.Opcode())
 	}

 	return nil
 }

Comment on lines +340 to 341
return fmt.Errorf("public key not found")
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error context and check for tokenizer errors

While the error message has been simplified, we should still check for tokenizer errors and provide more context for debugging purposes.

-		return fmt.Errorf("public key not found")
+		if err := t.Err(); err != nil {
+			return fmt.Errorf("failed to parse public key: %w", err)
+		}
+		return fmt.Errorf("expected OP_DATA_32 for public key, got %v", t.Opcode())
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
return fmt.Errorf("public key not found")
}
if err := t.Err(); err != nil {
return fmt.Errorf("failed to parse public key: %w", err)
}
return fmt.Errorf("expected OP_DATA_32 for public key, got %v", t.Opcode())
}

Comment on lines +344 to 345
return fmt.Errorf("OP_CHECKSIG not found")
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error context and check for tokenizer errors

Similar to the previous comment, enhance error handling for the OP_CHECKSIG case.

-		return fmt.Errorf("OP_CHECKSIG not found")
+		if err := t.Err(); err != nil {
+			return fmt.Errorf("failed to parse OP_CHECKSIG: %w", err)
+		}
+		return fmt.Errorf("expected OP_CHECKSIG, got %v", t.Opcode())

Committable suggestion skipped: line range outside the PR's diff.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
audit Fixes for issues found in audit chain:bitcoin Bitcoin chain related
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants