-
Notifications
You must be signed in to change notification settings - Fork 110
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(zetaclient)!: orchestrator V2 #3332
base: develop
Are you sure you want to change the base?
Conversation
Important Review skippedAuto incremental reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the You can disable this status message by setting the 📝 WalkthroughWalkthroughThis pull request introduces a comprehensive refactoring of the Bitcoin chain handling in the ZetaChain node, focusing on modernizing the orchestrator architecture and consolidating Bitcoin-related functionalities. The changes primarily involve creating an orchestrator V2, removing Bitcoin-specific legacy code, and restructuring Bitcoin chain operations under a common package. Changes
Assessment against linked issues
Possibly related issues
Suggested labels
Suggested reviewers
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
Documentation and Community
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 11
🔭 Outside diff range comments (1)
zetaclient/chains/bitcoin/observer/inbound.go (1)
Line range hint
306-347
: Ensure threadsafe and tested approach for verifying inbound events
GetBtcEventWithoutWitness
checks for P2WPKH script, calculates depositor fees, and extracts fromAddress. Given the multiple steps, ensure concurrency testing, especially if the application might handle many parallel inbound checks.
🧹 Nitpick comments (57)
zetaclient/orchestrator/v2_bootstrap.go (8)
22-25
: Handle missing or invalid app context more gracefullyCurrently, an error is simply returned upon failing to retrieve app context. Consider either recovering or logging additional diagnostics to help troubleshoot configuration issues.
27-30
: Consider integrating a friendly message or retry for missing BTC configsReturning the wrapped
errSkipChain
is appropriate. However, if this orchestrator environment is dynamic, consider adding logs or instructions for missing config, so operators quickly diagnose the cause.
32-35
: Wrap RPCClient creation errors with the correct contextWhile you wrap the error, consider adding more context—for example, whether it is a misconfiguration or a network connectivity issue. This makes troubleshooting more efficient in production.
37-40
: Promote consistent namingVariables
rawChain
andrawChainParams
might be more descriptive, such asbitcoinChain
andbitcoinParams
. Though it is minor, it improves clarity.
44-47
: Evaluate the impact of 'true' in db.NewFromSqlite() initializationDouble-check that enabling advanced or WAL journaling is intended. Confirm that the concurrency level or performance implications suit your environment.
49-52
: Leverage the TODO comments for base observer & signer extractionThese placeholders indicate a plan to move logic to a base observer or signer. Aim to refactor soon before the codebase grows more complex, maintaining DRY principles.
67-70
: Check TSS signer concurrency & lifecycleWhen settings are updated or the chain toggles states, confirm that reinitializing or shutting down the signer does not leave leftover goroutines. Proper cleanup significantly reduces resource leaks over time.
72-73
: Return additional context for caller usageReturning only the
*bitcoin.Bitcoin
can be sufficient. If more context (e.g., the observer or signer) is needed for test harness or instrumentation, consider returning them as well or providing a dedicated accessor.zetaclient/chains/bitcoin/bitcoin.go (7)
1-25
: Set an explicit interface or layered architectureThis struct effectively aggregates scheduling, observing, signing, and outbound processing. Consider an interface-based layout or layering approach, so each responsibility (observer, signer, UTXO manager) can be tested and evolved independently.
27-42
: Ensure that default or fallback conditions are documentedThe constructor sets up an outbound processor. Verify that fallback or default behaviors (e.g., if the chain is invalid) are well documented. This helps maintain code clarity when more chain types are introduced.
115-118
: Log shutdown triggers before calling StopYou do log that the observer is stopping. Ensure that you also manage partial states (if the observer was never fully started) to avoid incomplete teardown or resource leaks.
120-124
: Use more explicit naming for group construction
fmt.Sprintf("btc:%d", b.observer.Chain().ChainId)
is short and direct. For clarity or tooling, consider something likechain=btc,chainID=XYZ
. This can help parse logs in search queries.
126-204
: Consider further clarifying inbound scheduling logicThese lines implement a complex system controlling cross-chain transactions, controlling concurrency (nonce checks, lookahead, etc.). Provide in-code clarifications of concurrency assumptions, especially how you handle partial signatures or re-entrancy. This is important for multi-operator coordination and ensures new teammates won't get lost in the logic.
208-224
: Extend chain param updates to re-trigger sub-interval changes if neededYou update chain params, but if the scheduler intervals rely on them, consider adding a re-trigger or re-registration step. Otherwise, tasks might continue running with outdated parameters until the next orchestrator cycle.
226-230
: Improve outbound logger naming or add structured fields for easy searchingYou already add
outbound.id
, which is helpful. Consider also including chain info or a consistent subsystem identifier in the logs, to make correlation easier across multiple chain outbounds.zetaclient/orchestrator/v2_orchestrator.go (9)
33-37
: Align naming or docstrings for struct loggers
loggers
has multiple fields for the base, sampled, etc. Document or rename them for clarity, e.g.,loggerBase
,loggerSampled
.
41-45
: Include graceful or blocking stop in ObserverSigner interfaceThe interface includes
Start
andStop
. Consider specifying ifStop
is synchronous—for instance, do you wait for all chained goroutines to exit? Consistent semantics across all chain implementations helps avoid partial shutdown states.
54-65
: Surface potential invalid arguments more clearlyIn
validateConstructor
, you return raw errors for each nil or empty condition. Logging these or providing an aggregated message can help debugging, e.g., “Missing dependencies: TSS, Telemetry, DBPath.”
67-89
: Validate automated tasks with custom intervalsYou register tasks to update context and sync chains. Evaluate if the intervals and group naming sufficiently isolate them from other system tasks. This will reduce confusion as the orchestrator grows more complex or other modules add concurrency tasks.
124-125
: Centralize errSkipChain usage
errSkipChain
is used here and in the bootstrap. Ensure all chain bootstrap logic references the same skip logic or constant. This keeps the orchestrator consistent in how it handles unsupported or incomplete chain states.
211-221
: Return chain list from within locked scope or pass a snapshot
chainIDs
copies the map keys while locked, which is correct. For large or rapidly changing chain lists, confirm that the overhead is acceptable. If this function is called many times, you could consider a versioned approach or batched sync strategy.
233-247
: Ensure idempotent chain removalIf an observer is in an error or partially started state,
removeChain
might need special handling. Right now, it tries toStop()
. Thoroughly test how partial starts or repeated remove calls behave.
273-290
: Enhance constructor validation with aggregated logsYou individually check for nil scheduler, dependencies, etc. Consider logging them all at once or returning a combined error indicating which fields are missing. This helps operators fix multiple issues at once.
292-300
: Attach chain or orchestrator info to logs in newLoggersYou add a new module field (“orchestrator”). If you have multiple orchestrators or multiple modules, consider adding chain or orchestrator version details. This helps multi-tenant or multi-network debugging.
zetaclient/chains/bitcoin/observer/inbound.go (7)
37-38
: Improve debugging log on node inactivity"Bitcoin node is not enabled" is logged at Debug level. Consider logging at Warn for better visibility in production, as it indicates an uninitialized or misconfigured node.
111-113
: Refine the method docstring to reflect trackers logicThe comment references “process inbound trackers,” but the function name is
ObserveInboundTrackers
. Provide consistent docstrings for future maintainers deciding where to place inbound tracker logic or how to reuse it.
183-183
: Use consistent depositor fee calculator usage
CalcDepositorFee
is invoked here. If you support multiple fee calculations or chain environments, consider a pluggable approach so that different Bitcoin networks have different fee rules if needed.
223-223
: Provide more robust fallback or retry logic on parse errorsYou currently bail out upon any error decoding OP_RETURN or the Tx. Potentially, you could log partial progress or skip a single transaction while continuing with others. Evaluate whether a partial approach is needed for resilience.
288-288
: Consolidate fee calculator usage in single function or interfaceThe event creation references
feeCalculator
. Consider abstracting deposit fee logic behind a single interface for deposit fees across multiple networks. This ensures consistent behavior across chain refactors.
Line range hint
321-347
: Log successes and partial failures for script decodingWhen you decode or skip an event, consider logging each skip or reason at debug/info level. This is especially crucial for diagnosing missing or unhandled transactions in production.
407-407
: Document the range of script typesDecodeSenderFromScript
supportsIt is essential to clarify if only P2WPKH or P2PKH scripts are handled. If a user tries other script types, the system might skip them. This should be reflected in usage instructions or logs.
zetaclient/chains/bitcoin/observer/observer.go (4)
197-197
: Ensure backward compatibility with fee calculationsSwitching to
common.FeeRateToSatPerByte
is correct for consistency. Confirm there are no custom fee calculations in older code referencing the removedbitcoin.FeeRateToSatPerByte
method.
233-235
: Refine error wrapping in FetchUTXOs
"unable to get block height"
is a good wrap. Consider including additional details about the failing node or environment for clarity in production logs.
246-246
: Inform about partial listing results from RPC endpoints
ListUnspentMinMaxAddresses
may partially succeed if the node only indexes some transactions. Observe logs and handle partial data from the endpoint more gracefully, in case the node’s indexing is incomplete.
264-264
: Document rationale for skipping UTXOs belowcommon.DefaultDepositorFee
This line excludes small UTXOs. Confirm that small leftover dust UTXOs do not accumulate. If needed, plan a dust consolidation strategy or put a comment explaining the approach.
zetaclient/orchestrator/bootstrap.go (1)
139-140
: Delegating Bitcoin to Orchestrator V2By continuing here, Bitcoin chain signer creation is effectively skipped, moving its handling to Orchestrator V2. This is aligned with the PR’s objective to migrate all Bitcoin logic. Ensure no residual references rely on this branch; otherwise, they may break.
zetaclient/orchestrator/orchestrator.go (1)
380-381
: Skip Bitcoin scheduling under Orchestrator V2Here, the Bitcoin scheduling steps are bypassed. Ensure backward compatibility if older code references the Bitcoin scheduling logic. Revisit or remove references in older orchestrator versions, if any linger.
zetaclient/chains/bitcoin/observer/outbound.go (2)
45-48
: Warning about multiple outbound hashesHelpful log statement. Consider adding a remediation strategy if repeated collisions appear, or track how often multiple hashes occur.
50-63
: Identifying truly included transactionsSequentially verifying each candidate hash is a practical solution. Confirm performance is acceptable and consider a short-circuit if a likely valid transaction is found early.
zetaclient/testutils/testlog/log.go (1)
17-20
: Consider using embedded Buffer initialization in concurrentBytesBuffer.While explicitly instantiating the
bytes.Buffer
is correct, consider embedding it in the struct to reduce pointer indirections and slightly improve performance under concurrency.zetaclient/chains/bitcoin/common/utils.go (1)
Line range hint
20-32
: Potential floating-point pitfalls inGetSatoshis
.Relying on custom rounding can produce edge-case inconsistencies when converting from float to satoshis. Consider using
math.Round
for more explicit rounding behavior or accepting integer inputs for precision.e2e/e2etests/test_bitcoin_std_deposit_and_call.go (1)
13-13
: Use a clear alias to reflect the nature of the common package.
Renaming the import alias fromzetabitcoin
to something more descriptive likebtccommon
can enhance readability, particularly if multiple Bitcoin modules are imported in the future.- zetabitcoin "github.com/zeta-chain/node/zetaclient/chains/bitcoin/common" + btccommon "github.com/zeta-chain/node/zetaclient/chains/bitcoin/common"e2e/e2etests/test_bitcoin_deposit_call.go (2)
12-12
: Align import naming conventions.
Using"common"
without an explicit alias is acceptable, but if the same codebase references multiple Bitcoin-related modules, an alias clarifies usage and improves consistency.
48-48
: Ensure correct BTC conversion.
GetSatoshis
is an efficient utility for conversion, but consider adding boundary checks or validation for unusually large amounts to maintain robust test coverage in production scenarios.e2e/e2etests/test_bitcoin_std_memo_inscribed_deposit_and_call.go (1)
13-13
: Keep consistent import naming.
Similar to other files, consider applying an explicit alias to maintain uniformity if multiple modules are imported.zetaclient/orchestrator/v2_bootstrap_test.go (3)
19-55
: Solid test structure for orchestrator bootstrap.The test is well-arranged (ARRANGE, ACT, ASSERT), and the usage of
assert.Eventually
is appropriate to confirm asynchronous startup. Consider adding negative tests to handle misconfiguration or network failure scenarios proactively.
57-67
: Helper function clarity.
tasksHaveGroup
is concise and readable. Implementing an early return upon finding a match could slightly simplify logic. However, the current version is clear enough.- if !found && task.Group() == scheduler.Group(group) { + if task.Group() == scheduler.Group(group) {
69-78
: Comprehensive mocks for Bitcoin calls.The mock definitions for BTC-related RPC calls are thorough. For enhanced reliability, consider adding error-response scenarios in your mocks to test resilience.
zetaclient/maintenance/shutdown_listener_test.go (1)
18-18
: Channel closure behavior changed from fail-fast to error logging.Using
t.Errorf
instead oft.FailNow
allows the test to proceed after logging the error, which can be beneficial for collecting additional diagnostics. If an immediate test termination is required, consider reverting tot.FailNow
.cmd/zetaclientd/inbound.go (1)
158-172
: Elaborate on “not implemented” or remove the commented-out code lines.Currently, the code is replaced with a “not implemented” error for Bitcoin. If this path is expected to be implemented, consider removing the commented-out code in favor of a clear TODO or proceed with a proper implementation soon. Otherwise, remove the commented code to avoid confusion.
Would you like me to generate a placeholder function or open an issue to track the future implementation?
zetaclient/context/chain.go (1)
67-69
: Consider using defer for shorter locking scopes.Currently, the lock/unlock calls are placed before and after retrieving
maps.Values(cr.chains)
. Possibly replacing them with adefer cr.mu.Unlock()
or local scoping might simplify future maintenance and reduce lock hold times.pkg/ticker/ticker.go (1)
Line range hint
101-142
: Robust “Start” method with panic recovery.The approach appropriately encapsulates preventing double runs, initial run invocation, and panic recovery. Consider verifying any external usage patterns to ensure repeated calls to
Start
are handled as intended.zetaclient/chains/bitcoin/observer/witness.go (1)
162-162
: Consistent decoding logic with new packageReplacing
bitcoin.DecodeScript
withcommon.DecodeScript
ensures a single authoritative decoder for Bitcoin script-related operations, improving code consistency and maintainability.cmd/zetaclientd/start.go (1)
156-174
: Parallel Orchestrator V2 for incremental rolloutThe creation of
maestroV2
alongside the original orchestrator is well-structured. It ensures a smooth migration or testing period while allowing for incremental refactoring. However, consider clearly documenting shutdown coordination if both orchestrators operate on overlapping resources or states.zetaclient/orchestrator/v2_orchestrator_test.go (1)
193-207
: Reflect-based config injection for test scenariosBy design, the sealed config is updated using reflection. While sufficient for testing, ensure that such reflection usage is strictly limited to test code to prevent accidental misuse in production.
zetaclient/chains/bitcoin/observer/witness_test.go (1)
63-63
: Consider extracting magic number to a configuration constant.
Currently, "28" is hard-coded. Exposing this as a named constant in thecommon
package or a config file would improve maintainability.zetaclient/chains/bitcoin/signer/signer.go (1)
309-309
: Refined function signature for TryProcessOutbound.
Replacing the generic observer interface with a concrete observer reference can simplify logic, but consider preserving an interface if mocking or decoupling is desired across codebases.
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (45)
cmd/zetaclientd/inbound.go
(1 hunks)cmd/zetaclientd/start.go
(2 hunks)e2e/e2etests/test_bitcoin_deposit_and_call_revert.go
(1 hunks)e2e/e2etests/test_bitcoin_deposit_and_call_revert_with_dust.go
(1 hunks)e2e/e2etests/test_bitcoin_deposit_call.go
(3 hunks)e2e/e2etests/test_bitcoin_donation.go
(1 hunks)e2e/e2etests/test_bitcoin_std_deposit.go
(2 hunks)e2e/e2etests/test_bitcoin_std_deposit_and_call.go
(1 hunks)e2e/e2etests/test_bitcoin_std_memo_inscribed_deposit_and_call.go
(2 hunks)e2e/runner/bitcoin.go
(6 hunks)go.mod
(2 hunks)pkg/chains/chain.go
(2 hunks)pkg/scheduler/opts.go
(1 hunks)pkg/scheduler/scheduler.go
(3 hunks)pkg/ticker/ticker.go
(3 hunks)zetaclient/chains/base/observer.go
(1 hunks)zetaclient/chains/bitcoin/bitcoin.go
(1 hunks)zetaclient/chains/bitcoin/common/errors.go
(1 hunks)zetaclient/chains/bitcoin/common/fee.go
(1 hunks)zetaclient/chains/bitcoin/common/fee_test.go
(1 hunks)zetaclient/chains/bitcoin/common/tx_script.go
(1 hunks)zetaclient/chains/bitcoin/common/tx_script_test.go
(31 hunks)zetaclient/chains/bitcoin/common/utils.go
(1 hunks)zetaclient/chains/bitcoin/observer/inbound.go
(11 hunks)zetaclient/chains/bitcoin/observer/inbound_test.go
(9 hunks)zetaclient/chains/bitcoin/observer/observer.go
(6 hunks)zetaclient/chains/bitcoin/observer/outbound.go
(4 hunks)zetaclient/chains/bitcoin/observer/rpc_status.go
(1 hunks)zetaclient/chains/bitcoin/observer/witness.go
(5 hunks)zetaclient/chains/bitcoin/observer/witness_test.go
(2 hunks)zetaclient/chains/bitcoin/rpc/rpc_live_test.go
(4 hunks)zetaclient/chains/bitcoin/signer/signer.go
(10 hunks)zetaclient/context/chain.go
(2 hunks)zetaclient/context/context.go
(1 hunks)zetaclient/maintenance/shutdown_listener_test.go
(1 hunks)zetaclient/orchestrator/bootstrap.go
(2 hunks)zetaclient/orchestrator/bootstrap_test.go
(8 hunks)zetaclient/orchestrator/contextupdater.go
(0 hunks)zetaclient/orchestrator/orchestrator.go
(2 hunks)zetaclient/orchestrator/v2_bootstrap.go
(1 hunks)zetaclient/orchestrator/v2_bootstrap_test.go
(1 hunks)zetaclient/orchestrator/v2_orchestrator.go
(1 hunks)zetaclient/orchestrator/v2_orchestrator_test.go
(1 hunks)zetaclient/testutils/mocks/chain_params.go
(1 hunks)zetaclient/testutils/testlog/log.go
(1 hunks)
💤 Files with no reviewable changes (1)
- zetaclient/orchestrator/contextupdater.go
✅ Files skipped from review due to trivial changes (4)
- zetaclient/chains/bitcoin/common/errors.go
- zetaclient/chains/bitcoin/common/fee.go
- zetaclient/chains/bitcoin/common/fee_test.go
- zetaclient/chains/bitcoin/common/tx_script.go
👮 Files not reviewed due to content moderation or server errors (2)
- zetaclient/testutils/mocks/chain_params.go
- go.mod
🧰 Additional context used
📓 Path-based instructions (39)
zetaclient/testutils/mocks/chain_params.go (1)
Pattern **/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.
pkg/chains/chain.go (1)
Pattern **/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.
zetaclient/context/context.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.
cmd/zetaclientd/inbound.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_call.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/e2etests/test_bitcoin_donation.go (1)
Pattern **/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.
cmd/zetaclientd/start.go (1)
Pattern **/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.
e2e/e2etests/test_bitcoin_deposit_and_call_revert_with_dust.go (1)
Pattern **/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.
pkg/scheduler/opts.go (1)
Pattern **/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.
zetaclient/chains/bitcoin/common/utils.go (1)
Pattern **/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.
zetaclient/chains/bitcoin/observer/rpc_status.go (1)
Pattern **/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.
zetaclient/chains/base/observer.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.
pkg/scheduler/scheduler.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_memo_inscribed_deposit_and_call.go (1)
Pattern **/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.
zetaclient/orchestrator/orchestrator.go (1)
Pattern **/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.
pkg/ticker/ticker.go (1)
Pattern **/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.
zetaclient/context/chain.go (1)
Pattern **/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.
zetaclient/maintenance/shutdown_listener_test.go (1)
Pattern **/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.
zetaclient/testutils/testlog/log.go (1)
Pattern **/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.
zetaclient/orchestrator/bootstrap_test.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.
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.
zetaclient/chains/bitcoin/rpc/rpc_live_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.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/chains/bitcoin/bitcoin.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/orchestrator/v2_bootstrap_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/orchestrator/v2_orchestrator_test.go (1)
Pattern **/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.
zetaclient/orchestrator/v2_orchestrator.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.go (1)
Pattern **/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.
zetaclient/chains/bitcoin/common/tx_script_test.go (1)
Pattern **/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.
zetaclient/orchestrator/bootstrap.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_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_test.go (1)
Pattern **/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.
📓 Learnings (4)
zetaclient/chains/bitcoin/rpc/rpc_live_test.go (1)
Learnt from: ws4charlie
PR: zeta-chain/node#2899
File: zetaclient/chains/bitcoin/observer/inbound.go:366-371
Timestamp: 2024-11-12T13:20:12.658Z
Learning: The `bitcoin.CalcDepositorFee` function is covered by live tests.
zetaclient/chains/bitcoin/observer/inbound.go (2)
Learnt from: ws4charlie
PR: zeta-chain/node#3025
File: zetaclient/chains/bitcoin/observer/event.go:110-115
Timestamp: 2024-11-12T13:20:12.658Z
Learning: In the `DecodeEventMemoBytes` function, a non-nil `memoStd` with a non-nil `err` indicates that the memo bytes are well-formatted as a memo but contain improper data.
Learnt from: ws4charlie
PR: zeta-chain/node#2899
File: zetaclient/chains/bitcoin/observer/inbound.go:131-132
Timestamp: 2024-11-12T13:20:12.658Z
Learning: ObserveInbound coverage will be improved in future refactor.
zetaclient/chains/bitcoin/observer/witness_test.go (1)
Learnt from: ws4charlie
PR: zeta-chain/node#2899
File: zetaclient/chains/bitcoin/observer/inbound.go:366-371
Timestamp: 2024-11-12T13:20:12.658Z
Learning: The `bitcoin.CalcDepositorFee` function is covered by live tests.
zetaclient/chains/bitcoin/observer/inbound_test.go (1)
Learnt from: ws4charlie
PR: zeta-chain/node#2899
File: zetaclient/chains/bitcoin/observer/inbound.go:366-371
Timestamp: 2024-11-12T13:20:12.658Z
Learning: The `bitcoin.CalcDepositorFee` function is covered by live tests.
🔇 Additional comments (113)
zetaclient/orchestrator/v2_bootstrap.go (3)
16-20
: Validate chain type before proceedingThis check is good for ensuring the method only boots a Bitcoin chain. Ensure no other code paths rely on the assumption that
chain.IsBitcoin()
is always true, since an unexpected chain type would not boot properly.
42-43
: File naming caution for database creationUsing the chain name to build the database filename is sensible. Ensure collisions cannot occur with similarly named test networks or future expansions.
53-65
: Verify observer initialization consistencyWhen you create a new Bitcoin observer, ensure that its critical fields align with the requirement for multi-network or future concurrency expansions (e.g., ensuring safe usage of DB and concurrency).
zetaclient/chains/bitcoin/bitcoin.go (2)
44-46
: Favor using chain's identity from the aggregatorWhile returning
b.observer.Chain()
is straightforward, confirm that it consistently reflects the same chain data across observer, signer, and scheduler. Desyncs can occur if chain references are updated incorrectly.
112-113
: Confirm early exit is correct upon Start successThe method returns
nil
if no immediate errors occurred. Make sure any asynchronous errors triggered by the tasks get handled or logged to prevent silent failures.zetaclient/orchestrator/v2_orchestrator.go (3)
47-52
: Confirm telemetry usage is always safeTelemetry references might operate asynchronously. Ensure they are thread-safe under heavy concurrency or repeated orchestrator lifecycles.
91-96
: Stop call usage
oc.scheduler.Stop()
stops all tasks. If partially used by other orchestrators or older code, confirm that stopping one orchestrator does not unexpectedly interrupt tasks not associated with V2.
126-201
: Improve chain detection logic for new or removed chainsYour loop over
app.ListChains()
carefully decides to add or remove chains. Incorporate robust logging and tests to confirm you do not inadvertently skip a chain that is partially configured or in transitional states (like a chain upgrade).zetaclient/chains/bitcoin/observer/inbound.go (1)
17-17
: Confirm correct usage of movedcommon
packageImports from
github.com/zeta-chain/node/zetaclient/chains/bitcoin/common
appear to replace olderbitcoin
references. Verify that the functions (like fee calculators, decoders) match the required functionality to avoid subtle differences in logic.zetaclient/chains/bitcoin/observer/observer.go (3)
21-21
: Check alignment of newcommon
usage with legacy referencesReplacing old references to
bitcoin
withcommon
is a good step. Verify that any leftover references tobitcoin
do not break functionalities or lead to partial code references.
241-243
: Check the TSS address retrieval for test networksYou retrieve the TSS address from the chain ID. For multi-environment setups or ephemeral test networks, confirm that TSS addresses are aligned with chain parameters to avoid mismatch or invalid addresses.
381-381
: Account for varied fee rates in testnet
common.GetRecentFeeRate
is a helpful approach, but testnet volatility can differ from mainnet. Ensure you have fallback or bounding logic if returned rates fluctuate or appear unreasonably large.zetaclient/orchestrator/orchestrator.go (1)
202-202
: Check for nil chain parameters before settingInvoking
observer.SetChainParams(*chain.Params())
directly dereferences the chain parameters. Consider a prior nil check or graceful fallback ifchain.Params()
is unexpectedly nil.zetaclient/chains/bitcoin/observer/outbound.go (11)
17-17
: Introduction of thecommon
packageUsing
common
fosters shared utilities across Bitcoin modules, reducing code duplication. This approach enhances code reusability and clarity.
24-25
: New function signatureObserveOutbound
Replaces prior polling-based approach, simplifying logic to a single call. Validate invocation frequency elsewhere to ensure timely processing.
27-27
: Asynchronous retrieval of all outbound trackersGrabbing all trackers in ascending order seems correct. Confirm that no partial or large-batch side effects occur for massive tracker lists.
29-29
: Error wrapping for clarity
return errors.Wrap(err, "unable to get all outbound trackers")
helps track the origin of failures. This is a good pattern for debugging.
32-38
: Iterating through outbound trackersThe loop fetches CCTX by nonce and checks consistency. This procedure is straightforward and robust, ensure concurrency concerns are addressed if multiple calls can overlap.
40-43
: Nonce mismatch checkExcellent safeguard ensuring tracker and CCTX remain consistent. This prevents incorrect or stale data from propagating.
66-67
: No functional changeThese lines appear to be closing braces. No actionable feedback needed.
68-72
: Handling multiple or zero included transactionsRobust approach to either set or remove included transactions. Consider logging each scenario for debugging if multiple collisions happen frequently.
75-76
: Return on completionThe function now returns a single
error
ornil
. This is a clean, straightforward exit point.
382-382
: Use ofcommon.GetSatoshis
Leverages the shared logic. Handle and log errors carefully if conversion fails for unexpected amounts.
626-626
: Decoding TSS output withcommon.DecodeTSSVout
Applying a common function for decoding ensures consistency across the Bitcoin observer code. This fosters maintainability and shared improvements.
zetaclient/chains/bitcoin/observer/rpc_status.go (6)
5-5
: Blank line modificationNo functional changes here.
6-6
: Importinggithub.com/pkg/errors
Adopts standard error wrapping conventions. This is consistent with the rest of the codebase.
11-12
: Renamed function with context parameter
CheckRPCStatus
usescontext.Context
, enabling better cancellation and timeouts. Ensures best practices for external calls.
15-15
: Wrapping TSS address errorProactive approach to provide context about address fetching failures. A well-structured error message is beneficial for debugging.
20-20
: Wrapping RPC status errorSimilar approach as above. Maintains consistency throughout the observer’s error handling.
24-25
: Block latency reporting and returnReporting metrics is helpful to track node health. The function’s concluding
return nil
is semantically clean.zetaclient/context/context.go (1)
11-11
: Improved error message for missing AppContextSwitching to “unable to get AppContext from context.Context” clarifies the root cause. This fosters better debugging and explicit problem statements.
zetaclient/testutils/testlog/log.go (2)
22-32
: Well-structured concurrency approach for test logging.The approach of combining
zerolog.NewTestWriter(t)
with a thread-safe buffer ensures minimal data races when capturing logs in parallel test scenarios. This is a neat and purposeful solution.
38-43
: Efficient lock usage.Locking at write scope is appropriate for this scenario, ensuring log entry atomicity without overcomplicating concurrency. This design is suitable for capturing test logs.
zetaclient/chains/bitcoin/common/utils.go (1)
1-1
: Reorganized to acommon
package.This refactor promotes clearer responsibility separation. Ensure that references to
bitcoin
are updated accordingly across the entire codebase.e2e/e2etests/test_bitcoin_donation.go (1)
12-12
: Import path aligns with refactored structure.This change consistently follows the adoption of the
common
package for Bitcoin utilities. Good job keeping references precise.pkg/scheduler/opts.go (2)
32-32
: Clear documentation enhancement.Clarifying that returning true will skip the task prevents confusion and ensures correct usage.
39-42
: Immediate interval assignment.Applying
opts.interval = intervalUpdater()
before setting the updater function ensures the first task iteration reflects the latest interval. This is a practical approach to sync the schedule from the outset.e2e/e2etests/test_bitcoin_deposit_and_call_revert.go (1)
9-9
: Confirm the new import path aligns with the refactoring.
Bringing in thecommon
package is consistent with the broader refactoring. Ensure that any references to Bitcoin-specific constants or methods still function as intended and do not break any existing tests.e2e/e2etests/test_bitcoin_deposit_call.go (1)
23-23
: Validate fee usage in test scenarios.
Adding the default depositor fee is correct for typical deposit flows. However, confirm that all test cases handle edge scenarios (e.g., dust inputs or minimum transaction fees) to maintain coverage.e2e/e2etests/test_bitcoin_std_memo_inscribed_deposit_and_call.go (1)
56-56
: Review deposit fee logic for large memos.
When inscribing large memos, the depositor fee calculation could interact with variable on-chain fees. Confirm that the deposit fee covers all overhead scenarios so no partial or failed transactions occur in certain corner cases.e2e/e2etests/test_bitcoin_std_deposit.go (2)
13-13
: Renamed import path aligns with refactoring.Switching from
bitcoin
tocommon
indicates a reorganization of shared Bitcoin-related utilities. This change strengthens modularity and prevents import cycles.
57-57
: Direct usage ofcommon.GetSatoshis
is valid.No functional issues found. The rename appears consistent with the broader refactoring, and the usage in the deposit test remains correct.
e2e/e2etests/test_bitcoin_deposit_and_call_revert_with_dust.go (1)
13-13
: New import path promotes code reusability.Adopting
common
for Bitcoin utilities removes potential duplication across packages. This update is in line with the ongoing reorganization.pkg/scheduler/scheduler.go (3)
147-151
: Logging enhancements look good.Including the number of tasks and group being stopped is helpful for debugging and monitoring.
181-183
: MethodGroup()
is straightforward and adequately encapsulated.
185-187
: MethodName()
is clear and consistent with the rest of the task structure.zetaclient/context/chain.go (1)
148-150
: LogFields() method nicely extends the Chain struct’s logging capabilities.Exposing log fields via
LogFields
promotes structured logging and consistent log formats.pkg/ticker/ticker.go (2)
217-219
: Avoid potential nil-pointer by checkingt.ticker != nil
before stopping.This check ensures safe invocation of
t.ticker.Stop()
. The current approach is correct and prevents runtime panics.
224-229
:isStopped
method is a concise helper for checking the ticker’s state.This approach cleanly handles concurrency by locking while reading the
stopped
flag.zetaclient/chains/bitcoin/observer/witness.go (4)
13-13
: Reorganized import for extensibilityImporting
common
from the newbitcoin/common
package aligns with the broader refactoring effort and consolidates Bitcoin utilities under a single package. This change fosters maintainability and clearer boundaries between modules.
27-27
: Updated parameter type for deposit fee calculationSwitching from
bitcoin.DepositorFeeCalculator
tocommon.DepositorFeeCalculator
is consistent with the reorganization in thecommon
package. This unifies the code structure for fee calculations across Bitcoin-related modules.
140-140
: Preserved logic while updating OP_RETURN decoderThe invocation of
common.DecodeOpReturnMemo
preserves OP_RETURN parsing and ensures that any future improvements in the sharedcommon
package are automatically leveraged.
190-190
: Unified approach for P2WPKH script decodingUsing
common.DecodeScriptP2WPKH
centralizes the decoding logic, preventing discrepancies across different Bitcoin modules. This also guards against future code duplication.cmd/zetaclientd/start.go (1)
17-17
: New import for scheduled orchestrationIntroducing the
scheduler
package paves the way for more structured, time-based tasks and periodic triggers in the orchestrator, improving modularity and maintainability.pkg/chains/chain.go (2)
11-12
: Importing logs package for structured loggingIntroducing
logs
fromzetaclient/logs
suggests structured and contextual logging support for chain-related activities, which enhances debugging and traceability.
113-119
: New LogFields method for improved observabilityProviding a
LogFields
method promotes structured logging across components. This is beneficial for debugging multi-chain environments where chain identification is critical. Ensure that potential sensitive data (if any) is never logged.zetaclient/orchestrator/v2_orchestrator_test.go (6)
1-2
: New orchestrator V2 test file initializationDeclaring the package and initiating the test file structure sets the foundation for comprehensive testing of orchestrator V2. This organized approach is commendable.
29-74
: Test coverage for orchestrator V2’s dynamic context updatesThe
TestOrchestratorV2
sub-test structure effectively verifies that updated chain parameters propagate to the application context in real time. This is an excellent pattern for validating runtime adjustments and ensuring concurrency safety.
75-92
: Centralized test suite designUsing a
testSuite
struct to bundle test dependencies (logger, appContext, chains, etc.) facilitates reusability and readability, especially for complex test scenarios.
106-169
: Comprehensive test suite setup
newTestSuite
neatly composes all mock services and orchestrator dependencies. This approach encourages clarity, as all major test objects are created in one place, preventing hidden side effects.
171-179
: Dynamic chain params mocking
MockChainParams
method provides a swift mechanism to inject test scenarios on-the-fly. This approach is well-suited for verifying orchestrator responsiveness to rapid chain parameter changes.
Line range hint
254-269
: Utility for chain membership verification
chainsContain
is a clean helper function that grants quick validation of chain presence within the application context. The use of sets simplifies membership checks and fosters clarity.zetaclient/chains/bitcoin/observer/witness_test.go (1)
13-13
: Consistent package import.
Switching from thebitcoin
package to thecommon
package is consistent with the new modular structure.zetaclient/orchestrator/bootstrap_test.go (9)
9-9
: No issues with new import.
Adding the mock library import is standard practice.
68-69
: Graceful exclusion of BTC signer from V1 orchestrator.
Updating the assertion to 1 signer aligns with the updated logic that moves BTC to V2.
75-75
: Explicit inclusion of Polygon chain.
Ensures that Polygon is considered at runtime.
109-109
: Re-enable Ethereum chain test scenario.
This test name and scenario properly document the reintroduction of Ethereum as an active chain.
154-155
: Mock client call for Zetacore.
UtilizingmockZetacore(client)
ensures consistent tests and avoids unmocked calls.
193-194
: Clarity in chain usage comments.
Lines now emphasize that Polygon and Solana are intentionally excluded here and BTC is handled in orchestrator V2.Also applies to: 198-198
209-209
: Observer count updated for BTC shift.
Asserted observer count of 2 and explicitly excluding Bitcoin aligns with the orchestrator V2 approach.Also applies to: 212-212
417-418
: Helper function annotation.
Marking the function as a test helper ensures clearer stack traces if assertions fail.
429-437
: Comprehensive mock setup for Zetacore.
Provides stable test scenarios by defining flexible expectations forPostVoteGasPrice
.zetaclient/chains/bitcoin/signer/signer.go (13)
27-27
: Separation of common utilities.
Importingcommon
clarifies that shared Bitcoin functionality is decoupled from chain-specific logic.
102-102
: Use of common.GetSatoshis.
Properly leverages the new utility method for unit conversion, improving code cohesion.
109-109
: Calculation of remaining satoshis.
Usescommon.GetSatoshis()
for consistency and clarity.
169-169
: Fee estimation with OutboundBytesMax.
Making fees dependent on maximum outbound bytes is consistent with bridging constraints.
208-208
: Outbound size estimation.
Utilizescommon.EstimateOutboundSize
, reflecting the new modular approach for BTC logic.
212-212
: Size limit check against BtcOutboundBytesWithdrawer.
Ensures a separate fee structure for ZRC20 'withdraw' calls.
216-219
: Enforce minimum size if under OutboundBytesMin.
Correctly prevents underestimation of transaction size.
221-224
: Enforce maximum size if above OutboundBytesMax.
Safeguards against overly large transactions.
245-245
: Conversion of multi-UTXO amounts.
Maintains consistency in satoshi conversion for each input.
338-338
: Explicit chain retrieval.
Extractingobserver.Chain()
clarifies which chain is being processed.
373-373
: Fee rate conversion using FeeRateToSatPerByte.
Provides clearer bridging between network relay fees and local gas price.
402-402
: Observer parameter alignment.
Ensures direct access to the relevant Bitcoin observer methods.
449-449
: Tracking broadcasted transaction.
observer.SaveBroadcastedTx
properly records successful BTC outbound transactions.e2e/runner/bitcoin.go (6)
26-26
: Rename tozetabtc
import.
The rename clarifies that these helpers belong to the updated Bitcoin common package.
103-103
: Default depositor fee usage.
Explicitly addingzetabtc.DefaultDepositorFee
ensures consistent deposit fees.
151-151
: BTC deposit plus default fee.
Aligns with centralized handling of depositor fees, improving code clarity.
244-244
: Integer conversion withGetSatoshis
.
Makes deposit operations less error-prone by using shared conversion logic.
354-354
: Consistent satoshi conversion for inscriptions.
ReusesGetSatoshis
to unify how amounts are processed in reveal transactions.
415-415
: UseDecodeScriptP2WPKH
.
Decodes the script with the newzetabtc
method for consistent script parsing.zetaclient/chains/base/observer.go (1)
169-175
: Avoid redundant parameter assignments and logs.
This newly introduced check prevents unnecessary reassignments when thechainParams
haven't changed, enhancing efficiency and reducing log noise. Implementation appears correct, with proper locking to avoid data races.zetaclient/chains/bitcoin/rpc/rpc_live_test.go (5)
21-21
: Well-aligned package restructuring.
Importing thecommon
package for Bitcoin-related logic consolidates functionality, improving maintainability.
366-366
: Refactor for consistency.
Switching tobtc.CalcBlockAvgFeeRate
in thecommon
package aligns with the new code structure, maintaining consistency throughout the codebase.
418-418
: Enhanced modular approach.
The usage ofbtc.GetRecentFeeRate
from thecommon
package is coherent with the broader refactoring effort.
599-601
: Test coverage for default depositor fee.
The test accurately enforces and verifies the expected default depositor fee behavior.
605-611
: Concise calculation check.
Calculating and comparing the depositor fee with the expected dynamic fee rate ensures correctness. The test is well-structured to catch regressions.zetaclient/chains/bitcoin/observer/inbound_test.go (4)
19-19
: Seamless shift to thecommon
package.
Switching imports to referencecommon
maintains consistency in the refactored architecture.
35-35
: Appropriate mock creation.
DefiningmockDepositFeeCalculator
in terms ofcommon.DepositorFeeCalculator
keeps tests aligned with the new package.
Line range hint
58-147
: Unified usage ofcommon.CalcBlockAvgFeeRate
.
All references toCalcBlockAvgFeeRate
have been updated to use the common package. The tests remain clear and thorough, verifying correct handling of various edge cases (e.g., empty blocks, coinbase issues, invalid heights).
286-286
: Consistent depositor fee calculation.
Replacingbitcoin.DepositorFee
withcommon.DepositorFee
ensures uniformity in fee computations across the codebase.zetaclient/chains/bitcoin/common/tx_script_test.go (12)
Line range hint
1-20
: Well-structured rename tocommon_test
.
Renaming the package and updating the import paths clarifies the scope. UpdatingTestDataDir
ensures correct file paths after the reorganization.
Line range hint
33-72
: Spot-on P2TR decoding tests.
Decoding logic for P2TR is now hosted incommon
, with comprehensive tests for invalid and valid scenarios. This shift is well justified.
Line range hint
88-127
: Robust P2WSH decoding coverage.
Both success cases and failure modes (e.g., wrong hash length, invalid OP codes) are adequately tested. Refactoring tocommon
introduces no regressions.
145-155
: P2WPKH decoding verification.
These additions ensure that inbound/outbound transactions relying on P2WPKH scripts are validated properly under the new structure.
174-189
: Reliability for P2WPKH error handling.
Handling various script anomalies ensures the decode pipeline is robust. All negative paths appear well tested.
221-250
: Distinct P2SH decode logic.
Shifting tocommon.DecodeScriptP2SH
centralizes script handling, with thorough coverage of known script pitfalls.
Line range hint
266-328
: P2PKH decoding validated.
Confirming that typical pay-to-pubkey-hash scripts decode consistently matches the overall approach in the other script decodes.
Line range hint
372-417
: Comprehensive OP_RETURN memo decoding checks.
Tests highlight multiple edge cases, including pushdata size mismatches and invalid OP codes. These checks significantly reduce the risk of parsing errors.
495-495
:DecodeSenderFromScript
function usage.
This test thoroughly evaluates script-based address decoding under various script types, ensuring correctness for all common use cases.
Line range hint
513-561
: Expanded TSS vout decoding.
Incorporating all major script types (P2TR, P2WSH, P2WPKH, P2SH, P2PKH) in the TSS decode path underscores the new package’s versatility.
Line range hint
580-613
: Solid negative testing for TSS vout decode.
Covers invalid amounts, unsupported chain IDs, incorrect address decodes, and broken scripts. The variety of test cases is beneficial for reliability.
Line range hint
626-695
: Detailed multi-path script decoding coverage.
Complex scripts, large pushdata sequences, truncated data, and missing opcodes—each scenario is explicitly tested. This broad coverage instills confidence in the decoding routine.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 5
🔭 Outside diff range comments (1)
zetaclient/chains/bitcoin/observer/inbound.go (1)
Line range hint
306-347
: Strengthen script validation.
GetBtcEventWithoutWitness
checks for P2WPKH scripts. For better reliability, consider verifying script type more rigorously (e.g., explicit length checks for the entire script).
🧹 Nitpick comments (53)
pkg/chains/chain.go (1)
113-119
: Extend logging fields for added clarity.The method is concise and supports structured logging. Consider including fields like
logs.FieldChainName
or consensus type for easier debugging.func (chain Chain) LogFields() map[string]any { return map[string]any{ logs.FieldChain: chain.ChainId, logs.FieldChainNetwork: chain.Network.String(), + logs.FieldChainName: chain.Name, + "consensus": chain.Consensus.String(), } }zetaclient/chains/bitcoin/observer/rpc_status.go (2)
5-6
: Consider migrating fromgithub.com/pkg/errors
to Go's standard library error wrapping.
This import ofgithub.com/pkg/errors
is consistent with many existing codebases, but since Go 1.13 introduced native error wrapping with thefmt.Errorf("...: %w", err)
pattern, you might consider migrating to reduce external dependencies and improve maintainability.
24-25
: Optional logging of successful checks.
The function currently returns without logging success. In case additional observability is desired, consider logging or tracing upon successful RPC status checks.zetaclient/orchestrator/v2_bootstrap.go (4)
22-25
: Ensure consistent error handling.
Ifzctx.FromContext(ctx)
fails, consider logging more context to help diagnose the issue.
49-51
: Address pending TODO items.
The comment suggests extracting a base observer and signer. Consider implementing these as interfaces or abstractions to reduce duplication across multiple chain bootstraps.
67-70
: Add logging for signer initialization.
For better maintainability, log relevant config details or chain ID upon signer creation. This helps trace issues during production.
72-72
: Consider injecting the outbound processor from the orchestrator.
Though returningbitcoin.New(...)
is valid, centralizing outbound processing instantiation at a higher level can help with future chain expansions or design changes.cmd/zetaclientd/start.go (2)
156-157
: Clarify usage of the new TaskScheduler.
It is introduced here but consider documenting the rationale for a separate scheduler instance as opposed to reusing existing components.
164-167
: Handle orchestrator V2 errors gracefully.
The new orchestrator is created, but if it fails to start properly, ensure a robust fallback or a clear exit.zetaclient/chains/bitcoin/bitcoin.go (5)
20-25
: Promote clarity through docstrings.
TheBitcoin
struct is self-explanatory. Consider adding docstrings to clarify ownership ofscheduler
,observer
, andsigner
, especially for new contributors.
27-42
: Revisit outbound processor ownership.
Constructing theoutboundprocessor.Processor
here is fine. However, if it is shared across different chains or responsibilities, consider centralizing its creation to reduce coupling.
101-108
: Group tasks with consistent naming.
The tasks are named “observe_inbound” and so forth. Ensure naming remains consistent across all relevant orchestrators for easier debugging.
204-206
: Return meaningful status or metrics.
After scheduling CCTX, returningnil
is functionally sound, but consider updating metrics or logs about how many CCTX were processed.
226-230
: Consider logging improvements.
outboundLogger
helps unify outbound logs. If logs become too verbose, introduce sampling or a dynamic debug level.zetaclient/orchestrator/v2_orchestrator.go (5)
22-31
: Document concurrency strategy forchains
.
mu sync.RWMutex
implies concurrency. Provide docstrings to explain how read/write lock usage ensures data consistency.
54-65
: Enhance logging on orchestrator creation.
WhenV2
is instantiated, consider streaming the chain IDs or other relevant metadata to logs.
67-89
: Consider scheduling dependencies in smaller tasks.
UpdateContext
andSyncChains
are top-level tasks. If they become too large, splitting them can isolate issues and improve modular testing.
150-167
: Plan for multi-chain expansions.
A switch statement forchain.IsBitcoin()
,chain.IsEVM()
, etc., is manageable now. In future expansions for multiple EVM chain types, refactor to a registry-based approach if needed.
223-231
: Prevent duplication.
Ensure you do not add the same chain multiple times. A quick re-check insideaddChain
is already happening withhasChain
, but consider single-responsibility to avoid race conditions.zetaclient/chains/bitcoin/observer/inbound.go (3)
37-38
: Provide more detail in debug logs.
When the Bitcoin node is disabled or returning block 0, consider adding metadata such as node version or connection status to facilitate troubleshooting.
111-113
: Refactor inbound tracker logic.
The comment suggests further decoupling inbound tracker logic. Implementing a dedicated file for inbound trackers might enhance clarity and ease of testing.
407-407
: Log or handle unknown script cases more robustly.
common.DecodeSenderFromScript(pkScript, net)
can return an empty string for unknown scripts. Consider logging these unknown scripts for better diagnostics.zetaclient/chains/bitcoin/observer/observer.go (4)
233-233
: Add more diagnostic context
Consider including chain details orchainID
in the error string to aid runtime diagnostics, for example:- return errors.Wrap(err, "unable to get block height") + return errors.Wrapf(err, "unable to get block height for chain %d", ob.Chain().ChainId)
241-241
: Enhance error logging details
Similarly, adding chain information or relevant identifiers (e.g., TSS address) to the error improves debug clarity.
246-246
: Increase specificity in error messages
Adding the contextual details, such as the addresses in question, can expedite troubleshooting.
264-264
: Parameterize deposit fee limit
Hard-codingcommon.DefaultDepositorFee
may lead to rigid fee structures. Consider making this threshold user-configurable or environment-configurable.zetaclient/chains/bitcoin/observer/outbound.go (1)
24-76
: Streamlined approach to outbound observation
This newObserveOutbound
function exhibits several improvements:
- Incorporates immediate error returns (
errors.Wrap(...)
) for clearer error handling.- Ensures that each tracker's
nonce
aligns with the cctx'sTssNonce
, potentially preventing mismatched states.- Manages multiple outbound hashes more robustly by removing all if duplicates appear.
Recommended adjustments/observations:
- Early Logging: When returning errors inside the loop at lines 37 and 42, consider logging the partial progress so far, if relevant.
- Performance Considerations: Because the entire list of trackers is processed sequentially, a large number of trackers could slow down the method. Evaluate if concurrency or batched evaluations are safe or beneficial.
e2e/e2etests/test_bitcoin_deposit_call.go (1)
23-23
: Reference toDefaultDepositorFee
is coherent.Using
common.DefaultDepositorFee
maintains consistency with the new package structure. Consider retrieving the fee from a configuration if you anticipate future variability.zetaclient/orchestrator/v2_bootstrap_test.go (2)
48-48
: Consider reducing the waiting time in “assert.Eventually”.The current interval of 5 seconds with 100ms polling is acceptable for integration tests but can slow down the test suite. You may consider a shorter timeout if these tests are run frequently, or mock the logic more extensively to avoid waiting.
53-53
: Log string checks can be fragile.Relying on
assert.Contains(t, ts.Log.String(), "Added observer-signer")
may break if the log format changes. If feasible, consider using a structured log approach or verifying state changes directly.zetaclient/maintenance/shutdown_listener_test.go (1)
18-18
: Replacing FailNow with Errorf may obscure follow-up failures.Switching from
t.FailNow()
tot.Errorf
allows the test to proceed further even when the channel is unexpectedly closed, which might lead to subsequent errors or false positives. Consider whether immediate failure is desirable in this scenario.cmd/zetaclientd/inbound.go (1)
158-172
: Placeholder for unimplemented Bitcoin logic.Returning “not implemented” for Bitcoin inbound transactions is acceptable during refactoring, but be sure to track this as a TODO item so that the functionality is completed.
Would you like me to open an issue describing the steps to implement Bitcoin inbound processing?
pkg/ticker/ticker.go (2)
Line range hint
101-140
: Refine logging and context cancellation flow inStart
method.The
Start
method is well-organized, but consider clarifying any retained resources or partial state if the task panics or fails on the initial run. Having a clear cleanup routine after the initial run can prevent hidden resource locking or partial states.
224-229
: Add short doc comment forisStopped()
.The function is well-implemented. A succinct doc comment clearly explaining it returns the ticker’s internal
stopped
state under a lock helps maintain clarity for maintainers and code readers.zetaclient/chains/bitcoin/observer/witness.go (2)
27-27
: Consider renaming for clarity.The parameter
feeCalculator common.DepositorFeeCalculator
is descriptive, but consider a name such ascalculateFee
orcalculateDepositorFee
to align with function usage for improved readability.
190-190
: Validate production scenarios forDecodeScriptP2WPKH
.Ensure robust error handling around
DecodeScriptP2WPKH
. Consider logging warning details or capturing metrics for invalid scripts to easily track mal-formed transactions.zetaclient/orchestrator/v2_orchestrator_test.go (8)
29-73
: Enhance test reliability with additional negative test cases.Currently, the test focuses primarily on successful chain updates. Consider adding negative tests, such as invalid chain IDs or no chains returned, to confirm robust error handling in the orchestrator.
75-92
: Document concurrency intestSuite
.Since the test suite uses shared state (
mu
lock, etc.), adding a short doc or comment clarifying concurrency usage helps future maintainers.
106-169
: EnsureNewV2
handles partial or missing dependencies elegantly.In
newTestSuite
, if scheduling or TSS creation fails, confirmNewV2
has robust fallback or logging. This helps ensure clarity when investigating startup errors.
171-179
: Lock usage inMockChainParams
.Acquiring a lock to mutate both
ts.chains
andts.chainParams
is correct. Consider an atomic swap pattern if you expect high concurrency or repeated calls for performance.
181-185
: Return possible errors forgetSupportedChains
.The function signature returns an error but is never used to signal a problem. Consider returning a relevant error if the chain list is unexpectedly empty.
187-191
: Surface errors forgetChainParams
.Similar to
getSupportedChains
, if params are empty or invalid, consider returning an error to help troubleshoot misconfigurations.
193-207
: Document potential side effects ofUpdateConfig
.Any modifications to sealed configs via reflection can be fragile. A doc note stating it’s solely for testing ensures clarity and prevents production misuse.
254-267
: Simplify membership checks inchainsContain
.Although using a set is efficient, you can unify the membership check in one pass or use a slice-based approach. This is minor but can simplify code.
zetaclient/orchestrator/bootstrap_test.go (6)
68-68
: Revisit numeric literal usage in assertions.Using
1
directly can be fine, but consider symbolic constants if you foresee multiple references to expected lengths. This helps keep test logic clearly descriptive.
75-75
: Document thoroughness of chains tested.When adding polygon at runtime, ensure test coverage addresses ephemeral or corner-case logic, e.g., removing polygon again after an addition.
193-193
: Clarify comment about missing polygon & SOL.The statement about the chain slice “LACKS polygon & SOL on purpose” might need further explanation. If that logic changes, tests can break unexpectedly.
209-209
: Use consistent wording for signers vs. observers.The comment references “signers” but the code is about “observers.” Update this to avoid confusion, especially when tracking chain observer creation.
212-212
: Confirm future usage ofmissesObserver
for BTC.Currently the test ensures we do not want a BTC observer in V1. If partial migration occurs in v2, ensure no partial references or stubs remain.
429-437
: ExpandmockZetacore
coverage.Currently only
PostVoteGasPrice
is mocked. If the orchestrator or observers rely on additional Zetacore calls, consider mocking them in future tests to prevent partial coverage or silent failures.zetaclient/chains/bitcoin/signer/signer.go (1)
208-224
: Maintain consistent validation oftxSize
.
The bounding logic fortxSize
is valid, though further logging might help clarify boundary values for watchers and operators.zetaclient/chains/bitcoin/rpc/rpc_live_test.go (1)
418-418
: Consider fallback for fee retrieval errors.
Usage ofbtc.GetRecentFeeRate
is consistent with the code refactor. However, if the remote call fails, consider implementing a fallback or additional logging to handle unexpected missing fee data.zetaclient/orchestrator/orchestrator.go (1)
380-381
: Segregation of Bitcoin logic.
Skipping BTC scheduling here with a comment referencing Orchestrator V2 is acceptable. Ensure thorough coverage in V2 to avoid missing any corner cases once the old path is fully deprecated.
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (45)
cmd/zetaclientd/inbound.go
(1 hunks)cmd/zetaclientd/start.go
(2 hunks)e2e/e2etests/test_bitcoin_deposit_and_call_revert.go
(1 hunks)e2e/e2etests/test_bitcoin_deposit_and_call_revert_with_dust.go
(1 hunks)e2e/e2etests/test_bitcoin_deposit_call.go
(3 hunks)e2e/e2etests/test_bitcoin_donation.go
(1 hunks)e2e/e2etests/test_bitcoin_std_deposit.go
(2 hunks)e2e/e2etests/test_bitcoin_std_deposit_and_call.go
(1 hunks)e2e/e2etests/test_bitcoin_std_memo_inscribed_deposit_and_call.go
(2 hunks)e2e/runner/bitcoin.go
(6 hunks)go.mod
(2 hunks)pkg/chains/chain.go
(2 hunks)pkg/scheduler/opts.go
(1 hunks)pkg/scheduler/scheduler.go
(3 hunks)pkg/ticker/ticker.go
(3 hunks)zetaclient/chains/base/observer.go
(1 hunks)zetaclient/chains/bitcoin/bitcoin.go
(1 hunks)zetaclient/chains/bitcoin/common/errors.go
(1 hunks)zetaclient/chains/bitcoin/common/fee.go
(1 hunks)zetaclient/chains/bitcoin/common/fee_test.go
(1 hunks)zetaclient/chains/bitcoin/common/tx_script.go
(1 hunks)zetaclient/chains/bitcoin/common/tx_script_test.go
(31 hunks)zetaclient/chains/bitcoin/common/utils.go
(1 hunks)zetaclient/chains/bitcoin/observer/inbound.go
(11 hunks)zetaclient/chains/bitcoin/observer/inbound_test.go
(9 hunks)zetaclient/chains/bitcoin/observer/observer.go
(6 hunks)zetaclient/chains/bitcoin/observer/outbound.go
(4 hunks)zetaclient/chains/bitcoin/observer/rpc_status.go
(1 hunks)zetaclient/chains/bitcoin/observer/witness.go
(5 hunks)zetaclient/chains/bitcoin/observer/witness_test.go
(2 hunks)zetaclient/chains/bitcoin/rpc/rpc_live_test.go
(4 hunks)zetaclient/chains/bitcoin/signer/signer.go
(10 hunks)zetaclient/context/chain.go
(2 hunks)zetaclient/context/context.go
(1 hunks)zetaclient/maintenance/shutdown_listener_test.go
(1 hunks)zetaclient/orchestrator/bootstrap.go
(2 hunks)zetaclient/orchestrator/bootstrap_test.go
(8 hunks)zetaclient/orchestrator/contextupdater.go
(0 hunks)zetaclient/orchestrator/orchestrator.go
(2 hunks)zetaclient/orchestrator/v2_bootstrap.go
(1 hunks)zetaclient/orchestrator/v2_bootstrap_test.go
(1 hunks)zetaclient/orchestrator/v2_orchestrator.go
(1 hunks)zetaclient/orchestrator/v2_orchestrator_test.go
(1 hunks)zetaclient/testutils/mocks/chain_params.go
(1 hunks)zetaclient/testutils/testlog/log.go
(1 hunks)
💤 Files with no reviewable changes (1)
- zetaclient/orchestrator/contextupdater.go
✅ Files skipped from review due to trivial changes (5)
- zetaclient/chains/bitcoin/common/errors.go
- zetaclient/chains/bitcoin/common/fee.go
- e2e/e2etests/test_bitcoin_deposit_and_call_revert.go
- zetaclient/chains/bitcoin/common/tx_script.go
- zetaclient/chains/bitcoin/common/fee_test.go
🧰 Additional context used
📓 Path-based instructions (38)
cmd/zetaclientd/inbound.go (1)
Pattern **/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.
pkg/chains/chain.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.
zetaclient/maintenance/shutdown_listener_test.go (1)
Pattern **/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.
zetaclient/chains/bitcoin/common/utils.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_call.go (1)
Pattern **/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.
pkg/scheduler/opts.go (1)
Pattern **/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.
pkg/ticker/ticker.go (1)
Pattern **/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.
e2e/e2etests/test_bitcoin_deposit_and_call_revert_with_dust.go (1)
Pattern **/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.
zetaclient/chains/bitcoin/observer/witness_test.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.
zetaclient/orchestrator/orchestrator.go (1)
Pattern **/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.
zetaclient/orchestrator/bootstrap.go (1)
Pattern **/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.
zetaclient/chains/bitcoin/observer/rpc_status.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.
zetaclient/orchestrator/v2_bootstrap_test.go (1)
Pattern **/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.
pkg/scheduler/scheduler.go (1)
Pattern **/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.
zetaclient/testutils/testlog/log.go (1)
Pattern **/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.
zetaclient/context/context.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_memo_inscribed_deposit_and_call.go (1)
Pattern **/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.
cmd/zetaclientd/start.go (1)
Pattern **/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.
zetaclient/context/chain.go (1)
Pattern **/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.
zetaclient/chains/bitcoin/rpc/rpc_live_test.go (1)
Pattern **/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.
zetaclient/chains/base/observer.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.
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/orchestrator/bootstrap_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/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/outbound.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/testutils/mocks/chain_params.go (1)
Pattern **/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.
zetaclient/chains/bitcoin/common/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/bitcoin/bitcoin.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/orchestrator/v2_orchestrator_test.go (1)
Pattern **/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.
zetaclient/orchestrator/v2_orchestrator.go (1)
Pattern **/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.
📓 Learnings (5)
zetaclient/chains/bitcoin/observer/witness_test.go (1)
Learnt from: ws4charlie
PR: zeta-chain/node#2899
File: zetaclient/chains/bitcoin/observer/inbound.go:366-371
Timestamp: 2024-11-12T13:20:12.658Z
Learning: The `bitcoin.CalcDepositorFee` function is covered by live tests.
zetaclient/chains/bitcoin/rpc/rpc_live_test.go (1)
Learnt from: ws4charlie
PR: zeta-chain/node#2899
File: zetaclient/chains/bitcoin/observer/inbound.go:366-371
Timestamp: 2024-11-12T13:20:12.658Z
Learning: The `bitcoin.CalcDepositorFee` function is covered by live tests.
zetaclient/chains/bitcoin/observer/inbound.go (2)
Learnt from: ws4charlie
PR: zeta-chain/node#3025
File: zetaclient/chains/bitcoin/observer/event.go:110-115
Timestamp: 2024-11-12T13:20:12.658Z
Learning: In the `DecodeEventMemoBytes` function, a non-nil `memoStd` with a non-nil `err` indicates that the memo bytes are well-formatted as a memo but contain improper data.
Learnt from: ws4charlie
PR: zeta-chain/node#2899
File: zetaclient/chains/bitcoin/observer/inbound.go:131-132
Timestamp: 2024-11-12T13:20:12.658Z
Learning: ObserveInbound coverage will be improved in future refactor.
zetaclient/chains/bitcoin/observer/outbound.go (1)
Learnt from: ws4charlie
PR: zeta-chain/node#2899
File: zetaclient/chains/bitcoin/observer/inbound.go:131-132
Timestamp: 2024-11-12T13:20:12.658Z
Learning: ObserveInbound coverage will be improved in future refactor.
zetaclient/chains/bitcoin/observer/inbound_test.go (1)
Learnt from: ws4charlie
PR: zeta-chain/node#2899
File: zetaclient/chains/bitcoin/observer/inbound.go:366-371
Timestamp: 2024-11-12T13:20:12.658Z
Learning: The `bitcoin.CalcDepositorFee` function is covered by live tests.
🔇 Additional comments (110)
zetaclient/context/chain.go (2)
67-69
: Ensure unlock is called in all code paths for robust concurrency.The use of a mutex here is appropriate. Confirm that any potential error paths or early returns do not bypass
cr.mu.Unlock()
.
148-150
: Pass-through logging fields implemented.This convenience method properly delegates to the underlying raw chain’s logging fields. Looks good and keeps the code DRY.
pkg/chains/chain.go (1)
11-12
: Import statements properly structured.Importing the logging definitions from
zetaclient/logs
is consistent with the rest of the codebase.zetaclient/chains/bitcoin/observer/rpc_status.go (3)
11-12
: Public function name and doc comment alignment look good.
The exported function now has an appropriate doc comment that starts with the method name and clearly describes its purpose. No issues found here.
15-15
: Error wrapping is clear and consistent.
Usingerrors.Wrap
adds valuable context. Keep the approach consistent across the codebase.
20-20
: Solid error handling.
Likewise, continuing to wrap errors here ensures the origin of failures remains transparent.zetaclient/orchestrator/v2_bootstrap.go (3)
16-20
: Validate early chain checks.
Ifchain.IsBitcoin()
is false, returning an error is correct. This is a suitable guard clause that prevents confusion and misconfiguration.
27-31
: Revisit error type inerrSkipChain
.
UsingerrSkipChain
is fine, but ensure the broader orchestration logic also properly handles chain skipping without leaving orphaned resources.
53-65
: Check concurrency approach for the observer.
Review if the observer’s internal logic spawns routines or uses any concurrency that might require careful orchestration with the new orchestrator.cmd/zetaclientd/start.go (2)
157-162
: Validate constructor parameters forDependencies
.
If any required fields (likeZetacore
) are missing or misconfigured, consider a pre-check, returning a descriptive error. This will aid debugging.
172-173
: Evaluate orchestrator V2 lifecycle.
Adding the orchestrator V2 tograceful.AddService
is correct. Confirm that any externally spawned goroutines and resources within V2 are also properly shut down.zetaclient/chains/bitcoin/bitcoin.go (7)
48-52
: Double-check concurrency safety.
The function callsb.observer.Observer.Start()
but does not evidently manage concurrency around shared states. Confirm that internal observer structures are thread-safe.
53-63
: Check subscription error handling.
The code logs errors when creating the new block subscriber fails. Ensure the app’s top-level error handling can gracefully degrade if the subscription fails.
64-91
: Keep schedulers well-defined.
Registering multiple intervals with specialized skip conditions is good practice. Confirm that overlapping intervals (inbound vs. outbound) do not create race conditions on shared data.
109-113
: Scrutinize block-based scheduling.
Usingscheduler.BlockTicker(newBlockChan)
is an effective approach, but confirm that blocking or slow tasks do not lead to queue buildup.
126-130
: Enhance documentation.
The scheduleCCTX constraints are well-described in comments. This clarity is helpful for new devs.
153-160
: Validate chain ID usage.
In the loop, line 161 logs a mismatch ifparams.ReceiverChainId != chainID
. Ensure inbound chain ID checks are consistent across the codebase.
208-224
: Validate chain param updates.
updateChainParams
refreshes chain parameters from the updated context. Confirm that concurrency is not overwriting old data structures inobserver
.zetaclient/orchestrator/v2_orchestrator.go (5)
124-125
: Confirm usage oferrSkipChain
.
This sentinel error merges seamlessly with orchestrator logic. Validate usage across other chain bootstraps to avoid partial states.
203-209
: SafeguardhasChain
concurrency.
Currently,hasChain
obtains anRLock
for read access. Confirm no chain updates occur outside the orchestrator that might need synchronization or atomic references.
233-247
: Encapsulate chain stopping logic.
removeChain
callsStop()
on the observer signer. If the chain implementer changes the stop signature, ensure no partial states remain unclosed.
249-271
: Optimize chain removal.
removeMissingChains
uses a straightforward approach. For large-scale environments, a more efficient set difference approach may be beneficial, but this is acceptable for typical chain counts.
273-290
: Fail fast on missing dependencies.
validateConstructor
ensures the orchestrator cannot be misconfigured. This is an excellent pattern to prevent runtime errors.zetaclient/chains/bitcoin/observer/inbound.go (3)
17-17
: Use the common package consistently.
Importingcommon
for Bitcoin-specific logic looks structured. Ensure references tocommon
are consistently used throughout the observer codebase to avoid confusion.
183-183
: Confirm depositor fee assumptions.
common.CalcDepositorFee
is invoked here. Validate that fee logic aligns with chain updates (e.g., changes in dust threshold or transaction priorities).
223-223
: Confirm block re-scan fallback behavior.
IfGetBtcEvent
fails for a single transaction, the code returns an error, prompting a re-scan. Ensure this re-scan occurs so one failing transaction does not block the entire block’s inbound processing.zetaclient/chains/bitcoin/observer/observer.go (5)
21-21
: Keep imports aligned with the newcommon
package structure
By importingcommon
, you're adhering to the recent restructuring. This promotes clarity and centralizes shared utilities.
136-136
: Good use of error wrapping
This statement provides valuable context to help diagnose issues quickly.
141-141
: Error wrapping is consistent
Continuing the consistent approach of wrapping errors helps with deeper debugging contexts.
197-197
: Fee conversion logic appears correct
This line demonstrates proper adaptation to thecommon.FeeRateToSatPerByte
utility, ensuring consistent fee conversions.
381-381
: Transparent fee rate retrieval
This line properly delegates fee rate acquisition to a centralized method in thecommon
package, improving maintainability.zetaclient/chains/bitcoin/observer/outbound.go (4)
17-17
: Consistent import usage
Importing thecommon
package aligns with the refactored structure, maintaining uniform references.
382-382
: Validate return type
common.GetSatoshis
processes floating amounts into integer satoshis. Ensure subsequent operations handle potential rounding issues or remainders gracefully.
572-572
: Maintain flexible decoding
common.DecodeTSSVout
is well-named; confirm that any future expansions to script types do not break backward compatibility.
626-626
: Ensure canceled vout consistency
Decoding withcommon.DecodeTSSVout
for a canceled transaction is correct. Confirm that no additional checks on dust or edge cases are necessary if partial refunds are canceled.zetaclient/context/context.go (1)
11-11
: Improved clarity in error message
Changing the text to “unable to get AppContext” is more direct, helping developers quickly identify missing context usage.zetaclient/testutils/testlog/log.go (8)
1-2
: Structured package declaration
The package nametestlog
clearly indicates its intended role in providing logging utilities for tests.
3-10
: Selective imports
All imported packages appear relevant to the logging buffer and test environment. No concerns at this stage.
12-15
: Central logger struct
Embeddingzerolog.Logger
provides flexible and concise custom logging for tests. Storing a buffer pointer allows introspection.
17-20
: Concurrent buffer struct
Maintaining a dedicatedbytes.Buffer
protected bysync.RWMutex
is a neat approach to thread-safe log capture.
22-32
: Constructor method
Instantiating a multiwriter with both a test writer and the buffer ensures logs appear in standard test outputs and are concurrently captured. This helps in advanced test analysis.
34-36
: String retrieval
Providing aString()
method to the mainLog
struct simplifies log content retrieval for assertions or debugging.
38-43
: Thread-safe writes
Locking for writes protects the buffer from concurrent modifications, ensuring log integrity.
45-50
: Thread-safe read
Locking for reads prevents race conditions. This design choice is well-suited for test logs, even under parallel test execution.zetaclient/chains/bitcoin/common/utils.go (1)
1-1
: Refactored package name
Switching frombitcoin
tocommon
clarifies the scope of shared functionality and aligns with the multi-chain structure.e2e/e2etests/test_bitcoin_donation.go (1)
12-12
: Import path update appears consistent.The updated import path reflects a centralized consolidation of Bitcoin functionalities under the
common
package, promoting clearer code organization.pkg/scheduler/opts.go (2)
32-32
: Enhanced clarity in the skipper function comment.Documenting the skipper behavior (that
true
skips the task) is helpful for maintainers and clarifies task flow.
39-42
: Immediate interval update ensures consistency.Calling
intervalUpdater()
to setopts.interval
right away aligns the initial interval setting with the updated logic. Ensure thread-safety if multiple goroutines invoke this option concurrently.e2e/e2etests/test_bitcoin_std_deposit_and_call.go (1)
13-13
: Aligned import path with refactored Bitcoin code.Switching to the
common
package unifies Bitcoin utilities and aligns with ongoing modularization efforts.e2e/e2etests/test_bitcoin_deposit_call.go (2)
12-12
: Refactored import path.Moving to
common
fosters more maintainable Bitcoin-related code.
48-48
: ReplacingGetSatoshis
reference for clarity.Adopting
common.GetSatoshis(amount)
improves readability, reflecting the refactoring choices of the newcommon
package. Ensure all references to this function are consistently updated across tests.zetaclient/testutils/mocks/chain_params.go (1)
35-35
: Reassess default ticker value.Previously set to zero, the
WatchUtxoTicker
is now set to 1. Ensure this increment does not negatively affect workflow or system resources. Consider verifying if a non-zero default value causes unintended overhead in test environments.e2e/e2etests/test_bitcoin_std_memo_inscribed_deposit_and_call.go (2)
13-13
: Modular import path transition acknowledged.Switching from the main
bitcoin
package to thecommon
sub-package is consistent with the ongoing refactoring. This enhances maintainability and keeps common logic centralized.
56-56
: Validate depositor fee usage and error handling.Here, the
common.DefaultDepositorFee
is converted to satoshis. Ensure this default aligns with operational requirements and that any errors in retrieval are handled gracefully beyond merely logging.e2e/e2etests/test_bitcoin_std_deposit.go (2)
13-13
: Unified Bitcoin logic import recognized.Importing from the
common
package centralizes Bitcoin utility functions, promoting code reuse. This is a good step toward a cleaner architecture.
57-57
: Check numeric conversions and ensure consistent usage.Converting floats to satoshis can cause rounding discrepancies. Confirm that the
GetSatoshis
function correctly handles edge cases (e.g., extremely small amounts) to avoid rounding errors.e2e/e2etests/test_bitcoin_deposit_and_call_revert_with_dust.go (1)
13-13
: Refactoring import path for improved consistency.Switching to the
common
package matches the broader shift across the codebase. This maintains consistency and simplifies future changes in Bitcoin processing logic.zetaclient/orchestrator/v2_bootstrap_test.go (4)
19-23
: Smooth test initialization.The initialization of the test suite and orchestrator setup is well-structured. The approach of creating a new test suite (
ts := newTestSuite(t)
) is clear and fosters maintainable testing patterns.
28-30
: Configuration update usage looks solid.Assigning the
btcConfig
tocfg.BTCChainConfigs[chains.BitcoinMainnet.ChainId]
is straightforward and keeps the Bitcoin-specific logic isolated.
57-67
: Helper function for task grouping is concise.The
tasksHaveGroup
function efficiently checks for group membership, contributing to clear test readability.
69-78
: Mock setup for Bitcoin calls is clean.The
mockBitcoinCalls
function properly configures the mocked environment, making the test deterministic and easier to maintain.pkg/scheduler/scheduler.go (2)
147-151
: Informative logging for group stop operation.Logging the count of tasks being stopped in a group gives clear operational insights and is beneficial for troubleshooting.
181-187
: Getter methods for Task struct are straightforward.The
Group()
andName()
methods improve code clarity by exposing task properties succinctly.pkg/ticker/ticker.go (2)
142-142
: Validate concurrency safety fortask
invocation.Inside the loop, if multiple ticks occur sequentially in quick succession, ensure the method enforces concurrency controls on
task
usage (if thetask
is not inherently thread-safe).
217-219
: Use consistent checks fort.ticker != nil
before stopping.Since
t.ticker
is conditionally created, ensure code paths always guard calls that referencet.ticker
. This helps prevent inadvertent nil-pointer dereferences if the ticker was not successfully started.zetaclient/chains/bitcoin/observer/witness.go (3)
13-13
: Confirm dependencies incommon
package exist and are tested.With the new import reference to
common
, ensure that all dependencies (e.g.,common.DepositorFeeCalculator
) are properly tested and documented, preventing regressions in deposit fee logic.
140-140
: Avoid potential nil index ontx.Vout[1]
.Although the code checks
len(tx.Vout) < 2
before referencingtx.Vout[1]
, ensure there are no parallel changes that might skip this early check.
162-162
: Guardscript
usage intryExtractInscription
.In the loop,
script
can benil
if decoding the final witness element fails. You have a check to continue, which is good. Just confirm no panics arise in subsequent logic.zetaclient/orchestrator/v2_orchestrator_test.go (3)
1-28
: Keep test imports minimal and cohesive.The import set is clean. Just ensure no redundant test dependencies are introduced to maintain lean test coverage.
94-105
: Maintain consistent chain usage indefaultChainsWithParams
.
defaultChainsWithParams
includes both EVM and non-EVM chains. Ensure the test suite does not inadvertently test unsupported chains or create confusion in chain-specific logic.
208-252
: Handle partial/empty chain lists innewAppContext
.If chainList is empty,
Update(...)
might skip certain validations. Consider logging or returning an error for an empty chain set.zetaclient/orchestrator/bootstrap_test.go (4)
9-9
: Check for redundant or missing imports.The updated import block is straightforward. Confirm no extraneous imports remain and that new mocks or testing libraries remain necessary.
109-109
: Maintain consistent runtime chain toggling coverage.Re-enabling Ethereum after prior removal is good coverage. Also consider verifying chain-dependent resources remain consistent, e.g., signers or config references.
154-154
: EvaluatemockZetacore
usage across tests.Centralizing Zetacore mocks in one helper function is beneficial. Ensure each test scenario that requires
PostVoteGasPrice
either sets a proper expectation or clarifies if the call is not expected.
417-418
: Split out helper logic from test assertion code.The
hasObserver
function callst.Helper()
, which is excellent for clarity. If it grows more complex, consider a dedicated test utility package.zetaclient/orchestrator/bootstrap.go (1)
139-140
: Ensure graceful fallback for residual Bitcoin flows.
By continuing here, you skip Bitcoin signers for orchestrator V1. Ensure that any residual or legacy Bitcoin flows gracefully transition to orchestrator V2, or provide a clear error path if orchestrator V2 is unavailable.zetaclient/chains/bitcoin/signer/signer.go (9)
27-27
: Modular usage ofcommon
package acknowledged.
Switching tocommon
fosters improved clarity and reusability across Bitcoin-related functionality.
102-109
: Check for integer overflow on large amounts.
Whilecommon.GetSatoshis()
is helpful, consider verifying that large floats do not overflow when converted to satoshis.
169-169
: Fee calculation is clear.
MultiplyinggasPrice.Uint64()
bycommon.OutboundBytesMax
is straightforward and aligns well with prior logic. No immediate concerns.
245-245
: Re-check theprevOuts[ix].Amount
for edge cases.
Defensive checks against zero or negative amounts can prevent potential underflows in corner cases.
309-309
: Cross-module type usage is consistent.
Injectingobserver *observer.Observer
is a reasonable pattern to keep chain details together for BTC sign operations.
338-338
: Minimal overhead in retrieving chain object.
Acquiring the chain fromobserver
ensures alignment with the local chain context.
373-373
: Synergy withFeeRateToSatPerByte
.
Good to see a consistent method for relay fee handling.
402-402
: Consistent function signature extension.
The extended function signature withobserver
parameter properly centralizes chain data.
449-449
: Broadcast record introduced.
Storing broadcasted TX inobserver
helps with concurrency and indexing in the new orchestrator design.e2e/runner/bitcoin.go (6)
26-26
: Clarified aliaszetabtc
.
Renaming the import alias to distinctly represent thecommon
package fosters better readability.
103-103
: Ensure deposit fee is consistently updated.
Appendingzetabtc.DefaultDepositorFee
ensures deposit amounts remain correct. Keep the default fee synchronized with any global parameters.
151-151
: Inline arithmetic.
Combining1.15 + zetabtc.DefaultDepositorFee
is straightforward. Consider verifying that these default additions remain aligned with the expected test flows.
244-244
: Satoshis conversion logic.
Double-check for potential floating-point boundary conditions. Overall, the call tozetabtc.GetSatoshis
is consistent with prior logic.
354-354
: Uniform usage ofGetSatoshis
.
This confirms a unified approach for inscriptions as well. Maintain consistent usage across all deposit and inscription flows.
415-415
: Decoding script is well-rationalized.
Decoupling script decoding tozetabtc.DecodeScriptP2WPKH
standardizes the approach for P2WPKH addresses.zetaclient/chains/base/observer.go (1)
169-175
: Early return avoids redundant updates.
The addition of a parameter-equality check eliminates needless churn. This ensures improved stability and cleaner logs.zetaclient/chains/bitcoin/rpc/rpc_live_test.go (3)
21-21
: Migration tobtc
alias looks consistent.
No concerns here; referencing thecommon
package under thebtc
alias is in line with the ongoing refactor.
366-366
: Confirm edge-case handling.
The switch tobtc.CalcBlockAvgFeeRate
is valid. Ensure that large or small block sizes and edge cases (e.g., zero transactions) are addressed in the function’s implementation.
599-611
: Testing different network parameters.
Lines 599-611 demonstrate correct usage ofbtc.CalcDepositorFee
under different Bitcoin network parameters. Validating deposit fees across MainNet, RegressionNet, etc., is a good practice.zetaclient/orchestrator/orchestrator.go (1)
202-202
: Chain parameter assignment is clear.
Straightforward parameter injection for the observer. Check whether any additional safety checks are needed ifchain.Params()
returns unexpected values.zetaclient/chains/bitcoin/observer/inbound_test.go (5)
19-19
: New import path is aligned with consolidation efforts.
Switching frombitcoin
tobitcoin/common
refines the structure and improves maintainability.
35-35
: Mocking deposit fee calculator.
The updated return type,common.DepositorFeeCalculator
, aligns with the new package structure. The mock approach looks straightforward and test-friendly.
Line range hint
58-122
: Refactored fee rate calculations.
These lines consistently usecommon.CalcBlockAvgFeeRate
. Ensure that any potential integer overflow or type conversion issues are handled inside this function, especially for large blocks or unusual transaction fees.Also applies to: 147-147
286-286
: Inline deposit fee assignment.
Switch tocommon.DepositorFee
withclientcommon.BTCOutboundGasPriceMultiplier
is noted. Continue verifying that the multiplier is up-to-date with any dynamic fee adjustments.
Line range hint
372-417
: Consistent usage ofcommon.DecodeOpReturnMemo
.
The new function calls for decoding OP_RETURN data appear logical and consistent. Verify that long or malformed inputs are handled without panics.zetaclient/chains/bitcoin/common/tx_script_test.go (7)
Line range hint
1-20
: Rename tocommon_test
and updated imports.
The package rename better reflects the shared nature of this code. The reference to the test data directory is also properly maintained.
Line range hint
33-128
: Decoding various P2TR/P2WSH scripts.
The test coverage for decoding logic is quite comprehensive. Be sure to keep an eye out for new script types or any consensus rule changes that could break assumptions here.
Line range hint
145-328
: Expanded tests for P2WPKH, P2SH, P2PKH decodes.
These updates consistently callcommon.DecodeScript*
functions. The guard clauses and error checks appear robust.
Line range hint
372-417
: OP_RETURN memo decoding.
Decoding logic is thorough and accounts for multiple OP_PUSHDATA scenarios. This helps ensure that complex memos or on-chain data are properly parsed without corruption.
Line range hint
495-561
: Decode TSS vout approach.
These lines ensure that different script types (P2TR, P2WSH, P2WPKH, P2SH, P2PKH) can still decode TSS vout data. The approach is clean and consistent.
Line range hint
580-613
: Error handling withinDecodeTSSVout
.
Negative amounts, invalid chain IDs, or mismatched addresses now produce readable error messages. This is good for debugging.
Line range hint
626-695
: General script decoding.
The extended coverage for unusual or truncated scripts is commendable. This robust handling will prevent silent failures when new script patterns or malformed data are encountered.zetaclient/chains/bitcoin/observer/witness_test.go (1)
13-13
: LGTM! Import path update aligns with package restructuring.The change to use the new
bitcoin/common
package is consistent with the PR's objective of consolidating Bitcoin-related functionalities.go.mod (1)
166-166
: LGTM! Dependencies now directly used.The transition of these dependencies from indirect to direct usage aligns with the PR's integration of Prometheus metrics. The versions are maintained, ensuring stability.
Run the following script to verify the latest stable versions of the dependencies:
Also applies to: 252-253
✅ Verification successful
Dependencies are correctly transitioned and actively used in the codebase
The verification confirms that:
github.com/google/uuid
is actively used inzetaclient/orchestrator/v2_bootstrap_test.go
andpkg/scheduler/scheduler.go
- Prometheus-related packages are extensively used across multiple files in the
zetaclient
directory- The transition from indirect to direct dependencies is justified by their actual usage in the codebase
- The version v1.6.0 of uuid package was already present in the previous go.mod, maintaining stability
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Check for latest versions of the direct dependencies # Check latest versions on pkg.go.dev for pkg in "github.com/google/uuid" "github.com/prometheus/client_model" "github.com/prometheus/common"; do echo "Checking $pkg..." curl -s "https://pkg.go.dev/$pkg" | grep -A 1 "Latest version" doneLength of output: 851
Script:
#!/bin/bash # Let's verify if these dependencies are actually used in the codebase # and check their transition from indirect to direct dependencies # First, let's check the old go.mod state to confirm they were indirect git show HEAD^:go.mod | grep -A 1 "google/uuid" # Then verify actual usage of these packages in the code echo "Checking usage of github.com/google/uuid:" rg "github.com/google/uuid" --type go # Check for prometheus dependencies usage echo -e "\nChecking usage of prometheus packages:" rg "github.com/prometheus" --type goLength of output: 1363
Uint64("outbound.earliest_pending_nonce", cctxList[0].GetCurrentOutboundParam().TssNonce). | ||
Msg("Schedule CCTX: lookahead reached") | ||
return nil | ||
case !b.proc.IsOutboundActive(outboundID): |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The original condition nonce%interval == zetaHeight%interval
allows the chain params to control the retry interval on pending CCTXs.
For example:
Given CCTX nonce=1
and interval = 3
, the keysign will be retried on zeta heights 1, 4, 7, 10, 13, etc.
. Removing the condition will be like using a constant retry interval of 1
?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Indeed. Let's take BTC as an example:
Based on network params, the interval is 10 (chain id 8332).
- nonce % 10 is 0...9; let's say it's equal to 7 (just an example)
- The probability of
zetaHeight % 10 == 7
is 1/10 (1/interval
)
This effectively means that:
- Best case we'll schedule outbound cctx in the current block
- Avg case we'll schedule outbound cctx in the next FIVE blocks
- Worst-case: NINE blocks.
5 or 9 blocks is ~30s
to ~50s
just to decide on cctx scheduling. Each retry will also happen in the next X blocks.
Also, currently, we schedule only ONE cctx per BTC scheduler tick => per one zeta block
node/zetaclient/orchestrator/orchestrator.go
Line 547 in ef4c1d4
// schedule at most one keysign per ticker
I don't see any obstacles to firing outbounds as soon as possible. We only need to ensure that we don't have congestion in TSS signatures AND we sign one cctx only once and cache it in memory.
Maybe I am missing something, correct me if I'm wrong 🙏 cc @lumtis @gartnera @brewmaster012
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Don't see any obstacle to this change. What do you think if we try setting the interval
in Bitcoin mainnet chain params to 1
to exercise before making it a constant? It has the same effect.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't see any obstacles to firing outbounds as soon as possible. We only need to ensure that we don't have congestion in TSS signatures AND we sign one cctx only once and cache it in memory.
Don't see an issue here
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Looks good, left minor comment.
# Conflicts: # zetaclient/orchestrator/orchestrator.go
!!!WARNING!!! Be very careful about using 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 Pay extra attention to the way |
E2E fail locally due to unknown websocket issues: zetaclient
node/zetaclient/orchestrator/orchestrator.go Line 301 in 87820c3
zetacore
|
UPD Found the issue: cosmos WS client doesn't support multiple subscription channels per event. So if we have multiple https://github.com/cometbft/cometbft/blob/main/rpc/client/http/http.go#L688
|
# Conflicts: # cmd/zetaclientd/start.go
This PR adds a new orchestrator (V2) service to zetaclient. V2 will co-exist with V1 until all types of chains will be refactored (BTC, EVM, SOL, TON).
The gist of V2 can be viewed in
bitcoin.go
: https://github.com/zeta-chain/node/pull/3332/files#diff-c32c755943473aac40e3fbf800f1eae43a8482a9aef0277fc04d56c7309e0e95R48⚙️ Note that each method has structured logs, automatic tickers, panic recovery, and Prometheus metrics
Orchestrator, Scheduler, and other common logic will be streamlined further to a common denominator in the following PRs
ObserverSigner
, move BTC orchestration therenonce%interval == zetaHeight%interval
(=> faster outbounds)
bitcoin/common
pkg (fixes import cycle)testingSuite
framework for easy unit/feature tests in V2testlog
package for log-based assertions (race-free)Closes #3303
Closes #2532
Closes #2790
Summary by CodeRabbit
Based on the comprehensive summary, here are the release notes:
New Features
Bug Fixes
Refactoring
Chores