diff --git a/CHANGELOG.md b/CHANGELOG.md index 8146b36ac4..039038bc08 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -46,6 +46,8 @@ Ref: https://keepachangelog.com/en/1.0.0/ ### Improvements +* (cli) [#17389](https://github.com/cosmos/cosmos-sdk/pull/17389) gRPC CometBFT commands have been added under ` q consensus comet`. CometBFT commands placement in the SDK has been simplified. See the exhaustive list below. + * `client/rpc.StatusCommand()` is now at `server.StatusCommand()` * (cli) [#17187](https://github.com/cosmos/cosmos-sdk/pull/17187) Do not use `ctx.PrintObjectLegacy` in commands anymore. * ` q gov proposer [proposal-id]` now returns a proposal id as int instead of string. * (testutil) [#17216](https://github.com/cosmos/cosmos-sdk/issues/17216) Add `DefaultContextWithKeys` to `testutil` package. diff --git a/client/grpc/cmtservice/autocli.go b/client/grpc/cmtservice/autocli.go new file mode 100644 index 0000000000..8fae4b915b --- /dev/null +++ b/client/grpc/cmtservice/autocli.go @@ -0,0 +1,71 @@ +package cmtservice + +import ( + autocliv1 "cosmossdk.io/api/cosmos/autocli/v1" + cmtv1beta1 "cosmossdk.io/api/cosmos/base/tendermint/v1beta1" +) + +var CometBFTAutoCLIDescriptor = &autocliv1.ServiceCommandDescriptor{ + Service: cmtv1beta1.Service_ServiceDesc.ServiceName, + RpcCommandOptions: []*autocliv1.RpcCommandOptions{ + { + RpcMethod: "GetNodeInfo", + Use: "node-info", + Short: "Query the current node info", + }, + { + RpcMethod: "GetSyncing", + Use: "syncing", + Short: "Query node syncing status", + }, + { + RpcMethod: "GetLatestBlock", + Use: "block-latest", + Short: "Query for the latest committed block", + }, + { + RpcMethod: "GetBlockByHeight", + Use: "block-by-height [height]", + Short: "Query for a committed block by height", + Long: "Query for a specific committed block using the CometBFT RPC `block_by_height` method", + PositionalArgs: []*autocliv1.PositionalArgDescriptor{{ProtoField: "height"}}, + }, + { + RpcMethod: "GetLatestValidatorSet", + Use: "validator-set", + Alias: []string{"validator-set-latest", "comet-validator-set", "cometbft-validator-set", "tendermint-validator-set"}, + Short: "Query for the latest validator set", + }, + { + RpcMethod: "GetValidatorSetByHeight", + Use: "validator-set-by-height [height]", + Short: "Query for a validator set by height", + PositionalArgs: []*autocliv1.PositionalArgDescriptor{{ProtoField: "height"}}, + }, + { + RpcMethod: "ABCIQuery", + Skip: true, + }, + }, +} + +// NewCometBFTCommands is a fake `appmodule.Module` to be considered as a module +// and be added in AutoCLI. +func NewCometBFTCommands() *cometModule { //nolint:revive // fake module and limiting import of core + return &cometModule{} +} + +type cometModule struct{} + +func (m cometModule) IsOnePerModuleType() {} +func (m cometModule) IsAppModule() {} + +func (m cometModule) Name() string { + return "comet" +} + +func (m cometModule) AutoCLIOptions() *autocliv1.ModuleOptions { + return &autocliv1.ModuleOptions{ + Query: CometBFTAutoCLIDescriptor, + } +} diff --git a/client/grpc/cmtservice/block.go b/client/grpc/cmtservice/block.go index 1575626fa6..f1cde440f9 100644 --- a/client/grpc/cmtservice/block.go +++ b/client/grpc/cmtservice/block.go @@ -10,7 +10,7 @@ import ( ) func getBlockHeight(ctx context.Context, clientCtx client.Context) (int64, error) { - status, err := getNodeStatus(ctx, clientCtx) + status, err := GetNodeStatus(ctx, clientCtx) if err != nil { return 0, err } diff --git a/client/grpc/cmtservice/service.go b/client/grpc/cmtservice/service.go index 39e17ce1a9..e26e653328 100644 --- a/client/grpc/cmtservice/service.go +++ b/client/grpc/cmtservice/service.go @@ -49,7 +49,7 @@ func NewQueryServer( // GetSyncing implements ServiceServer.GetSyncing func (s queryServer) GetSyncing(ctx context.Context, _ *GetSyncingRequest) (*GetSyncingResponse, error) { - status, err := getNodeStatus(ctx, s.clientCtx) + status, err := GetNodeStatus(ctx, s.clientCtx) if err != nil { return nil, err } @@ -189,7 +189,7 @@ func ValidatorsOutput(ctx context.Context, clientCtx client.Context, height *int // GetNodeInfo implements ServiceServer.GetNodeInfo func (s queryServer) GetNodeInfo(ctx context.Context, _ *GetNodeInfoRequest) (*GetNodeInfoResponse, error) { - status, err := getNodeStatus(ctx, s.clientCtx) + status, err := GetNodeStatus(ctx, s.clientCtx) if err != nil { return nil, err } diff --git a/client/grpc/cmtservice/status.go b/client/grpc/cmtservice/status.go index 9f03a71a76..ea32e00b79 100644 --- a/client/grpc/cmtservice/status.go +++ b/client/grpc/cmtservice/status.go @@ -8,7 +8,8 @@ import ( "github.com/cosmos/cosmos-sdk/client" ) -func getNodeStatus(ctx context.Context, clientCtx client.Context) (*coretypes.ResultStatus, error) { +// GetNodeStatus returns the status of the node. +func GetNodeStatus(ctx context.Context, clientCtx client.Context) (*coretypes.ResultStatus, error) { node, err := clientCtx.GetNode() if err != nil { return &coretypes.ResultStatus{}, err diff --git a/client/grpc/cmtservice/status_test.go b/client/grpc/cmtservice/status_test.go new file mode 100644 index 0000000000..73c86e1bfc --- /dev/null +++ b/client/grpc/cmtservice/status_test.go @@ -0,0 +1,30 @@ +package cmtservice_test + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/cosmos/cosmos-sdk/server" + clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" + "github.com/cosmos/cosmos-sdk/testutil/network" +) + +func TestStatusCommand(t *testing.T) { + cfg, err := network.DefaultConfigWithAppConfig(network.MinimumAppConfig()) + require.NoError(t, err) + + network, err := network.New(t, t.TempDir(), cfg) + require.NoError(t, err) + require.NoError(t, network.WaitForNextBlock()) + + val0 := network.Validators[0] + cmd := server.StatusCommand() + + out, err := clitestutil.ExecTestCLICmd(val0.ClientCtx, cmd, []string{}) + require.NoError(t, err) + + // Make sure the output has the validator moniker. + require.Contains(t, out.String(), fmt.Sprintf("\"moniker\":\"%s\"", val0.Moniker)) +} diff --git a/client/rpc/rpc_test.go b/client/rpc/rpc_test.go index 3bd9c39ec8..bffdbf927d 100644 --- a/client/rpc/rpc_test.go +++ b/client/rpc/rpc_test.go @@ -11,8 +11,6 @@ import ( "google.golang.org/grpc" "google.golang.org/grpc/metadata" - "github.com/cosmos/cosmos-sdk/client/rpc" - clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" "github.com/cosmos/cosmos-sdk/testutil/network" "github.com/cosmos/cosmos-sdk/testutil/testdata" "github.com/cosmos/cosmos-sdk/types/address" @@ -44,17 +42,6 @@ func (s *IntegrationTestSuite) TearDownSuite() { s.network.Cleanup() } -func (s *IntegrationTestSuite) TestStatusCommand() { - val0 := s.network.Validators[0] - cmd := rpc.StatusCommand() - - out, err := clitestutil.ExecTestCLICmd(val0.ClientCtx, cmd, []string{}) - s.Require().NoError(err) - - // Make sure the output has the validator moniker. - s.Require().Contains(out.String(), fmt.Sprintf("\"moniker\":\"%s\"", val0.Moniker)) -} - func (s *IntegrationTestSuite) TestCLIQueryConn() { s.T().Skip("data race in comet is causing this to fail") var header metadata.MD diff --git a/client/rpc/status.go b/client/rpc/status.go deleted file mode 100644 index 5f50ae36af..0000000000 --- a/client/rpc/status.go +++ /dev/null @@ -1,58 +0,0 @@ -package rpc - -import ( - "context" - - cmtjson "github.com/cometbft/cometbft/libs/json" - coretypes "github.com/cometbft/cometbft/rpc/core/types" - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" -) - -// StatusCommand returns the command to return the status of the network. -func StatusCommand() *cobra.Command { - cmd := &cobra.Command{ - Use: "status", - Short: "Query remote node for status", - RunE: func(cmd *cobra.Command, _ []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - status, err := getNodeStatus(clientCtx) - if err != nil { - return err - } - - output, err := cmtjson.Marshal(status) - if err != nil { - return err - } - - // In order to maintain backwards compatibility, the default json format output - outputFormat, _ := cmd.Flags().GetString(flags.FlagOutput) - if outputFormat == flags.OutputFormatJSON { - clientCtx = clientCtx.WithOutputFormat(flags.OutputFormatJSON) - } - - return clientCtx.PrintRaw(output) - }, - } - - cmd.Flags().StringP(flags.FlagNode, "n", "tcp://localhost:26657", "Node to connect to") - cmd.Flags().StringP(flags.FlagOutput, "o", "json", "Output format (text|json)") - - return cmd -} - -func getNodeStatus(clientCtx client.Context) (*coretypes.ResultStatus, error) { - node, err := clientCtx.GetNode() - if err != nil { - return &coretypes.ResultStatus{}, err - } - - return node.Status(context.Background()) -} diff --git a/client/v2/README.md b/client/v2/README.md index 6218a0385e..516c7f4956 100644 --- a/client/v2/README.md +++ b/client/v2/README.md @@ -177,6 +177,16 @@ https://github.com/cosmos/cosmos-sdk/blob/fa4d87ef7e6d87aaccc94c337ffd2fe90fcb7a If not set to true, `AutoCLI` will not generate commands for the module if there are already commands registered for the module (when `GetTxCmd()` or `GetTxCmd()` are defined). +### Use AutoCLI for non module commands + +It is possible to use `AutoCLI` for non module commands. The trick is still to implement the `appmodule.Module` interface and append it to the `appOptions.ModuleOptions` map. + +For example, here is how the SDK does it for `cometbft` gRPC commands: + +```go reference +https://github.com/cosmos/cosmos-sdk/blob/julien/autocli-comet/client/grpc/cmtservice/autocli.go#L52-L71 +``` + ## Summary `autocli` let you generate CLI to your Cosmos SDK-based applications without any cobra boilerplate. It allows you to easily generate CLI commands and flags from your protobuf messages, and provides many options for customising the behavior of your CLI application. diff --git a/client/v2/autocli/flags.go b/client/v2/autocli/flags.go new file mode 100644 index 0000000000..e6e153fcc6 --- /dev/null +++ b/client/v2/autocli/flags.go @@ -0,0 +1,3 @@ +package autocli + +var flagNoIndent = "no-indent" diff --git a/client/v2/autocli/msg.go b/client/v2/autocli/msg.go index a46387e97a..682f6c8e75 100644 --- a/client/v2/autocli/msg.go +++ b/client/v2/autocli/msg.go @@ -104,6 +104,10 @@ func (b *Builder) BuildMsgMethodCommand(descriptor protoreflect.MethodDescriptor } cmd, err := b.buildMethodCommandCommon(descriptor, options, func(cmd *cobra.Command, input protoreflect.Message) error { + if noIdent, _ := cmd.Flags().GetBool(flagNoIndent); noIdent { + jsonMarshalOptions.Indent = "" + } + bz, err := jsonMarshalOptions.Marshal(input.Interface()) if err != nil { return err @@ -114,6 +118,8 @@ func (b *Builder) BuildMsgMethodCommand(descriptor protoreflect.MethodDescriptor if b.AddTxConnFlags != nil { b.AddTxConnFlags(cmd) + + cmd.Flags().BoolP(flagNoIndent, "", false, "Do not indent JSON output") } return cmd, err diff --git a/client/v2/autocli/query.go b/client/v2/autocli/query.go index 0a89ac9ab1..d73a7601d0 100644 --- a/client/v2/autocli/query.go +++ b/client/v2/autocli/query.go @@ -110,6 +110,10 @@ func (b *Builder) BuildQueryMethodCommand(descriptor protoreflect.MethodDescript } cmd, err := b.buildMethodCommandCommon(descriptor, options, func(cmd *cobra.Command, input protoreflect.Message) error { + if noIdent, _ := cmd.Flags().GetBool(flagNoIndent); noIdent { + jsonMarshalOptions.Indent = "" + } + clientConn, err := getClientConn(cmd) if err != nil { return err @@ -134,6 +138,8 @@ func (b *Builder) BuildQueryMethodCommand(descriptor protoreflect.MethodDescript if b.AddQueryConnFlags != nil { b.AddQueryConnFlags(cmd) + + cmd.Flags().BoolP(flagNoIndent, "", false, "Do not indent JSON output") } return cmd, nil diff --git a/client/v2/autocli/testdata/help-deprecated-msg.golden b/client/v2/autocli/testdata/help-deprecated-msg.golden index 31d61d736c..4de93a2d06 100644 --- a/client/v2/autocli/testdata/help-deprecated-msg.golden +++ b/client/v2/autocli/testdata/help-deprecated-msg.golden @@ -37,6 +37,7 @@ Flags: --keyring-backend string Select keyring's backend (os|file|kwallet|pass|test|memory) (default "os") --keyring-dir string The client Keyring directory; if omitted, the default 'home' directory will be used --ledger Use a connected Ledger device + --no-indent Do not indent JSON output --node string : to CometBFT rpc interface for this chain (default "tcp://localhost:26657") --note string Note to add a description to the transaction (previously --memo) --offline Offline mode (does not allow any online functionality) diff --git a/client/v2/autocli/testdata/help-deprecated.golden b/client/v2/autocli/testdata/help-deprecated.golden index 2987afd7b9..b9f8082195 100644 --- a/client/v2/autocli/testdata/help-deprecated.golden +++ b/client/v2/autocli/testdata/help-deprecated.golden @@ -26,6 +26,7 @@ Flags: --map-string-coin map[string]cosmos.base.v1beta1.Coin --map-string-string stringToString (default []) --map-string-uint32 stringToUint32 + --no-indent Do not indent JSON output --node string : to CometBFT RPC interface for this chain (default "tcp://localhost:26657") -o, --output string Output format (text|json) (default "text") --page-count-total diff --git a/client/v2/autocli/testdata/help-echo-msg.golden b/client/v2/autocli/testdata/help-echo-msg.golden index 0b5e9e69b7..7a0905579a 100644 --- a/client/v2/autocli/testdata/help-echo-msg.golden +++ b/client/v2/autocli/testdata/help-echo-msg.golden @@ -41,6 +41,7 @@ Flags: --keyring-backend string Select keyring's backend (os|file|kwallet|pass|test|memory) (default "os") --keyring-dir string The client Keyring directory; if omitted, the default 'home' directory will be used --ledger Use a connected Ledger device + --no-indent Do not indent JSON output --node string : to CometBFT rpc interface for this chain (default "tcp://localhost:26657") --note string Note to add a description to the transaction (previously --memo) --offline Offline mode (does not allow any online functionality) diff --git a/client/v2/autocli/testdata/help-echo.golden b/client/v2/autocli/testdata/help-echo.golden index 7047649a29..856ef2c833 100644 --- a/client/v2/autocli/testdata/help-echo.golden +++ b/client/v2/autocli/testdata/help-echo.golden @@ -32,6 +32,7 @@ Flags: --map-string-coin map[string]cosmos.base.v1beta1.Coin some map of string to coin --map-string-string stringToString some map of string to string (default []) --map-string-uint32 stringToUint32 some map of string to int32 + --no-indent Do not indent JSON output --node string : to CometBFT RPC interface for this chain (default "tcp://localhost:26657") -o, --output string Output format (text|json) (default "text") --page-count-total diff --git a/runtime/autocli.go b/runtime/autocli.go index 62e1b45694..49ff961911 100644 --- a/runtime/autocli.go +++ b/runtime/autocli.go @@ -7,33 +7,35 @@ import ( ) func (m appModule) AutoCLIOptions() *autocliv1.ModuleOptions { - return &autocliv1.ModuleOptions{Query: &autocliv1.ServiceCommandDescriptor{ - Service: appv1alpha1.Query_ServiceDesc.ServiceName, - RpcCommandOptions: []*autocliv1.RpcCommandOptions{ - { - RpcMethod: "Config", - Short: "Queries the current app config", - }, - }, - SubCommands: map[string]*autocliv1.ServiceCommandDescriptor{ - "autocli": { - Service: autocliv1.Query_ServiceDesc.ServiceName, - RpcCommandOptions: []*autocliv1.RpcCommandOptions{ - { - RpcMethod: "AppOptions", - Short: "Queries custom autocli options", - }, + return &autocliv1.ModuleOptions{ + Query: &autocliv1.ServiceCommandDescriptor{ + Service: appv1alpha1.Query_ServiceDesc.ServiceName, + RpcCommandOptions: []*autocliv1.RpcCommandOptions{ + { + RpcMethod: "Config", + Short: "Query the current app config", }, }, - "reflection": { - Service: reflectionv1.ReflectionService_ServiceDesc.ServiceName, - RpcCommandOptions: []*autocliv1.RpcCommandOptions{ - { - RpcMethod: "FileDescriptors", - Short: "Queries the app's protobuf file descriptors", + SubCommands: map[string]*autocliv1.ServiceCommandDescriptor{ + "autocli": { + Service: autocliv1.Query_ServiceDesc.ServiceName, + RpcCommandOptions: []*autocliv1.RpcCommandOptions{ + { + RpcMethod: "AppOptions", + Short: "Query the custom autocli options", + }, + }, + }, + "reflection": { + Service: reflectionv1.ReflectionService_ServiceDesc.ServiceName, + RpcCommandOptions: []*autocliv1.RpcCommandOptions{ + { + RpcMethod: "FileDescriptors", + Short: "Query the app's protobuf file descriptors", + }, }, }, }, }, - }} + } } diff --git a/server/cmt_cmds.go b/server/cmt_cmds.go index 1decc4c59f..f03694c93d 100644 --- a/server/cmt_cmds.go +++ b/server/cmt_cmds.go @@ -8,6 +8,7 @@ import ( "strings" cmtcfg "github.com/cometbft/cometbft/config" + cmtjson "github.com/cometbft/cometbft/libs/json" "github.com/cometbft/cometbft/light" "github.com/cometbft/cometbft/node" "github.com/cometbft/cometbft/p2p" @@ -24,6 +25,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/client/grpc/cmtservice" rpc "github.com/cosmos/cosmos-sdk/client/rpc" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" servercmtlog "github.com/cosmos/cosmos-sdk/server/log" @@ -34,6 +36,43 @@ import ( auth "github.com/cosmos/cosmos-sdk/x/auth/client/cli" ) +// StatusCommand returns the command to return the status of the network. +func StatusCommand() *cobra.Command { + cmd := &cobra.Command{ + Use: "status", + Short: "Query remote node for status", + RunE: func(cmd *cobra.Command, _ []string) error { + clientCtx, err := client.GetClientQueryContext(cmd) + if err != nil { + return err + } + + status, err := cmtservice.GetNodeStatus(context.Background(), clientCtx) + if err != nil { + return err + } + + output, err := cmtjson.Marshal(status) + if err != nil { + return err + } + + // In order to maintain backwards compatibility, the default json format output + outputFormat, _ := cmd.Flags().GetString(flags.FlagOutput) + if outputFormat == flags.OutputFormatJSON { + clientCtx = clientCtx.WithOutputFormat(flags.OutputFormatJSON) + } + + return clientCtx.PrintRaw(output) + }, + } + + cmd.Flags().StringP(flags.FlagNode, "n", "tcp://localhost:26657", "Node to connect to") + cmd.Flags().StringP(flags.FlagOutput, "o", "json", "Output format (text|json)") + + return cmd +} + // ShowNodeIDCmd - ported from CometBFT, dump node ID to stdout func ShowNodeIDCmd() *cobra.Command { return &cobra.Command{ @@ -48,7 +87,7 @@ func ShowNodeIDCmd() *cobra.Command { return err } - fmt.Println(nodeKey.ID()) + cmd.Println(nodeKey.ID()) return nil }, } @@ -80,7 +119,7 @@ func ShowValidatorCmd() *cobra.Command { return err } - fmt.Println(string(bz)) + cmd.Println(string(bz)) return nil }, } @@ -100,7 +139,8 @@ func ShowAddressCmd() *cobra.Command { privValidator := pvm.LoadFilePV(cfg.PrivValidatorKeyFile(), cfg.PrivValidatorStateFile()) valConsAddr := (sdk.ConsAddress)(privValidator.GetAddress()) - fmt.Println(valConsAddr.String()) + + cmd.Println(valConsAddr.String()) return nil }, } @@ -130,7 +170,7 @@ func VersionCmd() *cobra.Command { return err } - cmd.Print(string(bs)) + cmd.Println(string(bs)) return nil }, } diff --git a/simapp/simd/cmd/commands.go b/simapp/simd/cmd/commands.go index 06858fc938..0ab6421642 100644 --- a/simapp/simd/cmd/commands.go +++ b/simapp/simd/cmd/commands.go @@ -19,7 +19,6 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/keys" "github.com/cosmos/cosmos-sdk/client/pruning" - "github.com/cosmos/cosmos-sdk/client/rpc" "github.com/cosmos/cosmos-sdk/client/snapshot" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" @@ -126,7 +125,7 @@ func initRootCmd( // add keybase, auxiliary RPC, query, genesis, and tx child commands rootCmd.AddCommand( - rpc.StatusCommand(), + server.StatusCommand(), genesisCommand(txConfig, basicManager), queryCommand(), txCommand(), @@ -159,7 +158,6 @@ func queryCommand() *cobra.Command { } cmd.AddCommand( - rpc.ValidatorCommand(), server.QueryBlockCmd(), authcmd.QueryTxsByEventsCmd(), server.QueryBlocksCmd(), diff --git a/x/consensus/autocli.go b/x/consensus/autocli.go index 54f3dfcf32..a8bb0f49c6 100644 --- a/x/consensus/autocli.go +++ b/x/consensus/autocli.go @@ -3,6 +3,8 @@ package consensus import ( autocliv1 "cosmossdk.io/api/cosmos/autocli/v1" consensusv1 "cosmossdk.io/api/cosmos/consensus/v1" + + "github.com/cosmos/cosmos-sdk/client/grpc/cmtservice" ) // AutoCLIOptions implements the autocli.HasAutoCLIConfig interface. @@ -17,6 +19,9 @@ func (am AppModule) AutoCLIOptions() *autocliv1.ModuleOptions { Short: "Query the current consensus parameters", }, }, + SubCommands: map[string]*autocliv1.ServiceCommandDescriptor{ + "comet": cmtservice.CometBFTAutoCLIDescriptor, + }, }, // Tx is purposely left empty, as the only tx is MsgUpdateParams which is gov gated. }