reduce module interdependancy, /client refactor (#4415)

* abstract staking BuildCreateValidatorMsg, genutil defines its own flags

* client/ refactor

* staking move keys from keeper to types
This commit is contained in:
frog power 4000
2019-05-28 09:44:04 +01:00
committed by Alessio Treglia
parent 91e75cb74a
commit 73e5ef7c13
72 changed files with 854 additions and 659 deletions
+36 -96
View File
@@ -10,76 +10,70 @@ import (
"path/filepath"
"github.com/spf13/cobra"
flag "github.com/spf13/pflag"
"github.com/spf13/viper"
cfg "github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/crypto"
tmcli "github.com/tendermint/tendermint/libs/cli"
"github.com/tendermint/tendermint/libs/common"
tmtypes "github.com/tendermint/tendermint/types"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/context"
"github.com/cosmos/cosmos-sdk/client/keys"
"github.com/cosmos/cosmos-sdk/client/utils"
"github.com/cosmos/cosmos-sdk/codec"
kbkeys "github.com/cosmos/cosmos-sdk/crypto/keys"
"github.com/cosmos/cosmos-sdk/server"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth"
authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder"
"github.com/cosmos/cosmos-sdk/x/genutil"
"github.com/cosmos/cosmos-sdk/x/staking/client/cli"
)
var (
defaultTokens = sdk.TokensFromTendermintPower(100)
defaultAmount = defaultTokens.String() + sdk.DefaultBondDenom
defaultCommissionRate = "0.1"
defaultCommissionMaxRate = "0.2"
defaultCommissionMaxChangeRate = "0.01"
defaultMinSelfDelegation = "1"
)
// helpers for message building gen-tx command
type StakingMsgBuildingHelpers interface {
CreateValidatorMsgHelpers(ipDefault string) (fs *flag.FlagSet, nodeIDFlag, pubkeyFlag, amountFlag, defaultsDesc string)
PrepareFlagsForTxCreateValidator(config *cfg.Config, nodeID, chainID string, valPubKey crypto.PubKey)
BuildCreateValidatorMsg(cliCtx context.CLIContext, txBldr authtxb.TxBuilder) (authtxb.TxBuilder, sdk.Msg, error)
}
// GenTxCmd builds the application's gentx command.
// nolint: errcheck
func GenTxCmd(ctx *server.Context, cdc *codec.Codec, mbm sdk.ModuleBasicManager,
func GenTxCmd(ctx *server.Context, cdc *codec.Codec, mbm sdk.ModuleBasicManager, smbh StakingMsgBuildingHelpers,
genAccIterator genutil.GenesisAccountsIterator, defaultNodeHome, defaultCLIHome string) *cobra.Command {
ipDefault, _ := server.ExternalIP()
fsCreateValidator, flagNodeID, flagPubKey, flagAmount, defaultsDesc := smbh.CreateValidatorMsgHelpers(ipDefault)
cmd := &cobra.Command{
Use: "gentx",
Short: "Generate a genesis tx carrying a self delegation",
Args: cobra.NoArgs,
Long: fmt.Sprintf(`This command is an alias of the 'tx create-validator' command'.
It creates a genesis piece carrying a self delegation with the
following delegation and commission default parameters:
It creates a genesis transaction to create a validator.
The following default parameters are included:
%s`, defaultsDesc),
delegation amount: %s
commission rate: %s
commission max rate: %s
commission max change rate: %s
minimum self delegation: %s
`, defaultAmount, defaultCommissionRate, defaultCommissionMaxRate, defaultCommissionMaxChangeRate, defaultMinSelfDelegation),
RunE: func(cmd *cobra.Command, args []string) error {
config := ctx.Config
config.SetRoot(viper.GetString(tmcli.HomeFlag))
config.SetRoot(viper.GetString(client.FlagHome))
nodeID, valPubKey, err := genutil.InitializeNodeValidatorFiles(ctx.Config)
if err != nil {
return err
}
// Read --nodeID, if empty take it from priv_validator.json
if nodeIDString := viper.GetString(cli.FlagNodeID); nodeIDString != "" {
if nodeIDString := viper.GetString(flagNodeID); nodeIDString != "" {
nodeID = nodeIDString
}
ip := viper.GetString(cli.FlagIP)
if ip == "" {
fmt.Fprintf(os.Stderr, "couldn't retrieve an external IP; "+
"the tx's memo field will be unset")
// Read --pubkey, if empty take it from priv_validator.json
if valPubKeyString := viper.GetString(flagPubKey); valPubKeyString != "" {
valPubKey, err = sdk.GetConsPubKeyBech32(valPubKeyString)
if err != nil {
return err
}
}
genDoc, err := tmtypes.GenesisDocFromFile(config.GenesisFile())
@@ -96,7 +90,7 @@ following delegation and commission default parameters:
return err
}
kb, err := keys.NewKeyBaseFromDir(viper.GetString(flagClientHome))
kb, err := client.NewKeyBaseFromDir(viper.GetString(flagClientHome))
if err != nil {
return err
}
@@ -107,23 +101,12 @@ following delegation and commission default parameters:
return err
}
// Read --pubkey, if empty take it from priv_validator.json
if valPubKeyString := viper.GetString(cli.FlagPubKey); valPubKeyString != "" {
valPubKey, err = sdk.GetConsPubKeyBech32(valPubKeyString)
if err != nil {
return err
}
}
website := viper.GetString(cli.FlagWebsite)
details := viper.GetString(cli.FlagDetails)
identity := viper.GetString(cli.FlagIdentity)
// Set flags for creating gentx
prepareFlagsForTxCreateValidator(config, nodeID, ip, genDoc.ChainID, valPubKey, website, details, identity)
viper.Set(client.FlagHome, viper.GetString(flagClientHome))
smbh.PrepareFlagsForTxCreateValidator(config, nodeID, genDoc.ChainID, valPubKey)
// Fetch the amount of coins staked
amount := viper.GetString(cli.FlagAmount)
amount := viper.GetString(flagAmount)
coins, err := sdk.ParseCoins(amount)
if err != nil {
return err
@@ -134,8 +117,8 @@ following delegation and commission default parameters:
return err
}
txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc))
cliCtx := context.NewCLIContext().WithCodec(cdc)
txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(client.GetTxEncoder(cdc))
cliCtx := client.NewCLIContext().WithCodec(cdc)
// XXX: Set the generate-only flag here after the CLI context has
// been created. This allows the from name/key to be correctly populated.
@@ -145,7 +128,7 @@ following delegation and commission default parameters:
viper.Set(client.FlagGenerateOnly, true)
// create a 'create-validator' message
txBldr, msg, err := cli.BuildCreateValidatorMsg(cliCtx, txBldr)
txBldr, msg, err := smbh.BuildCreateValidatorMsg(cliCtx, txBldr)
if err != nil {
return err
}
@@ -157,14 +140,14 @@ following delegation and commission default parameters:
if info.GetType() == kbkeys.TypeOffline || info.GetType() == kbkeys.TypeMulti {
fmt.Println("Offline key passed in. Use `tx sign` command to sign:")
return utils.PrintUnsignedStdTx(txBldr, cliCtx, []sdk.Msg{msg})
return client.PrintUnsignedStdTx(txBldr, cliCtx, []sdk.Msg{msg})
}
// write the unsigned transaction to the buffer
w := bytes.NewBuffer([]byte{})
cliCtx = cliCtx.WithOutput(w)
if err = utils.PrintUnsignedStdTx(txBldr, cliCtx, []sdk.Msg{msg}); err != nil {
if err = client.PrintUnsignedStdTx(txBldr, cliCtx, []sdk.Msg{msg}); err != nil {
return err
}
@@ -175,7 +158,7 @@ following delegation and commission default parameters:
}
// sign the transaction and write it to the output file
signedTx, err := utils.SignStdTx(txBldr, cliCtx, name, stdTx, false, true)
signedTx, err := client.SignStdTx(txBldr, cliCtx, name, stdTx, false, true)
if err != nil {
return err
}
@@ -199,22 +182,13 @@ following delegation and commission default parameters:
},
}
ip, _ := server.ExternalIP()
cmd.Flags().String(tmcli.HomeFlag, defaultNodeHome, "node's home directory")
cmd.Flags().String(client.FlagHome, defaultNodeHome, "node's home directory")
cmd.Flags().String(flagClientHome, defaultCLIHome, "client's home directory")
cmd.Flags().String(client.FlagName, "", "name of private key with which to sign the gentx")
cmd.Flags().String(client.FlagOutputDocument, "",
"write the genesis transaction JSON document to the given file instead of the default location")
cmd.Flags().String(cli.FlagIP, ip, "The node's public IP")
cmd.Flags().String(cli.FlagNodeID, "", "The node's NodeID")
cmd.Flags().String(cli.FlagWebsite, "", "The validator's (optional) website")
cmd.Flags().String(cli.FlagDetails, "", "The validator's (optional) details")
cmd.Flags().String(cli.FlagIdentity, "", "The (optional) identity signature (ex. UPort or Keybase)")
cmd.Flags().AddFlagSet(cli.FsCommissionCreate)
cmd.Flags().AddFlagSet(cli.FsMinSelfDelegation)
cmd.Flags().AddFlagSet(cli.FsAmount)
cmd.Flags().AddFlagSet(cli.FsPk)
cmd.Flags().AddFlagSet(fsCreateValidator)
cmd.MarkFlagRequired(client.FlagName)
return cmd
}
@@ -251,38 +225,4 @@ func writeSignedGenTx(cdc *codec.Codec, outputDocument string, tx auth.StdTx) er
return err
}
func prepareFlagsForTxCreateValidator(
config *cfg.Config, nodeID, ip, chainID string, valPubKey crypto.PubKey, website, details, identity string,
) {
viper.Set(tmcli.HomeFlag, viper.GetString(flagClientHome))
viper.Set(client.FlagChainID, chainID)
viper.Set(client.FlagFrom, viper.GetString(client.FlagName))
viper.Set(cli.FlagNodeID, nodeID)
viper.Set(cli.FlagIP, ip)
viper.Set(cli.FlagPubKey, sdk.MustBech32ifyConsPub(valPubKey))
viper.Set(cli.FlagMoniker, config.Moniker)
viper.Set(cli.FlagWebsite, website)
viper.Set(cli.FlagDetails, details)
viper.Set(cli.FlagIdentity, identity)
if config.Moniker == "" {
viper.Set(cli.FlagMoniker, viper.GetString(client.FlagName))
}
if viper.GetString(cli.FlagAmount) == "" {
viper.Set(cli.FlagAmount, defaultAmount)
}
if viper.GetString(cli.FlagCommissionRate) == "" {
viper.Set(cli.FlagCommissionRate, defaultCommissionRate)
}
if viper.GetString(cli.FlagCommissionMaxRate) == "" {
viper.Set(cli.FlagCommissionMaxRate, defaultCommissionMaxRate)
}
if viper.GetString(cli.FlagCommissionMaxChangeRate) == "" {
viper.Set(cli.FlagCommissionMaxChangeRate, defaultCommissionMaxChangeRate)
}
if viper.GetString(cli.FlagMinSelfDelegation) == "" {
viper.Set(cli.FlagMinSelfDelegation, defaultMinSelfDelegation)
}
}
// DONTCOVER
-95
View File
@@ -1,95 +0,0 @@
package cli
import (
"testing"
"github.com/spf13/viper"
"github.com/stretchr/testify/require"
tcmd "github.com/tendermint/tendermint/cmd/tendermint/commands"
cfg "github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/crypto"
"github.com/tendermint/tendermint/libs/log"
"github.com/cosmos/cosmos-sdk/server"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/staking/client/cli"
)
func Test_prepareFlagsForTxCreateValidator(t *testing.T) {
defer server.SetupViper(t)()
defer setupClientHome(t)()
config, err := tcmd.ParseConfig()
require.Nil(t, err)
logger := log.NewNopLogger()
ctx := server.NewContext(config, logger)
valPubKey, _ := sdk.GetConsPubKeyBech32("cosmosvalconspub1zcjduepq7jsrkl9fgqk0wj3ahmfr8pgxj6vakj2wzn656s8pehh0zhv2w5as5gd80a")
type args struct {
config *cfg.Config
nodeID string
ip string
chainID string
valPubKey crypto.PubKey
website string
details string
identity string
}
type extraParams struct {
amount string
commissionRate string
commissionMaxRate string
commissionMaxChangeRate string
minSelfDelegation string
}
type testcase struct {
name string
args args
}
runTest := func(t *testing.T, tt testcase, params extraParams) {
prepareFlagsForTxCreateValidator(tt.args.config, tt.args.nodeID,
tt.args.ip, tt.args.chainID, tt.args.valPubKey, tt.args.website,
tt.args.details, tt.args.identity)
require.Equal(t, tt.args.website, viper.GetString(cli.FlagWebsite))
require.Equal(t, tt.args.details, viper.GetString(cli.FlagDetails))
require.Equal(t, tt.args.identity, viper.GetString(cli.FlagIdentity))
require.Equal(t, params.amount, viper.GetString(cli.FlagAmount))
require.Equal(t, params.commissionRate, viper.GetString(cli.FlagCommissionRate))
require.Equal(t, params.commissionMaxRate, viper.GetString(cli.FlagCommissionMaxRate))
require.Equal(t, params.commissionMaxChangeRate, viper.GetString(cli.FlagCommissionMaxChangeRate))
require.Equal(t, params.minSelfDelegation, viper.GetString(cli.FlagMinSelfDelegation))
}
tests := []testcase{
{"No parameters", args{ctx.Config, "X", "0.0.0.0", "chainId", valPubKey, "", "", ""}},
{"Optional parameters fed", args{ctx.Config, "X", "0.0.0.0", "chainId", valPubKey, "cosmos.network", "details", "identity"}},
}
defaultParams := extraParams{
defaultAmount,
defaultCommissionRate,
defaultCommissionMaxRate,
defaultCommissionMaxChangeRate,
defaultMinSelfDelegation,
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Run(tt.name, func(t *testing.T) { runTest(t, tt, defaultParams) })
})
}
// Override default params
params := extraParams{"5stake", "1.0", "1.0", "1.0", "1.0"}
viper.Set(cli.FlagAmount, params.amount)
viper.Set(cli.FlagCommissionRate, params.commissionRate)
viper.Set(cli.FlagCommissionMaxRate, params.commissionMaxRate)
viper.Set(cli.FlagCommissionMaxChangeRate, params.commissionMaxChangeRate)
viper.Set(cli.FlagMinSelfDelegation, params.minSelfDelegation)
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { runTest(t, tt, params) })
}
}