Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs(zetaclient): add more function and package documentation #2321

Merged
merged 18 commits into from
Jun 26, 2024

Conversation

lumtis
Copy link
Member

@lumtis lumtis commented Jun 5, 2024

Description

  • Add missing documentation for some functions
  • Add documentation for the packages
  • Add some TODO(revamp) entries to track as a chunk several code improvement to do in the ZetaClient

Summary by CodeRabbit

  • New Features

    • Introduced new signer functionality for transactions using grants.
    • Added extensive metrics functionalities for better system tracking.
  • Bug Fixes

    • Improved handling and validation of inbound and outbound transactions for Bitcoin and EVM chains.
  • Documentation

    • Enhanced documentation for ZetaClient functions and packages.
    • Added comments and TODOs for future improvements and refactoring.
  • Refactor

    • Restructured and simplified various observer, signer, and utility functions across Bitcoin and EVM chains.
  • Tests

    • Included test coverage placeholders to ensure comprehensive future testing.

Copy link

github-actions bot commented Jun 5, 2024

!!!WARNING!!!
nosec detected in the following files: zetaclient/chains/bitcoin/utils.go

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

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

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

@github-actions github-actions bot added the nosec label Jun 5, 2024
Copy link
Contributor

@skosito skosito left a comment

Choose a reason for hiding this comment

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

looks good, do we want comment on all packages and public functions or? i guess to be used with go doc tools?

zetaclient/authz/authz_signer.go Show resolved Hide resolved
zetaclient/authz/authz_signer.go Show resolved Hide resolved
zetaclient/chains/bitcoin/observer/observer.go Outdated Show resolved Hide resolved
zetaclient/chains/bitcoin/observer/outbound.go Outdated Show resolved Hide resolved
Copy link
Contributor

@ws4charlie ws4charlie left a comment

Choose a reason for hiding this comment

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

looks good. Just some clarifications on the files that we would like group logics into.

@lumtis
Copy link
Member Author

lumtis commented Jun 25, 2024

Waiting on #2359 first since would introduce many conflict

@lumtis lumtis requested a review from swift1337 as a code owner June 26, 2024 14:39
Copy link
Contributor

coderabbitai bot commented Jun 26, 2024

Important

Review skipped

Review was skipped due to path filters

Files ignored due to path filters (1)
  • changelog.md is excluded by none and included by none

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The series of changes enhance the ZetaClient by introducing comprehensive refactoring across multiple files, focusing on improving documentation, adding new functionalities, reorganizing code for clarity, and enhancing the observance of inbound and outbound transactions. No changes were made to the declarations of exported or public entities in most test files.

Changes

Files/Groups Change Summary
changelog.md Improved documentation for functions and packages in ZetaClient.
zetaclient/authz/authz_signer.go Introduced a new signer object for transactions using grants, with functionalities for managing and retrieving signers.
zetaclient/authz/authz_signer_test.go Added package declaration, including tests for package coverage (currently empty).
zetaclient/chains/bitcoin/observer/... Refactored Bitcoin chain watching processes, added comments, methods restructuring, and utility functions.
zetaclient/chains/bitcoin/signer/signer.go Added comments, reorganized fields, updated method signatures, added new Broadcast and TryProcessOutbound methods.
zetaclient/chains/bitcoin/utils.go Added utility functions: PrettyPrintStruct, GetSatoshis, and round.
zetaclient/chains/evm/observer/... Refactored EVM chain watching functionalities, added comments and TODOs for future refactoring.
zetaclient/chains/evm/signer/signer.go Added various new functions, comments, field renaming, and simplifications for EVM signing and processing outbounds.
zetaclient/chains/interfaces/interfaces.go Added package comment describing the interfaces package purpose.
zetaclient/compliance/compliance.go Added package comment detailing the compliance functionalities related to cross-chain compliance.
zetaclient/config/config.go Updated with new package documentation, constants for filenames, folders, additional functions for loading compliance data, and path handling.
zetaclient/config/config_chain.go Added ABI strings, new initialization functions, and default configurations for Bitcoin regnet and EVM chains.
zetaclient/context/zetacore_context.go Added new methods for ZetacoreContext struct to retrieve keygen, TSS signing functionalities, and various metadata.
zetaclient/metrics/metrics.go Introduced new metrics functionalities, including gauges and counters for system tracking, a Metrics struct, and functions to manage metrics server operations.
zetaclient/tss/tss_signer.go Enhanced functionality for TSS signer operations, including TSS key creation, server setup, TSS validation, address generation, key share verification, and testing.

Poem

In the land of Zeta and chains so bright,
Signers and watchers come to light.
With code refined and functions clear,
Metrics hum, transactions steer.
From Bitcoin's heart to EVM's grace,
ZetaClient moves with agile pace.
🌟✨ In this grand code's embrace, let's trace! ⚙️🌐


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 39

Outside diff range and nitpick comments (26)
zetaclient/hsm/hsm_signer.go (4)

Line range hint 14-26: Consider adding detailed error messages for better debugging.

The function returns immediately on errors, which is good. However, adding more detailed error messages could help in identifying issues more quickly during debugging.

- return
+ return nil, errors.Wrap(err, "failed to create keyring")

Line range hint 28-38: Enhance error handling with detailed error messages.

Like the Sign function, consider adding more detailed error messages to improve debugging capabilities.

- return nil, err
+ return nil, errors.Wrap(err, "failed to generate new key")

Line range hint 40-52: Add detailed error messages for clarity.

The function would benefit from more detailed error messages to aid in troubleshooting, similar to previous functions.

- return nil, nil, err
+ return nil, nil, errors.Wrap(err, "failed to retrieve key")

Line range hint 163-171: Enhance the error message to specify missing environment variables.

The error message in GetPKCS11Config could be more descriptive by specifying which environment variable(s) are missing. This would aid in quicker configuration troubleshooting.

- err = errors.New("error getting pkcs11 config, make sure env variables are set")
+ err = errors.New("error getting pkcs11 config, check if HSM_PATH, HSM_PIN, or HSM_LABEL are set")
zetaclient/chains/bitcoin/observer/inbound.go (1)

Line range hint 30-42: Review of WatchInbound function: Add error handling and logging improvements.

  1. The function logs an error if the ticker cannot be created but continues execution which could lead to a nil pointer dereference on ticker.C(). Consider returning an error or halting execution.
  2. The use of defer ticker.Stop() is good practice to ensure resources are cleaned up.
if err != nil {
-   ob.logger.Inbound.Error().Err(err).Msg("error creating ticker")
-   return
+   ob.logger.Inbound.Error().Err(err).Msg("Fatal error: Failed to create ticker")
+   return err
}
zetaclient/chains/bitcoin/signer/signer.go (5)

Line range hint 68-100: Ensure proper error handling in NewSigner constructor.

The constructor initializes the Signer struct. It handles errors from the RPC client creation but does not log them. Consider adding logging before returning the error for better debuggability.

if err != nil {
+  logger.Error().Err(err).Msg("Failed to create bitcoin RPC client")
   return nil, fmt.Errorf("error creating bitcoin rpc client: %s", err)
}

Line range hint 153-194: Review the method AddWithdrawTxOutputs for potential security and correctness issues.

The method handles cryptocurrency calculations and outputs. Ensure all calculations are secure against integer overflows and rounding errors. Consider using fixed-point arithmetic or libraries designed for financial calculations to improve security.

- remainingSats -= fees.Int64()
- remainingSats -= nonceMark
+ remainingSats = big.NewInt(remainingSats).Sub(fees).Sub(big.NewInt(nonceMark)).Int64() // Use big.Int for safe arithmetic

Line range hint 181-255: Complex logic in SignWithdrawTx needs simplification and error handling improvements.

The method contains complex logic for selecting UTXOs, building transactions, and handling errors. Consider refactoring to simplify the logic and improve readability. Additionally, enhance error handling to avoid silent failures.

// Refactor UTXO selection and error handling logic
if err != nil {
+  logger.Error().Err(err).Msg("Failed to fetch UTXOs")
   return nil, err
}

Line range hint 304-320: Check error handling in Broadcast method.

The method serializes and broadcasts a Bitcoin transaction. Ensure that all possible errors are handled appropriately and that the transaction data is correctly formatted before broadcasting.

if err != nil {
+  logger.Error().Err(err).Msg("Failed to serialize transaction")
   return err
}

Line range hint 325-425: Complex and lengthy method TryProcessOutbound needs refactoring.

The method is overly complex and lengthy, making it hard to maintain and understand. Consider breaking it down into smaller, more manageable functions. Also, ensure comprehensive error handling and logging throughout the method to improve reliability and traceability.

- for i := 0; i < 5; i++ {
+ for i := 0; i < maxRetryCount; i++ { // Use a constant for max retries
zetaclient/zetacore/query.go (3)

Line range hint 71-76: Consider enhancing the error message in GetChainParams.

Adding the retry attempt in the error message would provide more context on failure.

- return nil, fmt.Errorf("failed to get chain params | err %s", err.Error())
+ return nil, fmt.Errorf("failed to get chain params after %d attempts | err %s", i+1, err.Error())

Line range hint 258-263: Consider enhancing the error message in GetNodeInfo.

Including the retry attempt in the error message would provide more context on failure.

- return nil, err
+ return nil, fmt.Errorf("failed to get node info after %d attempts | err %s", i+1, err.Error())

Line range hint 328-333: Consider enhancing the error message in GetKeyGen.

Including the retry attempt in the error message would provide more context on failure.

- return nil, fmt.Errorf("failed to get keygen | err %s", err.Error())
+ return nil, fmt.Errorf("failed to get keygen after %d attempts | err %s", i+1, err.Error())
zetaclient/tss/tss_signer.go (4)

Line range hint 52-63: Enhance error logging in NewTSSKey.

Consider adding more context to the error messages to aid in debugging. For example, include the Bech32 key that caused the failure when logging errors.

-		log.Error().Err(err).Msgf("GetPubKeyFromBech32 from %s", pk)
+		log.Error().Err(err).Msgf("Failed to get public key from Bech32 string '%s'", pk)
-		return nil, fmt.Errorf("NewTSS: DecompressPubkey error: %w", err)
+		return nil, fmt.Errorf("Failed to decompress public key for Bech32 string '%s': %w", pk, err)

Line range hint 149-192: Consider refactoring SetupTSSServer to its own file.

The TODO comment suggests moving this function to a dedicated TSS server file, which could improve modularity and maintainability. Consider creating a tss_server.go file and moving related functionalities there.


Line range hint 216-268: Refactor the blame posting logic in Sign.

The current implementation posts blame data within the same function that handles signing. Consider separating these concerns for better clarity and testability.

+ func (tss *TSS) postBlameData(ksRes *keysign.Response, chain *chains.Chain, digest []byte, height uint64, nonce uint64) error {
+     digestHex := hex.EncodeToString(digest)
+     index := observertypes.GetBlameIndex(chain.ChainId, nonce, digestHex, height)
+     zetaHash, err := tss.ZetacoreClient.PostBlameData(&ksRes.Blame, chain.ChainId, index)
+     if err != nil {
+         log.Error().Err(err).Msg("error sending blame data to core")
+         return err
+     }
+     log.Info().Msgf("keysign posted blame data tx hash: %s", zetaHash)
+     return nil
+ }

Line range hint 414-422: Improve structure of Validate function.

Consider separating the validation logic for EVM and BTC addresses into separate methods. This can make the code cleaner and more maintainable.

+ func (tss *TSS) validateEVMAddress() error {
+     evmAddress := tss.EVMAddress()
+     blankAddress := ethcommon.Address{}
+     if evmAddress == blankAddress {
+         return fmt.Errorf("invalid EVM address: %s", evmAddress.String())
+     }
+     return nil
+ }
+
+ func (tss *TSS) validateBTCAddress() error {
+     if tss.BTCAddressWitnessPubkeyHash() == nil {
+         return fmt.Errorf("invalid BTC pubkey hash: %s", tss.BTCAddress())
+     }
+     return nil
+ }
zetaclient/chains/bitcoin/observer/outbound.go (5)

Line range hint 30-114: Refactor suggestion for WatchOutbound function.

This function performs multiple tasks and could benefit from decomposition into smaller, more manageable functions. This would improve readability and maintainability.

- func (ob *Observer) WatchOutbound() {
+ func (ob *Observer) setupOutboundWatcher() (*types.DynamicTicker, error) {
+     ticker, err := types.NewDynamicTicker("Bitcoin_WatchOutbound", ob.GetChainParams().OutboundTicker)
+     if err != nil {
+         return nil, err
+     }
+     return ticker, nil
+ }
+
+ func (ob *Observer) processOutboundTransactions(ticker *types.DynamicTicker) {
+     for {
+         select {
+         case <-ticker.C():
+             // existing logic here
+         case <-ob.stop:
+             return
+         }
+     }
+ }
+
- ticker, err := types.NewDynamicTicker("Bitcoin_WatchOutbound", ob.GetChainParams().OutboundTicker)
- if err != nil {
-     ob.logger.Outbound.Error().Err(err).Msg("error creating ticker ")
-     return
- }
- defer ticker.Stop()
-
- ob.logger.Outbound.Info().Msgf("WatchInbound started for chain %d", ob.chain.ChainId)
- sampledLogger := ob.logger.Outbound.Sample(&zerolog.BasicSampler{N: 10})
-
- for {
-     select {
-     case <-ticker.C():
-         if !context.IsOutboundObservationEnabled(ob.coreContext, ob.GetChainParams()) {
-             sampledLogger.Info().
-                 Msgf("WatchOutbound: outbound observation is disabled for chain %d", ob.chain.ChainId)
-             continue
-         }
-         trackers, err := ob.zetacoreClient.GetAllOutboundTrackerByChain(ob.chain.ChainId, interfaces.Ascending)
-         if err != nil {
-             ob.logger.Outbound.Error().
-                 Err(err).
-                 Msgf("WatchOutbound: error GetAllOutboundTrackerByChain for chain %d", ob.chain.ChainId)
-             continue
-         }
-         for _, tracker := range trackers {
-             // existing logic here
-         }
-         ticker.UpdateInterval(ob.GetChainParams().OutboundTicker, ob.logger.Outbound)
-     case <-ob.stop:
-         ob.logger.Outbound.Info().Msgf("WatchOutbound stopped for chain %d", ob.chain.ChainId)
-         return
-     }
- }

Line range hint 114-217: Review of IsOutboundProcessed function.

The function's logic is complex and handles multiple scenarios for transaction processing. Consider breaking down this function into smaller, more manageable functions to improve readability and maintainability.


Line range hint 218-335: Refactor suggestion for SelectUTXOs function.

This function is complex and handles multiple aspects of UTXO selection. Consider breaking it down into smaller, more manageable functions to improve readability and maintainability.

- func (ob *Observer) SelectUTXOs(amount float64, utxosToSpend uint16, nonce uint64, consolidateRank uint16, test bool) ([]btcjson.ListUnspentResult, float64, uint16, float64, error) {
+ func (ob *Observer) setupUTXOSelection(amount float64, utxosToSpend uint16, nonce uint64, consolidateRank uint16, test bool) ([]btcjson.ListUnspentResult, float64, uint16, float64, error) {
+     // existing logic here
+ }

Line range hint 335-372: Consider enhancing logging for better traceability.

Adding more detailed logging statements can help in troubleshooting and understanding the flow of transactions, especially when errors occur.

+ ob.logger.Chain.Debug().Msgf("refreshPendingNonce: current pending nonce %d, new nonce low %d", ob.pendingNonce, nonceLow)

Line range hint 336-372: Review of getOutboundIDByNonce function.

The function is well-implemented with clear separation of concerns for unit test and production scenarios. Consider improving error handling to provide more specific error messages for different failure scenarios.

+ if txid == "" {
+     return "", fmt.Errorf("getOutboundIDByNonce: empty txid for nonce %d", nonce)
+ }
zetaclient/chains/evm/observer/inbound.go (2)

Line range hint 37-58: Verify error handling in WatchInbound.

The function logs an error if the ticker fails to create but does not stop the execution or return an error. This might lead to unintended behaviors or silent failures in production.

-		ob.logger.Inbound.Error().Err(err).Msg("error creating ticker")
-		return
+		ob.logger.Inbound.Error().Err(err).Msg("error creating ticker")
+		return err

Line range hint 74-99: Verify error handling in WatchInboundTracker.

The function logs an error if the ticker fails to create but does not stop the execution or return an error. This might lead to unintended behaviors or silent failures in production.

-		ob.logger.Inbound.Err(err).Msg("error creating ticker")
-		return
+		ob.logger.Inbound.Err(err).Msg("error creating ticker")
+		return err
changelog.md (2)

Line range hint 91-91: Grammar correction suggested.

Consider revising the phrase to active voice for clarity:

  • Original: "Updating admin policies now requires to send a governance proposal executing the UpdatePolicies message in the authority module."
  • Suggested: "Updating admin policies now requires sending a governance proposal that executes the UpdatePolicies message in the authority module."
- Updating admin policies now requires to send a governance proposal executing the `UpdatePolicies` message in the `authority` module.
+ Updating admin policies now requires sending a governance proposal that executes the `UpdatePolicies` message in the `authority` module.
Tools
LanguageTool

[style] ~72-~72: Consider changing the order of words to improve your wording. (TO_NOT_VB)
Context: ...ocker build step for non release builds to not overwrite the github tag. * [2192](http...


Line range hint 438-438: Grammar correction in verb form.

Consider revising the sentence to correct the verb form:

  • Original: "this can be either be run a tombstoned observer/validator or via admin_policy_group_2."
  • Suggested: "this can either run a tombstoned observer/validator or be managed via admin_policy_group_2."
- this can be either be run a tombstoned observer/validator or via admin_policy_group_2.
+ this can either run a tombstoned observer/validator or be managed via admin_policy_group_2.
Tools
LanguageTool

[style] ~72-~72: Consider changing the order of words to improve your wording. (TO_NOT_VB)
Context: ...ocker build step for non release builds to not overwrite the github tag. * [2192](http...

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between a28d7e1 and ce1d372.

Files selected for processing (40)
  • changelog.md (1 hunks)
  • zetaclient/authz/authz_signer.go (4 hunks)
  • zetaclient/authz/authz_signer_test.go (1 hunks)
  • zetaclient/chains/bitcoin/observer/inbound.go (8 hunks)
  • zetaclient/chains/bitcoin/observer/observer.go (23 hunks)
  • zetaclient/chains/bitcoin/observer/outbound.go (5 hunks)
  • zetaclient/chains/bitcoin/signer/signer.go (5 hunks)
  • zetaclient/chains/bitcoin/utils.go (3 hunks)
  • zetaclient/chains/evm/observer/inbound.go (4 hunks)
  • zetaclient/chains/evm/observer/observer.go (13 hunks)
  • zetaclient/chains/evm/observer/outbound.go (2 hunks)
  • zetaclient/chains/evm/signer/signer.go (9 hunks)
  • zetaclient/chains/interfaces/interfaces.go (1 hunks)
  • zetaclient/compliance/compliance.go (1 hunks)
  • zetaclient/config/config.go (4 hunks)
  • zetaclient/config/config_chain.go (1 hunks)
  • zetaclient/config/types.go (6 hunks)
  • zetaclient/context/app_context.go (2 hunks)
  • zetaclient/context/zetacore_context.go (5 hunks)
  • zetaclient/hsm/hsm_signer.go (2 hunks)
  • zetaclient/keys/keys.go (3 hunks)
  • zetaclient/metrics/metrics.go (4 hunks)
  • zetaclient/metrics/telemetry.go (3 hunks)
  • zetaclient/orchestrator/orchestrator.go (5 hunks)
  • zetaclient/outboundprocessor/outbound_processor_manager.go (6 hunks)
  • zetaclient/ratelimiter/rate_limiter.go (1 hunks)
  • zetaclient/supplychecker/logger.go (1 hunks)
  • zetaclient/supplychecker/validate.go (1 hunks)
  • zetaclient/supplychecker/zeta_supply_checker.go (6 hunks)
  • zetaclient/testutils/mempool_client.go (5 hunks)
  • zetaclient/testutils/testdata.go (1 hunks)
  • zetaclient/tss/tss_signer.go (16 hunks)
  • zetaclient/types/dynamic_ticker.go (3 hunks)
  • zetaclient/types/ethish.go (1 hunks)
  • zetaclient/types/sql_evm.go (6 hunks)
  • zetaclient/zetacore/broadcast.go (2 hunks)
  • zetaclient/zetacore/client.go (2 hunks)
  • zetaclient/zetacore/query.go (36 hunks)
  • zetaclient/zetacore/query_test.go (1 hunks)
  • zetaclient/zetacore/tx.go (12 hunks)
Files not reviewed due to errors (5)
  • zetaclient/config/types.go (no review received)
  • zetaclient/types/sql_evm.go (no review received)
  • zetaclient/testutils/mempool_client.go (no review received)
  • zetaclient/context/zetacore_context.go (no review received)
  • zetaclient/zetacore/tx.go (no review received)
Files skipped from review due to trivial changes (7)
  • zetaclient/authz/authz_signer_test.go
  • zetaclient/chains/interfaces/interfaces.go
  • zetaclient/compliance/compliance.go
  • zetaclient/context/app_context.go
  • zetaclient/keys/keys.go
  • zetaclient/ratelimiter/rate_limiter.go
  • zetaclient/zetacore/broadcast.go
Additional context used
LanguageTool
changelog.md

[uncategorized] ~7-~7: Possible missing article found. (AI_HYDRA_LEO_MISSING_A)
Context: ...## Unreleased ### Breaking Changes * [List of the breaking changes can be found in...


[uncategorized] ~71-~71: When ‘mac-specific’ is used as a modifier, it is usually spelled with a hyphen. (SPECIFIC_HYPHEN)
Context: ...me which should be the version. Removed mac specific build as the arm build should handle th...


[style] ~72-~72: Consider changing the order of words to improve your wording. (TO_NOT_VB)
Context: ...ocker build step for non release builds to not overwrite the github tag. * [2192](http...


[uncategorized] ~90-~90: Possible missing comma found. (AI_HYDRA_LEO_MISSING_COMMA)
Context: ...ave been moved from observer to a new module authority. * Updating admin policie...


[grammar] ~91-~91: Did you mean “sending”? Or maybe you should add a pronoun? In active voice, ‘require’ + ‘to’ takes an object, usually a pronoun. (ALLOW_TO)
Context: ... * Updating admin policies now requires to send a governance proposal executing the `Up...


[uncategorized] ~163-~163: Use a comma before ‘so’ if it connects two independent clauses (unless they are closely connected and short). (COMMA_COMPOUND_SENTENCE_2)
Context: ...n/node/pull/1899) - add empty test files so packages are included in coverage * [19...


[uncategorized] ~194-~194: Possible missing comma found. (AI_HYDRA_LEO_MISSING_COMMA)
Context: ...eline to not execute tests that weren't selected so they show skipped instead of skippin...


[uncategorized] ~214-~214: Loose punctuation mark. (UNLIKELY_OPENING_PUNCTUATION)
Context: ... Breaking Changes * zetaclientd start: now requires 2 inputs from stdin: hotke...


[grammar] ~251-~251: Did you mean “running”? Or maybe you should add a pronoun? In active voice, ‘allow’ + ‘to’ takes an object, usually a pronoun. (ALLOW_TO)
Context: ....com//pull/1584) - allow to run E2E tests on any networks * [1746](http...


[grammar] ~260-~260: The operating system from Apple is written “macOS”. (MAC_OS)
Context: ...nto dockerhub on release for ubuntu and macos. * Adjusted the pipeline for building a...


[grammar] ~261-~261: The operating system from Apple is written “macOS”. (MAC_OS)
Context: ... building and pushing docker images for MacOS to install and run docker. * Added dock...


[uncategorized] ~267-~267: When ‘start-up’ is used as a noun or modifier, it needs to be hyphenated. (VERB_NOUN_CONFUSION)
Context: ...he new docker image that facilitate the start up automation. * Adjusted the docker pipel...


[grammar] ~288-~288: Before the countable noun ‘to’ an article or a possessive pronoun is necessary. (IN_NN_CC_VBG)
Context: ...ssues/1610) - add pending outtx hash to tracker after monitoring for 10 minutes * [1656...


[uncategorized] ~345-~345: Loose punctuation mark. (UNLIKELY_OPENING_PUNCTUATION)
Context: ...g nonces for the chain. * ChainNonces : Changed from `/zeta-chain/crosschain/ch...


[uncategorized] ~346-~346: Loose punctuation mark. (UNLIKELY_OPENING_PUNCTUATION)
Context: ...dress for the chain. * ChainNoncesAll :Changed from `/zeta-chain/crosschain/cha...


[uncategorized] ~350-~350: Loose punctuation mark. (UNLIKELY_OPENING_PUNCTUATION)
Context: ...ame observer set. * AllObserverMappers: `/zeta-chain/observer/all_observer_mapp...


[uncategorized] ~353-~353: Possible missing comma found. (AI_HYDRA_LEO_MISSING_COMMA)
Context: ...er params data have been moved to chain params described below. * GetCoreParams: Ren...


[uncategorized] ~354-~354: Loose punctuation mark. (UNLIKELY_OPENING_PUNCTUATION)
Context: ...arams described below. * GetCoreParams: Renamed into GetChainParams. `/zeta-c...


[uncategorized] ~355-~355: Loose punctuation mark. (UNLIKELY_OPENING_PUNCTUATION)
Context: ..._chain_params. * GetCoreParamsByChain: Renamed into GetChainParamsForChain`. ...


[uncategorized] ~358-~358: Possible missing article found. (AI_HYDRA_LEO_MISSING_AN)
Context: ...ver/getTssAddress/{bitcoin_chain_id}` . Optional bitcoin chain id can now be passed as a...


[uncategorized] ~358-~358: Possible missing article found. (AI_HYDRA_LEO_MISSING_THE)
Context: ... parameter to fetch the correct tss for required BTC chain. This parameter only affects ...


[uncategorized] ~438-~438: Possible wrong verb form detected. Did you mean “been” or “being”? (BE_WITH_WRONG_VERB_FORM)
Context: ... update an observer, this can be either be run a tombstoned observer/validator or ...


[grammar] ~478-~478: Did you mean “testing”? Or maybe you should add a pronoun? In active voice, ‘allow’ + ‘to’ takes an object, usually a pronoun. (ALLOW_TO)
Context: ...pgrade name, and allow download. allows to test release * [1153](https://github.com/zet...


[misspelling] ~486-~486: This word is normally spelled with a hyphen. (EN_COMPOUNDS_CHERRY_PICK)
Context: ...github.com//pull/1235) - cherry pick all hotfix from v10.0.x (zero-amount, p...

Markdownlint
changelog.md

208-208: Expected: asterisk; Actual: dash (MD004, ul-style)
Unordered list style


259-259: Expected: 0 or 2; Actual: 1 (MD009, no-trailing-spaces)
Trailing spaces


265-265: Expected: 0 or 2; Actual: 1 (MD009, no-trailing-spaces)
Trailing spaces


418-418: Expected: 0 or 2; Actual: 1 (MD009, no-trailing-spaces)
Trailing spaces


459-459: Expected: 0 or 2; Actual: 1 (MD009, no-trailing-spaces)
Trailing spaces


499-499: Expected: 0 or 2; Actual: 1 (MD009, no-trailing-spaces)
Trailing spaces


203-203: Expected: 1; Actual: 0; Below (MD022, blanks-around-headings)
Headings should be surrounded by blank lines


225-225: null (MD024, no-duplicate-heading)
Multiple headings with the same content


272-272: null (MD024, no-duplicate-heading)
Multiple headings with the same content


328-328: null (MD024, no-duplicate-heading)
Multiple headings with the same content


204-204: null (MD032, blanks-around-lists)
Lists should be surrounded by blank lines


344-344: null (MD032, blanks-around-lists)
Lists should be surrounded by blank lines


349-349: null (MD032, blanks-around-lists)
Lists should be surrounded by blank lines


353-353: null (MD032, blanks-around-lists)
Lists should be surrounded by blank lines


358-358: null (MD032, blanks-around-lists)
Lists should be surrounded by blank lines


227-227: null (MD034, no-bare-urls)
Bare URL used


517-517: null (MD047, single-trailing-newline)
Files should end with a single newline character

Additional comments not posted (126)
zetaclient/types/ethish.go (1)

7-7: Well-documented utility function for Ethereum hex conversion.

The function BytesToEthHex is simple and well-documented, serving its purpose effectively.

zetaclient/supplychecker/logger.go (1)

24-24: Effective logging mechanism within LogOutput.

The function effectively logs structured data using an external utility, with appropriate error handling.

zetaclient/supplychecker/validate.go (1)

8-8: Robust validation logic with clear structuring and deferred logging.

The function ValidateZetaSupply is well-structured with clear logic, and uses deferred logging to ensure that relevant information is always logged.

zetaclient/types/dynamic_ticker.go (1)

17-17: Dynamic ticker management functions are robust and well-implemented.

The DynamicTicker struct provides comprehensive management of a ticker's lifecycle, ensuring flexibility and robust operation with its updatable interval.

Also applies to: 35-35

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

13-13: Comprehensive utility functions with thorough error handling and security considerations.

The utility functions in utils.go are well-implemented with thorough error handling and security annotations, ensuring robust and secure operations.

Also applies to: 26-26, 46-46

zetaclient/authz/authz_signer.go (3)

12-12: Document the purpose of KeyType in Signer struct.

The KeyType field in the Signer struct is not self-explanatory and could benefit from a comment explaining its purpose and usage.


19-19: Approve the implementation of String() method for Signer.

The String() method provides a clear, concatenated string representation of a Signer. This is straightforward and follows best practices for implementing stringer methods in Go.


45-45: Approve the GetSigner function.

The GetSigner function provides a straightforward way to retrieve a Signer by msgURL. This function is simple and effective.

zetaclient/outboundprocessor/outbound_processor_manager.go (4)

24-24: Approve the implementation of NewProcessor.

The NewProcessor function correctly initializes a new Processor instance with appropriate default values. It follows best practices for constructor functions in Go.


46-46: Approve the implementation of EndTryProcess.

The EndTryProcess function correctly handles the removal of an outbound ID from tracking and logs the relevant information. This method is well-implemented.


57-57: Approve the implementation of IsOutboundActive.

The IsOutboundActive function provides a straightforward way to check if an outbound ID is currently being processed. This method is simple and effective.


65-65: Approve the implementation of TimeInTryProcess.

The TimeInTryProcess function correctly calculates the time elapsed since the processing of an outbound ID started. This method is well-implemented.

zetaclient/config/config.go (2)

15-15: Document the purpose of filename and folder constants.

The filename and folder constants are used in the configuration path but lack comments explaining their specific roles. Adding comments would improve code readability and maintainability.


18-18: Approve the implementation of Save function.

The Save function correctly handles the creation of directories and saving of configuration files. It uses appropriate error handling and file path sanitation.

zetaclient/metrics/telemetry.go (5)

107-107: Approve the implementation of Stop function in TelemetryServer.

The Stop function correctly handles the graceful shutdown of the HTTP server with proper context handling and error logging.


118-118: Approve the implementation of pingHandler.

The pingHandler function correctly returns a 200 OK response, which is a standard practice for health check endpoints.


123-123: Approve the implementation of p2pHandler.

The p2pHandler function correctly retrieves and returns the P2P ID. This method is well-implemented and follows best practices for HTTP handlers.


131-131: Approve the implementation of ipHandler.

The ipHandler function correctly retrieves and returns the IP address. This method is well-implemented and follows best practices for HTTP handlers.


139-139: Approve the implementation of hotKeyFeeBurnRate.

The hotKeyFeeBurnRate function correctly retrieves and returns the burn rate of the hot key. This method is well-implemented and follows best practices for HTTP handlers.

zetaclient/metrics/metrics.go (15)

15-15: Approve the implementation of Metrics struct.

The Metrics struct is well-defined and serves as a container for the HTTP server instance used for metrics.


24-24: Approve the implementation of PendingTxsPerChain.

The PendingTxsPerChain gauge is correctly initialized with appropriate labels and help text. This metric is essential for monitoring the number of pending transactions per chain.


31-31: Approve the implementation of GetFilterLogsPerChain.

The GetFilterLogsPerChain counter is correctly initialized with appropriate labels and help text. This metric is essential for monitoring the number of getLogs RPC calls per chain.


38-38: Approve the implementation of GetBlockByNumberPerChain.

The GetBlockByNumberPerChain counter is correctly initialized with appropriate labels and help text. This metric is essential for monitoring the number of getBlockByNumber RPC calls per chain.


45-45: Approve the implementation of TssNodeBlamePerPubKey.

The TssNodeBlamePerPubKey counter is correctly initialized with appropriate labels and help text. This metric is essential for monitoring the number of TSS node blames per pubkey.


52-52: Approve the implementation of HotKeyBurnRate.

The HotKeyBurnRate gauge is correctly initialized with appropriate labels and help text. This metric is essential for monitoring the fee burn rate of the hotkey.


59-59: Approve the implementation of NumberOfUTXO.

The NumberOfUTXO gauge is correctly initialized with appropriate labels and help text. This metric is essential for monitoring the number of UTXOs.


66-66: Approve the implementation of LastScannedBlockNumber.

The LastScannedBlockNumber gauge is correctly initialized with appropriate labels and help text. This metric is essential for monitoring the last scanned block number per chain.


73-73: Approve the implementation of LastCoreBlockNumber.

The LastCoreBlockNumber gauge is correctly initialized with appropriate labels and help text. This metric is essential for monitoring the last core block number.


80-80: Approve the implementation of Info.

The Info gauge is correctly initialized with appropriate labels and help text. This metric is essential for providing information about the ZetaClient environment.


87-87: Approve the implementation of LastStartTime.

The LastStartTime gauge is correctly initialized with appropriate labels and help text. This metric is essential for monitoring the start time in Unix time.


94-94: Approve the implementation of NumActiveMsgSigns.

The NumActiveMsgSigns gauge is correctly initialized with appropriate labels and help text. This metric is essential for monitoring the number of concurrent key signs.


101-101: Approve the implementation of PercentageOfRateReached.

The PercentageOfRateReached gauge is correctly initialized with appropriate labels and help text. This metric is essential for monitoring the percentage of the rate limiter rate reached.


109-109: Approve the implementation of NewMetrics.

The NewMetrics function correctly initializes a new Metrics instance with appropriate HTTP handlers for Prometheus metrics. This function follows best practices for constructor functions in Go.


140-140: Approve the implementation of Stop function in Metrics.

The Stop function correctly handles the graceful shutdown of the metrics server with proper context handling and error logging.

zetaclient/hsm/hsm_signer.go (1)

Line range hint 54-161: Consider adding comments to complex sections for better maintainability.

The function SignWithHSM involves multiple steps and checks. Adding comments to explain the reasoning behind these steps would improve the maintainability and understandability of the code.

zetaclient/supplychecker/zeta_supply_checker.go (2)

97-97: Ensure proper error handling and logging in Start method.

The Start method correctly catches errors from CheckZetaTokenSupply and logs them. However, consider adding more detailed error context or potential recovery mechanisms if applicable.


113-113: Good practice to log before stopping the service.

Logging before stopping the ZetaSupplyChecker in the Stop method is a good practice as it provides clarity on the state of the application before it stops.

zetaclient/zetacore/client.go (2)

293-293: Good use of channels in Unpause method to control client state.

The Unpause method effectively uses a channel to manage the state of the client, which is a good practice for concurrency control.


288-288: Ensure Pause method handles potential deadlocks or blocking issues.

The Pause method uses a channel to synchronize state, which can potentially lead to deadlocks if not handled correctly. Ensure that there are adequate safeguards against such issues.

zetaclient/config/config_chain.go (2)

21-26: Good encapsulation of ABI retrieval in getter functions.

Encapsulating the ABI strings within getter functions is a good practice as it hides the implementation details and allows for easy updates in the future.


31-32: Ensure New function initializes all necessary configurations.

The New function initializes default chain configurations. Ensure that all necessary configurations are included and correctly initialized to prevent runtime issues.

Verification successful

The New function initializes all necessary configurations.

The New function correctly initializes the EVMChainConfigs and BitcoinConfig with comprehensive configurations for EVM and Bitcoin chains respectively.

  • EVMConfig includes Chain and Endpoint.
  • BTCConfig includes RPCUsername, RPCPassword, RPCHost, and RPCParams.

These fields cover the essential parameters required for the configurations.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that all necessary configurations are initialized in the New function.
# Test: Search for initialization patterns in the New function. Expect: All configurations are initialized.
ast-grep --lang go --pattern $'func New() Config {
  $$$
}'

Length of output: 412



Script:

#!/bin/bash
# Description: Locate and display the definitions and initializations of `evmChainsConfigs` and `bitcoinConfigRegnet`.
# This will help verify if all necessary configurations are covered.
rg 'evmChainsConfigs|bitcoinConfigRegnet' --type go

Length of output: 520



Script:

#!/bin/bash
# Description: Locate and display the definitions and initializations of `BTCConfig` and `EVMConfig`.
# This will help verify if all necessary configurations are included.
rg 'type BTCConfig|type EVMConfig' --type go

Length of output: 196



Script:

#!/bin/bash
# Description: Display the contents of `zetaclient/config/types.go` to review the `EVMConfig` and `BTCConfig` definitions.
cat zetaclient/config/types.go

Length of output: 4939

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

179-179: Consolidate ticker-related logic as previously noted.

Reiterating the earlier suggestion to move ticker-related methods to a dedicated file to centralize related logic and enhance code organization.

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

49-65: New struct Signer added to handle Bitcoin transaction signing.

The struct is well-encapsulated and uses appropriate types for its fields. However, ensure that all fields are necessary and used efficiently throughout the code.

zetaclient/zetacore/query.go (26)

28-31: Function GetCrosschainFlags looks good.


38-41: Function GetBlockHeaderEnabledChains is correctly implemented.


48-51: Function GetRateLimiterFlags is implemented correctly.


Line range hint 58-62: Function GetChainParamsForChainID meets the expected standards.


Line range hint 87-91: Function GetUpgradePlan is implemented correctly.


Line range hint 98-102: Function GetAllCctx looks good.


Line range hint 108-112: Function GetCctxByHash is correctly implemented.


Line range hint 118-122: Function GetCctxByNonce meets the expected standards.


Line range hint 142-152: Function GetRateLimiterInput is implemented correctly, with appropriate message size handling.


Line range hint 158-168: Function ListPendingCctx is correctly implemented with appropriate large message handling.


Line range hint 174-184: Function ListPendingCctxWithinRatelimit is well-designed, effectively handling multiple return values and rate limits.


Line range hint 198-202: Function GetAbortedZetaAmount is implemented correctly.


Line range hint 208-226: Function GetGenesisSupply is well-implemented, handling multiple stages of data retrieval and transformation effectively.


Line range hint 227-231: Function GetZetaTokenSupplyOnNode meets the expected standards.


Line range hint 237-242: Function GetLastBlockHeight is correctly implemented with detailed error logging.


Line range hint 248-252: Function GetLatestZetaBlock is implemented correctly.


273-276: Function GetBlockHeight is correctly implemented.


Line range hint 283-288: Function GetBaseGasPrice is well-implemented with an additional safety check for nil base fee.


296-299: Function GetBallotByID is implemented correctly.


Line range hint 304-308: Function GetNonceByChain meets the expected standards.


Line range hint 317-322: Function GetAllNodeAccounts is correctly implemented with detailed debug logging.


Line range hint 343-347: Function GetBallot is correctly implemented.


Line range hint 355-359: Function GetInboundTrackersForChain meets the expected standards.


368-371: Function GetCurrentTss is implemented correctly.


Line range hint 389-393: Function GetBtcTssAddress meets the expected standards.


Line range hint 401-405: Function GetTssHistory is correctly implemented.

zetaclient/chains/evm/observer/observer.go (4)

44-44: Consider the merging process for Logger struct.

The TODO comment indicates plans to merge this logger with the Bitcoin logger. Ensure that this is tracked and prioritized appropriately.

#!/bin/bash
# Description: Verify the merging process for Logger structure.

# Test: Search for related issue discussions. Expect: Relevant discussions on issue #2022.
gh issue view 2022 --repo zeta-chain/node

67-121: Structural enhancements in Observer struct.

The addition of new fields and TODO comments in the Observer struct enhances its functionality and prepares it for future refactoring. Ensure that these TODOs are tracked in your project management tools to prioritize them effectively.


289-317: Refactor suggestion to improve modularity.

Moving contract-related functions to a dedicated package would improve code organization and maintainability. Ensure this refactoring is tracked and prioritized.


344-345: Refactor suggestion for WatchRPCStatus.

Consider moving the ticker and inner logic of WatchRPCStatus to separate functions or files to improve readability and maintainability. Track and prioritize this refactoring.

zetaclient/chains/evm/signer/signer.go (2)

69-69: New function NewSigner added.

This function initializes a new Signer instance. It is crucial to ensure that all parameters are correctly used and that error handling is robust, especially since it interacts with external systems (EVM RPC).


620-620: Field naming suggestion for EvmSigner.

The TODO comment indicates a need to rename the field to evmSigner to follow Go naming conventions, which promote clarity and consistency.

- return signer.ethSigner
+ return signer.evmSigner
zetaclient/chains/evm/observer/inbound.go (2)

Line range hint 106-127: Ensure proper error handling in ProcessInboundTrackers.

The function logs and returns errors appropriately. However, consider adding more specific error messages or handling strategies for different types of errors.


Line range hint 153-250: Review error handling and logic in ObserveInbound.

The function handles errors appropriately and logs detailed information about the process. The logic appears sound, but ensure that all edge cases are considered, especially in the complex conditions and multiple return points.

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

78-78: Consider moving BTCInboundEvent as suggested.

The struct is well-defined for its purpose. However, there's a TODO comment about moving it to another file which might be part of planned refactoring. It's important to track these TODOs to ensure they are addressed in future updates.
[TODO]


Line range hint 102-160: New fields in Observer struct are appropriate for enhanced functionality.

The additions to the Observer struct, including BlockCache, Mu, Tss, and others, are well-thought-out and seem to serve specific purposes such as caching, thread-safety, and external service interaction. Ensure that these fields are used appropriately throughout the observer's methods to fully leverage their potential.


251-251: Method implementation is correct, consider revising redundant comments.

The WithZetacoreClient method correctly implements thread safety. However, as noted in previous reviews, comments on similar methods have been deemed redundant. Consider simplifying or removing these if they do not add value.


258-258: Method implementation is correct, consider streamlining logger initialization.

The WithLogger method is implemented correctly with appropriate thread safety measures. However, the initialization of different logger types within this method could be streamlined or modularized for better clarity and maintainability.


271-271: Method implementation is correct.

The WithBtcClient method correctly attaches a Bitcoin RPC client to the observer, ensuring thread safety with mutex usage.


278-278: Method implementation is correct.

The WithChain method correctly attaches a chain to the observer, with proper thread safety measures.


285-285: Method implementation is correct.

The Chain method correctly retrieves the chain associated with the observer, ensuring thread safety with mutex usage.


292-292: Method implementation is correct.

The SetChainParams method correctly sets the chain parameters for the observer, with appropriate thread safety measures.


299-299: Method implementation is correct.

The GetChainParams method correctly retrieves the chain parameters for the observer, ensuring thread safety with mutex usage.


306-306: Method implementation is correct, ensure proper synchronization.

The Start method correctly initiates multiple concurrent watchers. Ensure that these watchers are properly synchronized to avoid race conditions or data corruption.


319-319: Method implementation is correct, consider refactoring as suggested.

The WatchRPCStatus method uses a ticker to periodically check the RPC status, handling errors and logging appropriately. However, consider refactoring to move ticker-related functions to a specific file for better modularity and maintainability, as suggested by the TODO comments.
[TODO]


381-381: Method implementation is correct.

The Stop method effectively uses a channel to signal all goroutines to stop, ensuring a clean shutdown of the observer processes.


388-388: Method implementation is correct.

The SetLastBlockHeight method correctly uses atomic operations to set the last block height, ensuring thread safety.


393-393: Method implementation is correct.

The GetLastBlockHeight method correctly uses atomic operations to retrieve the last block height, ensuring thread safety.


398-398: Method implementation is correct, good use of metrics.

The SetLastBlockHeightScanned method correctly uses atomic operations to set the last block height scanned and updates a metric, which is a good practice for monitoring.


404-404: Method implementation is correct.

The GetLastBlockHeightScanned method correctly uses atomic operations to retrieve the last block height scanned, ensuring thread safety.


409-409: Method implementation is correct.

The GetPendingNonce method correctly retrieves the number of pending nonces for outbounds, ensuring thread safety with mutex usage.


417-417: Method implementation is correct, consider implementing as suggested.

The GetBaseGasPrice method correctly returns a placeholder value as it's not currently used for Bitcoin. However, consider implementing the functionality as suggested in the TODO comment if applicable in the future.
[TODO]


Line range hint 424-424: Method implementation is correct.

The ConfirmationsThreshold method correctly determines the number of required Bitcoin confirmations based on the sent amount and chain parameters.


439-439: Method implementation is correct, consider refactoring as suggested.

The WatchGasPrice method uses a ticker to periodically check and post gas prices. Consider refactoring to move ticker-related functions to a specific file for better modularity and maintainability, as suggested by the TODO comments.
[TODO]


476-476: Method implementation is correct, consider refactoring as suggested.

The PostGasPrice method handles various scenarios and errors appropriately when posting gas prices to Zetacore. However, consider refactoring to move this function to a gas price file as suggested in the TODO comment for better organization.
[TODO]


522-522: Method implementation is correct, consider refactoring as suggested.

The GetSenderAddressByVin method correctly handles various Bitcoin script types to decode the sender address. However, consider refactoring to move this function to a separate file as suggested in the TODO comment for better organization.
[TODO]


566-566: Method implementation is correct, consider refactoring as suggested.

The WatchUTXOS method uses a ticker to fetch UTXOs at regular intervals. Consider refactoring to move ticker-related functions to a specific file for better modularity and maintainability, as suggested by the TODO comments.
[TODO]


594-594: Method implementation is correct, consider refactoring as suggested.

The FetchUTXOS method correctly fetches and filters UTXOs owned by the TSS address. It also includes a deferred function to handle panics, which is a good practice. However, consider refactoring to move this function to a UTXO file as suggested in the TODO comment for better organization.
[TODO]


658-658: Method implementation is correct, consider refactoring as suggested.

The SaveBroadcastedTx method correctly saves broadcasted transaction hashes and associated outbound IDs to the database. It also logs the operation appropriately. However, consider refactoring to move this function to a database file as suggested in the TODO comment for better organization.
[TODO]

zetaclient/zetacore/query_test.go (22)

Line range hint 23-35: Well-implemented mock server setup function.

This function effectively sets up a mock server for gRPC testing, which is crucial for isolating the system under test and controlling the test environment.


Line range hint 37-41: Proper closure of mock server with appropriate error handling.

The function ensures that any errors during the server closure are caught and handled correctly, which is essential for clean test teardowns.


Line range hint 43-50: Simplified client setup function for testing.

The function provides a straightforward and isolated setup for Client instances, which is suitable for unit testing scenarios.


Line range hint 52-69: Comprehensive test for GetBallotByID with proper mocking and assertions.

This test effectively checks the functionality and error handling of GetBallotByID, ensuring that the client behaves as expected under controlled conditions.


Line range hint 71-88: Effectively tests the retrieval of crosschain flags with good isolation and assertion practices.

The test ensures that the GetCrosschainFlags function returns the correct data and handles errors appropriately, following best practices for unit testing.


Line range hint 90-109: Thorough test for retrieving rate limiter flags, using samples and effective mocking.

The test methodically checks the GetRateLimiterFlags function, using a sample for input data and asserting the correct behavior through a controlled mock environment.


Line range hint 111-128: Effective testing of header-enabled chains retrieval with appropriate mocking and assertions.

The test correctly isolates the function under test and ensures that it behaves as expected, using a controlled environment to simulate real interactions.


Line range hint 130-147: Clear and effective test for retrieving chain parameters for a specific chain ID.

The test methodically checks the GetChainParamsForChainID function, ensuring it returns the correct parameters and handles errors properly.


Line range hint 149-166: Comprehensive test for retrieving general chain parameters, maintaining consistency with best practices.

The test effectively isolates the function under test and checks its behavior in a controlled environment, ensuring the correctness of the retrieval process.


Line range hint 168-185: Effectively tests the retrieval of the current upgrade plan with robust mocking and assertions.

This test ensures the GetUpgradePlan function behaves as expected, returning the correct upgrade plan and handling any occurring errors properly.


Line range hint 187-204: Thorough test for retrieving all cross-chain transactions, using effective mocking and assertions.

The test correctly isolates the function under test and ensures that it behaves as expected, using a controlled environment to simulate real interactions.


Line range hint 206-223: Clear and effective test for retrieving a cross-chain transaction by hash.

The test methodically checks the GetCctxByHash function, ensuring it returns the correct transaction and handles errors properly.


Line range hint 225-242: Thorough test for retrieving a cross-chain transaction by nonce, using effective mocking and assertions.

The test correctly isolates the function under test and ensures that it behaves as expected, using a controlled environment to simulate real interactions.


Line range hint 244-261: Clear and effective test for retrieving the observer list.

The test methodically checks the GetObserverList function, ensuring it returns the correct list of observers and handles errors properly.


Line range hint 263-280: Thorough test for retrieving rate limiter input data, using effective mocking and assertions.

The test correctly isolates the function under test and ensures that it behaves as expected, using a controlled environment to simulate real interactions.


Line range hint 282-299: Clear and effective test for listing pending cross-chain transactions.

The test methodically checks the ListPendingCctx function, ensuring it returns the correct list of pending transactions and handles errors properly.


Line range hint 301-318: Thorough test for retrieving the aborted Zeta amount, using effective mocking and assertions.

The test correctly isolates the function under test and ensures that it behaves as expected, using a controlled environment to simulate real interactions.


Line range hint 320-320: Test implementation needed for TestZetacore_GetGenesisSupply.

This test is marked for future implementation and currently lacks content to review.


Line range hint 322-343: Clear and effective test for retrieving the Zeta token supply on a node.

The test methodically checks the GetZetaTokenSupplyOnNode function, ensuring it returns the correct token supply and handles errors properly.


Line range hint 345-368: Thorough test for retrieving the last block height, using effective mocking and assertions.

The test correctly isolates the function under test and ensures that it behaves as expected, using a controlled environment to simulate real interactions.


Line range hint 370-387: Clear and effective test for retrieving the latest Zeta block.

The test methodically checks the GetLatestZetaBlock function, ensuring it returns the correct block data and handles errors properly.


Line range hint 389-406: Thorough test for retrieving node information, using effective mocking and assertions.

The test correctly isolates the function under test and ensures that it behaves as expected, using a controlled environment to simulate real interactions.

changelog.md (2)

Line range hint 260-260: Typographical correction for macOS.

The operating system from Apple should be written as "macOS" instead of "MacOS".

- Adjusted the pipeline for building and pushing docker images for MacOS to install and run docker.
+ Adjusted the pipeline for building and pushing docker images for macOS to install and run docker.
Tools
LanguageTool

[style] ~72-~72: Consider changing the order of words to improve your wording. (TO_NOT_VB)
Context: ...ocker build step for non release builds to not overwrite the github tag. * [2192](http...


77-77: Verify PR link and description accuracy.

Please ensure that the PR link is active and the description accurately reflects the changes made in PR 2321. The link format and description seem correct, but it's always good to double-check for any updates or changes in the PR description.

zetaclient/chains/evm/signer/signer.go Show resolved Hide resolved
zetaclient/chains/evm/signer/signer.go Show resolved Hide resolved
zetaclient/chains/evm/signer/signer.go Show resolved Hide resolved
zetaclient/chains/evm/signer/signer.go Show resolved Hide resolved
zetaclient/chains/evm/signer/signer.go Show resolved Hide resolved
zetaclient/config/config.go Show resolved Hide resolved
zetaclient/config/config.go Show resolved Hide resolved
zetaclient/metrics/telemetry.go Outdated Show resolved Hide resolved
zetaclient/metrics/telemetry.go Show resolved Hide resolved
zetaclient/metrics/metrics.go Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 59

Outside diff range and nitpick comments (13)
zetaclient/context/zetacore_context.go (2)

Line range hint 55-73: Ensure proper handling of nil slices in GetKeygen method.

The method GetKeygen copies the slice keygen.GranteePubkeys if it's not nil. However, it would be more robust to check if keygen itself is nil to prevent potential runtime panics.

	if c.keygen != nil && c.keygen.GranteePubkeys != nil {
		copiedPubkeys = make([]string, len(c.keygen.GranteePubkeys))
		copy(copiedPubkeys, c.keygen.GranteePubkeys)
	}

Line range hint 104-113: Optimize GetAllEVMChainParams method by directly copying struct values.

The method GetAllEVMChainParams performs a deep copy of evmChainParams. Currently, it redundantly initializes a new struct before copying the values. This can be optimized.

	for chainID, evmConfig := range c.evmChainParams {
-		copied[chainID] = &observertypes.ChainParams{}
-		*copied[chainID] = *evmConfig
+		copiedChainParams := *evmConfig
+		copied[chainID] = &copiedChainParams
	}
zetaclient/chains/bitcoin/observer/inbound.go (1)

Line range hint 28-42: Consider consolidating ticker-related methods as suggested in the TODO.

The WatchInbound function starts a ticker to observe inbound transactions. The TODO comment suggests moving all ticker-related methods to a separate file, which could improve modularity and maintainability.

zetaclient/tss/tss_signer.go (3)

Line range hint 52-63: Consider simplifying error handling in NewTSSKey.

The function NewTSSKey logs and wraps the error which might lead to redundancy in error messages if the error is logged again by the caller. Consider removing the log statement or changing it to debug level if detailed tracing is not typically needed.

-		log.Error().Err(err).Msgf("GetPubKeyFromBech32 from %s", pk)
+		log.Debug().Err(err).Msgf("GetPubKeyFromBech32 from %s", pk)

Line range hint 148-195: Refactor SetupTSSServer to handle potential configuration issues more gracefully.

The function SetupTSSServer does not handle potential misconfigurations (like an empty tsspath or IP) robustly. It logs an error but proceeds with defaults which might not be obvious to the user.

-	if len(tsspath) == 0 {
-		log.Error().Msg("empty env TSSPATH")
+	if len(tsspath) == 0 {
+		return nil, fmt.Errorf("TSSPATH environment variable is required but not set")

Also, consider making the error messages more user-friendly by suggesting corrective actions.


Line range hint 414-424: Improve error messages in Validate for better clarity.

The error messages in the Validate method could be more descriptive to help in troubleshooting.

-	return fmt.Errorf("invalid evm address : %s", evmAddress.String())
+	return fmt.Errorf("invalid EVM address: %s, expected a non-zero address", evmAddress.String())
-	return fmt.Errorf("invalid btc pub key hash : %s", tss.BTCAddress())
+	return fmt.Errorf("invalid BTC public key hash for address: %s, expected a non-nil value", tss.BTCAddress())
zetaclient/chains/bitcoin/observer/observer.go (2)

Line range hint 306-318: Enhance error handling and resource management in monitoring methods.

The Start and WatchRPCStatus methods are central to the observer's functionality. Consider enhancing error handling in these methods to ensure robustness, especially in network or RPC failures. Also, ensure that resources like tickers are properly managed to avoid leaks.

Consider adding more comprehensive error handling and resource cleanup mechanisms, especially for long-running goroutines and periodic checks.

Also applies to: 319-381


Line range hint 438-475: Track and address TODO comments for code restructuring.

Many TODO comments throughout the file suggest moving functions to more appropriate files or packages. These comments are important for future code maintenance and should be tracked in the project's issue or task management system to ensure they are not overlooked.

Would you like me to help create tasks or issues for these planned code movements?

Also applies to: 522-565, 593-658, 675-750, 766-798

changelog.md (5)

Line range hint 208-208: Inconsistent List Style

Please use asterisks consistently for list items instead of dashes to maintain a consistent style throughout the document.

- - [2306](https://github.com/zeta-chain/node/pull/2306) - refactor zetaclient outbound transaction signing logic
+ * [2306](https://github.com/zeta-chain/node/pull/2306) - refactor zetaclient outbound transaction signing logic
Tools
LanguageTool

[style] ~72-~72: Consider changing the order of words to improve your wording. (TO_NOT_VB)
Context: ...ocker build step for non release builds to not overwrite the github tag. * [2192](http...


Line range hint 225-225: Duplicate Heading Issue

The heading "Refactor" appears multiple times in the document. Consider merging similar sections under a single heading or renaming them distinctly to avoid confusion.

Tools
LanguageTool

[style] ~72-~72: Consider changing the order of words to improve your wording. (TO_NOT_VB)
Context: ...ocker build step for non release builds to not overwrite the github tag. * [2192](http...


Line range hint 227-227: Bare URL Usage

It's good practice to provide descriptive text for URLs to improve accessibility and context.

- [https://github.com/zeta-chain/node/pull/2279](https://github.com/zeta-chain/node/pull/2279)
+ [PR #2279 - Add a CCTXGateway field to chain static data](https://github.com/zeta-chain/node/pull/2279)
Tools
LanguageTool

[style] ~72-~72: Consider changing the order of words to improve your wording. (TO_NOT_VB)
Context: ...ocker build step for non release builds to not overwrite the github tag. * [2192](http...


Line range hint 259-259: Trailing Spaces

Please remove trailing spaces to clean up the markdown syntax.

- * [2285](https://github.com/zeta-chain/node/pull/2285) - added nightly EVM performance testing pipeline, modified localnet testing docker image to utilitze debian:bookworm, removed build-jet runners where applicable, removed deprecated/removed upgrade path testing pipeline. 
+ * [2285](https://github.com/zeta-chain/node/pull/2285) - added nightly EVM performance testing pipeline, modified localnet testing docker image to utilitze debian:bookworm, removed build-jet runners where applicable, removed deprecated/removed upgrade path testing pipeline.

Also applies to: 265-265, 418-418, 459-459, 499-499

Tools
LanguageTool

[style] ~72-~72: Consider changing the order of words to improve your wording. (TO_NOT_VB)
Context: ...ocker build step for non release builds to not overwrite the github tag. * [2192](http...


Line range hint 203-203: Missing Blank Lines Around Headings

Ensure that headings are surrounded by blank lines to enhance readability and comply with markdown best practices.

- * [1484](https://github.com/zeta-chain/node/issues/1484) - replaced hard-coded `MaxLookaheadNonce` with a default lookback factor
### Fixes
+ * [1484](https://github.com/zeta-chain/node/issues/1484) - replaced hard-coded `MaxLookaheadNonce` with a default lookback factor
+
### Fixes
Tools
LanguageTool

[style] ~72-~72: Consider changing the order of words to improve your wording. (TO_NOT_VB)
Context: ...ocker build step for non release builds to not overwrite the github tag. * [2192](http...

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between a28d7e1 and ce1d372.

Files selected for processing (40)
  • changelog.md (1 hunks)
  • zetaclient/authz/authz_signer.go (4 hunks)
  • zetaclient/authz/authz_signer_test.go (1 hunks)
  • zetaclient/chains/bitcoin/observer/inbound.go (8 hunks)
  • zetaclient/chains/bitcoin/observer/observer.go (23 hunks)
  • zetaclient/chains/bitcoin/observer/outbound.go (5 hunks)
  • zetaclient/chains/bitcoin/signer/signer.go (5 hunks)
  • zetaclient/chains/bitcoin/utils.go (3 hunks)
  • zetaclient/chains/evm/observer/inbound.go (4 hunks)
  • zetaclient/chains/evm/observer/observer.go (13 hunks)
  • zetaclient/chains/evm/observer/outbound.go (2 hunks)
  • zetaclient/chains/evm/signer/signer.go (9 hunks)
  • zetaclient/chains/interfaces/interfaces.go (1 hunks)
  • zetaclient/compliance/compliance.go (1 hunks)
  • zetaclient/config/config.go (4 hunks)
  • zetaclient/config/config_chain.go (1 hunks)
  • zetaclient/config/types.go (6 hunks)
  • zetaclient/context/app_context.go (2 hunks)
  • zetaclient/context/zetacore_context.go (5 hunks)
  • zetaclient/hsm/hsm_signer.go (2 hunks)
  • zetaclient/keys/keys.go (3 hunks)
  • zetaclient/metrics/metrics.go (4 hunks)
  • zetaclient/metrics/telemetry.go (3 hunks)
  • zetaclient/orchestrator/orchestrator.go (5 hunks)
  • zetaclient/outboundprocessor/outbound_processor_manager.go (6 hunks)
  • zetaclient/ratelimiter/rate_limiter.go (1 hunks)
  • zetaclient/supplychecker/logger.go (1 hunks)
  • zetaclient/supplychecker/validate.go (1 hunks)
  • zetaclient/supplychecker/zeta_supply_checker.go (6 hunks)
  • zetaclient/testutils/mempool_client.go (5 hunks)
  • zetaclient/testutils/testdata.go (1 hunks)
  • zetaclient/tss/tss_signer.go (16 hunks)
  • zetaclient/types/dynamic_ticker.go (3 hunks)
  • zetaclient/types/ethish.go (1 hunks)
  • zetaclient/types/sql_evm.go (6 hunks)
  • zetaclient/zetacore/broadcast.go (2 hunks)
  • zetaclient/zetacore/client.go (2 hunks)
  • zetaclient/zetacore/query.go (36 hunks)
  • zetaclient/zetacore/query_test.go (1 hunks)
  • zetaclient/zetacore/tx.go (12 hunks)
Files skipped from review due to trivial changes (6)
  • zetaclient/authz/authz_signer_test.go
  • zetaclient/chains/interfaces/interfaces.go
  • zetaclient/compliance/compliance.go
  • zetaclient/context/app_context.go
  • zetaclient/ratelimiter/rate_limiter.go
  • zetaclient/zetacore/query_test.go
Additional context used
LanguageTool
changelog.md

[uncategorized] ~7-~7: Possible missing article found. (AI_HYDRA_LEO_MISSING_A)
Context: ...## Unreleased ### Breaking Changes * [List of the breaking changes can be found in...


[uncategorized] ~71-~71: When ‘mac-specific’ is used as a modifier, it is usually spelled with a hyphen. (SPECIFIC_HYPHEN)
Context: ...me which should be the version. Removed mac specific build as the arm build should handle th...


[style] ~72-~72: Consider changing the order of words to improve your wording. (TO_NOT_VB)
Context: ...ocker build step for non release builds to not overwrite the github tag. * [2192](http...


[grammar] ~91-~91: Did you mean “sending”? Or maybe you should add a pronoun? In active voice, ‘require’ + ‘to’ takes an object, usually a pronoun. (ALLOW_TO)
Context: ... * Updating admin policies now requires to send a governance proposal executing the `Up...


[uncategorized] ~163-~163: Use a comma before ‘so’ if it connects two independent clauses (unless they are closely connected and short). (COMMA_COMPOUND_SENTENCE_2)
Context: ...n/node/pull/1899) - add empty test files so packages are included in coverage * [19...


[uncategorized] ~214-~214: Loose punctuation mark. (UNLIKELY_OPENING_PUNCTUATION)
Context: ... Breaking Changes * zetaclientd start: now requires 2 inputs from stdin: hotke...


[grammar] ~251-~251: Did you mean “running”? Or maybe you should add a pronoun? In active voice, ‘allow’ + ‘to’ takes an object, usually a pronoun. (ALLOW_TO)
Context: ....com//pull/1584) - allow to run E2E tests on any networks * [1746](http...


[uncategorized] ~259-~259: Possible missing comma found. (AI_HYDRA_LEO_MISSING_COMMA)
Context: ... required tests run before the approval step unless skipped. * Added pipeline to bu...


[grammar] ~260-~260: The operating system from Apple is written “macOS”. (MAC_OS)
Context: ...nto dockerhub on release for ubuntu and macos. * Adjusted the pipeline for building a...


[grammar] ~261-~261: The operating system from Apple is written “macOS”. (MAC_OS)
Context: ... building and pushing docker images for MacOS to install and run docker. * Added dock...


[uncategorized] ~267-~267: When ‘start-up’ is used as a noun or modifier, it needs to be hyphenated. (VERB_NOUN_CONFUSION)
Context: ...he new docker image that facilitate the start up automation. * Adjusted the docker pipel...


[grammar] ~288-~288: Before the countable noun ‘to’ an article or a possessive pronoun is necessary. (IN_NN_CC_VBG)
Context: ...ssues/1610) - add pending outtx hash to tracker after monitoring for 10 minutes * [1656...


[uncategorized] ~345-~345: Loose punctuation mark. (UNLIKELY_OPENING_PUNCTUATION)
Context: ...g nonces for the chain. * ChainNonces : Changed from `/zeta-chain/crosschain/ch...


[uncategorized] ~346-~346: Loose punctuation mark. (UNLIKELY_OPENING_PUNCTUATION)
Context: ...dress for the chain. * ChainNoncesAll :Changed from `/zeta-chain/crosschain/cha...


[uncategorized] ~350-~350: Loose punctuation mark. (UNLIKELY_OPENING_PUNCTUATION)
Context: ...ame observer set. * AllObserverMappers: `/zeta-chain/observer/all_observer_mapp...


[uncategorized] ~354-~354: Loose punctuation mark. (UNLIKELY_OPENING_PUNCTUATION)
Context: ...arams described below. * GetCoreParams: Renamed into GetChainParams. `/zeta-c...


[uncategorized] ~355-~355: Loose punctuation mark. (UNLIKELY_OPENING_PUNCTUATION)
Context: ..._chain_params. * GetCoreParamsByChain: Renamed into GetChainParamsForChain`. ...


[uncategorized] ~438-~438: Possible wrong verb form detected. Did you mean “been” or “being”? (BE_WITH_WRONG_VERB_FORM)
Context: ... update an observer, this can be either be run a tombstoned observer/validator or ...


[grammar] ~478-~478: Did you mean “testing”? Or maybe you should add a pronoun? In active voice, ‘allow’ + ‘to’ takes an object, usually a pronoun. (ALLOW_TO)
Context: ...pgrade name, and allow download. allows to test release * [1153](https://github.com/zet...


[misspelling] ~486-~486: This word is normally spelled with a hyphen. (EN_COMPOUNDS_CHERRY_PICK)
Context: ...github.com//pull/1235) - cherry pick all hotfix from v10.0.x (zero-amount, p...

Markdownlint
changelog.md

208-208: Expected: asterisk; Actual: dash (MD004, ul-style)
Unordered list style


259-259: Expected: 0 or 2; Actual: 1 (MD009, no-trailing-spaces)
Trailing spaces


265-265: Expected: 0 or 2; Actual: 1 (MD009, no-trailing-spaces)
Trailing spaces


418-418: Expected: 0 or 2; Actual: 1 (MD009, no-trailing-spaces)
Trailing spaces


459-459: Expected: 0 or 2; Actual: 1 (MD009, no-trailing-spaces)
Trailing spaces


499-499: Expected: 0 or 2; Actual: 1 (MD009, no-trailing-spaces)
Trailing spaces


203-203: Expected: 1; Actual: 0; Below (MD022, blanks-around-headings)
Headings should be surrounded by blank lines


225-225: null (MD024, no-duplicate-heading)
Multiple headings with the same content


272-272: null (MD024, no-duplicate-heading)
Multiple headings with the same content


328-328: null (MD024, no-duplicate-heading)
Multiple headings with the same content


204-204: null (MD032, blanks-around-lists)
Lists should be surrounded by blank lines


344-344: null (MD032, blanks-around-lists)
Lists should be surrounded by blank lines


349-349: null (MD032, blanks-around-lists)
Lists should be surrounded by blank lines


353-353: null (MD032, blanks-around-lists)
Lists should be surrounded by blank lines


358-358: null (MD032, blanks-around-lists)
Lists should be surrounded by blank lines


227-227: null (MD034, no-bare-urls)
Bare URL used


517-517: null (MD047, single-trailing-newline)
Files should end with a single newline character

Additional comments not posted (40)
zetaclient/types/ethish.go (1)

7-7: Function implementation looks good.

The function BytesToEthHex correctly converts bytes to an Ethereum hex string, which is crucial for Ethereum-related operations.

zetaclient/supplychecker/logger.go (1)

24-24: Proper use of logging and error handling.

The method LogOutput effectively uses the PrettyPrintStruct function to format the logging output, and properly handles errors which is a good practice.

zetaclient/supplychecker/validate.go (1)

8-8: ValidateZetaSupply function is well-structured and effectively logs its process.

However, consider adding a brief comment describing the purpose of the lhs and rhs calculations for better code clarity.

zetaclient/types/dynamic_ticker.go (1)

17-17: DynamicTicker class methods are correctly implemented.

The methods NewDynamicTicker and UpdateInterval are well-implemented with appropriate error handling and logging. This ensures robustness and maintainability.

Also applies to: 35-35

zetaclient/authz/authz_signer.go (2)

12-12: Clarify the purpose of the Signer struct.

The comment on the Signer struct is somewhat vague. It might be beneficial to explain what a "grantee key" is and how it relates to the functionality of the Signer.


19-19: String method: Consider adding more context.

While the String method is straightforward, it might be helpful to include a bit more context in the comment about what this string representation is used for, especially if it's logged or displayed in user interfaces.

zetaclient/outboundprocessor/outbound_processor_manager.go (3)

24-24: Review the new Processor instantiation.

The constructor method NewProcessor is well-defined. However, consider adding error handling or initialization checks if any part of the setup could potentially fail or if the logger setup is critical.


36-36: Ensure thread safety and efficiency in StartTryProcess and EndTryProcess.

These methods are correctly using mutexes to ensure thread safety. However, consider optimizing the locking strategy to reduce lock contention, especially if these methods are called frequently.

Also applies to: 46-46


57-57: Validate active tracking logic in IsOutboundActive and TimeInTryProcess.

These methods are crucial for tracking active outbounds. Ensure that the logic correctly handles edge cases, such as checking for existence before accessing start times.

Also applies to: 65-65

Verification successful

Validate active tracking logic in IsOutboundActive and TimeInTryProcess.

The methods IsOutboundActive and TimeInTryProcess correctly handle edge cases by checking for the existence of the outbound ID before accessing related data.

  • IsOutboundActive:

    func (p *Processor) IsOutboundActive(outboundID string) bool {
        p.mu.Lock()
        defer p.mu.Unlock()
        _, found := p.outboundActive[outboundID]
        return found
    }
  • TimeInTryProcess:

    func (p *Processor) TimeInTryProcess(outboundID string) time.Duration {
        p.mu.Lock()
        defer p.mu.Unlock()
        if _, found := p.outboundActive[outboundID]; found {
            return time.Since(p.outboundStartTime[outboundID])
        }
        return 0
    }

These implementations ensure that the existence of the outbound ID is verified before accessing or using the outboundStartTime.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Check for proper handling of edge cases in active tracking.

# Test: Search for usage of `IsOutboundActive` and `TimeInTryProcess`.
rg --type go $'IsOutboundActive|TimeInTryProcess'

Length of output: 797



Script:

#!/bin/bash
# Extract the definitions of IsOutboundActive and TimeInTryProcess from the specified file for review.
ast-grep --lang go --pattern $'func (p *Processor) IsOutboundActive($_) $_ {
  $$$
}

func (p *Processor) TimeInTryProcess($_) $_ {
  $$$
}' zetaclient/outboundprocessor/outbound_processor_manager.go

Length of output: 731



Script:

#!/bin/bash
# Extract the definition of IsOutboundActive from the specified file for review.
ast-grep --lang go --pattern $'func (p *Processor) IsOutboundActive($_) $_ {
  $$$
}' zetaclient/outboundprocessor/outbound_processor_manager.go

# Extract the definition of TimeInTryProcess from the specified file for review.
ast-grep --lang go --pattern $'func (p *Processor) TimeInTryProcess($_) $_ {
  $$$
}' zetaclient/outboundprocessor/outbound_processor_manager.go

Length of output: 1542

zetaclient/config/config.go (1)

15-18: Clarification on constants for filenames and paths.

The introduction of constants for filenames and folder paths is good for maintainability. Ensure that these constants are used consistently throughout your codebase.

zetaclient/metrics/telemetry.go (3)

93-93: Review the implementation of Start in TelemetryServer.

The method Start correctly handles errors and provides detailed logging. Ensure that the HTTP server address and configuration are appropriate for your deployment environment.


107-107: Check the shutdown process in Stop.

The method Stop uses a context with a timeout for graceful shutdown. This is a good practice, but ensure that the timeout duration is sufficient for your server's load and complexity.


147-147: Evaluate the logMiddleware for HTTP requests.

The logMiddleware function logs incoming HTTP requests, which is useful for debugging and monitoring. Ensure that it does not log sensitive information and complies with your privacy policies.

Verification successful

The logMiddleware function does not log sensitive information.

The logMiddleware function logs the route, port, and method of incoming HTTP requests, which generally do not contain sensitive information. Ensure that the URL path does not inadvertently contain sensitive data such as query parameters or user identifiers.

  • logMiddleware function definition and logging statements:
    func logMiddleware() mux.MiddlewareFunc {
    	return func(handler http.Handler) http.Handler {
    		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    			log.Debug().
    				Str("route", r.URL.Path).
    				Str("port", r.URL.Port()).
    				Str("method", r.Method).
    				Msg("HTTP request received")
    
    			handler.ServeHTTP(w, r)
    		})
    	}
    }
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Check for sensitive information logging.

# Test: Search for logging statements in `logMiddleware`.
rg --type go $'log.Debug'

Length of output: 414



Script:

#!/bin/bash
# Extract the logMiddleware function from the telemetry.go file to inspect its logging statements.
ast-grep --lang go --pattern $'func logMiddleware($_, $_) $_ {
  $$$
}' zetaclient/metrics/telemetry.go

Length of output: 104



Script:

#!/bin/bash
# List all function definitions in the telemetry.go file to locate logMiddleware.
ast-grep --lang go --pattern 'func $_($_, $_) $_ {
  $$$
}' zetaclient/metrics/telemetry.go

Length of output: 93



Script:

#!/bin/bash
# Search for the logMiddleware function definition and its content in the telemetry.go file.
rg 'func logMiddleware' -A 20 zetaclient/metrics/telemetry.go

Length of output: 405

zetaclient/metrics/metrics.go (3)

15-24: Review new metrics definitions.

The new metrics such as PendingTxsPerChain are well-defined with helpful comments. Ensure that these metrics are registered and used correctly throughout your application.


31-94: Evaluate the comprehensive set of new metrics.

The addition of various metrics like GetFilterLogsPerChain, GetBlockByNumberPerChain, TssNodeBlamePerPubKey, etc., provides a detailed insight into the system's operation. Ensure that these metrics are monitored and have alerting configured if necessary.


Line range hint 109-140: Assess the metrics server setup and management.

The methods Start and Stop for the metrics server are implemented with good practices such as logging and context handling. Review the server's configuration to ensure it meets your performance and security requirements.

zetaclient/hsm/hsm_signer.go (1)

Line range hint 1-163: Ensure proper error handling in SignWithHSM.

In SignWithHSM, there are multiple points where errors are returned directly without additional context or logging. This can make debugging difficult, especially in a production environment where understanding the context of an error is crucial.

Consider enhancing error messages with more context and adding logging statements before returning errors to aid in troubleshooting.

[REFACTOR_SUGGESTion]

- return err
+ logger.Error().Err(err).Msg("Error getting PKCS11 config")
+ return errors.Wrap(err, "failed to get PKCS11 config")
zetaclient/config/types.go (1)

15-22: Ensure consistency in JSON field naming.

The ClientConfiguration struct uses snake_case for JSON tags which is consistent with Go's common JSON naming conventions. However, the PR mentions a TODO about using snake_case for JSON fields. It's important to ensure that all JSON tags across the application follow the same naming convention to avoid confusion and potential bugs.

zetaclient/context/zetacore_context.go (1)

144-144: Consider adding logging or metrics for GetCrossChainFlags method.

The method GetCrossChainFlags retrieves crosschain flags but does not provide any logging or metrics. Adding logging could help in debugging and monitoring.

Consider adding debug logging to trace the value of crosschainFlags when retrieved.

zetaclient/supplychecker/zeta_supply_checker.go (2)

202-202: Improve error handling in AbortedTxAmount method.

The method AbortedTxAmount captures and wraps errors but does not log them, which could be useful for debugging.

Consider adding error logging to improve traceability and debugging.


119-119: Validate external chain configuration in CheckZetaTokenSupply.

The method CheckZetaTokenSupply assumes that all external chain configurations are correct. It would be prudent to validate these configurations before proceeding with the supply check.

Verification successful

Validate external chain configuration in CheckZetaTokenSupply.

The CheckZetaTokenSupply method in zetaclient/supplychecker/zeta_supply_checker.go does validate external chain configurations before proceeding with the supply check. Specifically, it retrieves and checks the EVM chain parameters for each external chain and ensures they are present before continuing.

  • Code Reference:
    • zetaclient/supplychecker/zeta_supply_checker.go:
      • Lines 124-127: Validates externalEvmChainParams.
      • Lines 150-153: Validates evmChainParams.
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify external chain configurations are valid.

# Test: Search for external chain configurations. Expect: Valid configurations.
rg --type go 'externalChainConfig'

Length of output: 34



Script:

#!/bin/bash
# Locate the implementation of the CheckZetaTokenSupply method in the Go codebase
ast-grep --lang go --pattern 'func CheckZetaTokenSupply($_) $_' --json

Length of output: 75



Script:

#!/bin/bash
# List all functions in the zetaclient/supplychecker/zeta_supply_checker.go file
ast-grep --lang go --pattern 'func $_($_) $_' zetaclient/supplychecker/zeta_supply_checker.go --json

Length of output: 105



Script:

#!/bin/bash
# Search for methods related to "ZetaTokenSupply" across the entire Go codebase
rg --type go 'ZetaTokenSupply'

Length of output: 1211



Script:

#!/bin/bash
# Extract the implementation of the CheckZetaTokenSupply method from the zetaclient/supplychecker/zeta_supply_checker.go file
ast-grep --lang go --pattern 'func (zs *ZetaSupplyChecker) CheckZetaTokenSupply() error {
  $$$
}' zetaclient/supplychecker/zeta_supply_checker.go

Length of output: 6540

zetaclient/config/config_chain.go (4)

21-21: Implementation of GetConnectorABI looks good.


26-26: Implementation of GetERC20CustodyABI looks good.


31-32: Constructor function New is implemented correctly.


40-48: Configuration constants for blockchain networks are well-defined.

Consider adding more detailed comments to explain the purpose and usage of these configurations, especially for new developers.

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

179-179: Consolidate ticker-related methods as previously noted.

This TODO is a duplicate of the one in WatchInbound. It's important to address this to avoid redundancy and maintain consistency.

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

58-58: Add a field loggerCompliance for compliance logging.

Adding a dedicated logger for compliance-related activities is a good practice, as it allows for better separation and tracking of compliance events.


68-68: Creation of NewSigner function is well-implemented.

This function properly initializes a new signer with all necessary dependencies, adhering to best practices for constructor functions.

zetaclient/zetacore/tx.go (1)

73-74: Clarify the documentation for WrapMessageWithAuthz.

The added documentation explains the use of a hotkey for broadcasting transactions, which is a crucial piece of information for understanding the operation of this method.

zetaclient/tss/tss_signer.go (1)

Line range hint 216-287: Enhance error handling and reduce potential logging of sensitive data in Sign.

The method logs potentially sensitive data which could lead to security issues. Consider reducing the verbosity of logs that include cryptographic material or hashes.
[SECURITY]

-	log.Debug().Msgf("hash of digest is %s", H)
+	log.Debug().Msg("hash of digest is being processed")

Additionally, improve the error handling to ensure that all paths that return an error also log the error consistently.

zetaclient/chains/evm/observer/observer.go (5)

67-121: Encapsulate Mutex Operations

Consider encapsulating the mutex operations within methods to ensure that all mutex locks and unlocks are handled correctly and to improve code maintainability.
[REFACTOR_SUGGESTion]

+ func (ob *Observer) lock() {
+   ob.Mu.Lock()
+ }
+
+ func (ob *Observer) unlock() {
+   ob.Mu.Unlock()
+ }

And replace direct ob.Mu.Lock() and ob.Mu.Unlock() calls with ob.lock() and ob.unlock() respectively.


121-121: Improve Error Handling in NewObserver

Enhance error handling by logging errors before returning them to provide better debugging information.
[REFACTOR_SUGGESTion]

+ ob.logger.Chain.Error().Err(err).Msg("evm chains params not initialized for chain")
  if !found {
-   return nil, fmt.Errorf("evm chains params not initialized for chain %d", evmCfg.Chain.ChainId)
+   return nil, fmt.Errorf("evm chains params not initialized for chain %d", evmCfg.Chain.ChainId)
  }

Apply this pattern to other error return statements in this function.


344-345: Refactor WatchRPCStatus for Better Organization

Consider moving the ticker and inner logic of WatchRPCStatus to separate functions or files as suggested by the TODO comments. This will improve modularity and testability.
[REFACTOR_SUGGESTion]

- ticker := time.NewTicker(60 * time.Second)
+ ticker := newRPCStatusTicker()
- // Inner logic
+ checkRPCStatus(ob)

Define newRPCStatusTicker() and checkRPCStatus(ob *Observer) in appropriate files.


44-44: Reminder: Merge Logger with Bitcoin Logger

There's a TODO comment about merging this logger with the one in bitcoin. Ensure that this is tracked properly in the linked issue.


289-290: Refactor FetchConnectorContract to Contract Package

This function is marked for movement to a contract package for better organization. Ensure that this refactoring is tracked and prioritized appropriately.

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

69-69: Ensure proper error handling in NewSigner.

The function NewSigner correctly handles errors when setting up the RPC client and parsing ABIs. However, consider adding more detailed logging for each error case to aid in debugging.
[REFACTOR_SUGGESTion]

- return nil, err
+ log.Error().Err(err).Msg("Failed to setup EVM RPC client")
+ return nil, err
zetaclient/chains/bitcoin/observer/observer.go (3)

Line range hint 102-160: Evaluate additions to the Observer struct.

Several fields have been added to the Observer struct to support new functionalities like caching, mutex locks, and TSS operations. These additions are generally well-integrated and necessary for the expanded functionality of the observer. Ensure that all new fields are properly initialized and used throughout the observer's methods to maintain state consistency and thread safety.


251-251: Method implementation is sound, but consider comment redundancy.

The WithZetacoreClient method is implemented correctly with appropriate locking. However, consider streamlining the comments if they are deemed redundant, as previously discussed in the review comments.

Consider reducing redundancy in method comments to streamline the codebase.


Line range hint 258-271: Review attachment methods for consistency and correctness.

Methods like WithLogger, WithBtcClient, WithChain, SetChainParams, and GetChainParams are crucial for configuring the observer dynamically. Ensure that all these methods use mutex locks correctly to prevent data races and check that the parameters passed to these methods are validated if necessary.
[APROVED]

Also applies to: 278-285, 292-299

changelog.md (1)

77-77: Documentation Update Noted

The entry correctly reflects the documentation improvements made in this PR.

zetaclient/chains/evm/signer/signer.go Show resolved Hide resolved
zetaclient/chains/evm/signer/signer.go Show resolved Hide resolved
zetaclient/metrics/telemetry.go Outdated Show resolved Hide resolved
zetaclient/keys/keys.go Show resolved Hide resolved
zetaclient/zetacore/broadcast.go Show resolved Hide resolved
zetaclient/zetacore/client.go Show resolved Hide resolved
zetaclient/testutils/testdata.go Show resolved Hide resolved
Copy link

gitguardian bot commented Jun 26, 2024

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

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

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

To avoid such incidents in the future consider


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

Copy link
Contributor

@ws4charlie ws4charlie left a comment

Choose a reason for hiding this comment

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

Looks good

@lumtis lumtis merged commit 57457fd into develop Jun 26, 2024
19 checks passed
@lumtis lumtis deleted the improve-docs branch June 26, 2024 17:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants