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

refactor(zetaclient): extract base observer and base signer from BTC #3394

Merged
merged 4 commits into from
Jan 23, 2025

Conversation

swift1337
Copy link
Contributor

@swift1337 swift1337 commented Jan 22, 2025

Closes #3331

Summary by CodeRabbit

  • Refactor

    • Simplified constructor methods for Bitcoin observer and signer
    • Introduced base observer and base signer patterns
    • Streamlined initialization process for Bitcoin-related components
  • New Features

    • Added a new constant btcBlocksPerDay for Bitcoin block caching
    • Enhanced modularity in observer and signer creation methods
  • Tests

    • Updated test cases to reflect new initialization patterns
    • Improved error handling in test setups

@swift1337 swift1337 added the no-changelog Skip changelog CI check label Jan 22, 2025
@swift1337 swift1337 self-assigned this Jan 22, 2025
@swift1337 swift1337 requested a review from a team as a code owner January 22, 2025 17:16
Copy link
Contributor

coderabbitai bot commented Jan 22, 2025

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

The pull request introduces a significant refactoring of the Bitcoin observer and signer initialization process across multiple files in the ZetaChain codebase. The primary objective is to decouple components by extracting base observer and base signer implementations, simplifying the constructor methods for Bitcoin-related components. This refactoring aims to improve modularity and testing flexibility by introducing a two-step initialization process using base observers and signers.

Changes

File Change Summary
zetaclient/chains/bitcoin/observer/observer.go Replaced NewObserver with New method, simplifying constructor with reduced parameters
zetaclient/chains/bitcoin/observer/observer_test.go Updated test cases to use new two-step observer initialization with base.NewObserver
zetaclient/chains/bitcoin/signer/signer.go Modified New function to accept base signer instead of individual components
zetaclient/orchestrator/v2_bootstrap.go Added newBaseSigner method and updated bootstrapBitcoin with base observer/signer creation

Assessment against linked issues

Objective Addressed Explanation
Decouple observer creation
Simplify signer initialization
Improve testability

Possibly related PRs

Suggested Labels

refactor, breaking:cli, chain:bitcoin, nosec, UPGRADE_LIGHT_TESTS

Suggested Reviewers

  • fbac
  • kingpinXD
  • lumtis
  • skosito
  • brewmaster012
  • ws4charlie

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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
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.

LGTM

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 comments (3)
zetaclient/chains/bitcoin/signer/signer.go (2)

Line range hint 149-150: Consider breaking down the SignWithdrawTx function.

The TODO comment suggests simplification. The function is complex and handles multiple responsibilities including UTXO selection, transaction building, size checking, fee calculation, and signing.

Consider splitting this into smaller, focused functions:

+ func (signer *Signer) buildTransactionInputs(prevOuts []common.Unspent) (*wire.MsgTx, error)
+ func (signer *Signer) calculateAndValidateSize(tx *wire.MsgTx, to btcutil.Address) (uint64, error)
+ func (signer *Signer) signTransactionInputs(ctx context.Context, tx *wire.MsgTx, prevOuts []common.Unspent, height uint64, nonce uint64, chainId int64) error

Line range hint 319-320: Simplify TryProcessOutbound function.

The TODO comment indicates this function needs simplification. It's handling too many responsibilities including parameter validation, compliance checks, transaction signing, and broadcasting.

Consider extracting the following responsibilities into separate methods:

+ func (signer *Signer) validateOutboundParams(params *types.OutboundParams) error
+ func (signer *Signer) handleComplianceAndDustChecks(cctx *types.CrossChainTx, params *types.OutboundParams) (bool, error)
+ func (signer *Signer) broadcastWithRetry(ctx context.Context, tx *wire.MsgTx, logger zerolog.Logger) error
zetaclient/chains/bitcoin/observer/observer.go (1)

Line range hint 124-149: Add Nil Check for baseObserver Parameter

The function assumes baseObserver is not nil. Adding a nil check ensures robustness and prevents potential runtime panics.

Apply this diff to validate the baseObserver:

 func New(chain chains.Chain, baseObserver *base.Observer, rpc RPC) (*Observer, error) {
+    if baseObserver == nil {
+        return nil, errors.New("baseObserver cannot be nil")
+    }
     // get the bitcoin network params
🧹 Nitpick comments (6)
zetaclient/chains/bitcoin/signer/signer.go (1)

Line range hint 319-476: Improve error handling in TryProcessOutbound.

The function uses early returns with logging but doesn't propagate errors, making it difficult to handle failures upstream.

Consider returning errors instead of just logging them:

- func (signer *Signer) TryProcessOutbound(ctx context.Context, ...) {
+ func (signer *Signer) TryProcessOutbound(ctx context.Context, ...) error {
     if err := validateParams(); err != nil {
-        logger.Error().Err(err).Msg("invalid params")
-        return
+        return fmt.Errorf("invalid params: %w", err)
     }
     // ... rest of the function
+    return nil
}
zetaclient/chains/bitcoin/observer/observer_test.go (2)

141-147: Replace Magic Number with Named Constant

The hardcoded value 100 used for blocksCacheSize reduces code readability. Consider defining a named constant or using an existing one to enhance clarity and maintainability.

Apply this diff to introduce a named constant:

+const testBlocksCacheSize = 100

 baseObserver, err := base.NewObserver(
     tt.chain,
     tt.chainParams,
     tt.coreClient,
     tt.tss,
-    100,
+    testBlocksCacheSize,
     tt.ts,
     database,
     tt.logger,
 )

329-335: Use Consistent Constants for Block Cache Size

The hardcoded value 100 for blocksCacheSize appears again. For consistency and ease of maintenance, consider defining and reusing a constant across tests.

Apply this diff to define a shared constant:

+const testBlocksCacheSize = 100

 baseObserver, err := base.NewObserver(
     chain,
     chainParams,
     zetacore,
     nil,
-    100,
+    testBlocksCacheSize,
     nil,
     database,
     base.Logger{Std: log, Compliance: log},
 )
zetaclient/chains/bitcoin/observer/observer.go (1)

Line range hint 138-140: Avoid Unnecessary Pointer Dereferencing

The assignment of ObserverLogger involves unnecessary dereferencing. Assigning the pointer directly enhances code efficiency.

Apply this diff to simplify the logger initialization:

 logger: Logger{
-    ObserverLogger: *baseObserver.Logger(),
+    ObserverLogger: baseObserver.Logger(),
     UTXOs:          baseObserver.Logger().Chain.With().Str("module", "utxos").Logger(),
 },
zetaclient/orchestrator/v2_bootstrap.go (2)

17-18: Document btcBlocksPerDay Constant

Adding documentation for btcBlocksPerDay improves code clarity by explaining its significance.

Apply this diff to include a comment:

+// btcBlocksPerDay represents the average number of Bitcoin blocks mined per day.
 const btcBlocksPerDay = 144

55-57: Check for Errors After Signer Initialization

Although btcsigner.New does not return an error, ensure that the returned signer is not nil before proceeding.

Apply this diff to include a nil check:

 signer := btcsigner.New(baseSigner, rpcClient)

+if signer == nil {
+    return nil, errors.New("failed to initialize Bitcoin signer")
+}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 13d1673 and a3e4000.

📒 Files selected for processing (6)
  • zetaclient/chains/bitcoin/observer/observer.go (1 hunks)
  • zetaclient/chains/bitcoin/observer/observer_test.go (2 hunks)
  • zetaclient/chains/bitcoin/observer/outbound_test.go (1 hunks)
  • zetaclient/chains/bitcoin/signer/signer.go (1 hunks)
  • zetaclient/chains/bitcoin/signer/signer_test.go (2 hunks)
  • zetaclient/orchestrator/v2_bootstrap.go (3 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
zetaclient/chains/bitcoin/observer/observer.go (1)

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

zetaclient/chains/bitcoin/signer/signer_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/outbound_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/observer_test.go (1)

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

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

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

zetaclient/orchestrator/v2_bootstrap.go (1)

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

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

61-62: LGTM! Clean constructor refactoring.

The simplified constructor improves modularity and testability by accepting a pre-configured base signer.

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

341-343: ⚠️ Potential issue

Add Error Handling After Observer Creation

After initializing the observer, it's crucial to handle any potential errors to ensure the observer is correctly instantiated.

Apply this diff to include error checking:

 ob, err := observer.New(chain, baseObserver, client)
+require.NoError(t, err)
 require.NoError(t, err)

Likely invalid or redundant comment.

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

Line range hint 156-160: Handle Context Errors Appropriately

Ensure that any errors due to context timeouts or cancellations in LoadLastBlockScanned and LoadBroadcastedTxMap are properly handled to prevent unexpected behavior.

Review the internal implementations to confirm that context-related errors are managed correctly.

zetaclient/orchestrator/v2_bootstrap.go (2)

72-75: Reuse Existing Constants for Block Cache Size

The conditionally set blocksCacheSize duplicates the value of btcBlocksPerDay. Since the constant is already defined, this implementation is appropriate.


89-90: Ensure Consistent Error Handling in newBaseSigner

Though base.NewSigner currently does not return an error, consider future-proofing by handling potential errors that may arise from changes in its implementation.

Review base.NewSigner for any changes that might introduce errors, and update the method signature and error handling accordingly.

zetaclient/chains/bitcoin/signer/signer_test.go (1)

53-55: LGTM! Clean separation of concerns in signer initialization.

The two-step initialization pattern improves modularity by clearly separating the base signer creation from the Bitcoin-specific signer initialization.

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

46-50: LGTM! Consistent initialization pattern with proper error handling.

The two-step initialization pattern with proper error handling aligns well with the signer implementation, improving code consistency across the codebase.

Copy link

codecov bot commented Jan 23, 2025

Codecov Report

Attention: Patch coverage is 80.64516% with 6 lines in your changes missing coverage. Please review.

Project coverage is 63.40%. Comparing base (ac3b447) to head (b1ad198).
Report is 1 commits behind head on develop.

Files with missing lines Patch % Lines
zetaclient/orchestrator/v2_bootstrap.go 77.77% 4 Missing and 2 partials ⚠️
Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff            @@
##           develop    #3394   +/-   ##
========================================
  Coverage    63.40%   63.40%           
========================================
  Files          436      436           
  Lines        30690    30690           
========================================
  Hits         19460    19460           
  Misses       10394    10394           
  Partials       836      836           
Files with missing lines Coverage Δ
zetaclient/chains/bitcoin/observer/observer.go 34.88% <100.00%> (-2.40%) ⬇️
zetaclient/chains/bitcoin/signer/signer.go 15.30% <100.00%> (-0.90%) ⬇️
zetaclient/orchestrator/v2_bootstrap.go 70.00% <77.77%> (+4.09%) ⬆️

@swift1337 swift1337 enabled auto-merge January 23, 2025 14:16
@swift1337 swift1337 added this pull request to the merge queue Jan 23, 2025
Merged via the queue into develop with commit b1bdb46 Jan 23, 2025
40 checks passed
@swift1337 swift1337 deleted the refactor/btc-obs-extractor branch January 23, 2025 14:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
breaking:cli no-changelog Skip changelog CI check
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Extract base observer and base signer from BTC
3 participants