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

feat(client/v2): broadcast logic #22282

Open
wants to merge 20 commits into
base: main
Choose a base branch
from

Conversation

JulianToledano
Copy link
Contributor

@JulianToledano JulianToledano commented Oct 16, 2024

Description

Closes:
#21851


Author Checklist

All items are required. Please add a note to the item if the item is not applicable and
please add links to any relevant follow up issues.

I have...

  • included the correct type prefix in the PR title, you can find examples of the prefixes below:
  • confirmed ! in the type prefix if API or client breaking change
  • targeted the correct branch (see PR Targeting)
  • provided a link to the relevant issue or specification
  • reviewed "Files changed" and left comments if necessary
  • included the necessary unit and integration tests
  • added a changelog entry to CHANGELOG.md
  • updated the relevant documentation or specification, including comments for documenting Go code
  • confirmed all CI checks have passed

Reviewers Checklist

All items are required. Please add a note if the item is not applicable and please add
your handle next to the items reviewed if you only reviewed selected items.

Please see Pull Request Reviewer section in the contributing guide for more information on how to review a pull request.

I have...

  • confirmed the correct type prefix in the PR title
  • confirmed all author checklist items have been addressed
  • reviewed state machine logic, API design and naming, documentation is accurate, tests and test coverage

Summary by CodeRabbit

  • New Features

    • Support for off-chain signing and verification of files.
    • Introduction of governance proposals and a transaction factory.
    • Extended keyring interface with new types.
    • Custom broadcast logic for enhanced transaction handling.
    • New CometBFT broadcasting client implementing the Broadcaster interface.
  • Improvements

    • Enhanced error messages to include possible enum values.
  • Bug Fixes

    • Resolved unmarshalling issues with transactions.
  • Documentation

    • Updated changelog to reflect new features, improvements, and breaking changes.
  • Tests

    • Added unit tests for the CometBFT broadcaster functionality.

@github-actions github-actions bot added the C:CLI label Oct 16, 2024
@JulianToledano JulianToledano linked an issue Oct 16, 2024 that may be closed by this pull request
@JulianToledano JulianToledano marked this pull request as ready for review October 16, 2024 17:22
Copy link
Contributor

coderabbitai bot commented Oct 16, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes in this pull request involve updates to the client/v2 module, including the addition of new features such as off-chain signing, governance proposals, and a transaction factory. The keyring interface has been extended, and custom broadcast logic has been introduced. Several dependencies have been modified across various go.mod files, and a new Broadcaster interface has been created. Additionally, new files for broadcasting and testing functionalities have been added, along with updates to the changelog reflecting these changes.

Changes

File Change Summary
client/v2/CHANGELOG.md Updated to include new features, improvements, API breaking changes, and bug fixes.
client/v2/go.mod Added go.uber.org/mock v0.5.0, updated cosmossdk.io/schema, and changed status of cometbft.
scripts/mockgen.sh Added command to generate a mock for comet.go.
simapp/go.mod Updated cosmossdk.io/schema and modified indirect dependencies.
simapp/v2/go.mod Updated cosmossdk.io/server/v2/cometbft dependency version.
tests/go.mod Updated cosmossdk.io/schema and added new indirect dependencies for testing.
client/v2/tx/tx.go Renamed and modified transaction generation and broadcasting functions to accept a broadcaster.
client/v2/broadcast/broadcaster.go Introduced a new Broadcaster interface with Broadcast and Consensus methods.
client/v2/broadcast/comet/comet.go Implemented CometBFTBroadcaster and related methods for transaction broadcasting.
client/v2/broadcast/comet/comet_test.go Added unit tests for CometBFTBroadcaster functionality.
client/v2/broadcast/comet/testutil/comet_mock.go Generated mock implementation of the CometRPC interface for testing.

Possibly related issues

Possibly related PRs

Suggested labels

C:x/auth, C:x/accounts, C:x/tx, C:server/v2, C:server/v2 cometbft, backport/v0.52.x

Suggested reviewers

  • aaronc
  • facundomedica
  • sontrinh16
  • testinginprod
  • kocubinski
  • julienrbrt

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

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

This comment has been minimized.

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: 9

🧹 Outside diff range and nitpick comments (9)
client/v2/internal/broadcast/broadcaster_test.go (2)

10-26: LGTM: Well-structured table-driven test.

The test function and test case structure are well-designed. Consider adding a comment describing the purpose of the Test_newBroadcaster function for better documentation.

You could add a comment like this before the function:

// Test_newBroadcaster verifies that the newBroadcaster function correctly creates
// and configures broadcasters based on different consensus types and options.
func Test_newBroadcaster(t *testing.T) {
    // ... (existing code)
}

27-39: LGTM: Well-implemented test execution loop.

The test execution loop is well-structured and covers both error and success cases. Consider adding a check for the broadcasting mode in non-error cases to ensure it's set correctly.

You could add a check like this after line 35:

if cometBroadcaster, ok := got.(*CometBftBroadcaster); ok {
    require.Equal(t, tt.opts[0].(func(*options)), cometBroadcaster.mode)
}

This assumes that the first option is always the mode setter. Adjust as necessary based on your actual implementation.

client/v2/internal/broadcast/comet_test.go (3)

21-51: Consider expanding test cases for TestNewCometBftBroadcaster.

While the current test case is a good start, consider adding more test cases to cover:

  1. Error scenarios (e.g., invalid options)
  2. Different combinations of options
  3. Edge cases (e.g., nil codec)

This will ensure more comprehensive testing of the NewCometBftBroadcaster function.


53-90: Enhance test coverage for TestCometBftBroadcaster_Broadcast.

To improve the test coverage:

  1. Add test cases for other broadcast modes (e.g., async, commit).
  2. Include error scenarios (e.g., RPC client returning an error).
  3. Test with different input payloads.
  4. Verify the returned TxResponse fields more thoroughly.

These additions will provide a more comprehensive test suite for the Broadcast method.


92-126: LGTM: Comprehensive error checking in Test_checkCometError.

The test function effectively covers various error scenarios and their corresponding response codes. The use of table-driven tests is commendable.

Minor suggestion: Consider adding a test case for an unknown error to ensure the function handles unexpected errors gracefully.

tests/go.mod (1)

Line range hint 232-268: Carefully manage replace directives for local development

The go.mod file contains numerous replace directives, many of which point to local paths. While this is common for local development in a monorepo setup, please consider the following:

  1. Ensure that these replace directives are necessary for the test environment and don't accidentally override important versions in production builds.
  2. Document the purpose of these replace directives, especially for newcomers to the project who might not be familiar with the local development setup.
  3. Consider implementing a mechanism to automatically update or remove these replace directives when creating release builds to ensure reproducibility.
  4. Regularly review and clean up any outdated or unnecessary replace directives to keep the go.mod file maintainable.

Consider adding a comment at the beginning of the replace section explaining its purpose and any necessary steps for contributors working with this setup.

client/v2/internal/broadcast/broadcaster.go (1)

46-46: Consider utilizing the 'context' parameter or removing it if unnecessary

The create method currently includes a context.Context parameter named _, which is unused. If the context isn't needed, consider removing it to simplify the function signature. If you plan to use it later, you might want to rename it from _ to ctx for clarity.

If removing the context parameter:

-func (f broadcasterFactory) create(_ context.Context, consensus, url string, opts ...Option) (Broadcaster, error) {
+func (f broadcasterFactory) create(consensus, url string, opts ...Option) (Broadcaster, error) {

If keeping it for future use:

-func (f broadcasterFactory) create(_ context.Context, consensus, url string, opts ...Option) (Broadcaster, error) {
+func (f broadcasterFactory) create(ctx context.Context, consensus, url string, opts ...Option) (Broadcaster, error) {
client/v2/internal/broadcast/comet.go (2)

76-76: Return nil slices when returning errors

When returning an error, it's idiomatic in Go to return nil slices instead of empty slices. This clearly indicates that no valid data is being returned.

Update the return statements:

- return []byte{}, fmt.Errorf("unknown broadcast mode: %s", c.mode)
+ return nil, fmt.Errorf("unknown broadcast mode: %s", c.mode)

- return []byte{}, err
+ return nil, err

Also applies to: 81-81


156-159: Avoid unnecessary named return values

The function parseABCILogs uses named return values, which are unnecessary in this context and can reduce code clarity.

Simplify the function signature:

- func parseABCILogs(logs string) (res []*apiacbci.ABCIMessageLog, err error) {
+ func parseABCILogs(logs string) ([]*apiacbci.ABCIMessageLog, error) {

Adjust the return statement accordingly:

return res, err
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 76529d7 and 39b5126.

⛔ Files ignored due to path filters (3)
  • client/v2/go.sum is excluded by !**/*.sum
  • simapp/go.sum is excluded by !**/*.sum
  • tests/go.sum is excluded by !**/*.sum
📒 Files selected for processing (9)
  • client/v2/go.mod (4 hunks)
  • client/v2/internal/broadcast/broadcaster.go (1 hunks)
  • client/v2/internal/broadcast/broadcaster_test.go (1 hunks)
  • client/v2/internal/broadcast/comet.go (1 hunks)
  • client/v2/internal/broadcast/comet_test.go (1 hunks)
  • client/v2/internal/broadcast/testutil/comet_mock.go (1 hunks)
  • simapp/go.mod (1 hunks)
  • simapp/v2/go.mod (1 hunks)
  • tests/go.mod (1 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
client/v2/internal/broadcast/broadcaster.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

client/v2/internal/broadcast/broadcaster_test.go (2)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

client/v2/internal/broadcast/comet.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

client/v2/internal/broadcast/comet_test.go (2)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

client/v2/internal/broadcast/testutil/comet_mock.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

tests/go.mod (1)

Pattern tests/**/*: "Assess the integration and e2e test code assessing sufficient code coverage for the changes associated in the pull request"

🪛 GitHub Check: CodeQL
client/v2/internal/broadcast/testutil/comet_mock.go

[notice] 14-14: Sensitive package import
Certain system packages contain functions which may be a possible source of non-determinism

🔇 Additional comments (12)
client/v2/internal/broadcast/broadcaster_test.go (1)

1-8: LGTM: Package declaration and imports are correct.

The package name is appropriate, and the imports are relevant and correctly ordered.

client/v2/internal/broadcast/comet_test.go (2)

3-17: LGTM: Import statements are well-organized.

The import statements are correctly grouped and organized, including both standard library and third-party packages. The use of aliasing for some imports (e.g., apiacbci, mockrpc) improves readability.


1-126: Overall assessment: Good foundation with room for improvement.

The comet_test.go file provides a solid foundation for testing the CometBftBroadcaster. The tests are well-structured and follow Go testing conventions. However, there's room for improvement in test coverage, particularly for edge cases and error scenarios.

Consider implementing the suggested enhancements to create a more robust and comprehensive test suite. This will increase confidence in the correctness and reliability of the CometBftBroadcaster implementation.

client/v2/go.mod (4)

32-32: Approve the update of cosmossdk.io/schema and monitor for stable releases.

The cosmossdk.io/schema dependency has been updated to a more recent pre-release version. This update likely includes bug fixes or new features that benefit the project.

To stay informed about new releases and potentially upgrade to a stable version in the future, you can periodically check for updates:

#!/bin/bash
go list -m -versions cosmossdk.io/schema

This will show all available versions, helping to identify when a stable release becomes available.


52-52: Verify the direct usage of github.com/cometbft/cometbft and its implications.

The github.com/cometbft/cometbft dependency is now directly used in this module, as indicated by the removal of the // indirect comment. This change suggests a more direct integration with CometBFT functionality.

To understand the extent of this change and its implications, you can run:

#!/bin/bash
# Search for direct usage of cometbft package
grep -R "github.com/cometbft/cometbft" --include="*.go" .

This will help identify where and how CometBFT is being used directly in the codebase. Consider reviewing these occurrences to ensure they align with the module's architecture and design goals.


180-185: Approve the addition of replace directives and verify local paths.

The new replace directives for cosmossdk.io/server/v2, cosmossdk.io/server/v2/cometbft, cosmossdk.io/store/v2, and cosmossdk.io/x/consensus are consistent with a monorepo structure or local development setup. This approach facilitates easier development and testing of interdependent modules.

To ensure these local paths are correct and the modules exist, you can run:

#!/bin/bash
# Check if the local paths exist
for path in ./../../server/v2 ./../../server/v2/cometbft ./../../store/v2 ./../../x/consensus; do
    if [ -d "$path" ]; then
        echo "$path exists"
    else
        echo "$path does not exist"
    fi
done

This script will verify the existence of the local paths specified in the replace directives. If any path is missing, it may indicate a potential issue with the project structure or an outdated replace directive.


17-17: Approve the addition of go.uber.org/mock and verify its usage.

The addition of go.uber.org/mock v0.4.0 is a positive step towards improving the testing infrastructure. This mocking framework can enhance the quality and reliability of unit tests.

To ensure this dependency is being utilized effectively, you can run:

This will help verify that the mocking framework is being used in the codebase and identify areas where it could be further leveraged.

tests/go.mod (3)

Line range hint 1-268: Overall assessment of go.mod changes

The changes to the tests/go.mod file align with the PR objectives of introducing new broadcast logic and expanding the test suite. The updates include:

  1. Updating existing dependencies, particularly cosmossdk.io/schema.
  2. Adding new dependencies related to testing and Cosmos SDK modules.
  3. Maintaining a set of replace directives for local development.

These changes suggest a significant expansion or improvement of the test suite, which is generally positive. However, to ensure the stability and maintainability of the project, please:

  1. Verify that all new dependencies are necessary and don't introduce conflicts.
  2. Ensure that the updated cosmossdk.io/schema dependency is compatible with the existing codebase.
  3. Carefully manage the replace directives to maintain reproducibility between development and production environments.
  4. Consider adding documentation about the purpose and management of the replace directives.

After addressing these points, the changes to the go.mod file appear to be appropriate for the PR objectives.


68-68: Verify compatibility with updated cosmossdk.io/schema dependency

The cosmossdk.io/schema dependency has been updated to version v0.3.1-0.20241010135032-192601639cac. Please ensure that this update doesn't introduce any breaking changes that could affect the tests. It's recommended to review the changelog of this dependency and run the test suite to confirm compatibility.

#!/bin/bash
# Description: Check for any breaking changes in the updated cosmossdk.io/schema dependency

# Test: Search for any usage of cosmossdk.io/schema in the test files
rg --type go 'cosmossdk\.io/schema' tests/

Line range hint 28-41: Verify necessity and impact of new dependencies

Several new dependencies have been added to the go.mod file, including testing libraries and Cosmos SDK modules. While expanding the test suite is generally positive, please ensure that:

  1. Each new dependency is necessary and serves a specific purpose in the tests.
  2. There are no version conflicts between the new and existing dependencies.
  3. The addition of these dependencies doesn't significantly increase the build time or complexity of the test suite.

It's recommended to document the purpose of each new dependency, especially for the newly added Cosmos SDK modules, to maintain clarity for future contributors.

✅ Verification successful

Dependencies Verified Successfully

All newly added dependencies in tests/go.mod are actively used in the test suite, ensuring their necessity and proper integration. No conflicts or unnecessary complexities were found.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for usage of newly added dependencies in test files

# Test: Search for usage of new dependencies in test files
for dep in "cosmossdk.io/core/testing" "cosmossdk.io/x/accounts" "cosmossdk.io/x/bank" "cosmossdk.io/x/gov" "github.com/cometbft/cometbft/api" "github.com/google/go-cmp" "github.com/google/gofuzz" "github.com/jhump/protoreflect" "github.com/rs/zerolog" "github.com/spf13/viper"; do
    echo "Checking usage of $dep"
    rg --type go "$dep" tests/
done

Length of output: 138


Script:

#!/bin/bash
# Description: Check for usage of newly added dependencies in test files

# Test: Search for usage of new dependencies in test files
for dep in "cosmossdk.io/core/testing" "cosmossdk.io/x/accounts" "cosmossdk.io/x/bank" "cosmossdk.io/x/gov" "github.com/cometbft/cometbft/api" "github.com/google/go-cmp" "github.com/google/gofuzz" "github.com/jhump/protoreflect" "github.com/rs/zerolog" "github.com/spf13/viper"; do
    echo "Checking usage of $dep"
    rg --type go "$dep" tests/
done

Length of output: 20189

simapp/go.mod (1)

65-65: Verify compatibility with updated cosmossdk.io/schema dependency

The cosmossdk.io/schema dependency has been updated to a newer version. While this update likely includes improvements or bug fixes, it's important to ensure compatibility with the rest of the module and its dependencies.

  1. Please verify that this update doesn't introduce any breaking changes that could affect the simapp module.
  2. Review the changelog or commit history of the cosmossdk.io/schema repository for any significant changes between September 30, 2024, and October 10, 2024.
  3. Consider running the test suite to ensure that the update doesn't cause any regressions.

To help verify the impact of this change, you can run the following script:

simapp/v2/go.mod (1)

14-14: Dependency update looks good, verify compatibility.

The update of cosmossdk.io/server/v2/cometbft to version v0.0.0-20241015140036-ee3d320eaa55 appears to be in line with the PR objectives. This change is likely related to the new broadcast logic being introduced.

To ensure compatibility, please run the following commands:

client/v2/internal/broadcast/broadcaster_test.go Outdated Show resolved Hide resolved
client/v2/go.mod Outdated Show resolved Hide resolved
client/v2/internal/broadcast/broadcaster.go Outdated Show resolved Hide resolved
client/v2/internal/broadcast/broadcaster.go Outdated Show resolved Hide resolved
client/v2/internal/broadcast/broadcaster.go Outdated Show resolved Hide resolved
client/v2/internal/broadcast/comet.go Outdated Show resolved Hide resolved
client/v2/internal/broadcast/comet.go Outdated Show resolved Hide resolved
client/v2/internal/broadcast/comet.go Outdated Show resolved Hide resolved
client/v2/internal/broadcast/comet.go Outdated Show resolved Hide resolved
client/v2/go.mod Outdated Show resolved Hide resolved
client/v2/internal/broadcast/comet.go Outdated 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: 2

🧹 Outside diff range and nitpick comments (4)
client/v2/internal/broadcast/broadcaster_test.go (1)

57-83: LGTM: Good test coverage for Factory.Register.

The TestFactory_Register function provides a good test case for registering and creating a custom broadcaster. The implementation is correct and follows Go testing conventions.

Consider adding an additional test case to verify the behavior when attempting to register a broadcaster with an already existing consensus type. This would ensure that the Register method handles potential conflicts correctly.

client/v2/CHANGELOG.md (1)

47-47: LGTM! Consider adding more detail to the feature description.

The new changelog entry for custom broadcast logic is correctly formatted and placed in the appropriate section. Well done!

To improve clarity, consider expanding the description slightly. For example:

* [#22282](https://github.com/cosmos/cosmos-sdk/pull/22282) Added custom broadcast logic to enhance transaction broadcasting flexibility.
client/v2/internal/broadcast/comet.go (2)

55-55: Rename struct field cdc to improve clarity

The field cdc in the CometBFTBroadcaster struct is not immediately descriptive. Renaming it to jsonCodec enhances readability and aligns with Go naming conventions.

Apply this diff to rename the field:

 type CometBFTBroadcaster struct {
     rpcClient CometRPC
     mode      string
-    cdc       codec.JSONCodec
+    jsonCodec codec.JSONCodec
 }

Ensure all references to c.cdc are updated to c.jsonCodec throughout the codebase.


60-64: Avoid unnecessary abbreviations in variable names

In the functions withMode and withJSONCodec, the variable cbc is used to represent a CometBFTBroadcaster. Using a more descriptive name like broadcaster improves code readability.

Update the variable names as shown:

For withMode:

 func withMode(mode string) func(broadcaster Broadcaster) {
     return func(b Broadcaster) {
-        cbc, ok := b.(*CometBFTBroadcaster)
+        broadcaster, ok := b.(*CometBFTBroadcaster)
         if !ok {
             return
         }
-        cbc.mode = mode
+        broadcaster.mode = mode
     }
 }

For withJSONCodec:

 func withJSONCodec(codec codec.JSONCodec) func(broadcaster Broadcaster) {
     return func(b Broadcaster) {
-        cbc, ok := b.(*CometBFTBroadcaster)
+        broadcaster, ok := b.(*CometBFTBroadcaster)
         if !ok {
             return
         }
-        cbc.jsonCodec = codec
+        broadcaster.jsonCodec = codec
     }
 }

Also applies to: 70-74

📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 39b5126 and c13fe79.

📒 Files selected for processing (7)
  • client/v2/CHANGELOG.md (1 hunks)
  • client/v2/go.mod (3 hunks)
  • client/v2/internal/broadcast/broadcaster.go (1 hunks)
  • client/v2/internal/broadcast/broadcaster_test.go (1 hunks)
  • client/v2/internal/broadcast/comet.go (1 hunks)
  • client/v2/internal/broadcast/comet_test.go (1 hunks)
  • client/v2/internal/broadcast/testutil/comet_mock.go (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • client/v2/internal/broadcast/testutil/comet_mock.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • client/v2/go.mod
  • client/v2/internal/broadcast/comet_test.go
🧰 Additional context used
📓 Path-based instructions (4)
client/v2/CHANGELOG.md (1)

Pattern **/*.md: "Assess the documentation for misspellings, grammatical errors, missing documentation and correctness"

client/v2/internal/broadcast/broadcaster.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

client/v2/internal/broadcast/broadcaster_test.go (2)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

client/v2/internal/broadcast/comet.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

🔇 Additional comments (11)
client/v2/internal/broadcast/broadcaster_test.go (3)

10-18: LGTM: testBFT struct implementation is correct.

The testBFT struct correctly implements the Broadcaster interface with Broadcast and Consensus methods. The implementation is suitable for testing purposes.


20-55: LGTM: Comprehensive test cases for newBroadcaster.

The Test_newBroadcaster function provides good coverage with test cases for both supported ("comet") and unsupported consensus types. This addresses the previous review comment about adding more test cases.


1-9: LGTM: File structure and imports are correct.

The file structure follows Go conventions, and the necessary imports are included without any unnecessary ones.

client/v2/internal/broadcast/broadcaster.go (7)

1-7: LGTM: Package declaration and imports are appropriate.

The package name "broadcast" is concise and descriptive, adhering to the Uber Golang style guide. The imports are standard and necessary for the functionality implemented in this file.


8-18: LGTM: Constants are well-defined and past review comment addressed.

The constants for broadcast modes and consensus engine are clearly defined and documented. The naming convention is consistent, and the previously suggested renaming of 'cometBftConsensus' to 'cometBFTConsensus' has been implemented, addressing the past review comment.


20-35: LGTM: Broadcaster interface and NewBroadcasterFn type are well-defined.

The Broadcaster interface and NewBroadcasterFn type are clearly defined and well-documented. The method names are descriptive and follow Go conventions. The structure provides a flexible way to create and use different broadcaster implementations.


36-47: LGTM: BroadcasterFactory interface is well-defined and addresses past concerns.

The BroadcasterFactory interface is clearly defined with Register and Create methods, following Go conventions. This design addresses the previous concern about extendability, allowing for easy registration of new broadcaster types.


49-68: LGTM: Factory struct and methods are well-implemented.

The Factory struct correctly implements the BroadcasterFactory interface. The Create method includes appropriate error handling for invalid consensus types, and the Register method allows for easy extension of supported consensus engines.


70-79: LGTM: NewFactory function is well-implemented and past review comment addressed.

The NewFactory function correctly initializes a Factory instance with a default CometBFT broadcaster. The previously suggested renaming of 'NewCometBftBroadcaster' to 'NewCometBFTBroadcaster' has been implemented, addressing the past review comment.


1-79: Overall: Excellent implementation of the broadcasting mechanism.

This file introduces a well-structured and extensible broadcasting mechanism for transactions. The code follows the Uber Golang style guide, with clear interfaces, appropriate documentation, and consistent naming conventions. All past review comments have been addressed, resulting in a robust and maintainable implementation.

client/v2/CHANGELOG.md (1)

Line range hint 1-148: Excellent adherence to changelog best practices!

The overall structure and formatting of the changelog are exemplary. It follows the guiding principles, maintains consistent formatting, and presents information in a clear, chronological order. Great job in maintaining a user-friendly and informative changelog!

client/v2/internal/broadcast/comet.go Outdated Show resolved Hide resolved
client/v2/internal/broadcast/comet.go Outdated 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: 6

🧹 Outside diff range and nitpick comments (17)
client/v2/broadcast/factory_test.go (4)

13-21: LGTM: Mock broadcaster implementation is suitable for testing.

The testBFT struct and its methods provide a simple mock implementation for testing purposes. This is a good approach for unit testing.

Consider expanding the Broadcast method to return meaningful values or errors in different scenarios, which could enable more comprehensive testing:

func (t testBFT) Broadcast(_ context.Context, msg []byte) ([]byte, error) {
    if len(msg) == 0 {
        return nil, errors.New("empty message")
    }
    return []byte("mocked response"), nil
}

23-58: LGTM: Well-structured test for the broadcaster factory.

The Test_newBroadcaster function is well-implemented using table-driven tests, which is a Go best practice. It covers both positive and negative test cases, and uses appropriate assertions with the require package.

Consider adding more test cases to cover edge cases or different configurations:

  1. Test with invalid URL format.
  2. Test with additional options for the CometBFTBroadcaster.
  3. Test error cases for the CometBFTBroadcaster creation.

Example:

{
    name:      "invalid_url",
    consensus: "comet",
    opts:      []types.Option{},
    wantErr:   true,
},
{
    name:      "comet_with_additional_options",
    consensus: "comet",
    opts: []types.Option{
        comet.WithMode(comet.BroadcastAsync),
        comet.WithTimeout(5 * time.Second),
    },
    want: &comet.CometBFTBroadcaster{},
},

60-86: LGTM: Good test coverage for broadcaster registration.

The TestFactory_Register function is well-implemented, following Go testing best practices with a table-driven approach. It effectively tests the registration and creation of a new broadcaster type.

To improve test coverage, consider adding the following test cases:

  1. Registering a broadcaster with an already existing consensus type (to test overwriting or error handling).
  2. Attempting to create a broadcaster that hasn't been registered.
  3. Testing with a creator function that returns an error.

Example:

{
    name:      "register_existing_consensus",
    consensus: "comet",
    creator: func(url string, opts ...types.Option) (types.Broadcaster, error) {
        return testBFT{}, nil
    },
},
{
    name:      "create_unregistered_broadcaster",
    consensus: "unregistered",
    creator:   nil,
},
{
    name:      "creator_returns_error",
    consensus: "errorBFT",
    creator: func(url string, opts ...types.Option) (types.Broadcaster, error) {
        return nil, errors.New("creation error")
    },
},

Also, consider testing the behavior when passing options to the Create method:

b, err := f.Create(context.Background(), tt.consensus, "localhost:26657", types.WithTimeout(5*time.Second))

1-86: Overall: Well-structured and comprehensive test file.

This test file for the broadcast package is well-organized and follows Go testing best practices. It provides good coverage of the basic functionality for the broadcaster factory and registration mechanism.

To further improve the test suite:

  1. Consider adding more edge cases and error scenarios to increase test coverage.
  2. Implement subtests for complex test cases to improve test organization and readability.
  3. Add benchmarks for performance-critical parts of the broadcaster, if any.
  4. Include examples in the test file to demonstrate usage, which can serve as documentation.

Example of adding a subtest:

t.Run("Create Broadcaster", func(t *testing.T) {
    // Existing Test_newBroadcaster logic
})

t.Run("Register Broadcaster", func(t *testing.T) {
    // Existing TestFactory_Register logic
})

Example of adding a benchmark:

func BenchmarkBroadcasterCreation(b *testing.B) {
    f := NewFactory()
    for i := 0; i < b.N; i++ {
        _, _ = f.Create(context.Background(), "comet", "localhost:26657")
    }
}
client/v2/internal/comet/comet_test.go (4)

22-52: LGTM: Well-structured table-driven test for NewCometBftBroadcaster.

The test function follows Go best practices for table-driven tests and covers the basic functionality of the constructor.

Consider adding more test cases to cover different combinations of options and potential error scenarios.


54-91: LGTM with suggestions: TestCometBftBroadcaster_Broadcast needs more coverage.

The test function correctly uses mocking and covers the basic functionality of the Broadcast method. However, there are areas for improvement:

  1. Add test cases for other broadcast modes (e.g., BroadcastAsync, BroadcastCommit).
  2. Include error scenarios to test error handling.
  3. Enhance assertions to check specific fields of the returned result, not just that it's non-nil.

93-127: LGTM: Comprehensive error handling tests for checkCometError.

The test function is well-structured and covers important error scenarios related to the mempool. The use of table-driven tests is appropriate, and the assertions are specific to the expected error codes.

Consider adding a test case for an unknown error type to ensure the function handles unexpected errors gracefully.


1-127: Overall, well-structured tests with room for improvement.

This test file provides a solid foundation for testing the CometBFTBroadcaster functionality. It follows Go testing best practices, uses appropriate mocking, and covers key functionalities. To further enhance the test suite:

  1. Expand test cases in TestNewCometBftBroadcaster and TestCometBftBroadcaster_Broadcast to cover more scenarios.
  2. Add tests for different broadcast modes and error handling in TestCometBftBroadcaster_Broadcast.
  3. Enhance assertions to be more specific about expected results.
  4. Consider adding a test case for unknown errors in Test_checkCometError.

These improvements will increase the robustness and reliability of the test suite.

scripts/mockgen.sh (2)

31-31: LGTM! Consider adding a comment for clarity.

The new mock generation command for the comet.go file is consistent with the existing pattern and supports the broadcast logic implementation mentioned in the PR objectives.

Consider adding a comment above this line to explain the purpose of this mock, for example:

+# Generate mock for CometRPC interface used in broadcast logic
$mockgen_cmd -source=client/v2/internal/comet/comet.go -package testutil -destination client/v2/internal/comet/testutil/comet_mock.go

Line range hint 1-31: Consider improving script organization and readability.

While the script functions correctly, its readability and maintainability could be enhanced:

  1. Group related mock generations together (e.g., by module or functionality).
  2. Add comments to separate different sections.
  3. Ensure consistent formatting across all commands (e.g., line breaks).

These improvements would make the script easier to understand and maintain as it grows.

Here's an example of how you could start reorganizing the script:

#!/usr/bin/env bash

mockgen_cmd="mockgen"

# Core mocks
$mockgen_cmd -source=baseapp/abci_utils.go -package mock -destination baseapp/testutil/mock/mocks.go
$mockgen_cmd -source=client/account_retriever.go -package mock -destination testutil/mock/account_retriever.go
$mockgen_cmd -source=types/module/module.go -package mock -destination testutil/mock/types_module_module.go
$mockgen_cmd -source=types/module/mock_appmodule_test.go -package mock -destination testutil/mock/types_mock_appmodule.go
$mockgen_cmd -source=types/invariant.go -package mock -destination testutil/mock/types_invariant.go

# External dependency mocks
$mockgen_cmd -package mock -destination testutil/mock/grpc_server.go github.com/cosmos/gogoproto/grpc Server
$mockgen_cmd -package mock -destination testutil/mock/logger.go cosmossdk.io/log Logger

# Module-specific mocks
## NFT module
$mockgen_cmd -source=x/nft/expected_keepers.go -package testutil -destination x/nft/testutil/expected_keepers_mocks.go

## Feegrant module
$mockgen_cmd -source=x/feegrant/expected_keepers.go -package testutil -destination x/feegrant/testutil/expected_keepers_mocks.go

# ... (continue grouping and commenting other mock generations)

# Client v2 mocks
$mockgen_cmd -source=client/v2/internal/comet/comet.go -package testutil -destination client/v2/internal/comet/testutil/comet_mock.go

This structure groups related mocks together and adds comments for clarity, making the script more organized and easier to maintain.

client/v2/internal/comet/testutil/comet_mock.go (1)

226-239: Minor inconsistency in Status method parameter naming.

The Status method uses arg0 for the context parameter, while other methods use ctx. Consider renaming arg0 to ctx for consistency.

Apply this change for better consistency:

-func (m *MockCometRPC) Status(arg0 context.Context) (*types.ResultStatus, error) {
+func (m *MockCometRPC) Status(ctx context.Context) (*types.ResultStatus, error) {
 	m.ctrl.T.Helper()
-	ret := m.ctrl.Call(m, "Status", arg0)
+	ret := m.ctrl.Call(m, "Status", ctx)
 	ret0, _ := ret[0].(*types.ResultStatus)
 	ret1, _ := ret[1].(error)
 	return ret0, ret1
 }

 // Status indicates an expected call of Status.
-func (mr *MockCometRPCMockRecorder) Status(arg0 any) *gomock.Call {
+func (mr *MockCometRPCMockRecorder) Status(ctx any) *gomock.Call {
 	mr.mock.ctrl.T.Helper()
-	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Status", reflect.TypeOf((*MockCometRPC)(nil).Status), arg0)
+	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Status", reflect.TypeOf((*MockCometRPC)(nil).Status), ctx)
 }
client/v2/broadcast/types/broadcaster.go (2)

18-19: Consider renaming NewBroadcasterFn to NewBroadcasterFunc for clarity

Using Func instead of Fn improves readability and aligns with common Go naming conventions for function types.

Apply this diff to rename the function type:

-// NewBroadcasterFn is a function type for creating Broadcaster instances.
-NewBroadcasterFn func(url string, opts ...Option) (Broadcaster, error)
+// NewBroadcasterFunc is a function type for creating Broadcaster instances.
+NewBroadcasterFunc func(url string, opts ...Option) (Broadcaster, error)

23-24: Update comment to reflect parameter type accurately

The comment references BroadcasterCreator, but the parameter is creator NewBroadcasterFn. For consistency, consider modifying the comment.

Apply this diff to correct the comment:

-// Register adds a new BroadcasterCreator for a given consensus type to the factory.
+// Register adds a new Broadcaster creator for a given consensus type to the factory.
client/v2/internal/comet/comet.go (4)

71-79: Handle type assertion failure in WithMode option

In the WithMode function, if the type assertion fails, the function silently returns without setting the mode. This can make debugging difficult if the wrong type is passed.

Consider logging a warning or returning an error to notify the user about the incorrect type:

func WithMode(mode string) func(broadcaster broadcasttypes.Broadcaster) {
	return func(b broadcasttypes.Broadcaster) {
		cbc, ok := b.(*CometBFTBroadcaster)
		if !ok {
-			return
+			fmt.Printf("WithMode option ignored: broadcaster is not a CometBFTBroadcaster\n")
			return
		}
		cbc.mode = mode
	}
}

81-89: Handle type assertion failure in WithJsonCodec option

Similar to WithMode, the WithJsonCodec function silently fails if the type assertion does not succeed.

Add a warning to inform the user:

func WithJsonCodec(codec codec.JSONCodec) func(broadcaster broadcasttypes.Broadcaster) {
	return func(b broadcasttypes.Broadcaster) {
		cbc, ok := b.(*CometBFTBroadcaster)
		if !ok {
-			return
+			fmt.Printf("WithJsonCodec option ignored: broadcaster is not a CometBFTBroadcaster\n")
			return
		}
		cbc.cdc = codec
	}
}

107-109: Consider using a pointer receiver for methods

The methods Consensus, Broadcast, and broadcast have a value receiver, which means the receiver is copied on each method call. Since CometBFTBroadcaster contains fields like rpcClient, copying could be inefficient.

Change the receiver to a pointer to improve efficiency:

- func (c CometBFTBroadcaster) Consensus() string {
+ func (c *CometBFTBroadcaster) Consensus() string {

- func (c CometBFTBroadcaster) Broadcast(ctx context.Context, txBytes []byte) ([]byte, error) {
+ func (c *CometBFTBroadcaster) Broadcast(ctx context.Context, txBytes []byte) ([]byte, error) {

- func (c CometBFTBroadcaster) broadcast(ctx context.Context, txbytes []byte, fn func(ctx context.Context, tx cmttypes.Tx) (*coretypes.ResultBroadcastTx, error), ) (*apiacbci.TxResponse, error) {
+ func (c *CometBFTBroadcaster) broadcast(ctx context.Context, txbytes []byte, fn func(ctx context.Context, tx cmttypes.Tx) (*coretypes.ResultBroadcastTx, error), ) (*apiacbci.TxResponse, error) {

137-137: Possible variable shadowing in error handling

In line 137, the variable errRes is introduced in the condition, which could potentially shadow other variables and lead to confusing code.

Define errRes outside the if condition for clarity:

func (c *CometBFTBroadcaster) broadcast(ctx context.Context, txbytes []byte,
	fn func(ctx context.Context, tx cmttypes.Tx) (*coretypes.ResultBroadcastTx, error),
) (*apiacbci.TxResponse, error) {
	bResult, err := fn(ctx, txbytes)
+	var errRes *apiacbci.TxResponse
	if err != nil {
-		if errRes := checkCometError(err, txbytes); errRes != nil {
+		errRes = checkCometError(err, txbytes)
+		if errRes != nil {
			return errRes, nil
		}
		return nil, err
	}
	return newResponseFormatBroadcastTx(bResult), nil
}
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between c13fe79 and bee57fa.

📒 Files selected for processing (7)
  • client/v2/broadcast/factory.go (1 hunks)
  • client/v2/broadcast/factory_test.go (1 hunks)
  • client/v2/broadcast/types/broadcaster.go (1 hunks)
  • client/v2/internal/comet/comet.go (1 hunks)
  • client/v2/internal/comet/comet_test.go (1 hunks)
  • client/v2/internal/comet/testutil/comet_mock.go (1 hunks)
  • scripts/mockgen.sh (1 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
client/v2/broadcast/factory.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

client/v2/broadcast/factory_test.go (2)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

client/v2/broadcast/types/broadcaster.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

client/v2/internal/comet/comet.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

client/v2/internal/comet/comet_test.go (2)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

client/v2/internal/comet/testutil/comet_mock.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

🔇 Additional comments (11)
client/v2/broadcast/factory_test.go (1)

3-11: LGTM: Import statements are appropriate.

The import statements are well-organized and include necessary packages for testing. The use of the require package from testify is a good practice for assertions in Go tests.

client/v2/internal/comet/comet_test.go (2)

3-18: LGTM: Import statements are well-organized.

The import statements are properly grouped and follow the Uber Go Style Guide recommendations. They include all necessary packages for the test file's functionality.


20-20: LGTM: Appropriate use of global variable for testing.

The global cdc variable is correctly initialized using a test utility, which is suitable for this test file.

client/v2/internal/comet/testutil/comet_mock.go (6)

1-11: LGTM: File header and package declaration are correct.

The file header correctly indicates that this is a generated file and should not be edited manually. The package name testutil is appropriate for a test utility mock.


12-21: LGTM: Imports are correct and necessary.

The imports include the required packages for the mock implementation, including the gomock package and the necessary types from the CometBFT project.


23-44: LGTM: MockCometRPC and MockCometRPCMockRecorder structures are correctly defined.

The MockCometRPC struct and its associated recorder are properly implemented, following the gomock conventions. The NewMockCometRPC function and EXPECT method are correctly defined.


46-59: LGTM: Sample methods (ABCIInfo, ABCIQuery, ABCIQueryWithOptions) are correctly implemented.

These methods demonstrate proper implementation of mock methods:

  1. Method signatures match the expected interface.
  2. They use m.ctrl.T.Helper() for test helper indication.
  3. m.ctrl.Call is used correctly for mocking method calls.
  4. Return values are properly type-asserted.
  5. Corresponding recorder methods are implemented correctly.

This pattern is consistent across all methods in the file.

Also applies to: 61-74, 76-89


166-209: LGTM: BroadcastTx methods are correctly implemented.

The BroadcastTxAsync, BroadcastTxCommit, and BroadcastTxSync methods are properly implemented, following the same pattern as other methods. They correctly use the types0.Tx type for the transaction parameter, which is consistent with the CometBFT types.


1-284: LGTM: Well-structured and comprehensive mock for CometRPC interface.

This generated mock file for the CometRPC interface is well-structured and follows best practices for mock objects using the gomock library. It provides mock implementations for all methods of the interface, enabling effective unit testing of components that depend on CometRPC.

Key strengths:

  1. Consistent implementation pattern across all methods.
  2. Proper use of gomock.Controller for managing mock behavior.
  3. Correct type assertions for return values.
  4. Inclusion of both mock methods and their corresponding recorder methods.

The only minor issue is the inconsistent parameter naming in the Status method, which has been addressed in a previous comment.

Overall, this mock file is of high quality and should serve its purpose well in the testing suite.

client/v2/broadcast/types/broadcaster.go (2)

1-32: Interfaces and types are well-structured and conform to Go conventions

The overall design of the interfaces and types is sound and follows Go best practices.


30-31: 🛠️ Refactor suggestion

Clarify the Option function signature

Since Broadcaster is an interface, passing it by value may not allow modification of the underlying implementation. Consider defining Option to accept a pointer to the concrete type or a configuration struct.

An example adjustment:

-// Option is a function that configures a Broadcaster.
-Option func(Broadcaster)
+// Option is a function that configures a Broadcaster implementation.
+Option func(interface{})

Likely invalid or redundant comment.

client/v2/broadcast/factory.go Outdated Show resolved Hide resolved
client/v2/broadcast/factory.go Outdated Show resolved Hide resolved
client/v2/internal/comet/comet.go Outdated Show resolved Hide resolved
client/v2/internal/comet/comet.go Outdated Show resolved Hide resolved
client/v2/internal/comet/comet.go Outdated Show resolved Hide resolved
client/v2/internal/comet/comet.go Outdated 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: 1

📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between bee57fa and b0094f3.

⛔ Files ignored due to path filters (3)
  • client/v2/go.sum is excluded by !**/*.sum
  • simapp/go.sum is excluded by !**/*.sum
  • tests/go.sum is excluded by !**/*.sum
📒 Files selected for processing (4)
  • client/v2/go.mod (3 hunks)
  • simapp/go.mod (1 hunks)
  • simapp/v2/go.mod (1 hunks)
  • tests/go.mod (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • simapp/go.mod
🚧 Files skipped from review as they are similar to previous changes (1)
  • client/v2/go.mod
🧰 Additional context used
📓 Path-based instructions (1)
tests/go.mod (1)

Pattern tests/**/*: "Assess the integration and e2e test code assessing sufficient code coverage for the changes associated in the pull request"

🔇 Additional comments (2)
simapp/v2/go.mod (2)

Line range hint 78-78: Note indirect dependency update.

The update to the indirect dependency cosmossdk.io/schema aligns the module with other parts of the project. This change is minor and doesn't require immediate action.


14-14: Approve dependency update with verification recommendation.

The update to a specific version of cosmossdk.io/server/v2/cometbft is a positive change, moving from an unstable pseudo-version to a more identifiable one. This can improve build reproducibility and stability.

Please verify that this version is compatible with the rest of the project and doesn't introduce any breaking changes. You can run the following script to check for any compatibility issues:

✅ Verification successful

Dependency update verified successfully.

No breaking changes or compatibility issues were found for cosmossdk.io/server/v2/cometbft version v0.0.0-20241015140036-ee3d320eaa55. The update is safe to proceed.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for compatibility issues with the updated cometbft dependency

# Test: Look for any breaking changes or compatibility issues mentioned in the changelog or release notes
gh repo view cosmos/cosmos-sdk --json url -q .url | xargs -I {} gh api {}/contents/server/v2/cometbft/CHANGELOG.md --jq .content | base64 -d | grep -i "breaking change\|compatibility"

# Test: Check if there are any open issues related to this version
gh issue list -R cosmos/cosmos-sdk --search "cometbft v0.0.0-20241015140036-ee3d320eaa55 in:body" --json title,url --jq '.[] | "- " + .title + " (" + .url + ")"'

Length of output: 480


Script:

#!/bin/bash
# Description: Check for compatibility issues with the updated cometbft dependency without using base64

# Test: Look for any breaking changes or compatibility issues mentioned in the changelog or release notes
gh api repos/cosmos/cosmos-sdk/contents/server/v2/cometbft/CHANGELOG.md -H "Accept: application/vnd.github.v3.raw" | grep -i -E "breaking change|compatibility"

# Test: Check if there are any open issues related to this version
gh issue list -R cosmos/cosmos-sdk --search "cometbft v0.0.0-20241015140036-ee3d320eaa55 in:body" --json title,url --jq '.[] | "- " + .title + " (" + .url + ")"'

Length of output: 350


Script:

#!/bin/bash
# Description: Locate all CHANGELOG.md files and search for compatibility issues with the updated cometbft dependency

# Find all CHANGELOG.md files in the repository
fd "CHANGELOG.md" > changelog_files.txt

# Search each CHANGELOG.md for breaking changes or compatibility issues
while read -r file; do
  echo "Searching in $file:"
  gh api repos/cosmos/cosmos-sdk/contents/"$file" -H "Accept: application/vnd.github.v3.raw" | grep -i -E "breaking change|compatibility"
done < changelog_files.txt

# Clean up
rm changelog_files.txt

# Check if there are any open issues related to this cometbft version
gh issue list -R cosmos/cosmos-sdk --search "cometbft v0.0.0-20241015140036-ee3d320eaa55 in:body" --json title,url --jq '.[] | "- " + .title + " (" + .url + ")"'

Length of output: 18403

tests/go.mod 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: 2

🧹 Outside diff range and nitpick comments (1)
client/v2/internal/comet/testutil/comet_mock.go (1)

6-6: Use //go:generate directive for code generation

It's recommended to use the //go:generate directive to automate code generation. This helps future developers easily regenerate the code and improves maintainability.

Apply this change:

-//	mockgen -source=client/v2/internal/comet/comet.go -package testutil -destination client/v2/internal/comet/testutil/comet_mock.go
+//go:generate mockgen -source=../comet.go -package testutil -destination=comet_mock.go
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between b0094f3 and ea3ffb8.

📒 Files selected for processing (6)
  • client/v2/broadcast/factory.go (1 hunks)
  • client/v2/broadcast/factory_test.go (1 hunks)
  • client/v2/go.mod (3 hunks)
  • client/v2/internal/comet/comet.go (1 hunks)
  • client/v2/internal/comet/comet_test.go (1 hunks)
  • client/v2/internal/comet/testutil/comet_mock.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
  • client/v2/broadcast/factory.go
  • client/v2/broadcast/factory_test.go
  • client/v2/go.mod
  • client/v2/internal/comet/comet.go
  • client/v2/internal/comet/comet_test.go
🧰 Additional context used
📓 Path-based instructions (1)
client/v2/internal/comet/testutil/comet_mock.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

client/v2/internal/comet/testutil/comet_mock.go Outdated Show resolved Hide resolved
client/v2/internal/comet/testutil/comet_mock.go Outdated Show resolved Hide resolved
client/v2/broadcast/factory.go Outdated Show resolved Hide resolved
client/v2/broadcast/factory.go Outdated 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: 1

📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between ea3ffb8 and 4ecd77f.

📒 Files selected for processing (4)
  • client/v2/broadcast/factory.go (1 hunks)
  • client/v2/broadcast/factory_test.go (1 hunks)
  • client/v2/broadcast/types/broadcaster.go (1 hunks)
  • client/v2/tx/tx.go (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • client/v2/broadcast/factory.go
  • client/v2/broadcast/factory_test.go
  • client/v2/broadcast/types/broadcaster.go
🧰 Additional context used
📓 Path-based instructions (1)
client/v2/tx/tx.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

🔇 Additional comments (7)
client/v2/tx/tx.go (7)

5-5: Importing the 'context' Package is Appropriate

The addition of the "context" import is necessary for handling context in function calls, specifically used in the getBroadcaster function.


14-15: Adding 'broadcast' Dependencies Correctly

The imports of "cosmossdk.io/client/v2/broadcast" and broadcasttypes "cosmossdk.io/client/v2/broadcast/types" are appropriate and required for the new broadcasting logic introduced in the code.


17-17: Including the 'comet' Internal Package

Importing "cosmossdk.io/client/v2/internal/comet" is necessary for creating the broadcaster with CometBFT-specific options, which aligns with the new implementation.


47-52: Proper Error Handling When Obtaining the Broadcaster

The code correctly initializes the broadcaster using getBroadcaster, checks for errors, and handles them appropriately before proceeding. This ensures robustness in the broadcasting process.


148-148: Updating 'BroadcastTx' Function Signature Enhances Modularity

The BroadcastTx function now accepts a broadcaster parameter, decoupling the broadcasting mechanism from the client context. This improves modularity and allows for greater flexibility in broadcasting strategies.


202-202: Utilizing the Broadcaster for Transaction Broadcasting

The change to use broadcaster.Broadcast ensures that the transaction broadcasting follows the new abstraction, making it consistent with the updated broadcasting logic.


207-207: 🛠️ Refactor suggestion

Enhance Broadcast Response Handling for Better User Feedback

The current implementation returns the broadcast response as a plain string, which might not provide sufficient information to the user, especially in the case of errors or detailed transaction results.

Consider parsing the response into a structured format or enriching the output to include more detailed information:

- return clientCtx.PrintString(string(res))
+ // Assuming 'res' is of a specific type that can be marshaled into JSON
+ output, err := ctx.Codec.MarshalJSON(res)
+ if err != nil {
+     return fmt.Errorf("failed to marshal broadcast response: %w", err)
+ }
+ return clientCtx.PrintString(string(output))

This approach provides a JSON-formatted response, improving readability and usefulness for the end-user.

Likely invalid or redundant comment.

client/v2/tx/tx.go Outdated Show resolved Hide resolved
Copy link
Member

@julienrbrt julienrbrt left a comment

Choose a reason for hiding this comment

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

lgtm! but imho we should delete the broadcast factory actual and let the caller handle calling the broadcaster, or use our helpers

Copy link
Member

Choose a reason for hiding this comment

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

Thinking about it, maybe we don't need a factory at all. When would you require multiple broadcasters? This adds another complexity layer

return BroadcastTx(ctx, txf, broadcaster, msgs...)
}

func getBroadcaster(ctx client.Context, flagSet *pflag.FlagSet) (broadcasttypes.Broadcaster, error) {
Copy link
Member

Choose a reason for hiding this comment

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

That works, but let's precise in the godoc that this uses by default a cometbft broadcaster.
Let's add GenerateOrBroadcastTxCLIWithBroadcaster as well so people don't need to re-implement this themselves.

}

// NewCometBFTBroadcaster creates a new CometBftBroadcaster.
func NewCometBFTBroadcaster(rpcURL string, opts ...broadcasttypes.Option) (*CometBFTBroadcaster, error) {
Copy link
Member

Choose a reason for hiding this comment

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

let's create a broadcaster package and make this public

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: 10

🧹 Outside diff range and nitpick comments (3)
client/v2/broadcast/broadcaster.go (1)

5-15: Consider enhancing the interface documentation.

While the current documentation provides basic information, it could be more comprehensive to help implementers better understand the contract.

Consider expanding the documentation as follows:

-// Broadcaster defines an interface for broadcasting transactions to the consensus engine.
+// Broadcaster defines an interface for broadcasting transactions to the consensus engine.
+// Implementations of this interface are responsible for handling the specifics of
+// transaction broadcasting for different consensus engines (e.g., CometBFT).
+//
+// Example usage:
+//
+//	broadcaster := GetBroadcaster()
+//	result, err := broadcaster.Broadcast(ctx, txBytes)
+//	if err != nil {
+//		// Handle error
+//	}
+//	// Process result

Also consider documenting common error conditions in the Broadcast method documentation:

 	// Broadcast sends a transaction to the network and returns the result.
 	//
 	// It returns a byte slice containing the formatted result that will be
-	// passed to the output writer, and an error if the broadcast failed.
+	// passed to the output writer, and an error if the broadcast failed.
+	// Common error conditions include:
+	// - Network connectivity issues
+	// - Invalid transaction format
+	// - Consensus engine-specific validation failures
client/v2/broadcast/comet/comet_test.go (2)

20-20: Consider adding a descriptive comment for the global codec variable.

While using a global codec variable is common in tests, adding a comment would help explain its purpose and configuration.

+// cdc is a codec instance used across all tests, configured with standard test options
 var cdc = testutil.CodecOptions{}.NewCodec()

22-58: Add more test cases for comprehensive constructor testing.

While the current test cases cover basic scenarios, consider adding tests for:

  1. Invalid broadcast mode
  2. Empty endpoint URL
  3. Malformed endpoint URL
 tests := []struct {
     name    string
     cdc     codec.JSONCodec
     mode    string
     want    *CometBFTBroadcaster
     wantErr bool
 }{
+    {
+        name:    "invalid mode",
+        mode:    "invalid",
+        cdc:     cdc,
+        wantErr: true,
+    },
+    {
+        name:    "empty endpoint",
+        mode:    BroadcastSync,
+        cdc:     cdc,
+        wantErr: true,
+    },
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 4ecd77f and 86b8d58.

📒 Files selected for processing (6)
  • client/v2/broadcast/broadcaster.go (1 hunks)
  • client/v2/broadcast/comet/comet.go (1 hunks)
  • client/v2/broadcast/comet/comet_test.go (1 hunks)
  • client/v2/broadcast/comet/testutil/comet_mock.go (1 hunks)
  • client/v2/tx/tx.go (5 hunks)
  • scripts/mockgen.sh (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • client/v2/broadcast/comet/testutil/comet_mock.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • scripts/mockgen.sh
🧰 Additional context used
📓 Path-based instructions (4)
client/v2/broadcast/broadcaster.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

client/v2/broadcast/comet/comet.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

client/v2/broadcast/comet/comet_test.go (2)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

client/v2/tx/tx.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

🔇 Additional comments (5)
client/v2/broadcast/broadcaster.go (1)

1-3: LGTM: Package declaration and imports are well-organized.

The package name is concise and follows Go conventions, and imports are properly organized.

client/v2/broadcast/comet/comet_test.go (1)

1-18: LGTM! Package and imports are well-organized.

The package name follows Go conventions, and imports are properly organized and necessary for the test implementation.

client/v2/broadcast/comet/comet.go (2)

100-101: 🛠️ Refactor suggestion

Improve the method comment to follow Go documentation conventions.

The comment for the Broadcast method should be more descriptive and start with the method name.

Apply this diff to enhance the comment:

-// Broadcast sends a transaction to the network and returns the result.
-// returns a byte slice containing the JSON-encoded result and an error if the broadcast failed.
+// Broadcast sends a transaction to the network and returns a JSON-encoded result.
+// It returns an error if the broadcast fails.

Likely invalid or redundant comment.


94-96: 🛠️ Refactor suggestion

Use pointer receiver for the Consensus method to avoid copying the struct.

Currently, the Consensus method has a value receiver. It's recommended to use a pointer receiver to avoid unnecessary copying of the CometBFTBroadcaster struct.

Apply this diff to change the method receiver:

-func (c CometBFTBroadcaster) Consensus() string {
+func (c *CometBFTBroadcaster) Consensus() string {
	return cometBFTConsensus
}

Likely invalid or redundant comment.

client/v2/tx/tx.go (1)

63-64: Handle errors returned by flagSet.GetString

The errors from flagSet.GetString for "node" and "broadcast-mode" are ignored. Consider handling these errors to prevent potential issues.

Apply this diff to handle the errors:

 func getCometBroadcaster(ctx client.Context, flagSet *pflag.FlagSet) (broadcast.Broadcaster, error) {
-	url, _ := flagSet.GetString("node")
-	mode, _ := flagSet.GetString("broadcast-mode")
+	url, err := flagSet.GetString("node")
+	if err != nil {
+		return nil, fmt.Errorf("failed to retrieve 'node' flag: %w", err)
+	}
+	mode, err := flagSet.GetString("broadcast-mode")
+	if err != nil {
+		return nil, fmt.Errorf("failed to retrieve 'broadcast-mode' flag: %w", err)
+	}
 	return comet.NewCometBFTBroadcaster(url, mode, ctx.Codec)
 }

client/v2/broadcast/comet/comet_test.go Outdated Show resolved Hide resolved
client/v2/broadcast/comet/comet_test.go Outdated Show resolved Hide resolved
client/v2/broadcast/comet/comet.go Outdated Show resolved Hide resolved
client/v2/broadcast/comet/comet.go Outdated Show resolved Hide resolved
client/v2/broadcast/comet/comet.go Outdated Show resolved Hide resolved
client/v2/broadcast/comet/comet.go Outdated Show resolved Hide resolved
client/v2/broadcast/comet/comet.go Outdated Show resolved Hide resolved
client/v2/broadcast/comet/comet.go Outdated Show resolved Hide resolved
client/v2/broadcast/comet/comet.go Outdated Show resolved Hide resolved
client/v2/tx/tx.go Outdated 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: 0

🧹 Outside diff range and nitpick comments (5)
client/v2/broadcast/comet/comet_test.go (4)

20-20: Consider moving the codec variable into test functions.

Package-level variables in tests can lead to shared state and potential test interdependence. Consider moving cdc into the test functions where it's needed for better test isolation.


23-45: Enhance test coverage for NewCometBftBroadcaster.

Consider adding these test cases:

  1. Invalid broadcast mode
  2. Validation of rpcClient initialization
 tests := []struct {
     name    string
     cdc     codec.JSONCodec
     mode    string
     want    *CometBFTBroadcaster
     wantErr bool
 }{
+    {
+        name:    "invalid broadcast mode",
+        mode:    "invalid_mode",
+        cdc:     cdc,
+        wantErr: true,
+    },
+    {
+        name:    "empty endpoint",
+        mode:    BroadcastSync,
+        cdc:     cdc,
+        wantErr: true,
+    },

105-110: Enhance broadcast response validation.

The test only checks if the response is not nil. Consider validating specific fields in the response:

  • Code
  • Data
  • Log
  • Codespace
  • Hash
-				require.NotNil(t, got)
+				require.Equal(t, uint32(0), got.Code)
+				require.NotEmpty(t, got.TxHash)
+				require.Empty(t, got.Codespace)

116-142: Enhance error checking test coverage.

Consider adding these test cases:

  1. Nil error (should return success response)
  2. Unknown error type (should return appropriate error code)

Also, validate additional response fields beyond just the Code:

  • Data
  • Log
  • Codespace
 tests := []struct {
     name string
     err  error
     want *apiacbci.TxResponse
 }{
+    {
+        name: "nil error",
+        err:  nil,
+        want: &apiacbci.TxResponse{
+            Code: 0,
+        },
+    },
+    {
+        name: "unknown error",
+        err:  errors.New("unknown error"),
+        want: &apiacbci.TxResponse{
+            Code:      1,
+            Log:      "unknown error",
+            Codespace: "sdk",
+        },
+    },
client/v2/tx/tx.go (1)

207-212: Consider documenting the response format.

The function now converts the broadcast response to a string before printing. It would be helpful to document the expected format of this response to help users parse or handle it appropriately.

 // BroadcastTx attempts to generate, sign and broadcast a transaction with the
 // given set of messages. It will also simulate gas requirements if necessary.
-// It will return an error upon failure.
+// It will return an error upon failure. The broadcast response is printed as a string
+// and follows the format: <describe expected format here>
 func BroadcastTx(clientCtx client.Context, txf Factory, broadcaster broadcast.Broadcaster, msgs ...transaction.Msg) error {
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between c840773 and 5b3db1e.

📒 Files selected for processing (3)
  • client/v2/broadcast/comet/comet.go (1 hunks)
  • client/v2/broadcast/comet/comet_test.go (1 hunks)
  • client/v2/tx/tx.go (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • client/v2/broadcast/comet/comet.go
🧰 Additional context used
📓 Path-based instructions (2)
client/v2/broadcast/comet/comet_test.go (2)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

client/v2/tx/tx.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

🔇 Additional comments (2)
client/v2/tx/tx.go (2)

Line range hint 24-47: LGTM! Well-structured function with clear separation of concerns.

The function properly handles different transaction modes and cleanly integrates the new broadcaster parameter.


60-64: Improve error handling in getCometBroadcaster.

The function currently ignores errors from flagSet.GetString. While these errors are unlikely in practice, proper error handling would make the code more robust.

This issue was previously identified in a past review. Please implement the suggested error handling:

func getCometBroadcaster(ctx client.Context, flagSet *pflag.FlagSet) (broadcast.Broadcaster, error) {
-    url, _ := flagSet.GetString("node")
-    mode, _ := flagSet.GetString("broadcast-mode")
+    url, err := flagSet.GetString("node")
+    if err != nil {
+        return nil, fmt.Errorf("failed to retrieve 'node' flag: %w", err)
+    }
+    mode, err := flagSet.GetString("broadcast-mode")
+    if err != nil {
+        return nil, fmt.Errorf("failed to retrieve 'broadcast-mode' flag: %w", err)
+    }
     return comet.NewCometBFTBroadcaster(url, mode, ctx.Codec)
}

Copy link
Member

@julienrbrt julienrbrt left a comment

Choose a reason for hiding this comment

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

lgtm!

@julienrbrt
Copy link
Member

blocked by #22362 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Client/v2 Custom Broadcast Logic
4 participants