forked from cosmos/cosmos-sdk
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcmt_cmds.go
391 lines (325 loc) · 10.6 KB
/
cmt_cmds.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
package server
import (
"context"
"encoding/json"
"fmt"
"strconv"
"strings"
cmtcfg "github.com/cometbft/cometbft/config"
cmtjson "github.com/cometbft/cometbft/libs/json"
"github.com/cometbft/cometbft/node"
"github.com/cometbft/cometbft/p2p"
pvm "github.com/cometbft/cometbft/privval"
cmtversion "github.com/cometbft/cometbft/version"
"github.com/spf13/cobra"
"sigs.k8s.io/yaml"
"cosmossdk.io/log"
auth "cosmossdk.io/x/auth/client/cli"
"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"
"github.com/cosmos/cosmos-sdk/server/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/query"
"github.com/cosmos/cosmos-sdk/version"
)
// 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{
Use: "show-node-id",
Short: "Show this node's ID",
RunE: func(cmd *cobra.Command, args []string) error {
serverCtx := GetServerContextFromCmd(cmd)
cfg := serverCtx.Config
nodeKey, err := p2p.LoadNodeKey(cfg.NodeKeyFile())
if err != nil {
return err
}
cmd.Println(nodeKey.ID())
return nil
},
}
}
// ShowValidatorCmd - ported from CometBFT, show this node's validator info
func ShowValidatorCmd() *cobra.Command {
cmd := cobra.Command{
Use: "show-validator",
Short: "Show this node's CometBFT validator info",
RunE: func(cmd *cobra.Command, args []string) error {
serverCtx := GetServerContextFromCmd(cmd)
cfg := serverCtx.Config
privValidator := pvm.LoadFilePV(cfg.PrivValidatorKeyFile(), cfg.PrivValidatorStateFile())
pk, err := privValidator.GetPubKey()
if err != nil {
return err
}
sdkPK, err := cryptocodec.FromCmtPubKeyInterface(pk)
if err != nil {
return err
}
clientCtx := client.GetClientContextFromCmd(cmd)
bz, err := clientCtx.Codec.MarshalInterfaceJSON(sdkPK)
if err != nil {
return err
}
cmd.Println(string(bz))
return nil
},
}
return &cmd
}
// ShowAddressCmd - show this node's validator address
func ShowAddressCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "show-address",
Short: "Shows this node's CometBFT validator consensus address",
RunE: func(cmd *cobra.Command, args []string) error {
serverCtx := GetServerContextFromCmd(cmd)
cfg := serverCtx.Config
privValidator := pvm.LoadFilePV(cfg.PrivValidatorKeyFile(), cfg.PrivValidatorStateFile())
valConsAddr := (sdk.ConsAddress)(privValidator.GetAddress())
cmd.Println(valConsAddr.String())
return nil
},
}
return cmd
}
// VersionCmd prints CometBFT and ABCI version numbers.
func VersionCmd() *cobra.Command {
return &cobra.Command{
Use: "version",
Short: "Print CometBFT libraries' version",
Long: "Print protocols' and libraries' version numbers against which this app has been compiled.",
RunE: func(cmd *cobra.Command, args []string) error {
bs, err := yaml.Marshal(&struct {
CometBFT string
ABCI string
BlockProtocol uint64
P2PProtocol uint64
}{
CometBFT: cmtversion.TMCoreSemVer,
ABCI: cmtversion.ABCIVersion,
BlockProtocol: cmtversion.BlockProtocol,
P2PProtocol: cmtversion.P2PProtocol,
})
if err != nil {
return err
}
cmd.Println(string(bs))
return nil
},
}
}
// QueryBlocksCmd returns a command to search through blocks by events.
func QueryBlocksCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "blocks",
Short: "Query for paginated blocks that match a set of events",
Long: `Search for blocks that match the exact given events where results are paginated.
The events query is directly passed to CometBFT's RPC BlockSearch method and must
conform to CometBFT's query syntax.
Please refer to each module's documentation for the full set of events to query
for. Each module documents its respective events under 'xx_events.md'.
`,
Example: fmt.Sprintf(
"$ %s query blocks --query \"message.sender='cosmos1...' AND block.height > 7\" --page 1 --limit 30 --order-by ASC",
version.AppName,
),
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
query, _ := cmd.Flags().GetString(auth.FlagQuery)
page, _ := cmd.Flags().GetInt(flags.FlagPage)
limit, _ := cmd.Flags().GetInt(flags.FlagLimit)
orderBy, _ := cmd.Flags().GetString(auth.FlagOrderBy)
blocks, err := rpc.QueryBlocks(clientCtx, page, limit, query, orderBy)
if err != nil {
return err
}
return clientCtx.PrintProto(blocks)
},
}
flags.AddQueryFlagsToCmd(cmd)
cmd.Flags().Int(flags.FlagPage, query.DefaultPage, "Query a specific page of paginated results")
cmd.Flags().Int(flags.FlagLimit, query.DefaultLimit, "Query number of transactions results per page returned")
cmd.Flags().String(auth.FlagQuery, "", "The blocks events query per CometBFT's query semantics")
cmd.Flags().String(auth.FlagOrderBy, "", "The ordering semantics (asc|dsc)")
_ = cmd.MarkFlagRequired(auth.FlagQuery)
return cmd
}
// QueryBlockCmd implements the default command for a Block query.
func QueryBlockCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "block --type=[height|hash] [height|hash]",
Short: "Query for a committed block by height, hash, or event(s)",
Long: "Query for a specific committed block using the CometBFT RPC `block` and `block_by_hash` method",
Example: strings.TrimSpace(fmt.Sprintf(`
$ %s query block --%s=%s <height>
$ %s query block --%s=%s <hash>
`,
version.AppName, auth.FlagType, auth.TypeHeight,
version.AppName, auth.FlagType, auth.TypeHash)),
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
typ, _ := cmd.Flags().GetString(auth.FlagType)
switch typ {
case auth.TypeHeight:
if args[0] == "" {
return fmt.Errorf("argument should be a block height")
}
// optional height
var height *int64
if len(args) > 0 {
height, err = parseOptionalHeight(args[0])
if err != nil {
return err
}
}
output, err := rpc.GetBlockByHeight(clientCtx, height)
if err != nil {
return err
}
if output.Header.Height == 0 {
return fmt.Errorf("no block found with height %s", args[0])
}
return clientCtx.PrintProto(output)
case auth.TypeHash:
if args[0] == "" {
return fmt.Errorf("argument should be a tx hash")
}
// If hash is given, then query the tx by hash.
output, err := rpc.GetBlockByHash(clientCtx, args[0])
if err != nil {
return err
}
if output.Header.AppHash == nil {
return fmt.Errorf("no block found with hash %s", args[0])
}
return clientCtx.PrintProto(output)
default:
return fmt.Errorf("unknown --%s value %s", auth.FlagType, typ)
}
},
}
flags.AddQueryFlagsToCmd(cmd)
cmd.Flags().String(auth.FlagType, auth.TypeHash, fmt.Sprintf("The type to be used when querying tx, can be one of \"%s\", \"%s\"", auth.TypeHeight, auth.TypeHash))
return cmd
}
// QueryBlockResultsCmd implements the default command for a BlockResults query.
func QueryBlockResultsCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "block-results [height]",
Short: "Query for a committed block's results by height",
Long: "Query for a specific committed block's results using the CometBFT RPC `block_results` method",
Args: cobra.RangeArgs(0, 1),
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
node, err := clientCtx.GetNode()
if err != nil {
return err
}
// optional height
var height *int64
if len(args) > 0 {
height, err = parseOptionalHeight(args[0])
if err != nil {
return err
}
}
blockRes, err := node.BlockResults(context.Background(), height)
if err != nil {
return err
}
// coretypes.ResultBlockResults doesn't implement proto.Message interface
// so we can't print it using clientCtx.PrintProto
// we choose to serialize it to json and print the json instead
blockResStr, err := json.Marshal(blockRes)
if err != nil {
return err
}
return clientCtx.PrintRaw(blockResStr)
},
}
flags.AddQueryFlagsToCmd(cmd)
return cmd
}
func parseOptionalHeight(heightStr string) (*int64, error) {
h, err := strconv.Atoi(heightStr)
if err != nil {
return nil, err
}
if h == 0 {
return nil, nil
}
tmp := int64(h)
return &tmp, nil
}
func BootstrapStateCmd(appCreator types.AppCreator) *cobra.Command {
cmd := &cobra.Command{
Use: "bootstrap-state",
Short: "Bootstrap CometBFT state at an arbitrary block height using a light client",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
serverCtx := GetServerContextFromCmd(cmd)
logger := log.NewLogger(cmd.OutOrStdout())
cfg := serverCtx.Config
height, err := cmd.Flags().GetInt64("height")
if err != nil {
return err
}
if height == 0 {
home := serverCtx.Viper.GetString(flags.FlagHome)
db, err := OpenDB(home, GetAppDBBackend(serverCtx.Viper))
if err != nil {
return err
}
app := appCreator(logger, db, nil, serverCtx.Viper)
height = app.CommitMultiStore().LastCommitID().Version
}
return node.BootstrapState(cmd.Context(), cfg, cmtcfg.DefaultDBProvider, uint64(height), nil)
},
}
cmd.Flags().Int64("height", 0, "Block height to bootstrap state at, if not provided it uses the latest block height in app state")
return cmd
}