/
root.go
444 lines (392 loc) · 15.6 KB
/
root.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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
package cmd
import (
"context"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"time"
dbm "github.com/cometbft/cometbft-db"
"github.com/rs/zerolog"
"github.com/spf13/cast"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
tmcfg "github.com/tendermint/tendermint/config"
tmcli "github.com/tendermint/tendermint/libs/cli"
"github.com/tendermint/tendermint/libs/log"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/debug"
"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"
"github.com/cosmos/cosmos-sdk/server"
serverconfig "github.com/cosmos/cosmos-sdk/server/config"
servertypes "github.com/cosmos/cosmos-sdk/server/types"
"github.com/cosmos/cosmos-sdk/snapshots"
snapshottypes "github.com/cosmos/cosmos-sdk/snapshots/types"
"github.com/cosmos/cosmos-sdk/store"
sdk "github.com/cosmos/cosmos-sdk/types"
authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli"
"github.com/cosmos/cosmos-sdk/x/auth/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/cosmos/cosmos-sdk/x/crisis"
genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli"
"github.com/provenance-io/provenance/app"
"github.com/provenance-io/provenance/app/params"
"github.com/provenance-io/provenance/cmd/provenanced/config"
"github.com/provenance-io/provenance/internal/pioconfig"
)
const (
// EnvTypeFlag is a flag for indicating a testnet
EnvTypeFlag = "testnet"
// Flag used to indicate coin type.
CoinTypeFlag = "coin-type"
)
// NewRootCmd creates a new root command for provenanced. It is called once in the main function.
// Providing sealConfig = false is only for unit tests that want to run multiple commands.
func NewRootCmd(sealConfig bool) (*cobra.Command, params.EncodingConfig) {
encodingConfig := app.MakeEncodingConfig()
initClientCtx := client.Context{}.
WithCodec(encodingConfig.Marshaler).
WithInterfaceRegistry(encodingConfig.InterfaceRegistry).
WithTxConfig(encodingConfig.TxConfig).
WithLegacyAmino(encodingConfig.Amino).
WithInput(os.Stdin).
WithAccountRetriever(types.AccountRetriever{}).
WithBroadcastMode(flags.BroadcastBlock).
WithHomeDir(app.DefaultNodeHome).
WithViper("PIO")
sdk.SetCoinDenomRegex(app.SdkCoinDenomRegex)
rootCmd := &cobra.Command{
Use: "provenanced",
Short: "Provenance Blockchain App",
PersistentPreRunE: func(cmd *cobra.Command, _ []string) error {
cmd.SetOut(cmd.OutOrStdout())
cmd.SetErr(cmd.ErrOrStderr())
if cmd.Flags().Changed(flags.FlagHome) {
rootDir, _ := cmd.Flags().GetString(flags.FlagHome)
initClientCtx = initClientCtx.WithHomeDir(rootDir)
}
if err := client.SetCmdClientContext(cmd, initClientCtx); err != nil {
return err
}
if err := config.InterceptConfigsPreRunHandler(cmd); err != nil {
return err
}
// set app context based on initialized EnvTypeFlag
vpr := server.GetServerContextFromCmd(cmd).Viper
testnet := vpr.GetBool(EnvTypeFlag)
app.SetConfig(testnet, sealConfig)
overwriteFlagDefaults(cmd, map[string]string{
// Override default value for coin-type to match our mainnet or testnet value.
CoinTypeFlag: fmt.Sprint(app.CoinType),
// Override min gas price(server level config) here since the provenance config would have been set based on flags.
server.FlagMinGasPrices: pioconfig.GetProvenanceConfig().ProvenanceMinGasPrices,
})
return nil
},
}
genAutoCompleteCmd(rootCmd)
initRootCmd(rootCmd, encodingConfig)
overwriteFlagDefaults(rootCmd, map[string]string{
flags.FlagChainID: "",
flags.FlagKeyringBackend: "test",
CoinTypeFlag: fmt.Sprint(app.CoinTypeMainNet),
})
return rootCmd, encodingConfig
}
// Execute executes the root command.
func Execute(rootCmd *cobra.Command) error {
// Create and set a client.Context on the command's Context. During the pre-run
// of the root command, a default initialized client.Context is provided to
// seed child command execution with values such as AccountRetriver, Keyring,
// and a Tendermint RPC. This requires the use of a pointer reference when
// getting and setting the client.Context. Ideally, we utilize
// https://github.com/spf13/cobra/pull/1118.
ctx := context.Background()
ctx = context.WithValue(ctx, client.ClientContextKey, &client.Context{})
ctx = context.WithValue(ctx, server.ServerContextKey, server.NewDefaultContext())
rootCmd.PersistentFlags().BoolP(EnvTypeFlag, "t", false, "Indicates this command should use the testnet configuration (default: false [mainnet])")
rootCmd.PersistentFlags().String(flags.FlagLogLevel, zerolog.InfoLevel.String(), "The logging level (trace|debug|info|warn|error|fatal|panic)")
rootCmd.PersistentFlags().String(flags.FlagLogFormat, tmcfg.LogFormatPlain, "The logging format (json|plain)")
// Custom denom flag added to root command
rootCmd.PersistentFlags().String(config.CustomDenomFlag, "", "Indicates if a custom denom is to be used, and the name of it (default nhash)")
// Custom msgFee floor price flag added to root command
rootCmd.PersistentFlags().Int64(config.CustomMsgFeeFloorPriceFlag, 0, "Custom msgfee floor price, optional (default 1905)")
executor := tmcli.PrepareBaseCmd(rootCmd, "", app.DefaultNodeHome)
return executor.ExecuteContext(ctx)
}
func initRootCmd(rootCmd *cobra.Command, encodingConfig params.EncodingConfig) {
rootCmd.AddCommand(
InitCmd(app.ModuleBasics),
genutilcli.CollectGenTxsCmd(banktypes.GenesisBalancesIterator{}, app.DefaultNodeHome),
genutilcli.GenTxCmd(app.ModuleBasics, encodingConfig.TxConfig, banktypes.GenesisBalancesIterator{}, app.DefaultNodeHome),
genutilcli.ValidateGenesisCmd(app.ModuleBasics),
AddGenesisAccountCmd(app.DefaultNodeHome),
AddRootDomainAccountCmd(app.DefaultNodeHome),
AddGenesisMarkerCmd(app.DefaultNodeHome),
AddGenesisMsgFeeCmd(app.DefaultNodeHome, encodingConfig.InterfaceRegistry),
AddGenesisCustomFloorPriceDenomCmd(app.DefaultNodeHome),
AddGenesisDefaultMarketCmd(app.DefaultNodeHome),
AddGenesisCustomMarketCmd(app.DefaultNodeHome),
tmcli.NewCompletionCmd(rootCmd, true),
testnetCmd(app.ModuleBasics, banktypes.GenesisBalancesIterator{}),
debug.Cmd(),
ConfigCmd(),
AddMetaAddressCmd(),
snapshot.Cmd(newApp),
GetPreUpgradeCmd(),
GetDocGenCmd(),
)
fixDebugPubkeyRawTypeFlag(rootCmd)
server.AddCommands(rootCmd, app.DefaultNodeHome, newApp, createAppAndExport, addModuleInitFlags)
// add keybase, auxiliary RPC, query, and tx child commands
rootCmd.AddCommand(
rpc.StatusCommand(),
queryCommand(),
txCommand(),
keys.Commands(app.DefaultNodeHome),
)
// Add Rosetta command
rootCmd.AddCommand(server.RosettaCommand(encodingConfig.InterfaceRegistry, encodingConfig.Marshaler))
rootCmd.AddCommand(pruning.PruningCmd(newApp))
// Disable usage when the start command returns an error.
startCmd, _, err := rootCmd.Find([]string{"start"})
if err != nil {
panic(fmt.Errorf("start command not found: %w", err))
}
startCmd.SilenceUsage = true
}
// genAutoCompleteCmd creates the command for autocomplete.
func genAutoCompleteCmd(rootCmd *cobra.Command) {
rootCmd.AddCommand(&cobra.Command{
Use: "enable-cli-autocomplete [bash|zsh|fish|powershell]",
Short: "Generates autocomplete scripts for the provenanced binary",
Long: `To configure your shell to load completions for each session, add to your profile:
# bash example
echo '. <(provenanced enable-cli-autocomplete bash)' >> ~/.bash_profile
source ~/.bash_profile
# zsh example
echo '. <(provenanced enable-cli-autocomplete zsh)' >> ~/.zshrc
source ~/.zshrc
`,
DisableFlagsInUseLine: true,
ValidArgs: []string{"bash", "zsh", "fish", "powershell"},
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
switch args[0] {
case "bash":
return cmd.Root().GenBashCompletion(os.Stdout)
case "zsh":
return cmd.Root().GenZshCompletion(os.Stdout)
case "fish":
return cmd.Root().GenFishCompletion(os.Stdout, true)
case "powershell":
return cmd.Root().GenPowerShellCompletionWithDesc(os.Stdout)
}
return fmt.Errorf("shell %s is not supported", args[0])
},
})
}
func addModuleInitFlags(startCmd *cobra.Command) {
crisis.AddModuleInitFlags(startCmd)
}
func queryCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "query",
Aliases: []string{"q"},
Short: "Querying subcommands",
DisableFlagParsing: true,
SuggestionsMinimumDistance: 2,
RunE: client.ValidateCmd,
}
cmd.AddCommand(
authcmd.GetAccountCmd(),
rpc.ValidatorCommand(),
rpc.BlockCommand(),
authcmd.QueryTxsByEventsCmd(),
authcmd.QueryTxCmd(),
)
app.ModuleBasics.AddQueryCommands(cmd)
cmd.PersistentFlags().String(flags.FlagChainID, "", "The network chain ID")
return cmd
}
func txCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "tx",
Short: "Transactions subcommands",
DisableFlagParsing: true,
SuggestionsMinimumDistance: 2,
RunE: client.ValidateCmd,
}
cmd.AddCommand(
authcmd.GetSignCommand(),
authcmd.GetSignBatchCommand(),
authcmd.GetMultiSignCommand(),
authcmd.GetValidateSignaturesCommand(),
flags.LineBreak,
authcmd.GetBroadcastCommand(),
authcmd.GetEncodeCommand(),
authcmd.GetDecodeCommand(),
GetCmdPioSimulateTx(),
flags.LineBreak,
)
app.ModuleBasics.AddTxCommands(cmd)
cmd.PersistentFlags().String(flags.FlagChainID, "", "The network chain ID")
return cmd
}
func newApp(logger log.Logger, db dbm.DB, traceStore io.Writer, appOpts servertypes.AppOptions) servertypes.Application {
warnAboutSettings(logger, appOpts)
var cache sdk.MultiStorePersistentCache
if cast.ToBool(appOpts.Get(server.FlagInterBlockCache)) {
cache = store.NewCommitKVStoreCacheManager()
}
skipUpgradeHeights := make(map[int64]bool)
for _, h := range cast.ToIntSlice(appOpts.Get(server.FlagUnsafeSkipUpgrades)) {
skipUpgradeHeights[int64(h)] = true
}
pruningOpts, err := server.GetPruningOptionsFromFlags(appOpts)
if err != nil {
panic(err)
}
snapshotDir := filepath.Join(cast.ToString(appOpts.Get(flags.FlagHome)), "data", "snapshots")
// Create the snapshot dir if not exists
if _, err = os.Stat(snapshotDir); os.IsNotExist(err) {
err = os.Mkdir(snapshotDir, 0o755)
if err != nil {
panic(err)
}
}
snapshotDB, err := dbm.NewDB("metadata", server.GetAppDBBackend(appOpts), snapshotDir)
if err != nil {
panic(err)
}
snapshotStore, err := snapshots.NewStore(snapshotDB, snapshotDir)
if err != nil {
panic(err)
}
snapshotOptions := snapshottypes.NewSnapshotOptions(
cast.ToUint64(appOpts.Get(server.FlagStateSyncSnapshotInterval)),
cast.ToUint32(appOpts.Get(server.FlagStateSyncSnapshotKeepRecent)),
)
return app.New(
logger, db, traceStore, true, skipUpgradeHeights,
cast.ToString(appOpts.Get(flags.FlagHome)),
cast.ToUint(appOpts.Get(server.FlagInvCheckPeriod)),
app.MakeEncodingConfig(), // Ideally, we would reuse the one created by NewRootCmd.
appOpts,
baseapp.SetPruning(pruningOpts),
baseapp.SetMinGasPrices(cast.ToString(appOpts.Get(server.FlagMinGasPrices))),
baseapp.SetMinRetainBlocks(cast.ToUint64(appOpts.Get(server.FlagMinRetainBlocks))),
baseapp.SetHaltHeight(cast.ToUint64(appOpts.Get(server.FlagHaltHeight))),
baseapp.SetHaltTime(cast.ToUint64(appOpts.Get(server.FlagHaltTime))),
baseapp.SetInterBlockCache(cache),
baseapp.SetTrace(cast.ToBool(appOpts.Get(server.FlagTrace))),
baseapp.SetIndexEvents(cast.ToStringSlice(appOpts.Get(server.FlagIndexEvents))),
baseapp.SetSnapshot(snapshotStore, snapshotOptions),
baseapp.SetIAVLCacheSize(getIAVLCacheSize(appOpts)),
baseapp.SetIAVLDisableFastNode(cast.ToBool(appOpts.Get(server.FlagDisableIAVLFastNode))),
baseapp.SetIAVLLazyLoading(cast.ToBool(appOpts.Get(server.FlagIAVLLazyLoading))),
)
}
// warnAboutSettings logs warnings about any settings that might cause problems.
func warnAboutSettings(logger log.Logger, appOpts servertypes.AppOptions) {
defer func() {
// If this func panics, just move on. It's just supposed to log things anyway.
_ = recover()
}()
chainID := cast.ToString(appOpts.Get(flags.FlagChainID))
if chainID == "pio-mainnet-1" {
skipTimeoutCommit := cast.ToBool(appOpts.Get("consensus.skip_timeout_commit"))
if !skipTimeoutCommit {
timeoutCommit := cast.ToDuration(appOpts.Get("consensus.timeout_commit"))
upperLimit := config.DefaultConsensusTimeoutCommit + 2*time.Second
if timeoutCommit > upperLimit {
logger.Error(fmt.Sprintf("Your consensus.timeout_commit config value is too high and should be decreased to at most %q. The recommended value is %q. Your current value is %q.",
upperLimit, config.DefaultConsensusTimeoutCommit, timeoutCommit))
}
}
}
}
func createAppAndExport(
logger log.Logger,
db dbm.DB,
traceStore io.Writer,
height int64,
forZeroHeight bool,
jailAllowedAddrs []string,
appOpts servertypes.AppOptions,
) (servertypes.ExportedApp, error) {
encCfg := app.MakeEncodingConfig() // Ideally, we would reuse the one created by NewRootCmd.
encCfg.Marshaler = codec.NewProtoCodec(encCfg.InterfaceRegistry)
var a *app.App
homePath, ok := appOpts.Get(flags.FlagHome).(string)
if !ok || homePath == "" {
return servertypes.ExportedApp{}, errors.New("application home not set")
}
if height != -1 {
a = app.New(logger, db, traceStore, false, map[int64]bool{}, homePath, cast.ToUint(appOpts.Get(server.FlagInvCheckPeriod)), encCfg, appOpts)
if err := a.LoadHeight(height); err != nil {
return servertypes.ExportedApp{}, err
}
} else {
a = app.New(logger, db, traceStore, true, map[int64]bool{}, homePath, cast.ToUint(appOpts.Get(server.FlagInvCheckPeriod)), encCfg, appOpts)
}
return a.ExportAppStateAndValidators(forZeroHeight, jailAllowedAddrs)
}
// fixDebugPubkeyRawTypeFlag removes the -t shorthand option of the --type flag from the debug pubkey-raw command.
// It clashes with our persistent --testnet/-t flag added to the root command.
func fixDebugPubkeyRawTypeFlag(rootCmd *cobra.Command) {
debugCmd, _, err := rootCmd.Find([]string{"debug", "pubkey-raw"})
if err != nil || debugCmd == nil {
// If the command doesn't exist, there's nothing to do.
return
}
// We can't just debugCmd.Flags().Lookup("type").Shorthand = "" here because
// there's some internal flagset stuff that needs clearing too, that we can't
// do from here. So we do this the hard way. We clear out the command's flags
// and re-add them all, but get rid of the shorthand on the type flag first.
debugFlags := debugCmd.Flags()
debugCmd.ResetFlags()
debugFlags.VisitAll(func(f *pflag.Flag) {
if f.Name == "type" {
f.Shorthand = ""
}
debugCmd.Flags().AddFlag(f)
})
}
func overwriteFlagDefaults(c *cobra.Command, defaults map[string]string) {
set := func(s *pflag.FlagSet, key, val string) {
if f := s.Lookup(key); f != nil {
if f.Changed {
return
}
f.DefValue = val
if err := f.Value.Set(val); err != nil {
panic(err)
}
}
}
for key, val := range defaults {
set(c.Flags(), key, val)
set(c.PersistentFlags(), key, val)
}
for _, c := range c.Commands() {
overwriteFlagDefaults(c, defaults)
}
}
// getIAVLCacheSize If app.toml has an entry iavl-cache-size = <value>, default is 781250
func getIAVLCacheSize(options servertypes.AppOptions) int {
iavlCacheSize := cast.ToInt(options.Get("iavl-cache-size"))
if iavlCacheSize == 0 {
// going with the DefaultConfig value(which is 781250),
// the store default value is DefaultIAVLCacheSize = 500000
return cast.ToInt(serverconfig.DefaultConfig().IAVLCacheSize)
}
return iavlCacheSize
}