Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

fix(server/v2/comebft): wire missing services + fix simulation #21964

Merged
merged 29 commits into from
Nov 19, 2024

Conversation

julienrbrt
Copy link
Member

@julienrbrt julienrbrt commented Sep 27, 2024

Description

Closes: #21958

IMPORTANT and discovered while working on this PR:

In v1, external grpc services were available to modules (comet services, node service, tx service)
In v2 they aren't, which is why we have a special handling for the tx service for simulation.


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

    • Introduced gRPC service for querying node-related information, including a Config method to retrieve minimum gas prices.
    • Added support for transaction simulation and broadcasting via gRPC.
  • Improvements

    • Enhanced error handling across various methods for better robustness.
    • Streamlined function signatures for querying operations, simplifying the interface.
  • Bug Fixes

    • Improved error reporting for unknown query paths in the consensus module.
  • Chores

    • Updated dependency management in go.mod files to reflect new paths and versions.

Copy link
Contributor

coderabbitai bot commented Sep 27, 2024

📝 Walkthrough

Walkthrough

This pull request introduces several changes across multiple files, primarily focusing on the implementation of gRPC services and protocol buffer message types for querying configuration and status in a Cosmos-based application. New message types ConfigRequest and ConfigResponse are defined, along with updates to service methods and error handling in various components. Additionally, the changes include modifications to dependency management and the removal of unused files related to CometBFT AutoCLI integration.

Changes

File Path Change Summary
api/cosmos/base/node/v2/query.pulsar.go Added message types ConfigRequest and ConfigResponse.
client/grpc/cmtservice/service.go Updated parameter names in NewQueryServer and RegisterTendermintService functions.
proto/cosmos/base/node/v2/query.proto Introduced gRPC service Service with RPC method Config, and message definitions for requests.
server/v2/api/grpc/nodeservice/service.go Implemented queryServer struct with Config method for handling configuration queries.
server/v2/api/grpc/server.go Added extraGRPCHandlers field and updated New function for service registration.
server/v2/cometbft/abci.go Enhanced Consensus struct with new query path constants and improved error handling.
server/v2/cometbft/abci_test.go Updated tests to align with changes in NewConsensus function parameters.
server/v2/cometbft/client/grpc/cmtservice/autocli.go Removed AutoCLI related functionalities.
server/v2/cometbft/client/grpc/cmtservice/service.go Removed gRPC query handling functionalities.
server/v2/cometbft/client/rpc/block.go Modified response handling in QueryBlocks, GetBlockByHeight, and GetBlockByHash functions.
server/v2/cometbft/client/rpc/utils.go Renamed NewResponseResultBlock to responseResultBlock and removed NewSearchBlocksResult.
server/v2/cometbft/go.mod Updated dependency management, including changes to gRPC version.
server/v2/cometbft/grpc.go Introduced gRPC service implementation for transaction and node-related calls.
server/v2/cometbft/query.go Simplified handleQueryStore function by removing unused parameters.
server/v2/cometbft/server.go Enhanced error handling and configuration management in CometBFTServer.
server/v2/go.mod Updated dependency for google.golang.org/genproto/googleapis/api.
server/v2/stf/branch/mergeiter.go Simplified variable declaration for errInvalidIterator.
simapp/v2/simdv2/cmd/commands.go Updated CommandDependencies struct to include ConsensusServer and ClientContext.
simapp/v2/simdv2/cmd/root_di.go Added ClientContext field to CommandDependencies[T] struct.
tests/integration/accounts/base_account_test.go Streamlined import statement for require.
tests/integration/accounts/wiring_test.go Streamlined import statement for require.
x/staking/keeper/grpc_query.go Updated Redelegations method to simplify querying logic and enhance error handling.

Assessment against linked issues

Objective Addressed Explanation
Ensure transaction simulation works with v2 (Issue #21958)

Possibly related PRs

Suggested labels

C:Simulations

Suggested reviewers

  • kocubinski
  • facundomedica
  • hieuvubk
  • sontrinh16

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.

@github-actions github-actions bot added C:server/v2 Issues related to server/v2 C:server/v2 cometbft labels Sep 27, 2024
@julienrbrt julienrbrt added the backport/v0.52.x PR scheduled for inclusion in the v0.52's next stable release label Sep 27, 2024
@julienrbrt julienrbrt changed the title feat(server/v2/comebft): fix simulation wiring fix(server/v2/comebft): fix simulation wiring Sep 27, 2024
@julienrbrt
Copy link
Member Author

julienrbrt commented Oct 27, 2024

i'll only try to finish this, this week. for all other matters (except reviews) i'm afk.

protoimpl "google.golang.org/protobuf/runtime/protoimpl"
timestamppb "google.golang.org/protobuf/types/known/timestamppb"
io "io"
reflect "reflect"

Check notice

Code scanning / CodeQL

Sensitive package import Note

Certain system packages contain functions which may be a possible source of non-determinism
switch fd.FullName() {
default:
if fd.IsExtension() {
panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.base.node.v2.ConfigRequest"))

Check warning

Code scanning / CodeQL

Panic in BeginBock or EndBlock consensus methods Warning

Possible panics in BeginBock- or EndBlock-related consensus methods could cause a chain halt
if fd.IsExtension() {
panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.base.node.v2.ConfigRequest"))
}
panic(fmt.Errorf("message cosmos.base.node.v2.ConfigRequest does not contain field %s", fd.FullName()))

Check warning

Code scanning / CodeQL

Panic in BeginBock or EndBlock consensus methods Warning

Possible panics in BeginBock- or EndBlock-related consensus methods could cause a chain halt
x.MinimumGasPrice = value.Interface().(string)
default:
if fd.IsExtension() {
panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.base.node.v2.ConfigResponse"))

Check warning

Code scanning / CodeQL

Panic in BeginBock or EndBlock consensus methods Warning

Possible panics in BeginBock- or EndBlock-related consensus methods could cause a chain halt
if fd.IsExtension() {
panic(fmt.Errorf("proto3 declared messages do not support extensions: cosmos.base.node.v2.ConfigResponse"))
}
panic(fmt.Errorf("message cosmos.base.node.v2.ConfigResponse does not contain field %s", fd.FullName()))

Check warning

Code scanning / CodeQL

Panic in BeginBock or EndBlock consensus methods Warning

Possible panics in BeginBock- or EndBlock-related consensus methods could cause a chain halt
api/cosmos/base/node/v2/query.pulsar.go Fixed Show fixed Hide fixed
api/cosmos/base/node/v2/query.pulsar.go Fixed Show fixed Hide fixed
api/cosmos/base/node/v2/query.pulsar.go Fixed Show fixed Hide fixed
api/cosmos/base/node/v2/query.pulsar.go Fixed Show fixed Hide fixed
@julienrbrt julienrbrt changed the title fix(server/v2/comebft): wire missing services fix(server/v2/comebft): wire missing services + fix simulation Nov 18, 2024
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: 7

🧹 Outside diff range and nitpick comments (21)
server/v2/api/grpc/nodeservice/service.go (2)

12-18: Add input validation in the constructor

Consider validating the cfg parameter to ensure it contains the required "server" configuration.

 func NewQueryServer(cfg server.ConfigMap) ServiceServer {
+	if cfg == nil {
+		panic("config map cannot be nil")
+	}
+	if _, ok := cfg["server"]; !ok {
+		panic("server configuration is required")
+	}
 	return queryServer{cfg: cfg}
 }

32-43: Track the Status implementation as a separate task

The Status method is currently a stub with commented-out implementation. The comment indicates that environment and execution context are missing, which needs to be addressed.

Would you like me to create a GitHub issue to track the implementation of the Status method? The issue would include:

  1. Requirements for environment and execution context
  2. Implementation details from the commented code
  3. Testing requirements
server/v2/cometbft/client/rpc/utils.go (1)

Line range hint 31-45: Consider optimizing the serialization steps.

The current implementation performs multiple serialization steps:

  1. Block → Proto
  2. Proto → Bytes
  3. Bytes → cmttypes.Block

Consider investigating if it's possible to convert directly from the initial proto to cmttypes.Block to reduce overhead.

proto/cosmos/base/node/v2/query.proto (3)

1-9: LGTM! Consider adding file-level documentation.

The file setup follows Cosmos SDK conventions. Consider adding a file-level comment describing the purpose and scope of these node-related queries.

 syntax = "proto3";
 package cosmos.base.node.v2;
 
+// query.proto defines the gRPC querier service for node-related information.
+
 import "google/api/annotations.proto";
🧰 Tools
🪛 buf

4-4: import "google/api/annotations.proto": file does not exist

(COMPILE)


10-20: Consider using a more specific service name.

The generic name Service could potentially cause naming conflicts. Consider renaming to NodeService or NodeQueryService to better reflect its purpose.

-service Service {
+service NodeService {

22-28: Add field documentation and consider additional configuration fields.

The minimum_gas_price field lacks documentation. Also, consider if other configuration fields might be useful for operators.

 message ConfigResponse {
-  string minimum_gas_price = 1;
+  // minimum_gas_price defines the minimum gas price value accepted by this node
+  string minimum_gas_price = 1;
+  // pruning_keep_recent defines the number of recent heights to keep on disk (optional)
+  uint64 pruning_keep_recent = 2;
+  // pruning_interval defines the height interval after which pruning will run (optional)
+  uint64 pruning_interval = 3;
 }
server/v2/server_test.go (1)

Line range hint 29-39: Improve test reliability and mock implementations

Several improvements could enhance the test's reliability and maintainability:

  1. The mock implementations currently panic. Consider implementing test-friendly versions:
func (*mockInterfaceRegistry) Resolve(typeUrl string) (gogoproto.Message, error) {
    return nil, errors.New("not implemented in test")
}
  1. Replace the fixed 5-second timeout with a more reliable approach:
- <-time.After(5 * time.Second)
+ done := make(chan struct{})
+ go func() {
+    // Wait for server to be ready
+    done <- struct{}{}
+ }()
+ select {
+ case <-done:
+ case <-time.After(10 * time.Second):
+    t.Fatal("server startup timeout")
+ }
  1. Improve error handling in the goroutine:
 go func() {
+    defer cancelFn()
     // wait 5sec and cancel context
     <-time.After(5 * time.Second)
-    cancelFn()
 
     err = server.Stop(ctx)
-    require.NoError(t, err)
+    if err != nil {
+        t.Errorf("failed to stop server: %v", err)
+    }
 }()

Also applies to: 82-91

simapp/v2/simdv2/cmd/root_di.go (1)

Line range hint 89-98: Consider enhancing error handling for dependency injection

While the current error handling is functional, consider wrapping the errors with more context to aid in debugging. This would help identify whether issues arise from app construction or client construction paths.

Example enhancement:

 	commandDeps := CommandDependencies[T]{
 		GlobalConfig:  configMap,
 		TxConfig:      clientCtx.TxConfig,
 		ModuleManager: moduleManager,
 		SimApp:        simApp,
 		ClientContext: clientCtx,
+		// Consider validating required dependencies here
+		if moduleManager == nil {
+			return fmt.Errorf("failed to initialize command dependencies: module manager is nil")
+		}
 	}
server/v2/cometbft/client/rpc/block.go (2)

Line range hint 74-80: Enhance error message clarity

While the error handling is good, the error message could be more specific about what failed during the conversion.

Consider this improvement:

-return nil, fmt.Errorf("unable to create response block from comet result block: %v", resBlock)
+return nil, fmt.Errorf("failed to convert comet result block to response block: block height %d", resBlock.Block.Header.Height)

Line range hint 99-105: Maintain consistent error handling style

Good consistency with GetBlockByHeight. Consider applying the same error message improvement here.

Consider this improvement:

-return nil, fmt.Errorf("unable to create response block from comet result block: %v", resBlock)
+return nil, fmt.Errorf("failed to convert comet result block to response block: block hash %X", resBlock.Block.Hash())
server/v2/cometbft/query.go (2)

Line range hint 88-92: Enhance error message for invalid height

The error message could be more specific about the valid height requirements.

Consider updating the error message:

-			"cannot query with proof when height <= 1; please provide a valid height",
+			"proof queries require height > 1",

Line range hint 112-127: Consider batching proof operations marshaling

The current implementation marshals and appends proof operations one at a time. Consider batching the operations to reduce allocations.

Here's a suggested optimization:

 if req.Prove {
+    ops := make([]crypto.ProofOp, len(qRes.ProofOps))
+    for i, proof := range qRes.ProofOps {
         bz, err := proof.Proof.Marshal()
         if err != nil {
             return nil, errorsmod.Wrap(err, "failed to marshal proof")
         }
-        res.ProofOps = &crypto.ProofOps{
-            Ops: []crypto.ProofOp{
-                {
-                    Type: proof.Type,
-                    Key:  proof.Key,
-                    Data: bz,
-                },
-            },
-        }
+        ops[i] = crypto.ProofOp{
+            Type: proof.Type,
+            Key:  proof.Key,
+            Data: bz,
+        }
     }
+    res.ProofOps = &crypto.ProofOps{Ops: ops}
 }
simapp/v2/simdv2/cmd/commands.go (1)

126-142: Enhance error handling in gRPC server initialization

While the initialization is well-structured, consider wrapping the error with additional context to aid in debugging.

 grpcServer, err := grpcserver.New[T](
   logger,
   simApp.InterfaceRegistry(),
   simApp.QueryHandlers(),
   simApp.Query,
   []func(*grpc.Server) error{
     deps.ConsensusServer.Consensus.GRPCServiceRegistrar(
       deps.ClientContext,
       deps.GlobalConfig,
     ),
   },
   deps.GlobalConfig,
 )
 if err != nil {
-  return nil, err
+  return nil, fmt.Errorf("failed to initialize gRPC server: %w", err)
 }
simapp/v2/go.mod (1)

Line range hint 3-3: Invalid Go version specified

The Go version 1.23.1 is not valid. The latest stable version of Go is 1.22.1.

Apply this diff to fix the Go version:

-go 1.23.1
+go 1.22
x/staking/keeper/grpc_query.go (1)

Line range hint 558-571: Consider adding error documentation

The implementation is clean and follows best practices. However, consider documenting the possible error cases in the function comment to help API consumers better handle errors.

+// queryAllRedelegations returns all redelegations for a delegator.
+// Returns collections.ErrNotFound if no redelegations exist for the delegator.
+// Returns error if the delegator address is invalid or if pagination fails.
 func queryAllRedelegations(ctx context.Context, k Querier, req *types.QueryRedelegationsRequest) (redels types.Redelegations, res *query.PageResponse, err error) {
server/v2/api/grpc/server.go (3)

74-75: Handle potential errors during service registration

Even if RegisterServiceServer does not currently return an error, future implementations or changes might introduce error handling. To make the code more robust, consider checking and handling any potential errors when registering the service.


77-77: Ensure error handling for node service registration

Similarly, consider capturing and handling any errors that might occur during nodeservice.RegisterServiceServer. This will enhance the reliability of the service initialization process.


79-79: Capitalize the first word in comments

According to the Uber Go Style Guide, comments should begin with a capital letter.

Apply this diff:

-    // reflection allows external clients to see what services and methods the gRPC server exposes.
+    // Reflection allows external clients to see what services and methods the gRPC server exposes.
server/v2/cometbft/grpc.go (2)

98-110: Add explanations for unimplemented methods

The methods GetBlockWithTxs, GetTx, and GetTxsEvent are unimplemented and currently return codes.Unimplemented errors. Consider adding comments to explain why these methods are unimplemented and specify any plans for future implementation.


137-142: Standardize error handling in the Simulate method

The Simulate method uses both errorsmod.Wrap and status.Errorf for error handling. To maintain consistency and clarity, consider standardizing the error handling approach throughout the method.

server/v2/cometbft/abci.go (1)

277-277: Extract hardcoded simulation path to a constant

To enhance maintainability and reduce the risk of typos, consider defining the simulation path "/cosmos.tx.v1beta1.Service/Simulate" as a constant.

Apply this diff to extract the simulation path:

+const SimulatePath = "/cosmos.tx.v1beta1.Service/Simulate"
...
-	if req.Path == "/cosmos.tx.v1beta1.Service/Simulate" {
+	if req.Path == SimulatePath {
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1b3aeb7 and eb78af6.

⛔ Files ignored due to path filters (3)
  • api/cosmos/base/node/v2/query_grpc.pb.go is excluded by !**/*.pb.go
  • server/v2/api/grpc/nodeservice/query.pb.go is excluded by !**/*.pb.go
  • server/v2/api/grpc/nodeservice/query.pb.gw.go is excluded by !**/*.pb.gw.go
📒 Files selected for processing (24)
  • api/cosmos/base/node/v2/query.pulsar.go (1 hunks)
  • client/grpc/cmtservice/service.go (2 hunks)
  • proto/cosmos/base/node/v2/query.proto (1 hunks)
  • server/v2/api/grpc/nodeservice/service.go (1 hunks)
  • server/v2/api/grpc/server.go (3 hunks)
  • server/v2/cometbft/abci.go (4 hunks)
  • server/v2/cometbft/abci_test.go (1 hunks)
  • server/v2/cometbft/client/grpc/cmtservice/autocli.go (0 hunks)
  • server/v2/cometbft/client/grpc/cmtservice/service.go (0 hunks)
  • server/v2/cometbft/client/rpc/block.go (3 hunks)
  • server/v2/cometbft/client/rpc/utils.go (2 hunks)
  • server/v2/cometbft/go.mod (2 hunks)
  • server/v2/cometbft/grpc.go (1 hunks)
  • server/v2/cometbft/query.go (1 hunks)
  • server/v2/cometbft/server.go (0 hunks)
  • server/v2/go.mod (1 hunks)
  • server/v2/server_test.go (1 hunks)
  • server/v2/stf/branch/mergeiter.go (1 hunks)
  • simapp/v2/go.mod (1 hunks)
  • simapp/v2/simdv2/cmd/commands.go (6 hunks)
  • simapp/v2/simdv2/cmd/root_di.go (1 hunks)
  • tests/integration/accounts/base_account_test.go (1 hunks)
  • tests/integration/accounts/wiring_test.go (1 hunks)
  • x/staking/keeper/grpc_query.go (2 hunks)
💤 Files with no reviewable changes (3)
  • server/v2/cometbft/client/grpc/cmtservice/autocli.go
  • server/v2/cometbft/client/grpc/cmtservice/service.go
  • server/v2/cometbft/server.go
✅ Files skipped from review due to trivial changes (4)
  • api/cosmos/base/node/v2/query.pulsar.go
  • server/v2/stf/branch/mergeiter.go
  • tests/integration/accounts/base_account_test.go
  • tests/integration/accounts/wiring_test.go
🧰 Additional context used
📓 Path-based instructions (13)
client/grpc/cmtservice/service.go (1)

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

server/v2/api/grpc/nodeservice/service.go (1)

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

server/v2/api/grpc/server.go (1)

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

server/v2/cometbft/abci.go (1)

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

server/v2/cometbft/abci_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"

server/v2/cometbft/client/rpc/block.go (1)

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

server/v2/cometbft/client/rpc/utils.go (1)

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

server/v2/cometbft/grpc.go (1)

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

server/v2/cometbft/query.go (1)

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

server/v2/server_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"

simapp/v2/simdv2/cmd/commands.go (1)

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

simapp/v2/simdv2/cmd/root_di.go (1)

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

x/staking/keeper/grpc_query.go (1)

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

📓 Learnings (1)
simapp/v2/simdv2/cmd/root_di.go (1)
Learnt from: kocubinski
PR: cosmos/cosmos-sdk#22267
File: simapp/v2/simdv2/cmd/root_di.go:26-26
Timestamp: 2024-11-10T03:53:32.474Z
Learning: In `simapp/v2/simdv2/cmd/root_di.go`, the initial call to `InitRootCmd` with empty `CommandDependencies` is required to initialize configuration.
🪛 buf
proto/cosmos/base/node/v2/query.proto

4-4: import "google/api/annotations.proto": file does not exist

(COMPILE)

🔇 Additional comments (22)
server/v2/api/grpc/nodeservice/service.go (3)

1-8: LGTM: Clean package structure and imports

The package name and imports follow Go conventions and are well-organized.


10-10: LGTM: Proper interface implementation check

Good practice using compile-time interface compliance check.


20-30: Previous review comment about safe type assertions is still applicable

server/v2/cometbft/client/rpc/utils.go (2)

Line range hint 18-24: LGTM! Error handling is thorough and follows best practices.

The error messages are descriptive and include the necessary context for debugging.


30-31: LGTM! Function name follows Go naming conventions.

The renaming from NewResponseResultBlock to responseResultBlock correctly reflects that this is an unexported utility function.

proto/cosmos/base/node/v2/query.proto (1)

30-39: LGTM! Well-documented status fields.

The status response fields are well-chosen and properly documented. The use of gogoproto for timestamp handling is appropriate.

server/v2/server_test.go (1)

56-56: Verify the purpose of the new nil parameter

The test should include cases that exercise the new parameter (extraOptions) with non-nil values to ensure proper functionality.

Consider adding test cases that:

  1. Pass valid options to verify proper initialization
  2. Pass invalid options to verify error handling
  3. Document the purpose of this parameter in the test
// Example test case structure
testCases := []struct {
    name         string
    extraOptions interface{}
    wantErr     bool
}{
    {"nil options", nil, false},
    {"valid options", validOptions, false},
    {"invalid options", invalidOptions, true},
}
✅ Verification successful

The nil parameter is for extraGRPCHandlers which allows registering additional handlers

The test case passes nil for extraGRPCHandlers parameter which is valid since it's an optional slice of handler registration functions. The nil value simply means no additional gRPC handlers will be registered beyond the default ones.

While adding test cases for non-nil values would improve coverage, passing nil is a valid use case that should be tested as it represents the common scenario where no extra handlers are needed.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for the definition and usage of grpc.New to understand the new parameter
ast-grep --pattern 'func New[transaction.Tx]($$$) ($$$)' 

Length of output: 58


Script:

#!/bin/bash
# Let's try a broader search for the grpc.New function definition
ast-grep --pattern 'func New[$_]($$$) ($$$)'

# Also search for any usage of grpc.New
rg "grpc\.New" -A 3

Length of output: 75750


Script:

#!/bin/bash
# Let's look for the grpc.New function definition in the API/GRPC package specifically
rg -A 10 "func New\[T transaction.Tx\]" server/v2/api/grpc/

# Also search for any changes related to extraGRPCHandlers
rg "extraGRPCHandlers" -A 3

Length of output: 1267

simapp/v2/simdv2/cmd/root_di.go (1)

97-97: LGTM: ClientContext addition is properly placed

The addition of ClientContext to CommandDependencies is well-positioned after proper initialization and follows the dependency injection pattern consistently.

server/v2/cometbft/client/rpc/block.go (1)

53-61: LGTM: Well-structured response handling

The direct initialization of SearchBlocksResult with pagination details is clear and maintainable. The totalPages calculation ensures accurate pagination information.

server/v2/cometbft/query.go (2)

86-86: LGTM! Function signature simplified

The removal of the types.Store parameter simplifies the interface while maintaining functionality through the consensus instance's store field.


Line range hint 94-98: Investigate store name encoding optimization

The TODO comment suggests a potential performance optimization for store name encoding. This should be investigated to determine if there's a meaningful performance impact.

Let's check for similar patterns in the codebase:

server/v2/go.mod (1)

38-38: LGTM! Verify dependency compatibility.

The addition of google.golang.org/genproto/googleapis/api is properly structured and aligns with the PR's objective of wiring missing services.

Let's verify the dependency compatibility:

✅ Verification successful

Dependency version is well-aligned across the ecosystem

The verification shows that:

  • The specific version v0.0.0-20240903143218-8af14fe29dc1 is consistently used across multiple Cosmos SDK modules and tools
  • No open bug issues are found for this version in the upstream repository
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for potential compatibility issues with the new dependency

# Check if this version is used by other cosmos-sdk modules
rg -l "google.golang.org/genproto/googleapis/api v0.0.0-20240903143218-8af14fe29dc1"

# Check if there are any known issues with this version
gh api graphql -f query='
{
  repository(owner: "googleapis", name: "go-genproto") {
    issues(first: 5, states: OPEN, labels: ["Type: Bug"]) {
      nodes {
        title
        url
        createdAt
      }
    }
  }
}'

Length of output: 1668

simapp/v2/simdv2/cmd/commands.go (3)

8-8: LGTM: Import changes are appropriate

The new imports support the enhanced gRPC functionality, and the alias helps avoid naming conflicts.

Also applies to: 16-16


44-47: LGTM: Well-documented structural changes

The new fields enhance the structure's capabilities while maintaining type safety. The comments effectively explain the design decision for using *cometbft.CometBFTServer[T] over a more generic type.


Line range hint 150-154: LGTM: Server command wiring is consistent

The updated AddCommands call correctly integrates the new ConsensusServer while maintaining the established parameter pattern.

client/grpc/cmtservice/service.go (2)

41-41: LGTM! Parameter name change improves clarity.

The rename from clientCtx to cometRPC better reflects the parameter's purpose and maintains consistency with the struct field name rpc.

Also applies to: 46-46


287-287: Verify the removal of interface registry usage.

The interface registry parameter has been marked as unused. While this follows Go conventions, please verify that this doesn't impact any potential type registration or interface unpacking needs, especially considering the presence of UnpackInterfaces method in this file.

✅ Verification successful

Let me generate additional verification scripts to check for UnpackInterfaces usage and interface registry dependencies.


Interface registry parameter can be safely removed

The interface registry parameter is only used as a dependency injection marker and is not actively used in the service implementation. The UnpackInterfaces functionality is self-contained within the GetLatestValidatorSetResponse type and uses the provided AnyUnpacker interface directly, without depending on the service's interface registry parameter. The only other usage is for creating Any types with codectypes.NewAnyWithValue() which also doesn't require the registry parameter.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for interface registry usage patterns in the codebase
# to ensure we're not breaking any existing functionality.

# Search for interface registry usage patterns
echo "Searching for interface registry usage patterns..."
rg -A 3 "RegisterInterface|RegisterImplementations" 

# Search for similar service registrations
echo "Searching for similar service registration patterns..."
ast-grep --pattern 'func Register$_Service($_, $_, $registry codectypes.InterfaceRegistry, $_)'

Length of output: 80539


Script:

#!/bin/bash
# Check for UnpackInterfaces usage and any interface registry dependencies in the service file

# Search for UnpackInterfaces method and its implementation
echo "Searching for UnpackInterfaces usage..."
rg -A 5 "UnpackInterfaces" client/grpc/cmtservice/service.go

# Search for any interface registry usage in the service file
echo "Searching for interface registry usage..."
rg "InterfaceRegistry|codectypes" client/grpc/cmtservice/service.go

Length of output: 871

server/v2/cometbft/abci_test.go (1)

702-702: ⚠️ Potential issue

The past review comment about error handling is still valid.

The NewConsensus initialization error is still not being handled, which could mask setup issues in tests.

As mentioned in the previous review, apply this diff to handle potential errors:

-	return NewConsensus[mock.Tx](log.NewNopLogger(), "testing-app", am,
+	consensus, err := NewConsensus[mock.Tx](log.NewNopLogger(), "testing-app", am,
		mempool, map[string]struct{}{}, nil, mockStore,
		Config{AppTomlConfig: DefaultAppTomlConfig()}, mock.TxCodec{}, "test")
+	require.NoError(t, err)
+	return consensus
x/staking/keeper/grpc_query.go (1)

437-437: LGTM! Clean refactor of queryAllRedelegations call

The simplified function call aligns with the removal of direct store access in favor of using the collections API.

server/v2/cometbft/grpc.go (3)

141-142: Duplicate Comment: Avoid potential nil pointer dereference when returning error

The past review comment regarding a potential nil pointer dereference at lines 141-142 remains valid and applicable to the current code segment.


195-198: Duplicate Comment: Prevent runtime panic by safely handling type assertions

The previous concern about unsafe type assertions at lines 195-198 is still valid and should be addressed to prevent potential runtime panics.


214-218: Duplicate Comment: Populate 'Timestamp' and 'AppHash' in 'StatusResponse'

The past suggestion to populate the Timestamp and AppHash fields in StatusResponse at lines 214-218 remains applicable. Providing these values would enhance the completeness of the status information.

server/v2/cometbft/client/rpc/block.go Show resolved Hide resolved
server/v2/cometbft/go.mod Show resolved Hide resolved
server/v2/cometbft/go.mod Show resolved Hide resolved
simapp/v2/go.mod Outdated Show resolved Hide resolved
server/v2/api/grpc/server.go Outdated Show resolved Hide resolved
server/v2/cometbft/abci.go Outdated Show resolved Hide resolved
server/v2/cometbft/abci.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

🧹 Outside diff range and nitpick comments (2)
server/v2/cometbft/abci.go (2)

275-317: Consider refactoring simulation handling for better maintainability

The simulation handling logic is complex and could benefit from being broken down into smaller, more focused functions.

Consider extracting these functions:

  1. handleSimulateRequest - For decoding and validating the request
  2. processSimulation - For running the simulation
  3. packMessageResponses - For handling message responses

Example refactor:

func (c *Consensus[T]) handleSimulateRequest(data []byte) (*txtypes.SimulateRequest, error) {
    simulateRequest := &txtypes.SimulateRequest{}
    if err := gogoproto.Unmarshal(data, simulateRequest); err != nil {
        return nil, fmt.Errorf("unable to decode simulate request: %w", err)
    }
    return simulateRequest, nil
}

func (c *Consensus[T]) processSimulation(ctx context.Context, txBytes []byte) (*server.TxResult, error) {
    tx, err := c.txCodec.Decode(txBytes)
    if err != nil {
        return nil, fmt.Errorf("failed to decode tx: %w", err)
    }
    
    txResult, _, err := c.app.Simulate(ctx, tx)
    if err != nil {
        if txResult != nil {
            return nil, fmt.Errorf("%v with gas used: '%d'", err, txResult.GasUsed)
        }
        return nil, fmt.Errorf("simulation failed: %v", err)
    }
    return txResult, nil
}

func (c *Consensus[T]) packMessageResponses(messages []gogoproto.Message) ([]*codectypes.Any, error) {
    msgResponses := make([]*codectypes.Any, 0, len(messages))
    for _, msg := range messages {
        anyMsg, err := codectypes.NewAnyWithValue(msg)
        if err != nil {
            return nil, fmt.Errorf("failed to pack message response: %w", err)
        }
        msgResponses = append(msgResponses, anyMsg)
    }
    return msgResponses, nil
}

294-303: Optimize message response handling

The message response handling could be optimized by pre-allocating the slice and using a single error check.

Apply this diff to optimize the code:

-msgResponses := make([]*codectypes.Any, 0, len(txResult.Resp))
-// pack the messages into Any
-for _, msg := range txResult.Resp {
-    anyMsg, err := codectypes.NewAnyWithValue(msg)
-    if err != nil {
-        return nil, true, fmt.Errorf("failed to pack message response: %w", err)
-    }
-
-    msgResponses = append(msgResponses, anyMsg)
-}
+msgResponses := make([]*codectypes.Any, len(txResult.Resp))
+var packErr error
+for i, msg := range txResult.Resp {
+    if msgResponses[i], packErr = codectypes.NewAnyWithValue(msg); packErr != nil {
+        return nil, true, fmt.Errorf("failed to pack message response at index %d: %w", i, packErr)
+    }
+}
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between eb78af6 and c7d65a8.

📒 Files selected for processing (1)
  • server/v2/cometbft/abci.go (4 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
server/v2/cometbft/abci.go (1)

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

🔇 Additional comments (2)
server/v2/cometbft/abci.go (2)

42-46: LGTM: Well-defined query path constants

The constants are well-named and improve code maintainability by centralizing query path definitions.


229-239: LGTM: Clear and informative query path handling

The switch statement is well-structured and the error message now includes the specific query path, improving debuggability.

server/v2/cometbft/abci.go Show resolved Hide resolved
@julienrbrt julienrbrt enabled auto-merge November 19, 2024 09:32
@julienrbrt julienrbrt disabled auto-merge November 19, 2024 11:16
return queryServer{cfg: cfg}
}

func (s queryServer) Config(ctx context.Context, _ *ConfigRequest) (*ConfigResponse, error) {
Copy link
Contributor

Choose a reason for hiding this comment

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

1 Q why we need v2 service since v1 was registed by comet. Like what is different?

Copy link
Member Author

Choose a reason for hiding this comment

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

The comet one is here for backward compatibility. But we cannot get all data there.

Copy link
Member Author

Choose a reason for hiding this comment

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

The comet one is here for backward compatibility. But we cannot get all data there.

This service has less fields as the other aren't relevant as they are store server or consensus server dependent.

// note, environment nor execution context isn't available in the context

// return &StatusResponse{
// Height: uint64(headerInfo.Height),
Copy link
Member

Choose a reason for hiding this comment

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

nit remove old code

Copy link
Contributor

@hieuvubk hieuvubk left a comment

Choose a reason for hiding this comment

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

ack

@julienrbrt julienrbrt enabled auto-merge November 19, 2024 13:35
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 (4)
proto/cosmos/base/node/v2/query.proto (2)

8-14: Consider a more specific service name

While the implementation is correct, the service name 'Service' is quite generic. Consider renaming it to something more specific like 'NodeService' or 'NodeQueryService' to better reflect its purpose.

Additionally, the RPC method documentation could be enhanced to describe the returned configuration details.

-// Service defines the gRPC querier service for node related queries.
-service Service {
+// NodeService defines the gRPC querier service for node related queries.
+service NodeService {
   // Config queries for the operator configuration.
+  // Returns the node's configuration including minimum gas price settings.
   rpc Config(ConfigRequest) returns (ConfigResponse) {

16-22: Document minimum_gas_price field format

Please enhance the documentation to specify:

  • The expected format of minimum_gas_price (e.g., "0.1uatom")
  • Any validation rules or constraints
  • Whether it supports multiple denominations
 // ConfigResponse defines the response structure for the Config gRPC query.
 message ConfigResponse {
+  // minimum_gas_price specifies the minimum gas price value for transactions
+  // Format: {amount}{denomination} (e.g., "0.1uatom")
   string minimum_gas_price = 1;
 }
simapp/v2/simdv2/cmd/commands.go (2)

43-46: Document the purpose of ClientContext field

While the ConsensusServer field is well documented, please add a comment explaining why ClientContext was added and its role in the dependency structure.


125-141: Consider more specific error handling

While the error handling is present, consider wrapping the error with more context about which part of the gRPC server creation failed (e.g., base initialization vs extra handlers registration).

 grpcServer, err := grpcserver.New[T](
   logger,
   simApp.InterfaceRegistry(),
   simApp.QueryHandlers(),
   simApp.Query,
   deps.GlobalConfig,
   grpcserver.WithExtraGRPCHandlers[T](
     deps.ConsensusServer.Consensus.GRPCServiceRegistrar(
       deps.ClientContext,
       deps.GlobalConfig,
     ),
   ),
 )
 if err != nil {
-  return nil, err
+  return nil, fmt.Errorf("failed to create gRPC server: %w", err)
 }
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c7d65a8 and c86df3a.

⛔ Files ignored due to path filters (3)
  • api/cosmos/base/node/v2/query_grpc.pb.go is excluded by !**/*.pb.go
  • server/v2/api/grpc/nodeservice/query.pb.go is excluded by !**/*.pb.go
  • server/v2/api/grpc/nodeservice/query.pb.gw.go is excluded by !**/*.pb.gw.go
📒 Files selected for processing (5)
  • api/cosmos/base/node/v2/query.pulsar.go (1 hunks)
  • proto/cosmos/base/node/v2/query.proto (1 hunks)
  • server/v2/api/grpc/nodeservice/service.go (1 hunks)
  • server/v2/api/grpc/server.go (5 hunks)
  • simapp/v2/simdv2/cmd/commands.go (6 hunks)
✅ Files skipped from review due to trivial changes (1)
  • api/cosmos/base/node/v2/query.pulsar.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • server/v2/api/grpc/nodeservice/service.go
🧰 Additional context used
📓 Path-based instructions (2)
server/v2/api/grpc/server.go (1)

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

simapp/v2/simdv2/cmd/commands.go (1)

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

🪛 buf
proto/cosmos/base/node/v2/query.proto

4-4: import "google/api/annotations.proto": file does not exist

(COMPILE)

🔇 Additional comments (9)
proto/cosmos/base/node/v2/query.proto (1)

1-7: LGTM: File structure follows best practices

The file structure follows protobuf best practices with proper syntax declaration, package naming convention, and go package specification.

🧰 Tools
🪛 buf

4-4: import "google/api/annotations.proto": file does not exist

(COMPILE)

simapp/v2/simdv2/cmd/commands.go (4)

15-15: LGTM: Clear import alias

The import alias grpcserver clearly distinguishes the gRPC server package and avoids potential naming conflicts.


81-85: LGTM: Clear server component initialization

The initialization of server components using struct literals improves code clarity and maintainability.


Line range hint 103-119: LGTM: Proper error handling and dependency injection

The ConsensusServer creation properly handles errors and follows good dependency injection patterns.


149-149: LGTM: Consistent server component usage

The server commands wiring consistently uses the new ConsensusServer component.

server/v2/api/grpc/server.go (4)

29-29: LGTM: Import added for nodeservice integration

The import is correctly added and follows Go import conventions.


43-44: LGTM: Server struct fields properly defined

The new fields grpcSrv and extraGRPCHandlers are well-typed and appropriately encapsulate the server's extended functionality.


78-79: LGTM: Node service properly registered

The node service is correctly registered with the gRPC server using the configuration from the server context.


100-114: LGTM: Well-implemented functional options pattern

The implementation follows Go best practices:

  • Proper use of generics with transaction.Tx constraint
  • Clear documentation for each option function
  • Clean implementation of the functional options pattern

@julienrbrt julienrbrt added this pull request to the merge queue Nov 19, 2024
Merged via the queue into main with commit d697a3d Nov 19, 2024
75 of 77 checks passed
@julienrbrt julienrbrt deleted the julien/fix-simulate branch November 19, 2024 13:55
mergify bot pushed a commit that referenced this pull request Nov 19, 2024
(cherry picked from commit d697a3d)

# Conflicts:
#	server/v2/api/grpc/server.go
#	server/v2/cometbft/go.mod
#	server/v2/go.mod
#	server/v2/stf/branch/mergeiter.go
julienrbrt added a commit that referenced this pull request Nov 19, 2024
alpe added a commit that referenced this pull request Nov 21, 2024
* main:
  build(deps): Bump cosmossdk.io/math from 1.3.0 to 1.4.0 (#22580)
  fix(server/v2/api/telemetry): enable global metrics  (#22571)
  refactor(server/v2/cometbft): add `codec.Codec` and clean-up APIs (#22566)
  feat(core/coretesting): make memDB satisfy db.Db interface (#22570)
  Merge commit from fork
  fix(server(/v2)): fix fallback genesis path (#22564)
  fix: only overwrite context chainID when necessary (#22568)
  docs(client): Update setFeeGranter and setFeePayer comments (#22526)
  fix(baseapp): populate header info in `NewUncachedContext` (#22557)
  build(deps): Bump buf.build/gen/go/cometbft/cometbft/protocolbuffers/go from 1.35.1-20240701160653-fedbb9acfd2f.1 to 1.35.2-20240701160653-fedbb9acfd2f.1 in /api (#22551)
  build(deps): Bump github.com/creachadair/atomicfile from 0.3.5 to 0.3.6 in /tools/confix (#22552)
  docs: Update reference of Approximation (#22550)
  fix(server/v2/comebft): wire missing services + fix simulation (#21964)
  ci: fix permissions for GITHUB_TOKEN on dependabot workflows (#22547)
  ci: fix permissions for GITHUB_TOKEN in spell check workflow (#22545)
  build(deps): Bump google.golang.org/protobuf from 1.35.1 to 1.35.2 (#22537)
  fix(cosmovisor): premature upgrade on restart (#22528)
  fix(store/v2/pebble): handle version 0 in keys (#22524)
  refactor(server/v2/telemetry): swap redirects (#22520)
  docs: Update content in  CODE_OF_CONDUCT.md (#22518)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
backport/v0.52.x PR scheduled for inclusion in the v0.52's next stable release C:CLI C:server/v2 api C:server/v2 cometbft C:server/v2 stf C:server/v2 Issues related to server/v2 C:x/staking
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Transaction simulation and v2
9 participants