diff --git a/.pending/breaking/sdk/4451-Improve-modular b/.pending/breaking/sdk/4451-Improve-modular new file mode 100644 index 000000000000..ce9278f18b3d --- /dev/null +++ b/.pending/breaking/sdk/4451-Improve-modular @@ -0,0 +1,5 @@ +#4451 Improve modularization of clients and modules: + * Module directory structure improved and standardized + * Aliases autogenerated + * Auth and bank related commands are now mounted under the respective moduels + * Client initialization and mounting standardized diff --git a/client/context/context.go b/client/context/context.go index 0b633fb20a9b..83122fa47ee5 100644 --- a/client/context/context.go +++ b/client/context/context.go @@ -8,15 +8,8 @@ import ( "path/filepath" "github.com/pkg/errors" - - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/client/keys" - "github.com/cosmos/cosmos-sdk/codec" - cryptokeys "github.com/cosmos/cosmos-sdk/crypto/keys" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/spf13/viper" - "gopkg.in/yaml.v2" + yaml "gopkg.in/yaml.v2" "github.com/tendermint/tendermint/libs/cli" "github.com/tendermint/tendermint/libs/log" @@ -24,7 +17,12 @@ import ( tmliteProxy "github.com/tendermint/tendermint/lite/proxy" rpcclient "github.com/tendermint/tendermint/rpc/client" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/client/keys" + "github.com/cosmos/cosmos-sdk/codec" + cryptokeys "github.com/cosmos/cosmos-sdk/crypto/keys" sdk "github.com/cosmos/cosmos-sdk/types" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" ) var ( @@ -36,7 +34,7 @@ var ( // transaction handling and queries. type CLIContext struct { Codec *codec.Codec - AccDecoder auth.AccountDecoder + AccDecoder authtypes.AccountDecoder Client rpcclient.Client Keybase cryptokeys.Keybase Output io.Writer @@ -90,7 +88,7 @@ func NewCLIContextWithFrom(from string) CLIContext { Client: rpc, Output: os.Stdout, NodeURI: nodeURI, - AccountStore: auth.StoreKey, + AccountStore: authtypes.StoreKey, From: viper.GetString(flags.FlagFrom), OutputFormat: viper.GetString(cli.OutputFlag), Height: viper.GetInt64(flags.FlagHeight), @@ -165,8 +163,8 @@ func (ctx CLIContext) WithCodec(cdc *codec.Codec) CLIContext { } // GetAccountDecoder gets the account decoder for auth.DefaultAccount. -func GetAccountDecoder(cdc *codec.Codec) auth.AccountDecoder { - return func(accBytes []byte) (acct auth.Account, err error) { +func GetAccountDecoder(cdc *codec.Codec) authtypes.AccountDecoder { + return func(accBytes []byte) (acct authtypes.Account, err error) { err = cdc.UnmarshalBinaryBare(accBytes, &acct) if err != nil { panic(err) diff --git a/client/context/query.go b/client/context/query.go index 0d3eda45cd25..fa1cceb5bb2c 100644 --- a/client/context/query.go +++ b/client/context/query.go @@ -16,7 +16,7 @@ import ( "github.com/cosmos/cosmos-sdk/store/rootmulti" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" ) // GetNode returns an RPC client. If the context's client is not defined, an @@ -59,7 +59,7 @@ func (ctx CLIContext) QuerySubspace(subspace []byte, storeName string) (res []sd // GetAccount queries for an account given an address and a block height. An // error is returned if the query or decoding fails. -func (ctx CLIContext) GetAccount(address []byte) (auth.Account, error) { +func (ctx CLIContext) GetAccount(address []byte) (authtypes.Account, error) { if ctx.AccDecoder == nil { return nil, errors.New("account decoder required but not provided") } @@ -69,7 +69,7 @@ func (ctx CLIContext) GetAccount(address []byte) (auth.Account, error) { return nil, err } - var account auth.Account + var account authtypes.Account if err := ctx.Codec.UnmarshalJSON(res, &account); err != nil { return nil, err } @@ -127,12 +127,12 @@ func (ctx CLIContext) EnsureAccountExistsFromAddr(addr sdk.AccAddress) error { // queryAccount queries an account using custom query endpoint of auth module // returns an error if result is `null` otherwise account data func (ctx CLIContext) queryAccount(addr sdk.AccAddress) ([]byte, error) { - bz, err := ctx.Codec.MarshalJSON(auth.NewQueryAccountParams(addr)) + bz, err := ctx.Codec.MarshalJSON(authtypes.NewQueryAccountParams(addr)) if err != nil { return nil, err } - route := fmt.Sprintf("custom/%s/%s", ctx.AccountStore, auth.QueryAccount) + route := fmt.Sprintf("custom/%s/%s", ctx.AccountStore, authtypes.QueryAccount) res, err := ctx.QueryWithData(route, bz) if err != nil { diff --git a/client/keys/codec.go b/client/keys/codec.go index 6bbb16850711..eae45446e784 100644 --- a/client/keys/codec.go +++ b/client/keys/codec.go @@ -9,6 +9,7 @@ var cdc *codec.Codec func init() { cdc = codec.New() codec.RegisterCrypto(cdc) + cdc.Seal() } // marshal keys diff --git a/client/rest/rest.go b/client/rest/rest.go index 325e54d14f57..6273afe63d7c 100644 --- a/client/rest/rest.go +++ b/client/rest/rest.go @@ -11,7 +11,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" "github.com/cosmos/cosmos-sdk/x/auth" - authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" ) //----------------------------------------------------------------------------- @@ -32,7 +31,7 @@ func WriteGenerateStdTxResponse(w http.ResponseWriter, cdc *codec.Codec, return } - txBldr := authtxb.NewTxBuilder( + txBldr := auth.NewTxBuilder( utils.GetTxEncoder(cdc), br.AccountNumber, br.Sequence, gas, gasAdj, br.Simulate, br.ChainID, br.Memo, br.Fees, br.GasPrices, ) diff --git a/client/routes.go b/client/routes.go new file mode 100644 index 000000000000..99d52d0ac8a4 --- /dev/null +++ b/client/routes.go @@ -0,0 +1,14 @@ +package client + +import ( + "github.com/gorilla/mux" + + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/codec" +) + +// Register routes +func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec) { + RegisterRPCRoutes(cliCtx, r) + RegisterTxRoutes(cliCtx, r, cdc) +} diff --git a/client/tx/broadcast.go b/client/tx/broadcast.go index 90d2ff792a04..d73c3ce8ebed 100644 --- a/client/tx/broadcast.go +++ b/client/tx/broadcast.go @@ -5,7 +5,6 @@ import ( "strings" "github.com/spf13/cobra" - amino "github.com/tendermint/go-amino" "github.com/cosmos/cosmos-sdk/types/rest" "github.com/cosmos/cosmos-sdk/x/auth" @@ -62,7 +61,7 @@ func BroadcastTxRequest(cliCtx context.CLIContext, cdc *codec.Codec) http.Handle } // GetBroadcastCommand returns the tx broadcast command. -func GetBroadcastCommand(codec *amino.Codec) *cobra.Command { +func GetBroadcastCommand(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "broadcast [file_path]", Short: "Broadcast transactions generated offline", @@ -75,7 +74,7 @@ $ tx broadcast ./mytxn.json `), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) (err error) { - cliCtx := context.NewCLIContext().WithCodec(codec) + cliCtx := context.NewCLIContext().WithCodec(cdc) stdTx, err := utils.ReadStdTxFromFile(cliCtx.Codec, args[0]) if err != nil { return diff --git a/client/tx/encode.go b/client/tx/encode.go index 36bb461a4ce6..7434f8547cbf 100644 --- a/client/tx/encode.go +++ b/client/tx/encode.go @@ -6,7 +6,6 @@ import ( "net/http" "github.com/spf13/cobra" - amino "github.com/tendermint/go-amino" "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/flags" @@ -69,7 +68,7 @@ func (txr txEncodeRespStr) String() string { // GetEncodeCommand returns the encode command to take a JSONified transaction and turn it into // Amino-serialized bytes -func GetEncodeCommand(codec *amino.Codec) *cobra.Command { +func GetEncodeCommand(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "encode [file]", Short: "Encode transactions generated offline", @@ -78,7 +77,7 @@ Read a transaction from , serialize it to the Amino wire protocol, and out If you supply a dash (-) argument in place of an input filename, the command reads from standard input.`, Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) (err error) { - cliCtx := context.NewCLIContext().WithCodec(codec) + cliCtx := context.NewCLIContext().WithCodec(cdc) stdTx, err := utils.ReadStdTxFromFile(cliCtx.Codec, args[0]) if err != nil { diff --git a/client/utils/utils.go b/client/utils/utils.go index 176db23589a9..12e6a5bc4622 100644 --- a/client/utils/utils.go +++ b/client/utils/utils.go @@ -18,8 +18,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/keys" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" - authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" ) // GasEstimateResponse defines a response definition for tx gas estimation. @@ -35,7 +34,7 @@ func (gr GasEstimateResponse) String() string { // the provided context has generate-only enabled, the tx will only be printed // to STDOUT in a fully offline manner. Otherwise, the tx will be signed and // broadcasted. -func GenerateOrBroadcastMsgs(cliCtx context.CLIContext, txBldr authtxb.TxBuilder, msgs []sdk.Msg) error { +func GenerateOrBroadcastMsgs(cliCtx context.CLIContext, txBldr authtypes.TxBuilder, msgs []sdk.Msg) error { if cliCtx.GenerateOnly { return PrintUnsignedStdTx(txBldr, cliCtx, msgs) } @@ -48,7 +47,7 @@ func GenerateOrBroadcastMsgs(cliCtx context.CLIContext, txBldr authtxb.TxBuilder // QueryContext. It ensures that the account exists, has a proper number and // sequence set. In addition, it builds and signs a transaction with the // supplied messages. Finally, it broadcasts the signed transaction to a node. -func CompleteAndBroadcastTxCLI(txBldr authtxb.TxBuilder, cliCtx context.CLIContext, msgs []sdk.Msg) error { +func CompleteAndBroadcastTxCLI(txBldr authtypes.TxBuilder, cliCtx context.CLIContext, msgs []sdk.Msg) error { txBldr, err := PrepareTxBuilder(txBldr, cliCtx) if err != nil { return err @@ -118,7 +117,7 @@ func CompleteAndBroadcastTxCLI(txBldr authtxb.TxBuilder, cliCtx context.CLIConte // EnrichWithGas calculates the gas estimate that would be consumed by the // transaction and set the transaction's respective value accordingly. -func EnrichWithGas(txBldr authtxb.TxBuilder, cliCtx context.CLIContext, msgs []sdk.Msg) (authtxb.TxBuilder, error) { +func EnrichWithGas(txBldr authtypes.TxBuilder, cliCtx context.CLIContext, msgs []sdk.Msg) (authtypes.TxBuilder, error) { _, adjusted, err := simulateMsgs(txBldr, cliCtx, msgs) if err != nil { return txBldr, err @@ -146,7 +145,7 @@ func CalculateGas(queryFunc func(string, common.HexBytes) ([]byte, error), } // PrintUnsignedStdTx builds an unsigned StdTx and prints it to os.Stdout. -func PrintUnsignedStdTx(txBldr authtxb.TxBuilder, cliCtx context.CLIContext, msgs []sdk.Msg) error { +func PrintUnsignedStdTx(txBldr authtypes.TxBuilder, cliCtx context.CLIContext, msgs []sdk.Msg) error { stdTx, err := buildUnsignedStdTxOffline(txBldr, cliCtx, msgs) if err != nil { return err @@ -165,11 +164,11 @@ func PrintUnsignedStdTx(txBldr authtxb.TxBuilder, cliCtx context.CLIContext, msg // is false, it replaces the signatures already attached with the new signature. // Don't perform online validation or lookups if offline is true. func SignStdTx( - txBldr authtxb.TxBuilder, cliCtx context.CLIContext, name string, - stdTx auth.StdTx, appendSig bool, offline bool, -) (auth.StdTx, error) { + txBldr authtypes.TxBuilder, cliCtx context.CLIContext, name string, + stdTx authtypes.StdTx, appendSig bool, offline bool, +) (authtypes.StdTx, error) { - var signedStdTx auth.StdTx + var signedStdTx authtypes.StdTx info, err := txBldr.Keybase().Get(name) if err != nil { @@ -201,9 +200,9 @@ func SignStdTx( // SignStdTxWithSignerAddress attaches a signature to a StdTx and returns a copy of a it. // Don't perform online validation or lookups if offline is true, else // populate account and sequence numbers from a foreign account. -func SignStdTxWithSignerAddress(txBldr authtxb.TxBuilder, cliCtx context.CLIContext, - addr sdk.AccAddress, name string, stdTx auth.StdTx, - offline bool) (signedStdTx auth.StdTx, err error) { +func SignStdTxWithSignerAddress(txBldr authtypes.TxBuilder, cliCtx context.CLIContext, + addr sdk.AccAddress, name string, stdTx authtypes.StdTx, + offline bool) (signedStdTx authtypes.StdTx, err error) { // check whether the address is a signer if !isTxSigner(addr, stdTx.GetSigners()) { @@ -226,7 +225,7 @@ func SignStdTxWithSignerAddress(txBldr authtxb.TxBuilder, cliCtx context.CLICont } // Read and decode a StdTx from the given filename. Can pass "-" to read from stdin. -func ReadStdTxFromFile(cdc *codec.Codec, filename string) (stdTx auth.StdTx, err error) { +func ReadStdTxFromFile(cdc *codec.Codec, filename string) (stdTx authtypes.StdTx, err error) { var bytes []byte if filename == "-" { bytes, err = ioutil.ReadAll(os.Stdin) @@ -243,8 +242,8 @@ func ReadStdTxFromFile(cdc *codec.Codec, filename string) (stdTx auth.StdTx, err } func populateAccountFromState( - txBldr authtxb.TxBuilder, cliCtx context.CLIContext, addr sdk.AccAddress, -) (authtxb.TxBuilder, error) { + txBldr authtypes.TxBuilder, cliCtx context.CLIContext, addr sdk.AccAddress, +) (authtypes.TxBuilder, error) { accNum, err := cliCtx.GetAccountNumber(addr) if err != nil { @@ -264,14 +263,14 @@ func populateAccountFromState( func GetTxEncoder(cdc *codec.Codec) (encoder sdk.TxEncoder) { encoder = sdk.GetConfig().GetTxEncoder() if encoder == nil { - encoder = auth.DefaultTxEncoder(cdc) + encoder = authtypes.DefaultTxEncoder(cdc) } return } // nolint // SimulateMsgs simulates the transaction and returns the gas estimate and the adjusted value. -func simulateMsgs(txBldr authtxb.TxBuilder, cliCtx context.CLIContext, msgs []sdk.Msg) (estimated, adjusted uint64, err error) { +func simulateMsgs(txBldr authtypes.TxBuilder, cliCtx context.CLIContext, msgs []sdk.Msg) (estimated, adjusted uint64, err error) { txBytes, err := txBldr.BuildTxForSim(msgs) if err != nil { return @@ -293,7 +292,7 @@ func parseQueryResponse(cdc *codec.Codec, rawRes []byte) (uint64, error) { } // PrepareTxBuilder populates a TxBuilder in preparation for the build of a Tx. -func PrepareTxBuilder(txBldr authtxb.TxBuilder, cliCtx context.CLIContext) (authtxb.TxBuilder, error) { +func PrepareTxBuilder(txBldr authtypes.TxBuilder, cliCtx context.CLIContext) (authtypes.TxBuilder, error) { if err := cliCtx.EnsureAccountExists(); err != nil { return txBldr, err } @@ -322,7 +321,7 @@ func PrepareTxBuilder(txBldr authtxb.TxBuilder, cliCtx context.CLIContext) (auth return txBldr, nil } -func buildUnsignedStdTxOffline(txBldr authtxb.TxBuilder, cliCtx context.CLIContext, msgs []sdk.Msg) (stdTx auth.StdTx, err error) { +func buildUnsignedStdTxOffline(txBldr authtypes.TxBuilder, cliCtx context.CLIContext, msgs []sdk.Msg) (stdTx authtypes.StdTx, err error) { if txBldr.SimulateAndExecute() { if cliCtx.GenerateOnly { return stdTx, errors.New("cannot estimate gas with generate-only") @@ -341,7 +340,7 @@ func buildUnsignedStdTxOffline(txBldr authtxb.TxBuilder, cliCtx context.CLIConte return stdTx, nil } - return auth.NewStdTx(stdSignMsg.Msgs, stdSignMsg.Fee, nil, stdSignMsg.Memo), nil + return authtypes.NewStdTx(stdSignMsg.Msgs, stdSignMsg.Fee, nil, stdSignMsg.Memo), nil } func isTxSigner(user sdk.AccAddress, signers []sdk.AccAddress) bool { diff --git a/client/utils/utils_test.go b/client/utils/utils_test.go index 767cf042f5f4..94df3e797d0d 100644 --- a/client/utils/utils_test.go +++ b/client/utils/utils_test.go @@ -15,7 +15,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" ) var ( @@ -73,7 +73,7 @@ func TestCalculateGas(t *testing.T) { func TestDefaultTxEncoder(t *testing.T) { cdc := makeCodec() - defaultEncoder := auth.DefaultTxEncoder(cdc) + defaultEncoder := authtypes.DefaultTxEncoder(cdc) encoder := GetTxEncoder(cdc) compareEncoders(t, defaultEncoder, encoder) @@ -99,8 +99,8 @@ func TestReadStdTxFromFile(t *testing.T) { sdk.RegisterCodec(cdc) // Build a test transaction - fee := auth.NewStdFee(50000, sdk.Coins{sdk.NewInt64Coin("atom", 150)}) - stdTx := auth.NewStdTx([]sdk.Msg{}, fee, []auth.StdSignature{}, "foomemo") + fee := authtypes.NewStdFee(50000, sdk.Coins{sdk.NewInt64Coin("atom", 150)}) + stdTx := authtypes.NewStdTx([]sdk.Msg{}, fee, []authtypes.StdSignature{}, "foomemo") // Write it to the file encodedTx, _ := cdc.MarshalJSON(stdTx) @@ -158,7 +158,7 @@ func TestValidateCmd(t *testing.T) { func compareEncoders(t *testing.T, expected sdk.TxEncoder, actual sdk.TxEncoder) { msgs := []sdk.Msg{sdk.NewTestMsg(addr)} - tx := auth.NewStdTx(msgs, auth.StdFee{}, []auth.StdSignature{}, "") + tx := authtypes.NewStdTx(msgs, authtypes.StdFee{}, []authtypes.StdSignature{}, "") defaultEncoderBytes, err := expected(tx) require.NoError(t, err) @@ -181,7 +181,7 @@ func makeCodec() *codec.Codec { var cdc = codec.New() sdk.RegisterCodec(cdc) codec.RegisterCrypto(cdc) - auth.RegisterCodec(cdc) + authtypes.RegisterCodec(cdc) cdc.RegisterConcrete(sdk.TestMsg{}, "cosmos-sdk/Test", nil) return cdc } diff --git a/crypto/keys/codec.go b/crypto/keys/codec.go index d85eeb3427ea..3181a9ef3e60 100644 --- a/crypto/keys/codec.go +++ b/crypto/keys/codec.go @@ -1,15 +1,16 @@ package keys import ( - amino "github.com/tendermint/go-amino" cryptoAmino "github.com/tendermint/tendermint/crypto/encoding/amino" + "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/crypto/keys/hd" ) -var cdc = amino.NewCodec() +var cdc *codec.Codec func init() { + cdc = codec.New() cryptoAmino.RegisterAmino(cdc) cdc.RegisterInterface((*Info)(nil), nil) cdc.RegisterConcrete(hd.BIP44Params{}, "crypto/keys/hd/BIP44Params", nil) @@ -17,4 +18,5 @@ func init() { cdc.RegisterConcrete(ledgerInfo{}, "crypto/keys/ledgerInfo", nil) cdc.RegisterConcrete(offlineInfo{}, "crypto/keys/offlineInfo", nil) cdc.RegisterConcrete(multiInfo{}, "crypto/keys/multiInfo", nil) + cdc.Seal() } diff --git a/crypto/ledger_mock.go b/crypto/ledger_mock.go index 8d2509bbe3ca..28ea2c9ab107 100644 --- a/crypto/ledger_mock.go +++ b/crypto/ledger_mock.go @@ -8,15 +8,15 @@ import ( "github.com/btcsuite/btcd/btcec" "github.com/pkg/errors" + secp256k1 "github.com/tendermint/btcd/btcec" + "github.com/tendermint/tendermint/crypto" + tmsecp256k1 "github.com/tendermint/tendermint/crypto/secp256k1" + bip39 "github.com/cosmos/go-bip39" "github.com/cosmos/cosmos-sdk/crypto/keys/hd" "github.com/cosmos/cosmos-sdk/tests" - "github.com/cosmos/cosmos-sdk/types" - - secp256k1 "github.com/tendermint/btcd/btcec" - "github.com/tendermint/tendermint/crypto" - tmsecp256k1 "github.com/tendermint/tendermint/crypto/secp256k1" + sdk "github.com/cosmos/cosmos-sdk/types" ) // If ledger support (build tag) has been enabled, which implies a CGO dependency, @@ -41,7 +41,7 @@ func (mock LedgerSECP256K1Mock) GetPublicKeySECP256K1(derivationPath []uint32) ( if derivationPath[0] != 44 { return nil, errors.New("Invalid derivation path") } - if derivationPath[1] != types.CoinType { + if derivationPath[1] != sdk.CoinType { return nil, errors.New("Invalid derivation path") } @@ -80,7 +80,7 @@ func (mock LedgerSECP256K1Mock) GetAddressPubKeySECP256K1(derivationPath []uint3 copy(compressedPublicKey[:], cmp.SerializeCompressed()) // Generate the bech32 addr using existing tmcrypto/etc. - addr := types.AccAddress(compressedPublicKey.Address()).String() + addr := sdk.AccAddress(compressedPublicKey.Address()).String() return pk, addr, err } diff --git a/crypto/ledger_secp256k1.go b/crypto/ledger_secp256k1.go index b0c573f113dd..ba3b2e8e2bce 100644 --- a/crypto/ledger_secp256k1.go +++ b/crypto/ledger_secp256k1.go @@ -7,12 +7,12 @@ import ( "github.com/btcsuite/btcd/btcec" "github.com/pkg/errors" - "github.com/cosmos/cosmos-sdk/crypto/keys/hd" - "github.com/cosmos/cosmos-sdk/types" - tmbtcec "github.com/tendermint/btcd/btcec" tmcrypto "github.com/tendermint/tendermint/crypto" tmsecp256k1 "github.com/tendermint/tendermint/crypto/secp256k1" + + "github.com/cosmos/cosmos-sdk/crypto/keys/hd" + sdk "github.com/cosmos/cosmos-sdk/types" ) var ( @@ -119,7 +119,7 @@ func LedgerShowAddress(path hd.BIP44Params, expectedPubKey tmcrypto.PubKey) erro return fmt.Errorf("the key's pubkey does not match with the one retrieved from Ledger. Check that the HD path and device are the correct ones") } - pubKey2, _, err := getPubKeyAddrSafe(device, path, types.Bech32PrefixAccAddr) + pubKey2, _, err := getPubKeyAddrSafe(device, path, sdk.Bech32PrefixAccAddr) if err != nil { return err } diff --git a/crypto/ledger_test.go b/crypto/ledger_test.go index 5a3f639e0d34..0f726b410d55 100644 --- a/crypto/ledger_test.go +++ b/crypto/ledger_test.go @@ -4,14 +4,13 @@ import ( "fmt" "testing" - "github.com/cosmos/cosmos-sdk/tests" + "github.com/stretchr/testify/require" tmcrypto "github.com/tendermint/tendermint/crypto" cryptoAmino "github.com/tendermint/tendermint/crypto/encoding/amino" - "github.com/stretchr/testify/require" - "github.com/cosmos/cosmos-sdk/crypto/keys/hd" + "github.com/cosmos/cosmos-sdk/tests" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/go.mod b/go.mod index 69411b1a95f7..7a9886c738ef 100644 --- a/go.mod +++ b/go.mod @@ -19,9 +19,7 @@ require ( github.com/jmhodges/levigo v1.0.0 // indirect github.com/magiconair/properties v1.8.0 // indirect github.com/mattn/go-isatty v0.0.6 - github.com/mattn/go-runewidth v0.0.4 // indirect github.com/mitchellh/mapstructure v1.1.2 // indirect - github.com/olekukonko/tablewriter v0.0.1 github.com/pelletier/go-toml v1.2.0 github.com/pkg/errors v0.8.1 github.com/prometheus/client_golang v0.9.2 // indirect diff --git a/go.sum b/go.sum index 75bd5f7481a0..1d0f153daa76 100644 --- a/go.sum +++ b/go.sum @@ -82,15 +82,11 @@ github.com/magiconair/properties v1.8.0 h1:LLgXmsheXeRoUOBOjtwPQCWIYqM/LU1ayDtDe github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/mattn/go-isatty v0.0.6 h1:SrwhHcpV4nWrMGdNcC2kXpMfcBVYGDuTArqyhocJgvA= github.com/mattn/go-isatty v0.0.6/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= -github.com/mattn/go-runewidth v0.0.4 h1:2BvfKmzob6Bmd4YsL0zygOqfdFnK7GR4QL06Do4/p7Y= -github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= -github.com/olekukonko/tablewriter v0.0.1 h1:b3iUnf1v+ppJiOfNX4yxxqfWKMQPZR5yoh8urCTFX88= -github.com/olekukonko/tablewriter v0.0.1/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.7.0 h1:WSHQ+IS43OoUrWtD1/bbclrwK8TTH5hzp+umCiuxHgs= github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= diff --git a/simapp/app.go b/simapp/app.go index 95036981d645..0b41b8f3a875 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -4,26 +4,29 @@ import ( "io" "os" + abci "github.com/tendermint/tendermint/abci/types" + cmn "github.com/tendermint/tendermint/libs/common" + dbm "github.com/tendermint/tendermint/libs/db" + "github.com/tendermint/tendermint/libs/log" + bam "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/version" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/auth/genaccounts" "github.com/cosmos/cosmos-sdk/x/bank" "github.com/cosmos/cosmos-sdk/x/crisis" distr "github.com/cosmos/cosmos-sdk/x/distribution" + distrclient "github.com/cosmos/cosmos-sdk/x/distribution/client" "github.com/cosmos/cosmos-sdk/x/genutil" "github.com/cosmos/cosmos-sdk/x/gov" "github.com/cosmos/cosmos-sdk/x/mint" "github.com/cosmos/cosmos-sdk/x/params" + paramsclient "github.com/cosmos/cosmos-sdk/x/params/client" "github.com/cosmos/cosmos-sdk/x/slashing" "github.com/cosmos/cosmos-sdk/x/staking" - - abci "github.com/tendermint/tendermint/abci/types" - cmn "github.com/tendermint/tendermint/libs/common" - dbm "github.com/tendermint/tendermint/libs/db" - "github.com/tendermint/tendermint/libs/log" ) const appName = "SimApp" @@ -35,14 +38,10 @@ var ( // default home directories for the application daemon DefaultNodeHome = os.ExpandEnv("$HOME/.simapp") - // The ModuleBasicManager is in charge of setting up basic, + // The module BasicManager is in charge of setting up basic, // non-dependant module elements, such as codec registration // and genesis verification. - ModuleBasics sdk.ModuleBasicManager -) - -func init() { - ModuleBasics = sdk.NewModuleBasicManager( + ModuleBasics = module.NewBasicManager( genaccounts.AppModuleBasic{}, genutil.AppModuleBasic{}, auth.AppModuleBasic{}, @@ -50,12 +49,12 @@ func init() { staking.AppModuleBasic{}, mint.AppModuleBasic{}, distr.AppModuleBasic{}, - gov.AppModuleBasic{}, + gov.NewAppModuleBasic(paramsclient.ProposalHandler, distrclient.ProposalHandler), params.AppModuleBasic{}, crisis.AppModuleBasic{}, slashing.AppModuleBasic{}, ) -} +) // custom tx codec func MakeCodec() *codec.Codec { @@ -100,7 +99,7 @@ type SimApp struct { paramsKeeper params.Keeper // the module manager - mm *sdk.ModuleManager + mm *module.Manager } // NewSimApp returns a reference to an initialized SimApp. @@ -169,7 +168,7 @@ func NewSimApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest bo app.stakingKeeper = *stakingKeeper.SetHooks( staking.NewMultiStakingHooks(app.distrKeeper.Hooks(), app.slashingKeeper.Hooks())) - app.mm = sdk.NewModuleManager( + app.mm = module.NewManager( genaccounts.NewAppModule(app.accountKeeper), genutil.NewAppModule(app.accountKeeper, app.stakingKeeper, app.BaseApp.DeliverTx), auth.NewAppModule(app.accountKeeper, app.feeCollectionKeeper), diff --git a/simapp/app_test.go b/simapp/app_test.go index d93a80734246..e5b6e5a10859 100644 --- a/simapp/app_test.go +++ b/simapp/app_test.go @@ -16,20 +16,10 @@ import ( func TestSimAppExport(t *testing.T) { db := db.NewMemDB() app := NewSimApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, 0) - setGenesis(app) - // Making a new app object with the db, so that initchain hasn't been called - app2 := NewSimApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, 0) - _, _, err := app2.ExportAppStateAndValidators(false, []string{}) - require.NoError(t, err, "ExportAppStateAndValidators should not have an error") -} - -func setGenesis(app *SimApp) error { genesisState := NewDefaultGenesisState() stateBytes, err := codec.MarshalJSONIndent(app.cdc, genesisState) - if err != nil { - return err - } + require.NoError(t, err) // Initialize the chain app.InitChain( @@ -38,7 +28,10 @@ func setGenesis(app *SimApp) error { AppStateBytes: stateBytes, }, ) - app.Commit() - return nil + + // Making a new app object with the db, so that initchain hasn't been called + app2 := NewSimApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, 0) + _, _, err = app2.ExportAppStateAndValidators(false, []string{}) + require.NoError(t, err, "ExportAppStateAndValidators should not have an error") } diff --git a/tests/util.go b/tests/util.go index d8ddd424e603..070073c2b3ed 100644 --- a/tests/util.go +++ b/tests/util.go @@ -5,17 +5,17 @@ import ( "io/ioutil" "net/http" "os" + "strings" "testing" "time" "github.com/stretchr/testify/require" - "strings" - - amino "github.com/tendermint/go-amino" tmclient "github.com/tendermint/tendermint/rpc/client" ctypes "github.com/tendermint/tendermint/rpc/core/types" rpcclient "github.com/tendermint/tendermint/rpc/lib/client" + + "github.com/cosmos/cosmos-sdk/codec" ) // Wait for the next tendermint block from the Tendermint RPC @@ -209,7 +209,7 @@ func NewTestCaseDir(t *testing.T) (string, func()) { return dir, func() { os.RemoveAll(dir) } } -var cdc = amino.NewCodec() +var cdc = codec.New() func init() { ctypes.RegisterAmino(cdc) diff --git a/types/config.go b/types/config.go index 96d12276cc81..ce116352f2bb 100644 --- a/types/config.go +++ b/types/config.go @@ -85,11 +85,13 @@ func (config *Config) SetAddressVerifier(addressVerifier func([]byte) error) { config.addressVerifier = addressVerifier } +// Set the BIP-0044 CoinType code on the config func (config *Config) SetCoinType(coinType uint32) { config.assertNotSealed() config.coinType = coinType } +// Set the FullFundraiserPath (BIP44Prefix) on the config func (config *Config) SetFullFundraiserPath(fullFundraiserPath string) { config.assertNotSealed() config.fullFundraiserPath = fullFundraiserPath @@ -144,10 +146,12 @@ func (config *Config) GetAddressVerifier() func([]byte) error { return config.addressVerifier } +// Get the BIP-0044 CoinType code on the config func (config *Config) GetCoinType() uint32 { return config.coinType } +// Get the FullFundraiserPath (BIP44Prefix) on the config func (config *Config) GetFullFundraiserPath() string { return config.fullFundraiserPath } diff --git a/types/context.go b/types/context.go index 1663a94e65ac..f626fc40caa6 100644 --- a/types/context.go +++ b/types/context.go @@ -257,7 +257,7 @@ type cloner interface { Clone() interface{} // deep copy } -// XXX add description +// TODO add description type Op struct { // type is always 'with' gen int diff --git a/types/module.go b/types/module/module.go similarity index 53% rename from types/module.go rename to types/module/module.go index ff1743a55d9f..b2e165d7dec2 100644 --- a/types/module.go +++ b/types/module/module.go @@ -1,8 +1,9 @@ /* -Package types contains application module patterns and associated "manager" functionality. +Package module contains application module patterns and associated "manager" functionality. The module pattern has been broken down by: - independent module functionality (AppModuleBasic) - - inter-dependent module functionality (AppModule) + - inter-dependent module genesis functionality (AppModuleGenesis) + - inter-dependent module full functionality (AppModule) inter-dependent module functionality is module functionality which somehow depends on other modules, typically through the module keeper. Many of the @@ -17,72 +18,114 @@ process. This separation is necessary, however we still want to allow for a high level pattern for modules to follow - for instance, such that we don't have to manually register all of the codecs for all the modules. This basic procedure as well as other basic patterns are handled through the use of -ModuleBasicManager. +BasicManager. + +Lastly the interface for genesis functionality (AppModuleGenesis) has been +separated out from full module functionality (AppModule) so that modules which +are only used for genesis can take advantage of the Module patterns without +needlessly defining many placeholder functions */ -package types +package module import ( "encoding/json" - "github.com/cosmos/cosmos-sdk/codec" + "github.com/gorilla/mux" "github.com/spf13/cobra" + abci "github.com/tendermint/tendermint/abci/types" -) -// ModuleClient helps modules provide a standard interface for exporting client functionality -type ModuleClient interface { - GetQueryCmd() *cobra.Command - GetTxCmd() *cobra.Command -} + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" +) //__________________________________________________________________________________________ // AppModuleBasic is the standard form for basic non-dependant elements of an application module. type AppModuleBasic interface { Name() string RegisterCodec(*codec.Codec) + + // genesis DefaultGenesis() json.RawMessage ValidateGenesis(json.RawMessage) error + + // client functionality + RegisterRESTRoutes(context.CLIContext, *mux.Router, *codec.Codec) + GetTxCmd(*codec.Codec) *cobra.Command + GetQueryCmd(*codec.Codec) *cobra.Command } // collections of AppModuleBasic -type ModuleBasicManager []AppModuleBasic +type BasicManager map[string]AppModuleBasic -func NewModuleBasicManager(modules ...AppModuleBasic) ModuleBasicManager { - return modules +func NewBasicManager(modules ...AppModuleBasic) BasicManager { + moduleMap := make(map[string]AppModuleBasic) + for _, module := range modules { + moduleMap[module.Name()] = module + } + return moduleMap } // RegisterCodecs registers all module codecs -func (mbm ModuleBasicManager) RegisterCodec(cdc *codec.Codec) { - for _, mb := range mbm { - mb.RegisterCodec(cdc) +func (bm BasicManager) RegisterCodec(cdc *codec.Codec) { + for _, b := range bm { + b.RegisterCodec(cdc) } } // Provided default genesis information for all modules -func (mbm ModuleBasicManager) DefaultGenesis() map[string]json.RawMessage { +func (bm BasicManager) DefaultGenesis() map[string]json.RawMessage { genesis := make(map[string]json.RawMessage) - for _, mb := range mbm { - genesis[mb.Name()] = mb.DefaultGenesis() + for _, b := range bm { + genesis[b.Name()] = b.DefaultGenesis() } return genesis } // Provided default genesis information for all modules -func (mbm ModuleBasicManager) ValidateGenesis(genesis map[string]json.RawMessage) error { - for _, mb := range mbm { - if err := mb.ValidateGenesis(genesis[mb.Name()]); err != nil { +func (bm BasicManager) ValidateGenesis(genesis map[string]json.RawMessage) error { + for _, b := range bm { + if err := b.ValidateGenesis(genesis[b.Name()]); err != nil { return err } } return nil } +// RegisterRestRoutes registers all module rest routes +func (bm BasicManager) RegisterRESTRoutes( + ctx context.CLIContext, rtr *mux.Router, cdc *codec.Codec) { + + for _, b := range bm { + b.RegisterRESTRoutes(ctx, rtr, cdc) + } +} + +// add all tx commands to the rootTxCmd +func (bm BasicManager) AddTxCommands(rootTxCmd *cobra.Command, cdc *codec.Codec) { + for _, b := range bm { + if cmd := b.GetTxCmd(cdc); cmd != nil { + rootTxCmd.AddCommand(cmd) + } + } +} + +// add all query commands to the rootQueryCmd +func (bm BasicManager) AddQueryCommands(rootQueryCmd *cobra.Command, cdc *codec.Codec) { + for _, b := range bm { + if cmd := b.GetQueryCmd(cdc); cmd != nil { + rootQueryCmd.AddCommand(cmd) + } + } +} + //_________________________________________________________ // AppModuleGenesis is the standard form for an application module genesis functions type AppModuleGenesis interface { AppModuleBasic - InitGenesis(Context, json.RawMessage) []abci.ValidatorUpdate - ExportGenesis(Context) json.RawMessage + InitGenesis(sdk.Context, json.RawMessage) []abci.ValidatorUpdate + ExportGenesis(sdk.Context) json.RawMessage } // AppModule is the standard form for an application module @@ -90,16 +133,16 @@ type AppModule interface { AppModuleGenesis // registers - RegisterInvariants(InvariantRouter) + RegisterInvariants(sdk.InvariantRouter) // routes Route() string - NewHandler() Handler + NewHandler() sdk.Handler QuerierRoute() string - NewQuerierHandler() Querier + NewQuerierHandler() sdk.Querier - BeginBlock(Context, abci.RequestBeginBlock) Tags - EndBlock(Context, abci.RequestEndBlock) ([]abci.ValidatorUpdate, Tags) + BeginBlock(sdk.Context, abci.RequestBeginBlock) sdk.Tags + EndBlock(sdk.Context, abci.RequestEndBlock) ([]abci.ValidatorUpdate, sdk.Tags) } //___________________________ @@ -116,34 +159,34 @@ func NewGenesisOnlyAppModule(amg AppModuleGenesis) AppModule { } // register invariants -func (GenesisOnlyAppModule) RegisterInvariants(_ InvariantRouter) {} +func (GenesisOnlyAppModule) RegisterInvariants(_ sdk.InvariantRouter) {} // module message route ngame func (GenesisOnlyAppModule) Route() string { return "" } // module handler -func (GenesisOnlyAppModule) NewHandler() Handler { return nil } +func (GenesisOnlyAppModule) NewHandler() sdk.Handler { return nil } // module querier route ngame func (GenesisOnlyAppModule) QuerierRoute() string { return "" } // module querier -func (gam GenesisOnlyAppModule) NewQuerierHandler() Querier { return nil } +func (gam GenesisOnlyAppModule) NewQuerierHandler() sdk.Querier { return nil } // module begin-block -func (gam GenesisOnlyAppModule) BeginBlock(ctx Context, req abci.RequestBeginBlock) Tags { - return EmptyTags() +func (gam GenesisOnlyAppModule) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) sdk.Tags { + return sdk.EmptyTags() } // module end-block -func (GenesisOnlyAppModule) EndBlock(_ Context, _ abci.RequestEndBlock) ([]abci.ValidatorUpdate, Tags) { - return []abci.ValidatorUpdate{}, EmptyTags() +func (GenesisOnlyAppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) ([]abci.ValidatorUpdate, sdk.Tags) { + return []abci.ValidatorUpdate{}, sdk.EmptyTags() } //____________________________________________________________________________ // module manager provides the high level utility for managing and executing // operations for a group of modules -type ModuleManager struct { +type Manager struct { Modules map[string]AppModule OrderInitGenesis []string OrderExportGenesis []string @@ -151,8 +194,8 @@ type ModuleManager struct { OrderEndBlockers []string } -// NewModuleManager creates a new ModuleManager object -func NewModuleManager(modules ...AppModule) *ModuleManager { +// NewModuleManager creates a new Manager object +func NewManager(modules ...AppModule) *Manager { moduleMap := make(map[string]AppModule) var modulesStr []string @@ -161,7 +204,7 @@ func NewModuleManager(modules ...AppModule) *ModuleManager { modulesStr = append(modulesStr, module.Name()) } - return &ModuleManager{ + return &Manager{ Modules: moduleMap, OrderInitGenesis: modulesStr, OrderExportGenesis: modulesStr, @@ -171,35 +214,35 @@ func NewModuleManager(modules ...AppModule) *ModuleManager { } // set the order of init genesis calls -func (mm *ModuleManager) SetOrderInitGenesis(moduleNames ...string) { - mm.OrderInitGenesis = moduleNames +func (m *Manager) SetOrderInitGenesis(moduleNames ...string) { + m.OrderInitGenesis = moduleNames } // set the order of export genesis calls -func (mm *ModuleManager) SetOrderExportGenesis(moduleNames ...string) { - mm.OrderExportGenesis = moduleNames +func (m *Manager) SetOrderExportGenesis(moduleNames ...string) { + m.OrderExportGenesis = moduleNames } // set the order of set begin-blocker calls -func (mm *ModuleManager) SetOrderBeginBlockers(moduleNames ...string) { - mm.OrderBeginBlockers = moduleNames +func (m *Manager) SetOrderBeginBlockers(moduleNames ...string) { + m.OrderBeginBlockers = moduleNames } // set the order of set end-blocker calls -func (mm *ModuleManager) SetOrderEndBlockers(moduleNames ...string) { - mm.OrderEndBlockers = moduleNames +func (m *Manager) SetOrderEndBlockers(moduleNames ...string) { + m.OrderEndBlockers = moduleNames } // register all module routes and module querier routes -func (mm *ModuleManager) RegisterInvariants(invarRouter InvariantRouter) { - for _, module := range mm.Modules { +func (m *Manager) RegisterInvariants(invarRouter sdk.InvariantRouter) { + for _, module := range m.Modules { module.RegisterInvariants(invarRouter) } } // register all module routes and module querier routes -func (mm *ModuleManager) RegisterRoutes(router Router, queryRouter QueryRouter) { - for _, module := range mm.Modules { +func (m *Manager) RegisterRoutes(router sdk.Router, queryRouter sdk.QueryRouter) { + for _, module := range m.Modules { if module.Route() != "" { router.AddRoute(module.Route(), module.NewHandler()) } @@ -210,13 +253,13 @@ func (mm *ModuleManager) RegisterRoutes(router Router, queryRouter QueryRouter) } // perform init genesis functionality for modules -func (mm *ModuleManager) InitGenesis(ctx Context, genesisData map[string]json.RawMessage) abci.ResponseInitChain { +func (m *Manager) InitGenesis(ctx sdk.Context, genesisData map[string]json.RawMessage) abci.ResponseInitChain { var validatorUpdates []abci.ValidatorUpdate - for _, moduleName := range mm.OrderInitGenesis { + for _, moduleName := range m.OrderInitGenesis { if genesisData[moduleName] == nil { continue } - moduleValUpdates := mm.Modules[moduleName].InitGenesis(ctx, genesisData[moduleName]) + moduleValUpdates := m.Modules[moduleName].InitGenesis(ctx, genesisData[moduleName]) // use these validator updates if provided, the module manager assumes // only one module will update the validator set @@ -233,19 +276,19 @@ func (mm *ModuleManager) InitGenesis(ctx Context, genesisData map[string]json.Ra } // perform export genesis functionality for modules -func (mm *ModuleManager) ExportGenesis(ctx Context) map[string]json.RawMessage { +func (m *Manager) ExportGenesis(ctx sdk.Context) map[string]json.RawMessage { genesisData := make(map[string]json.RawMessage) - for _, moduleName := range mm.OrderExportGenesis { - genesisData[moduleName] = mm.Modules[moduleName].ExportGenesis(ctx) + for _, moduleName := range m.OrderExportGenesis { + genesisData[moduleName] = m.Modules[moduleName].ExportGenesis(ctx) } return genesisData } // perform begin block functionality for modules -func (mm *ModuleManager) BeginBlock(ctx Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { - tags := EmptyTags() - for _, moduleName := range mm.OrderBeginBlockers { - moduleTags := mm.Modules[moduleName].BeginBlock(ctx, req) +func (m *Manager) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { + tags := sdk.EmptyTags() + for _, moduleName := range m.OrderBeginBlockers { + moduleTags := m.Modules[moduleName].BeginBlock(ctx, req) tags = tags.AppendTags(moduleTags) } @@ -255,11 +298,11 @@ func (mm *ModuleManager) BeginBlock(ctx Context, req abci.RequestBeginBlock) abc } // perform end block functionality for modules -func (mm *ModuleManager) EndBlock(ctx Context, req abci.RequestEndBlock) abci.ResponseEndBlock { +func (m *Manager) EndBlock(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { validatorUpdates := []abci.ValidatorUpdate{} - tags := EmptyTags() - for _, moduleName := range mm.OrderEndBlockers { - moduleValUpdates, moduleTags := mm.Modules[moduleName].EndBlock(ctx, req) + tags := sdk.EmptyTags() + for _, moduleName := range m.OrderEndBlockers { + moduleValUpdates, moduleTags := m.Modules[moduleName].EndBlock(ctx, req) tags = tags.AppendTags(moduleTags) // use these validator updates if provided, the module manager assumes diff --git a/types/module_test.go b/types/module/module_test.go similarity index 88% rename from types/module_test.go rename to types/module/module_test.go index 939d70bfb334..4f24de5a185a 100644 --- a/types/module_test.go +++ b/types/module/module_test.go @@ -1,4 +1,4 @@ -package types +package module import ( "testing" @@ -8,7 +8,7 @@ import ( ) func TestSetOrderBeginBlockers(t *testing.T) { - mm := NewModuleManager() + mm := NewManager() mm.SetOrderBeginBlockers("a", "b", "c") obb := mm.OrderBeginBlockers require.Equal(t, 3, len(obb)) diff --git a/x/auth/alias.go b/x/auth/alias.go new file mode 100644 index 000000000000..3c1fe15fde10 --- /dev/null +++ b/x/auth/alias.go @@ -0,0 +1,92 @@ +// nolint +// autogenerated code using github.com/rigelrozanski/multitool +// aliases generated for the following subdirectories: +// ALIASGEN: github.com/cosmos/cosmos-sdk/x/auth/types +package auth + +import ( + "github.com/cosmos/cosmos-sdk/x/auth/types" +) + +const ( + ModuleName = types.ModuleName + StoreKey = types.StoreKey + FeeStoreKey = types.FeeStoreKey + QuerierRoute = types.QuerierRoute + DefaultParamspace = types.DefaultParamspace + DefaultMaxMemoCharacters = types.DefaultMaxMemoCharacters + DefaultTxSigLimit = types.DefaultTxSigLimit + DefaultTxSizeCostPerByte = types.DefaultTxSizeCostPerByte + DefaultSigVerifyCostED25519 = types.DefaultSigVerifyCostED25519 + DefaultSigVerifyCostSecp256k1 = types.DefaultSigVerifyCostSecp256k1 + QueryAccount = types.QueryAccount +) + +var ( + // functions aliases + NewBaseAccount = types.NewBaseAccount + ProtoBaseAccount = types.ProtoBaseAccount + NewBaseAccountWithAddress = types.NewBaseAccountWithAddress + NewBaseVestingAccount = types.NewBaseVestingAccount + NewContinuousVestingAccountRaw = types.NewContinuousVestingAccountRaw + NewContinuousVestingAccount = types.NewContinuousVestingAccount + NewDelayedVestingAccountRaw = types.NewDelayedVestingAccountRaw + NewDelayedVestingAccount = types.NewDelayedVestingAccount + RegisterCodec = types.RegisterCodec + RegisterBaseAccount = types.RegisterBaseAccount + NewFeeCollectionKeeper = types.NewFeeCollectionKeeper + NewGenesisState = types.NewGenesisState + DefaultGenesisState = types.DefaultGenesisState + ValidateGenesis = types.ValidateGenesis + AddressStoreKey = types.AddressStoreKey + NewParams = types.NewParams + ParamKeyTable = types.ParamKeyTable + DefaultParams = types.DefaultParams + NewQueryAccountParams = types.NewQueryAccountParams + NewStdTx = types.NewStdTx + CountSubKeys = types.CountSubKeys + NewStdFee = types.NewStdFee + StdSignBytes = types.StdSignBytes + DefaultTxDecoder = types.DefaultTxDecoder + DefaultTxEncoder = types.DefaultTxEncoder + NewTestMsg = types.NewTestMsg + NewTestStdFee = types.NewTestStdFee + NewTestCoins = types.NewTestCoins + KeyTestPubAddr = types.KeyTestPubAddr + NewTestTx = types.NewTestTx + NewTestTxWithMemo = types.NewTestTxWithMemo + NewTestTxWithSignBytes = types.NewTestTxWithSignBytes + NewTxBuilder = types.NewTxBuilder + NewTxBuilderFromCLI = types.NewTxBuilderFromCLI + MakeSignature = types.MakeSignature + + // variable aliases + ModuleCdc = types.ModuleCdc + AddressStoreKeyPrefix = types.AddressStoreKeyPrefix + GlobalAccountNumberKey = types.GlobalAccountNumberKey + KeyMaxMemoCharacters = types.KeyMaxMemoCharacters + KeyTxSigLimit = types.KeyTxSigLimit + KeyTxSizeCostPerByte = types.KeyTxSizeCostPerByte + KeySigVerifyCostED25519 = types.KeySigVerifyCostED25519 + KeySigVerifyCostSecp256k1 = types.KeySigVerifyCostSecp256k1 +) + +type ( + Account = types.Account + VestingAccount = types.VestingAccount + AccountDecoder = types.AccountDecoder + BaseAccount = types.BaseAccount + BaseVestingAccount = types.BaseVestingAccount + ContinuousVestingAccount = types.ContinuousVestingAccount + DelayedVestingAccount = types.DelayedVestingAccount + FeeCollectionKeeper = types.FeeCollectionKeeper + GenesisState = types.GenesisState + Params = types.Params + QueryAccountParams = types.QueryAccountParams + StdSignMsg = types.StdSignMsg + StdTx = types.StdTx + StdFee = types.StdFee + StdSignDoc = types.StdSignDoc + StdSignature = types.StdSignature + TxBuilder = types.TxBuilder +) diff --git a/x/auth/ante.go b/x/auth/ante.go index b31ac30db304..28a16821e9ac 100644 --- a/x/auth/ante.go +++ b/x/auth/ante.go @@ -29,7 +29,7 @@ func init() { } // SignatureVerificationGasConsumer is the type of function that is used to both consume gas when verifying signatures -// and also to accept or reject different types of PubKey's. This is where apps can define their own PubKey types. +// and also to accept or reject different types of PubKey's. This is where apps can define their own PubKey type SignatureVerificationGasConsumer = func(meter sdk.GasMeter, sig []byte, pubkey crypto.PubKey, params Params) sdk.Result // NewAnteHandler returns an AnteHandler that checks and increments sequence @@ -165,7 +165,7 @@ func ValidateSigCount(stdTx StdTx, params Params) sdk.Result { sigCount := 0 for i := 0; i < len(stdSigs); i++ { - sigCount += countSubKeys(stdSigs[i].PubKey) + sigCount += CountSubKeys(stdSigs[i].PubKey) if uint64(sigCount) > params.TxSigLimit { return sdk.ErrTooManySignatures( fmt.Sprintf("signatures: %d, limit: %d", sigCount, params.TxSigLimit), @@ -237,7 +237,7 @@ func consumeSimSigGas(gasmeter sdk.GasMeter, pubkey crypto.PubKey, sig StdSignat simSig.Signature = simSecp256k1Sig[:] } - sigBz := moduleCdc.MustMarshalBinaryLengthPrefixed(simSig) + sigBz := ModuleCdc.MustMarshalBinaryLengthPrefixed(simSig) cost := sdk.Gas(len(sigBz) + 6) // If the pubkey is a multi-signature pubkey, then we estimate for the maximum diff --git a/x/auth/ante_test.go b/x/auth/ante_test.go index 380b8eb9141a..f0c3125144ff 100644 --- a/x/auth/ante_test.go +++ b/x/auth/ante_test.go @@ -13,6 +13,7 @@ import ( "github.com/tendermint/tendermint/crypto/secp256k1" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/types" ) // run the tx through the anteHandler and ensure its valid @@ -32,8 +33,8 @@ func checkInvalidTx(t *testing.T, anteHandler sdk.AnteHandler, ctx sdk.Context, require.Equal(t, sdk.CodespaceRoot, result.Codespace) if code == sdk.CodeOutOfGas { - stdTx, ok := tx.(StdTx) - require.True(t, ok, "tx must be in form auth.StdTx") + stdTx, ok := tx.(types.StdTx) + require.True(t, ok, "tx must be in form auth.types.StdTx") // GasWanted set correctly require.Equal(t, stdTx.Fee.Gas, result.GasWanted, "Gas wanted not set correctly") require.True(t, result.GasUsed > result.GasWanted, "GasUsed not greated than GasWanted") @@ -50,25 +51,25 @@ func TestAnteHandlerSigErrors(t *testing.T) { anteHandler := NewAnteHandler(input.ak, input.fck, DefaultSigVerificationGasConsumer) // keys and addresses - priv1, _, addr1 := keyPubAddr() - priv2, _, addr2 := keyPubAddr() - priv3, _, addr3 := keyPubAddr() + priv1, _, addr1 := KeyTestPubAddr() + priv2, _, addr2 := KeyTestPubAddr() + priv3, _, addr3 := KeyTestPubAddr() // msg and signatures var tx sdk.Tx - msg1 := newTestMsg(addr1, addr2) - msg2 := newTestMsg(addr1, addr3) - fee := newStdFee() + msg1 := NewTestMsg(addr1, addr2) + msg2 := NewTestMsg(addr1, addr3) + fee := NewTestStdFee() msgs := []sdk.Msg{msg1, msg2} // test no signatures privs, accNums, seqs := []crypto.PrivKey{}, []uint64{}, []uint64{} - tx = newTestTx(ctx, msgs, privs, accNums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accNums, seqs, fee) // tx.GetSigners returns addresses in correct order: addr1, addr2, addr3 expectedSigners := []sdk.AccAddress{addr1, addr2, addr3} - stdTx := tx.(StdTx) + stdTx := tx.(types.StdTx) require.Equal(t, expectedSigners, stdTx.GetSigners()) // Check no signatures fails @@ -76,12 +77,12 @@ func TestAnteHandlerSigErrors(t *testing.T) { // test num sigs dont match GetSigners privs, accNums, seqs = []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} - tx = newTestTx(ctx, msgs, privs, accNums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accNums, seqs, fee) checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeUnauthorized) // test an unrecognized account privs, accNums, seqs = []crypto.PrivKey{priv1, priv2, priv3}, []uint64{0, 1, 2}, []uint64{0, 0, 0} - tx = newTestTx(ctx, msgs, privs, accNums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accNums, seqs, fee) checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeUnknownAddress) // save the first account, but second is still unrecognized @@ -99,50 +100,50 @@ func TestAnteHandlerAccountNumbers(t *testing.T) { ctx := input.ctx.WithBlockHeight(1) // keys and addresses - priv1, _, addr1 := keyPubAddr() - priv2, _, addr2 := keyPubAddr() + priv1, _, addr1 := KeyTestPubAddr() + priv2, _, addr2 := KeyTestPubAddr() // set the accounts acc1 := input.ak.NewAccountWithAddress(ctx, addr1) - acc1.SetCoins(newCoins()) + acc1.SetCoins(NewTestCoins()) input.ak.SetAccount(ctx, acc1) acc2 := input.ak.NewAccountWithAddress(ctx, addr2) - acc2.SetCoins(newCoins()) + acc2.SetCoins(NewTestCoins()) input.ak.SetAccount(ctx, acc2) // msg and signatures var tx sdk.Tx - msg := newTestMsg(addr1) - fee := newStdFee() + msg := NewTestMsg(addr1) + fee := NewTestStdFee() msgs := []sdk.Msg{msg} // test good tx from one signer privs, accnums, seqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} - tx = newTestTx(ctx, msgs, privs, accnums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accnums, seqs, fee) checkValidTx(t, anteHandler, ctx, tx, false) // new tx from wrong account number seqs = []uint64{1} - tx = newTestTx(ctx, msgs, privs, []uint64{1}, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, []uint64{1}, seqs, fee) checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeUnauthorized) // from correct account number seqs = []uint64{1} - tx = newTestTx(ctx, msgs, privs, []uint64{0}, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, []uint64{0}, seqs, fee) checkValidTx(t, anteHandler, ctx, tx, false) // new tx with another signer and incorrect account numbers - msg1 := newTestMsg(addr1, addr2) - msg2 := newTestMsg(addr2, addr1) + msg1 := NewTestMsg(addr1, addr2) + msg2 := NewTestMsg(addr2, addr1) msgs = []sdk.Msg{msg1, msg2} privs, accnums, seqs = []crypto.PrivKey{priv1, priv2}, []uint64{1, 0}, []uint64{2, 0} - tx = newTestTx(ctx, msgs, privs, accnums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accnums, seqs, fee) checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeUnauthorized) // correct account numbers privs, accnums, seqs = []crypto.PrivKey{priv1, priv2}, []uint64{0, 1}, []uint64{2, 0} - tx = newTestTx(ctx, msgs, privs, accnums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accnums, seqs, fee) checkValidTx(t, anteHandler, ctx, tx, false) } @@ -154,50 +155,50 @@ func TestAnteHandlerAccountNumbersAtBlockHeightZero(t *testing.T) { ctx := input.ctx.WithBlockHeight(0) // keys and addresses - priv1, _, addr1 := keyPubAddr() - priv2, _, addr2 := keyPubAddr() + priv1, _, addr1 := KeyTestPubAddr() + priv2, _, addr2 := KeyTestPubAddr() // set the accounts acc1 := input.ak.NewAccountWithAddress(ctx, addr1) - acc1.SetCoins(newCoins()) + acc1.SetCoins(NewTestCoins()) input.ak.SetAccount(ctx, acc1) acc2 := input.ak.NewAccountWithAddress(ctx, addr2) - acc2.SetCoins(newCoins()) + acc2.SetCoins(NewTestCoins()) input.ak.SetAccount(ctx, acc2) // msg and signatures var tx sdk.Tx - msg := newTestMsg(addr1) - fee := newStdFee() + msg := NewTestMsg(addr1) + fee := NewTestStdFee() msgs := []sdk.Msg{msg} // test good tx from one signer privs, accnums, seqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} - tx = newTestTx(ctx, msgs, privs, accnums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accnums, seqs, fee) checkValidTx(t, anteHandler, ctx, tx, false) // new tx from wrong account number seqs = []uint64{1} - tx = newTestTx(ctx, msgs, privs, []uint64{1}, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, []uint64{1}, seqs, fee) checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeUnauthorized) // from correct account number seqs = []uint64{1} - tx = newTestTx(ctx, msgs, privs, []uint64{0}, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, []uint64{0}, seqs, fee) checkValidTx(t, anteHandler, ctx, tx, false) // new tx with another signer and incorrect account numbers - msg1 := newTestMsg(addr1, addr2) - msg2 := newTestMsg(addr2, addr1) + msg1 := NewTestMsg(addr1, addr2) + msg2 := NewTestMsg(addr2, addr1) msgs = []sdk.Msg{msg1, msg2} privs, accnums, seqs = []crypto.PrivKey{priv1, priv2}, []uint64{1, 0}, []uint64{2, 0} - tx = newTestTx(ctx, msgs, privs, accnums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accnums, seqs, fee) checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeUnauthorized) // correct account numbers privs, accnums, seqs = []crypto.PrivKey{priv1, priv2}, []uint64{0, 0}, []uint64{2, 0} - tx = newTestTx(ctx, msgs, privs, accnums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accnums, seqs, fee) checkValidTx(t, anteHandler, ctx, tx, false) } @@ -209,31 +210,31 @@ func TestAnteHandlerSequences(t *testing.T) { ctx := input.ctx.WithBlockHeight(1) // keys and addresses - priv1, _, addr1 := keyPubAddr() - priv2, _, addr2 := keyPubAddr() - priv3, _, addr3 := keyPubAddr() + priv1, _, addr1 := KeyTestPubAddr() + priv2, _, addr2 := KeyTestPubAddr() + priv3, _, addr3 := KeyTestPubAddr() // set the accounts acc1 := input.ak.NewAccountWithAddress(ctx, addr1) - acc1.SetCoins(newCoins()) + acc1.SetCoins(NewTestCoins()) input.ak.SetAccount(ctx, acc1) acc2 := input.ak.NewAccountWithAddress(ctx, addr2) - acc2.SetCoins(newCoins()) + acc2.SetCoins(NewTestCoins()) input.ak.SetAccount(ctx, acc2) acc3 := input.ak.NewAccountWithAddress(ctx, addr3) - acc3.SetCoins(newCoins()) + acc3.SetCoins(NewTestCoins()) input.ak.SetAccount(ctx, acc3) // msg and signatures var tx sdk.Tx - msg := newTestMsg(addr1) - fee := newStdFee() + msg := NewTestMsg(addr1) + fee := NewTestStdFee() msgs := []sdk.Msg{msg} // test good tx from one signer privs, accnums, seqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} - tx = newTestTx(ctx, msgs, privs, accnums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accnums, seqs, fee) checkValidTx(t, anteHandler, ctx, tx, false) // test sending it again fails (replay protection) @@ -241,37 +242,37 @@ func TestAnteHandlerSequences(t *testing.T) { // fix sequence, should pass seqs = []uint64{1} - tx = newTestTx(ctx, msgs, privs, accnums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accnums, seqs, fee) checkValidTx(t, anteHandler, ctx, tx, false) // new tx with another signer and correct sequences - msg1 := newTestMsg(addr1, addr2) - msg2 := newTestMsg(addr3, addr1) + msg1 := NewTestMsg(addr1, addr2) + msg2 := NewTestMsg(addr3, addr1) msgs = []sdk.Msg{msg1, msg2} privs, accnums, seqs = []crypto.PrivKey{priv1, priv2, priv3}, []uint64{0, 1, 2}, []uint64{2, 0, 0} - tx = newTestTx(ctx, msgs, privs, accnums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accnums, seqs, fee) checkValidTx(t, anteHandler, ctx, tx, false) // replay fails checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeUnauthorized) // tx from just second signer with incorrect sequence fails - msg = newTestMsg(addr2) + msg = NewTestMsg(addr2) msgs = []sdk.Msg{msg} privs, accnums, seqs = []crypto.PrivKey{priv2}, []uint64{1}, []uint64{0} - tx = newTestTx(ctx, msgs, privs, accnums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accnums, seqs, fee) checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeUnauthorized) // fix the sequence and it passes - tx = newTestTx(ctx, msgs, []crypto.PrivKey{priv2}, []uint64{1}, []uint64{1}, fee) + tx = NewTestTx(ctx, msgs, []crypto.PrivKey{priv2}, []uint64{1}, []uint64{1}, fee) checkValidTx(t, anteHandler, ctx, tx, false) // another tx from both of them that passes - msg = newTestMsg(addr1, addr2) + msg = NewTestMsg(addr1, addr2) msgs = []sdk.Msg{msg} privs, accnums, seqs = []crypto.PrivKey{priv1, priv2}, []uint64{0, 1}, []uint64{3, 2} - tx = newTestTx(ctx, msgs, privs, accnums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accnums, seqs, fee) checkValidTx(t, anteHandler, ctx, tx, false) } @@ -283,7 +284,7 @@ func TestAnteHandlerFees(t *testing.T) { anteHandler := NewAnteHandler(input.ak, input.fck, DefaultSigVerificationGasConsumer) // keys and addresses - priv1, _, addr1 := keyPubAddr() + priv1, _, addr1 := KeyTestPubAddr() // set the accounts acc1 := input.ak.NewAccountWithAddress(ctx, addr1) @@ -291,19 +292,20 @@ func TestAnteHandlerFees(t *testing.T) { // msg and signatures var tx sdk.Tx - msg := newTestMsg(addr1) + msg := NewTestMsg(addr1) privs, accnums, seqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} - fee := newStdFee() + fee := NewTestStdFee() msgs := []sdk.Msg{msg} // signer does not have enough funds to pay the fee - tx = newTestTx(ctx, msgs, privs, accnums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accnums, seqs, fee) checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeInsufficientFunds) acc1.SetCoins(sdk.NewCoins(sdk.NewInt64Coin("atom", 149))) input.ak.SetAccount(ctx, acc1) checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeInsufficientFunds) + emptyCoins := sdk.NewCoins() require.True(t, input.fck.GetCollectedFees(ctx).IsEqual(emptyCoins)) require.True(t, input.ak.GetAccount(ctx, addr1).GetCoins().AmountOf("atom").Equal(sdk.NewInt(149))) @@ -323,7 +325,7 @@ func TestAnteHandlerMemoGas(t *testing.T) { ctx := input.ctx.WithBlockHeight(1) // keys and addresses - priv1, _, addr1 := keyPubAddr() + priv1, _, addr1 := KeyTestPubAddr() // set the accounts acc1 := input.ak.NewAccountWithAddress(ctx, addr1) @@ -331,27 +333,27 @@ func TestAnteHandlerMemoGas(t *testing.T) { // msg and signatures var tx sdk.Tx - msg := newTestMsg(addr1) + msg := NewTestMsg(addr1) privs, accnums, seqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} fee := NewStdFee(0, sdk.NewCoins(sdk.NewInt64Coin("atom", 0))) // tx does not have enough gas - tx = newTestTx(ctx, []sdk.Msg{msg}, privs, accnums, seqs, fee) + tx = NewTestTx(ctx, []sdk.Msg{msg}, privs, accnums, seqs, fee) checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeOutOfGas) // tx with memo doesn't have enough gas fee = NewStdFee(801, sdk.NewCoins(sdk.NewInt64Coin("atom", 0))) - tx = newTestTxWithMemo(ctx, []sdk.Msg{msg}, privs, accnums, seqs, fee, "abcininasidniandsinasindiansdiansdinaisndiasndiadninsd") + tx = NewTestTxWithMemo(ctx, []sdk.Msg{msg}, privs, accnums, seqs, fee, "abcininasidniandsinasindiansdiansdinaisndiasndiadninsd") checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeOutOfGas) // memo too large fee = NewStdFee(9000, sdk.NewCoins(sdk.NewInt64Coin("atom", 0))) - tx = newTestTxWithMemo(ctx, []sdk.Msg{msg}, privs, accnums, seqs, fee, strings.Repeat("01234567890", 500)) + tx = NewTestTxWithMemo(ctx, []sdk.Msg{msg}, privs, accnums, seqs, fee, strings.Repeat("01234567890", 500)) checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeMemoTooLarge) // tx with memo has enough gas fee = NewStdFee(9000, sdk.NewCoins(sdk.NewInt64Coin("atom", 0))) - tx = newTestTxWithMemo(ctx, []sdk.Msg{msg}, privs, accnums, seqs, fee, strings.Repeat("0123456789", 10)) + tx = NewTestTxWithMemo(ctx, []sdk.Msg{msg}, privs, accnums, seqs, fee, strings.Repeat("0123456789", 10)) checkValidTx(t, anteHandler, ctx, tx, false) } @@ -362,43 +364,43 @@ func TestAnteHandlerMultiSigner(t *testing.T) { ctx := input.ctx.WithBlockHeight(1) // keys and addresses - priv1, _, addr1 := keyPubAddr() - priv2, _, addr2 := keyPubAddr() - priv3, _, addr3 := keyPubAddr() + priv1, _, addr1 := KeyTestPubAddr() + priv2, _, addr2 := KeyTestPubAddr() + priv3, _, addr3 := KeyTestPubAddr() // set the accounts acc1 := input.ak.NewAccountWithAddress(ctx, addr1) - acc1.SetCoins(newCoins()) + acc1.SetCoins(NewTestCoins()) input.ak.SetAccount(ctx, acc1) acc2 := input.ak.NewAccountWithAddress(ctx, addr2) - acc2.SetCoins(newCoins()) + acc2.SetCoins(NewTestCoins()) input.ak.SetAccount(ctx, acc2) acc3 := input.ak.NewAccountWithAddress(ctx, addr3) - acc3.SetCoins(newCoins()) + acc3.SetCoins(NewTestCoins()) input.ak.SetAccount(ctx, acc3) // set up msgs and fee var tx sdk.Tx - msg1 := newTestMsg(addr1, addr2) - msg2 := newTestMsg(addr3, addr1) - msg3 := newTestMsg(addr2, addr3) + msg1 := NewTestMsg(addr1, addr2) + msg2 := NewTestMsg(addr3, addr1) + msg3 := NewTestMsg(addr2, addr3) msgs := []sdk.Msg{msg1, msg2, msg3} - fee := newStdFee() + fee := NewTestStdFee() // signers in order privs, accnums, seqs := []crypto.PrivKey{priv1, priv2, priv3}, []uint64{0, 1, 2}, []uint64{0, 0, 0} - tx = newTestTxWithMemo(ctx, msgs, privs, accnums, seqs, fee, "Check signers are in expected order and different account numbers works") + tx = NewTestTxWithMemo(ctx, msgs, privs, accnums, seqs, fee, "Check signers are in expected order and different account numbers works") checkValidTx(t, anteHandler, ctx, tx, false) // change sequence numbers - tx = newTestTx(ctx, []sdk.Msg{msg1}, []crypto.PrivKey{priv1, priv2}, []uint64{0, 1}, []uint64{1, 1}, fee) + tx = NewTestTx(ctx, []sdk.Msg{msg1}, []crypto.PrivKey{priv1, priv2}, []uint64{0, 1}, []uint64{1, 1}, fee) checkValidTx(t, anteHandler, ctx, tx, false) - tx = newTestTx(ctx, []sdk.Msg{msg2}, []crypto.PrivKey{priv3, priv1}, []uint64{2, 0}, []uint64{1, 2}, fee) + tx = NewTestTx(ctx, []sdk.Msg{msg2}, []crypto.PrivKey{priv3, priv1}, []uint64{2, 0}, []uint64{1, 2}, fee) checkValidTx(t, anteHandler, ctx, tx, false) // expected seqs = [3, 2, 2] - tx = newTestTxWithMemo(ctx, msgs, privs, accnums, []uint64{3, 2, 2}, fee, "Check signers are in expected order and different account numbers and sequence numbers works") + tx = NewTestTxWithMemo(ctx, msgs, privs, accnums, []uint64{3, 2, 2}, fee, "Check signers are in expected order and different account numbers and sequence numbers works") checkValidTx(t, anteHandler, ctx, tx, false) } @@ -409,29 +411,29 @@ func TestAnteHandlerBadSignBytes(t *testing.T) { ctx := input.ctx.WithBlockHeight(1) // keys and addresses - priv1, _, addr1 := keyPubAddr() - priv2, _, addr2 := keyPubAddr() + priv1, _, addr1 := KeyTestPubAddr() + priv2, _, addr2 := KeyTestPubAddr() // set the accounts acc1 := input.ak.NewAccountWithAddress(ctx, addr1) - acc1.SetCoins(newCoins()) + acc1.SetCoins(NewTestCoins()) input.ak.SetAccount(ctx, acc1) acc2 := input.ak.NewAccountWithAddress(ctx, addr2) - acc2.SetCoins(newCoins()) + acc2.SetCoins(NewTestCoins()) input.ak.SetAccount(ctx, acc2) var tx sdk.Tx - msg := newTestMsg(addr1) + msg := NewTestMsg(addr1) msgs := []sdk.Msg{msg} - fee := newStdFee() - fee2 := newStdFee() + fee := NewTestStdFee() + fee2 := NewTestStdFee() fee2.Gas += 100 - fee3 := newStdFee() + fee3 := NewTestStdFee() fee3.Amount[0].Amount = fee3.Amount[0].Amount.AddRaw(100) // test good tx and signBytes privs, accnums, seqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} - tx = newTestTx(ctx, msgs, privs, accnums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accnums, seqs, fee) checkValidTx(t, anteHandler, ctx, tx, false) chainID := ctx.ChainID() @@ -449,14 +451,14 @@ func TestAnteHandlerBadSignBytes(t *testing.T) { {chainID2, 0, 1, fee, msgs, codeUnauth}, // test wrong chain_id {chainID, 0, 2, fee, msgs, codeUnauth}, // test wrong seqs {chainID, 1, 1, fee, msgs, codeUnauth}, // test wrong accnum - {chainID, 0, 1, fee, []sdk.Msg{newTestMsg(addr2)}, codeUnauth}, // test wrong msg + {chainID, 0, 1, fee, []sdk.Msg{NewTestMsg(addr2)}, codeUnauth}, // test wrong msg {chainID, 0, 1, fee2, msgs, codeUnauth}, // test wrong fee {chainID, 0, 1, fee3, msgs, codeUnauth}, // test wrong fee } privs, seqs = []crypto.PrivKey{priv1}, []uint64{1} for _, cs := range cases { - tx := newTestTxWithSignBytes( + tx := NewTestTxWithSignBytes( msgs, privs, accnums, seqs, fee, StdSignBytes(cs.chainID, cs.accnum, cs.seq, cs.fee, cs.msgs, ""), "", @@ -466,14 +468,14 @@ func TestAnteHandlerBadSignBytes(t *testing.T) { // test wrong signer if public key exist privs, accnums, seqs = []crypto.PrivKey{priv2}, []uint64{0}, []uint64{1} - tx = newTestTx(ctx, msgs, privs, accnums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accnums, seqs, fee) checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeUnauthorized) // test wrong signer if public doesn't exist - msg = newTestMsg(addr2) + msg = NewTestMsg(addr2) msgs = []sdk.Msg{msg} privs, accnums, seqs = []crypto.PrivKey{priv1}, []uint64{1}, []uint64{0} - tx = newTestTx(ctx, msgs, privs, accnums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accnums, seqs, fee) checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeInvalidPubKey) } @@ -484,35 +486,35 @@ func TestAnteHandlerSetPubKey(t *testing.T) { ctx := input.ctx.WithBlockHeight(1) // keys and addresses - priv1, _, addr1 := keyPubAddr() - _, _, addr2 := keyPubAddr() + priv1, _, addr1 := KeyTestPubAddr() + _, _, addr2 := KeyTestPubAddr() // set the accounts acc1 := input.ak.NewAccountWithAddress(ctx, addr1) - acc1.SetCoins(newCoins()) + acc1.SetCoins(NewTestCoins()) input.ak.SetAccount(ctx, acc1) acc2 := input.ak.NewAccountWithAddress(ctx, addr2) - acc2.SetCoins(newCoins()) + acc2.SetCoins(NewTestCoins()) input.ak.SetAccount(ctx, acc2) var tx sdk.Tx // test good tx and set public key - msg := newTestMsg(addr1) + msg := NewTestMsg(addr1) msgs := []sdk.Msg{msg} privs, accnums, seqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} - fee := newStdFee() - tx = newTestTx(ctx, msgs, privs, accnums, seqs, fee) + fee := NewTestStdFee() + tx = NewTestTx(ctx, msgs, privs, accnums, seqs, fee) checkValidTx(t, anteHandler, ctx, tx, false) acc1 = input.ak.GetAccount(ctx, addr1) require.Equal(t, acc1.GetPubKey(), priv1.PubKey()) // test public key not found - msg = newTestMsg(addr2) + msg = NewTestMsg(addr2) msgs = []sdk.Msg{msg} - tx = newTestTx(ctx, msgs, privs, []uint64{1}, seqs, fee) - sigs := tx.(StdTx).GetSignatures() + tx = NewTestTx(ctx, msgs, privs, []uint64{1}, seqs, fee) + sigs := tx.(types.StdTx).GetSignatures() sigs[0].PubKey = nil checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeInvalidPubKey) @@ -520,7 +522,7 @@ func TestAnteHandlerSetPubKey(t *testing.T) { require.Nil(t, acc2.GetPubKey()) // test invalid signature and public key - tx = newTestTx(ctx, msgs, privs, []uint64{1}, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, []uint64{1}, seqs, fee) checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeInvalidPubKey) acc2 = input.ak.GetAccount(ctx, addr2) @@ -532,8 +534,8 @@ func TestProcessPubKey(t *testing.T) { ctx := input.ctx // keys - _, _, addr1 := keyPubAddr() - priv2, _, addr2 := keyPubAddr() + _, _, addr1 := KeyTestPubAddr() + priv2, _, addr2 := KeyTestPubAddr() acc1 := input.ak.NewAccountWithAddress(ctx, addr1) acc2 := input.ak.NewAccountWithAddress(ctx, addr2) @@ -666,7 +668,7 @@ func TestCountSubkeys(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(T *testing.T) { - require.Equal(t, tt.want, countSubKeys(tt.args.pub)) + require.Equal(t, tt.want, CountSubKeys(tt.args.pub)) }) } } @@ -678,32 +680,32 @@ func TestAnteHandlerSigLimitExceeded(t *testing.T) { ctx := input.ctx.WithBlockHeight(1) // keys and addresses - priv1, _, addr1 := keyPubAddr() - priv2, _, addr2 := keyPubAddr() - priv3, _, addr3 := keyPubAddr() - priv4, _, addr4 := keyPubAddr() - priv5, _, addr5 := keyPubAddr() - priv6, _, addr6 := keyPubAddr() - priv7, _, addr7 := keyPubAddr() - priv8, _, addr8 := keyPubAddr() + priv1, _, addr1 := KeyTestPubAddr() + priv2, _, addr2 := KeyTestPubAddr() + priv3, _, addr3 := KeyTestPubAddr() + priv4, _, addr4 := KeyTestPubAddr() + priv5, _, addr5 := KeyTestPubAddr() + priv6, _, addr6 := KeyTestPubAddr() + priv7, _, addr7 := KeyTestPubAddr() + priv8, _, addr8 := KeyTestPubAddr() // set the accounts acc1 := input.ak.NewAccountWithAddress(ctx, addr1) - acc1.SetCoins(newCoins()) + acc1.SetCoins(NewTestCoins()) input.ak.SetAccount(ctx, acc1) acc2 := input.ak.NewAccountWithAddress(ctx, addr2) - acc2.SetCoins(newCoins()) + acc2.SetCoins(NewTestCoins()) input.ak.SetAccount(ctx, acc2) var tx sdk.Tx - msg := newTestMsg(addr1, addr2, addr3, addr4, addr5, addr6, addr7, addr8) + msg := NewTestMsg(addr1, addr2, addr3, addr4, addr5, addr6, addr7, addr8) msgs := []sdk.Msg{msg} - fee := newStdFee() + fee := NewTestStdFee() // test rejection logic privs, accnums, seqs := []crypto.PrivKey{priv1, priv2, priv3, priv4, priv5, priv6, priv7, priv8}, []uint64{0, 0, 0, 0, 0, 0, 0, 0}, []uint64{0, 0, 0, 0, 0, 0, 0, 0} - tx = newTestTx(ctx, msgs, privs, accnums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accnums, seqs, fee) checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeTooManySignatures) } @@ -774,16 +776,16 @@ func TestCustomSignatureVerificationGasConsumer(t *testing.T) { ctx := input.ctx.WithBlockHeight(1) // verify that an secp256k1 account gets rejected - priv1, _, addr1 := keyPubAddr() + priv1, _, addr1 := KeyTestPubAddr() acc1 := input.ak.NewAccountWithAddress(ctx, addr1) _ = acc1.SetCoins(sdk.NewCoins(sdk.NewInt64Coin("atom", 150))) input.ak.SetAccount(ctx, acc1) var tx sdk.Tx - msg := newTestMsg(addr1) + msg := NewTestMsg(addr1) privs, accnums, seqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} - fee := newStdFee() + fee := NewTestStdFee() msgs := []sdk.Msg{msg} - tx = newTestTx(ctx, msgs, privs, accnums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accnums, seqs, fee) checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeInvalidPubKey) // verify that an ed25519 account gets accepted @@ -793,10 +795,10 @@ func TestCustomSignatureVerificationGasConsumer(t *testing.T) { acc2 := input.ak.NewAccountWithAddress(ctx, addr2) _ = acc2.SetCoins(sdk.NewCoins(sdk.NewInt64Coin("atom", 150))) input.ak.SetAccount(ctx, acc2) - msg = newTestMsg(addr2) + msg = NewTestMsg(addr2) privs, accnums, seqs = []crypto.PrivKey{priv2}, []uint64{1}, []uint64{0} - fee = newStdFee() + fee = NewTestStdFee() msgs = []sdk.Msg{msg} - tx = newTestTx(ctx, msgs, privs, accnums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accnums, seqs, fee) checkValidTx(t, anteHandler, ctx, tx, false) } diff --git a/x/auth/client/cli/account.go b/x/auth/client/cli/query.go similarity index 56% rename from x/auth/client/cli/account.go rename to x/auth/client/cli/query.go index 4ce5556f0745..0227e30d1762 100644 --- a/x/auth/client/cli/account.go +++ b/x/auth/client/cli/query.go @@ -3,16 +3,31 @@ package cli import ( "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/client/utils" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/types" ) +// GetTxCmd returns the transaction commands for this module +func GetQueryCmd(cdc *codec.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: types.ModuleName, + Short: "Querying commands for the auth module", + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: utils.ValidateCmd, + } + cmd.AddCommand(GetAccountCmd(cdc)) + return cmd +} + // GetAccountCmd returns a query account that will display the state of the // account at a given address. // nolint: unparam -func GetAccountCmd(storeName string, cdc *codec.Codec) *cobra.Command { +func GetAccountCmd(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "account [address]", Short: "Query account balance", @@ -38,5 +53,5 @@ func GetAccountCmd(storeName string, cdc *codec.Codec) *cobra.Command { return cliCtx.PrintOutput(acc) }, } - return client.GetCommands(cmd)[0] + return flags.GetCommands(cmd)[0] } diff --git a/x/auth/client/cli/tx.go b/x/auth/client/cli/tx.go new file mode 100644 index 000000000000..83b6d46065ba --- /dev/null +++ b/x/auth/client/cli/tx.go @@ -0,0 +1,25 @@ +package cli + +import ( + "github.com/spf13/cobra" + + "github.com/cosmos/cosmos-sdk/client/utils" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/x/auth/types" +) + +// GetTxCmd returns the transaction commands for this module +func GetTxCmd(cdc *codec.Codec) *cobra.Command { + txCmd := &cobra.Command{ + Use: types.ModuleName, + Short: "Auth transaction subcommands", + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: utils.ValidateCmd, + } + txCmd.AddCommand( + GetMultiSignCommand(cdc), + GetSignCommand(cdc), + ) + return txCmd +} diff --git a/x/auth/client/cli/multisign.go b/x/auth/client/cli/tx_multisign.go similarity index 84% rename from x/auth/client/cli/multisign.go rename to x/auth/client/cli/tx_multisign.go index b1aa98fd58c1..c1a88a6a0b03 100644 --- a/x/auth/client/cli/multisign.go +++ b/x/auth/client/cli/tx_multisign.go @@ -8,22 +8,22 @@ import ( "github.com/spf13/cobra" "github.com/spf13/viper" - amino "github.com/tendermint/go-amino" + "github.com/tendermint/tendermint/crypto/multisig" "github.com/tendermint/tendermint/libs/cli" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/keys" "github.com/cosmos/cosmos-sdk/client/utils" + "github.com/cosmos/cosmos-sdk/codec" crkeys "github.com/cosmos/cosmos-sdk/crypto/keys" "github.com/cosmos/cosmos-sdk/version" - "github.com/cosmos/cosmos-sdk/x/auth" - authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" + "github.com/cosmos/cosmos-sdk/x/auth/types" ) // GetSignCommand returns the sign command -func GetMultiSignCommand(codec *amino.Codec) *cobra.Command { +func GetMultiSignCommand(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "multisign [file] [name] [[signature]...]", Short: "Generate multisig signatures for transactions generated offline", @@ -46,7 +46,7 @@ recommended to set such parameters manually. version.ClientName, ), ), - RunE: makeMultiSignCmd(codec), + RunE: makeMultiSignCmd(cdc), Args: cobra.MinimumNArgs(3), } @@ -55,10 +55,10 @@ recommended to set such parameters manually. cmd.Flags().String(flagOutfile, "", "The document will be written to the given file instead of STDOUT") // Add the flags here and return the command - return client.PostCommands(cmd)[0] + return flags.PostCommands(cmd)[0] } -func makeMultiSignCmd(cdc *amino.Codec) func(cmd *cobra.Command, args []string) error { +func makeMultiSignCmd(cdc *codec.Codec) func(cmd *cobra.Command, args []string) error { return func(cmd *cobra.Command, args []string) (err error) { stdTx, err := utils.ReadStdTxFromFile(cdc, args[0]) if err != nil { @@ -81,7 +81,7 @@ func makeMultiSignCmd(cdc *amino.Codec) func(cmd *cobra.Command, args []string) multisigPub := multisigInfo.GetPubKey().(multisig.PubKeyMultisigThreshold) multisigSig := multisig.NewMultisig(len(multisigPub.PubKeys)) cliCtx := context.NewCLIContext().WithCodec(cdc).WithAccountDecoder(cdc) - txBldr := authtxb.NewTxBuilderFromCLI() + txBldr := types.NewTxBuilderFromCLI() if !viper.GetBool(flagOffline) { addr := multisigInfo.GetAddress() @@ -106,7 +106,7 @@ func makeMultiSignCmd(cdc *amino.Codec) func(cmd *cobra.Command, args []string) } // Validate each signature - sigBytes := auth.StdSignBytes( + sigBytes := types.StdSignBytes( txBldr.ChainID(), txBldr.AccountNumber(), txBldr.Sequence(), stdTx.Fee, stdTx.GetMsgs(), stdTx.GetMemo(), ) @@ -118,8 +118,8 @@ func makeMultiSignCmd(cdc *amino.Codec) func(cmd *cobra.Command, args []string) } } - newStdSig := auth.StdSignature{Signature: cdc.MustMarshalBinaryBare(multisigSig), PubKey: multisigPub} - newTx := auth.NewStdTx(stdTx.GetMsgs(), stdTx.Fee, []auth.StdSignature{newStdSig}, stdTx.GetMemo()) + newStdSig := types.StdSignature{Signature: cdc.MustMarshalBinaryBare(multisigSig), PubKey: multisigPub} + newTx := types.NewStdTx(stdTx.GetMsgs(), stdTx.Fee, []types.StdSignature{newStdSig}, stdTx.GetMemo()) sigOnly := viper.GetBool(flagSigOnly) var json []byte @@ -156,7 +156,7 @@ func makeMultiSignCmd(cdc *amino.Codec) func(cmd *cobra.Command, args []string) } } -func readAndUnmarshalStdSignature(cdc *amino.Codec, filename string) (stdSig auth.StdSignature, err error) { +func readAndUnmarshalStdSignature(cdc *codec.Codec, filename string) (stdSig types.StdSignature, err error) { var bytes []byte if bytes, err = ioutil.ReadFile(filename); err != nil { return diff --git a/x/auth/client/cli/sign.go b/x/auth/client/cli/tx_sign.go similarity index 92% rename from x/auth/client/cli/sign.go rename to x/auth/client/cli/tx_sign.go index 6fbe51eaeb59..f7be335010e4 100644 --- a/x/auth/client/cli/sign.go +++ b/x/auth/client/cli/tx_sign.go @@ -9,13 +9,12 @@ import ( "github.com/spf13/viper" "github.com/tendermint/tendermint/crypto/multisig" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/utils" "github.com/cosmos/cosmos-sdk/codec" 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/auth/types" ) const ( @@ -77,8 +76,8 @@ be generated via the 'multisign' command. ) cmd.Flags().String(flagOutfile, "", "The document will be written to the given file instead of STDOUT") - cmd = client.PostCommands(cmd)[0] - cmd.MarkFlagRequired(client.FlagFrom) + cmd = flags.PostCommands(cmd)[0] + cmd.MarkFlagRequired(flags.FlagFrom) return cmd } @@ -87,8 +86,8 @@ func preSignCmd(cmd *cobra.Command, _ []string) { // Conditionally mark the account and sequence numbers required as no RPC // query will be done. if viper.GetBool(flagOffline) { - cmd.MarkFlagRequired(client.FlagAccountNumber) - cmd.MarkFlagRequired(client.FlagSequence) + cmd.MarkFlagRequired(flags.FlagAccountNumber) + cmd.MarkFlagRequired(flags.FlagSequence) } } @@ -101,7 +100,7 @@ func makeSignCmd(cdc *codec.Codec) func(cmd *cobra.Command, args []string) error offline := viper.GetBool(flagOffline) cliCtx := context.NewCLIContext().WithCodec(cdc).WithAccountDecoder(cdc) - txBldr := authtxb.NewTxBuilderFromCLI() + txBldr := types.NewTxBuilderFromCLI() if viper.GetBool(flagValidateSigs) { if !printAndValidateSigs(cliCtx, txBldr.ChainID(), stdTx, offline) { @@ -112,7 +111,7 @@ func makeSignCmd(cdc *codec.Codec) func(cmd *cobra.Command, args []string) error } // if --signature-only is on, then override --append - var newTx auth.StdTx + var newTx types.StdTx generateSignatureOnly := viper.GetBool(flagSigOnly) multisigAddrStr := viper.GetString(flagMultisig) @@ -161,7 +160,7 @@ func makeSignCmd(cdc *codec.Codec) func(cmd *cobra.Command, args []string) error } } -func getSignatureJSON(cdc *codec.Codec, newTx auth.StdTx, indent, generateSignatureOnly bool) ([]byte, error) { +func getSignatureJSON(cdc *codec.Codec, newTx types.StdTx, indent, generateSignatureOnly bool) ([]byte, error) { switch generateSignatureOnly { case true: switch indent { @@ -186,7 +185,7 @@ func getSignatureJSON(cdc *codec.Codec, newTx auth.StdTx, indent, generateSignat // its expected signers. In addition, if offline has not been supplied, the // signature is verified over the transaction sign bytes. func printAndValidateSigs( - cliCtx context.CLIContext, chainID string, stdTx auth.StdTx, offline bool, + cliCtx context.CLIContext, chainID string, stdTx types.StdTx, offline bool, ) bool { fmt.Println("Signers:") @@ -229,7 +228,7 @@ func printAndValidateSigs( return false } - sigBytes := auth.StdSignBytes( + sigBytes := types.StdSignBytes( chainID, acc.GetAccountNumber(), acc.GetSequence(), stdTx.Fee, stdTx.GetMsgs(), stdTx.GetMemo(), ) diff --git a/x/auth/client/rest/query.go b/x/auth/client/rest/query.go index 9df3c14bc055..348fab865abf 100644 --- a/x/auth/client/rest/query.go +++ b/x/auth/client/rest/query.go @@ -10,7 +10,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/auth/types" ) // register REST routes @@ -29,7 +29,7 @@ func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec, // query accountREST Handler func QueryAccountRequestHandlerFn( storeName string, cdc *codec.Codec, - decoder auth.AccountDecoder, cliCtx context.CLIContext, + decoder types.AccountDecoder, cliCtx context.CLIContext, ) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) @@ -41,7 +41,7 @@ func QueryAccountRequestHandlerFn( return } - res, err := cliCtx.QueryStore(auth.AddressStoreKey(addr), storeName) + res, err := cliCtx.QueryStore(types.AddressStoreKey(addr), storeName) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return @@ -49,7 +49,7 @@ func QueryAccountRequestHandlerFn( // the query will return empty account if there is no data if len(res) == 0 { - rest.PostProcessResponse(w, cdc, auth.BaseAccount{}, cliCtx.Indent) + rest.PostProcessResponse(w, cdc, types.BaseAccount{}, cliCtx.Indent) return } @@ -67,7 +67,7 @@ func QueryAccountRequestHandlerFn( // query accountREST Handler func QueryBalancesRequestHandlerFn( storeName string, cdc *codec.Codec, - decoder auth.AccountDecoder, cliCtx context.CLIContext, + decoder types.AccountDecoder, cliCtx context.CLIContext, ) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") @@ -80,7 +80,7 @@ func QueryBalancesRequestHandlerFn( return } - res, err := cliCtx.QueryStore(auth.AddressStoreKey(addr), storeName) + res, err := cliCtx.QueryStore(types.AddressStoreKey(addr), storeName) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return diff --git a/x/auth/client/txbuilder/stdsignmsg.go b/x/auth/client/txbuilder/stdsignmsg.go deleted file mode 100644 index f5c78cc3f929..000000000000 --- a/x/auth/client/txbuilder/stdsignmsg.go +++ /dev/null @@ -1,23 +0,0 @@ -package context - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" -) - -// StdSignMsg is a convenience structure for passing along -// a Msg with the other requirements for a StdSignDoc before -// it is signed. For use in the CLI. -type StdSignMsg struct { - ChainID string `json:"chain_id"` - AccountNumber uint64 `json:"account_number"` - Sequence uint64 `json:"sequence"` - Fee auth.StdFee `json:"fee"` - Msgs []sdk.Msg `json:"msgs"` - Memo string `json:"memo"` -} - -// get message bytes -func (msg StdSignMsg) Bytes() []byte { - return auth.StdSignBytes(msg.ChainID, msg.AccountNumber, msg.Sequence, msg.Fee, msg.Msgs, msg.Memo) -} diff --git a/x/auth/genaccounts/codec.go b/x/auth/genaccounts/codec.go index ccdc8b19e553..70edd800e3d1 100644 --- a/x/auth/genaccounts/codec.go +++ b/x/auth/genaccounts/codec.go @@ -8,7 +8,7 @@ import ( var moduleCdc *codec.Codec func init() { - cdc := codec.New() - codec.RegisterCrypto(cdc) - moduleCdc = cdc.Seal() + moduleCdc = codec.New() + codec.RegisterCrypto(moduleCdc) + moduleCdc.Seal() } diff --git a/x/auth/genaccounts/module.go b/x/auth/genaccounts/module.go index 89925e185c9a..4513312a8d26 100644 --- a/x/auth/genaccounts/module.go +++ b/x/auth/genaccounts/module.go @@ -3,15 +3,21 @@ package genaccounts import ( "encoding/json" + "github.com/gorilla/mux" + "github.com/spf13/cobra" + + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/auth" - abci "github.com/tendermint/tendermint/abci/types" ) var ( - _ sdk.AppModuleGenesis = AppModule{} - _ sdk.AppModuleBasic = AppModuleBasic{} + _ module.AppModuleGenesis = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} ) // module name @@ -43,6 +49,15 @@ func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { return ValidateGenesis(data) } +// register rest routes +func (AppModuleBasic) RegisterRESTRoutes(_ context.CLIContext, _ *mux.Router, _ *codec.Codec) {} + +// get the root tx command of this module +func (AppModuleBasic) GetTxCmd(_ *codec.Codec) *cobra.Command { return nil } + +// get the root query command of this module +func (AppModuleBasic) GetQueryCmd(_ *codec.Codec) *cobra.Command { return nil } + // extra function from sdk.AppModuleBasic // iterate the genesis accounts and perform an operation at each of them // - to used by other modules @@ -66,9 +81,9 @@ type AppModule struct { } // NewAppModule creates a new AppModule object -func NewAppModule(accountKeeper AccountKeeper) sdk.AppModule { +func NewAppModule(accountKeeper AccountKeeper) module.AppModule { - return sdk.NewGenesisOnlyAppModule(AppModule{ + return module.NewGenesisOnlyAppModule(AppModule{ AppModuleBasic: AppModuleBasic{}, accountKeeper: accountKeeper, }) diff --git a/x/auth/genesis.go b/x/auth/genesis.go index 885234f61c71..5ba1dda098c6 100644 --- a/x/auth/genesis.go +++ b/x/auth/genesis.go @@ -1,61 +1,20 @@ package auth import ( - "fmt" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/types" ) -// GenesisState - all auth state that must be provided at genesis -type GenesisState struct { - CollectedFees sdk.Coins `json:"collected_fees"` - Params Params `json:"params"` -} - -// NewGenesisState - Create a new genesis state -func NewGenesisState(collectedFees sdk.Coins, params Params) GenesisState { - return GenesisState{ - CollectedFees: collectedFees, - Params: params, - } -} - -// DefaultGenesisState - Return a default genesis state -func DefaultGenesisState() GenesisState { - return NewGenesisState(sdk.NewCoins(), DefaultParams()) -} - // InitGenesis - Init store state from genesis data -func InitGenesis(ctx sdk.Context, ak AccountKeeper, fck FeeCollectionKeeper, data GenesisState) { +func InitGenesis(ctx sdk.Context, ak AccountKeeper, fck types.FeeCollectionKeeper, data types.GenesisState) { ak.SetParams(ctx, data.Params) - fck.setCollectedFees(ctx, data.CollectedFees) + fck.AddCollectedFees(ctx, data.CollectedFees) } // ExportGenesis returns a GenesisState for a given context and keeper -func ExportGenesis(ctx sdk.Context, ak AccountKeeper, fck FeeCollectionKeeper) GenesisState { +func ExportGenesis(ctx sdk.Context, ak AccountKeeper, fck types.FeeCollectionKeeper) types.GenesisState { collectedFees := fck.GetCollectedFees(ctx) params := ak.GetParams(ctx) - return NewGenesisState(collectedFees, params) -} - -// ValidateGenesis performs basic validation of auth genesis data returning an -// error for any failed validation criteria. -func ValidateGenesis(data GenesisState) error { - if data.Params.TxSigLimit == 0 { - return fmt.Errorf("invalid tx signature limit: %d", data.Params.TxSigLimit) - } - if data.Params.SigVerifyCostED25519 == 0 { - return fmt.Errorf("invalid ED25519 signature verification cost: %d", data.Params.SigVerifyCostED25519) - } - if data.Params.SigVerifyCostSecp256k1 == 0 { - return fmt.Errorf("invalid SECK256k1 signature verification cost: %d", data.Params.SigVerifyCostSecp256k1) - } - if data.Params.MaxMemoCharacters == 0 { - return fmt.Errorf("invalid max memo characters: %d", data.Params.MaxMemoCharacters) - } - if data.Params.TxSizeCostPerByte == 0 { - return fmt.Errorf("invalid tx size cost per byte: %d", data.Params.TxSizeCostPerByte) - } - return nil + return types.NewGenesisState(collectedFees, params) } diff --git a/x/auth/keeper.go b/x/auth/keeper.go index f630381be1e6..7d7741054e95 100644 --- a/x/auth/keeper.go +++ b/x/auth/keeper.go @@ -7,27 +7,10 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/cosmos/cosmos-sdk/x/params/subspace" ) -const ( - // StoreKey is string representation of the store key for auth - StoreKey = "acc" - - // FeeStoreKey is a string representation of the store key for fees - FeeStoreKey = "fee" - - // QuerierRoute is the querier route for acc - QuerierRoute = StoreKey -) - -var ( - // AddressStoreKeyPrefix prefix for account-by-address store - AddressStoreKeyPrefix = []byte{0x01} - - globalAccountNumberKey = []byte("globalAccountNumber") -) - // AccountKeeper encodes/decodes accounts using the go-amino (binary) // encoding/decoding library. type AccountKeeper struct { @@ -35,7 +18,7 @@ type AccountKeeper struct { key sdk.StoreKey // The prototypical Account constructor. - proto func() Account + proto func() types.Account // The codec codec for binary encoding/decoding of accounts. cdc *codec.Codec @@ -47,19 +30,19 @@ type AccountKeeper struct { // (binary) encode and decode concrete sdk.Accounts. // nolint func NewAccountKeeper( - cdc *codec.Codec, key sdk.StoreKey, paramstore subspace.Subspace, proto func() Account, + cdc *codec.Codec, key sdk.StoreKey, paramstore subspace.Subspace, proto func() types.Account, ) AccountKeeper { return AccountKeeper{ key: key, proto: proto, cdc: cdc, - paramSubspace: paramstore.WithKeyTable(ParamKeyTable()), + paramSubspace: paramstore.WithKeyTable(types.ParamKeyTable()), } } // NewAccountWithAddress implements sdk.AccountKeeper. -func (ak AccountKeeper) NewAccountWithAddress(ctx sdk.Context, addr sdk.AccAddress) Account { +func (ak AccountKeeper) NewAccountWithAddress(ctx sdk.Context, addr sdk.AccAddress) types.Account { acc := ak.proto() err := acc.SetAddress(addr) if err != nil { @@ -75,22 +58,17 @@ func (ak AccountKeeper) NewAccountWithAddress(ctx sdk.Context, addr sdk.AccAddre } // NewAccount creates a new account -func (ak AccountKeeper) NewAccount(ctx sdk.Context, acc Account) Account { +func (ak AccountKeeper) NewAccount(ctx sdk.Context, acc types.Account) types.Account { if err := acc.SetAccountNumber(ak.GetNextAccountNumber(ctx)); err != nil { panic(err) } return acc } -// AddressStoreKey turn an address to key used to get it from the account store -func AddressStoreKey(addr sdk.AccAddress) []byte { - return append(AddressStoreKeyPrefix, addr.Bytes()...) -} - // GetAccount implements sdk.AccountKeeper. -func (ak AccountKeeper) GetAccount(ctx sdk.Context, addr sdk.AccAddress) Account { +func (ak AccountKeeper) GetAccount(ctx sdk.Context, addr sdk.AccAddress) types.Account { store := ctx.KVStore(ak.key) - bz := store.Get(AddressStoreKey(addr)) + bz := store.Get(types.AddressStoreKey(addr)) if bz == nil { return nil } @@ -99,9 +77,9 @@ func (ak AccountKeeper) GetAccount(ctx sdk.Context, addr sdk.AccAddress) Account } // GetAllAccounts returns all accounts in the accountKeeper. -func (ak AccountKeeper) GetAllAccounts(ctx sdk.Context) []Account { - accounts := []Account{} - appendAccount := func(acc Account) (stop bool) { +func (ak AccountKeeper) GetAllAccounts(ctx sdk.Context) []types.Account { + accounts := []types.Account{} + appendAccount := func(acc types.Account) (stop bool) { accounts = append(accounts, acc) return false } @@ -110,28 +88,28 @@ func (ak AccountKeeper) GetAllAccounts(ctx sdk.Context) []Account { } // SetAccount implements sdk.AccountKeeper. -func (ak AccountKeeper) SetAccount(ctx sdk.Context, acc Account) { +func (ak AccountKeeper) SetAccount(ctx sdk.Context, acc types.Account) { addr := acc.GetAddress() store := ctx.KVStore(ak.key) bz, err := ak.cdc.MarshalBinaryBare(acc) if err != nil { panic(err) } - store.Set(AddressStoreKey(addr), bz) + store.Set(types.AddressStoreKey(addr), bz) } // RemoveAccount removes an account for the account mapper store. // NOTE: this will cause supply invariant violation if called -func (ak AccountKeeper) RemoveAccount(ctx sdk.Context, acc Account) { +func (ak AccountKeeper) RemoveAccount(ctx sdk.Context, acc types.Account) { addr := acc.GetAddress() store := ctx.KVStore(ak.key) - store.Delete(AddressStoreKey(addr)) + store.Delete(types.AddressStoreKey(addr)) } // IterateAccounts implements sdk.AccountKeeper. -func (ak AccountKeeper) IterateAccounts(ctx sdk.Context, process func(Account) (stop bool)) { +func (ak AccountKeeper) IterateAccounts(ctx sdk.Context, process func(types.Account) (stop bool)) { store := ctx.KVStore(ak.key) - iter := sdk.KVStorePrefixIterator(store, AddressStoreKeyPrefix) + iter := sdk.KVStorePrefixIterator(store, types.AddressStoreKeyPrefix) defer iter.Close() for { if !iter.Valid() { @@ -182,7 +160,7 @@ func (ak AccountKeeper) setSequence(ctx sdk.Context, addr sdk.AccAddress, newSeq func (ak AccountKeeper) GetNextAccountNumber(ctx sdk.Context) uint64 { var accNumber uint64 store := ctx.KVStore(ak.key) - bz := store.Get(globalAccountNumberKey) + bz := store.Get(types.GlobalAccountNumberKey) if bz == nil { accNumber = 0 } else { @@ -193,7 +171,7 @@ func (ak AccountKeeper) GetNextAccountNumber(ctx sdk.Context) uint64 { } bz = ak.cdc.MustMarshalBinaryLengthPrefixed(accNumber + 1) - store.Set(globalAccountNumberKey, bz) + store.Set(types.GlobalAccountNumberKey, bz) return accNumber } @@ -202,12 +180,12 @@ func (ak AccountKeeper) GetNextAccountNumber(ctx sdk.Context) uint64 { // Params // SetParams sets the auth module's parameters. -func (ak AccountKeeper) SetParams(ctx sdk.Context, params Params) { +func (ak AccountKeeper) SetParams(ctx sdk.Context, params types.Params) { ak.paramSubspace.SetParamSet(ctx, ¶ms) } // GetParams gets the auth module's parameters. -func (ak AccountKeeper) GetParams(ctx sdk.Context) (params Params) { +func (ak AccountKeeper) GetParams(ctx sdk.Context) (params types.Params) { ak.paramSubspace.GetParamSet(ctx, ¶ms) return } @@ -215,7 +193,7 @@ func (ak AccountKeeper) GetParams(ctx sdk.Context) (params Params) { // ----------------------------------------------------------------------------- // Misc. -func (ak AccountKeeper) decodeAccount(bz []byte) (acc Account) { +func (ak AccountKeeper) decodeAccount(bz []byte) (acc types.Account) { err := ak.cdc.UnmarshalBinaryBare(bz, &acc) if err != nil { panic(err) diff --git a/x/auth/module.go b/x/auth/module.go index f7381e21f335..732d17375994 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -3,45 +3,65 @@ package auth import ( "encoding/json" + "github.com/gorilla/mux" + "github.com/spf13/cobra" + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - abci "github.com/tendermint/tendermint/abci/types" + "github.com/cosmos/cosmos-sdk/types/module" + "github.com/cosmos/cosmos-sdk/x/auth/client/cli" + "github.com/cosmos/cosmos-sdk/x/auth/client/rest" + "github.com/cosmos/cosmos-sdk/x/auth/types" ) var ( - _ sdk.AppModule = AppModule{} - _ sdk.AppModuleBasic = AppModuleBasic{} + _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} ) -// name of this module -const ModuleName = "auth" - // app module basics object type AppModuleBasic struct{} // module name func (AppModuleBasic) Name() string { - return ModuleName + return types.ModuleName } // register module codec func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) { - RegisterCodec(cdc) + types.RegisterCodec(cdc) } // default genesis state func (AppModuleBasic) DefaultGenesis() json.RawMessage { - return moduleCdc.MustMarshalJSON(DefaultGenesisState()) + return types.ModuleCdc.MustMarshalJSON(types.DefaultGenesisState()) } // module validate genesis func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { - var data GenesisState - err := moduleCdc.UnmarshalJSON(bz, &data) + var data types.GenesisState + err := types.ModuleCdc.UnmarshalJSON(bz, &data) if err != nil { return err } - return ValidateGenesis(data) + return types.ValidateGenesis(data) +} + +// register rest routes +func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router, cdc *codec.Codec) { + rest.RegisterRoutes(ctx, rtr, cdc, types.StoreKey) +} + +// get the root tx command of this module +func (AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command { + return cli.GetTxCmd(cdc) +} + +// get the root query command of this module +func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { + return cli.GetQueryCmd(cdc) } //___________________________ @@ -49,12 +69,12 @@ func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { type AppModule struct { AppModuleBasic accountKeeper AccountKeeper - feeCollectionKeeper FeeCollectionKeeper + feeCollectionKeeper types.FeeCollectionKeeper } // NewAppModule creates a new AppModule object func NewAppModule(accountKeeper AccountKeeper, - feeCollectionKeeper FeeCollectionKeeper) AppModule { + feeCollectionKeeper types.FeeCollectionKeeper) AppModule { return AppModule{ AppModuleBasic: AppModuleBasic{}, accountKeeper: accountKeeper, @@ -64,7 +84,7 @@ func NewAppModule(accountKeeper AccountKeeper, // module name func (AppModule) Name() string { - return ModuleName + return types.ModuleName } // register invariants @@ -78,7 +98,7 @@ func (AppModule) NewHandler() sdk.Handler { return nil } // module querier route name func (AppModule) QuerierRoute() string { - return QuerierRoute + return types.QuerierRoute } // module querier @@ -88,8 +108,8 @@ func (am AppModule) NewQuerierHandler() sdk.Querier { // module init-genesis func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate { - var genesisState GenesisState - moduleCdc.MustUnmarshalJSON(data, &genesisState) + var genesisState types.GenesisState + types.ModuleCdc.MustUnmarshalJSON(data, &genesisState) InitGenesis(ctx, am.accountKeeper, am.feeCollectionKeeper, genesisState) return []abci.ValidatorUpdate{} } @@ -97,7 +117,7 @@ func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.Va // module export genesis func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { gs := ExportGenesis(ctx, am.accountKeeper, am.feeCollectionKeeper) - return moduleCdc.MustMarshalJSON(gs) + return types.ModuleCdc.MustMarshalJSON(gs) } // module begin-block diff --git a/x/auth/querier.go b/x/auth/querier.go index 2a5dbf422a92..ea2fd5c46cd4 100644 --- a/x/auth/querier.go +++ b/x/auth/querier.go @@ -7,18 +7,14 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" -) - -// query endpoints supported by the auth Querier -const ( - QueryAccount = "account" + "github.com/cosmos/cosmos-sdk/x/auth/types" ) // creates a querier for auth REST endpoints func NewQuerier(keeper AccountKeeper) sdk.Querier { return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, sdk.Error) { switch path[0] { - case QueryAccount: + case types.QueryAccount: return queryAccount(ctx, req, keeper) default: return nil, sdk.ErrUnknownRequest("unknown auth query endpoint") @@ -26,19 +22,8 @@ func NewQuerier(keeper AccountKeeper) sdk.Querier { } } -// defines the params for query: "custom/acc/account" -type QueryAccountParams struct { - Address sdk.AccAddress -} - -func NewQueryAccountParams(addr sdk.AccAddress) QueryAccountParams { - return QueryAccountParams{ - Address: addr, - } -} - func queryAccount(ctx sdk.Context, req abci.RequestQuery, keeper AccountKeeper) ([]byte, sdk.Error) { - var params QueryAccountParams + var params types.QueryAccountParams if err := keeper.cdc.UnmarshalJSON(req.Data, ¶ms); err != nil { return nil, sdk.ErrInternal(fmt.Sprintf("failed to parse params: %s", err)) } diff --git a/x/auth/querier_test.go b/x/auth/querier_test.go index 6d9ec0e9630a..72e60b20868d 100644 --- a/x/auth/querier_test.go +++ b/x/auth/querier_test.go @@ -24,7 +24,7 @@ func Test_queryAccount(t *testing.T) { require.NotNil(t, err) require.Nil(t, res) - _, _, addr := keyPubAddr() + _, _, addr := KeyTestPubAddr() req.Data = input.cdc.MustMarshalJSON(NewQueryAccountParams(addr)) res, err = queryAccount(input.ctx, req, input.ak) require.NotNil(t, err) diff --git a/x/auth/test_common.go b/x/auth/test_common.go new file mode 100644 index 000000000000..557cc00ecb85 --- /dev/null +++ b/x/auth/test_common.go @@ -0,0 +1,49 @@ +// nolint +package auth + +import ( + abci "github.com/tendermint/tendermint/abci/types" + dbm "github.com/tendermint/tendermint/libs/db" + "github.com/tendermint/tendermint/libs/log" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/store" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/types" + "github.com/cosmos/cosmos-sdk/x/params/subspace" +) + +type testInput struct { + cdc *codec.Codec + ctx sdk.Context + ak AccountKeeper + fck types.FeeCollectionKeeper +} + +func setupTestInput() testInput { + db := dbm.NewMemDB() + + cdc := codec.New() + types.RegisterBaseAccount(cdc) + + authCapKey := sdk.NewKVStoreKey("authCapKey") + fckCapKey := sdk.NewKVStoreKey("fckCapKey") + keyParams := sdk.NewKVStoreKey("subspace") + tkeyParams := sdk.NewTransientStoreKey("transient_subspace") + + ms := store.NewCommitMultiStore(db) + ms.MountStoreWithDB(authCapKey, sdk.StoreTypeIAVL, db) + ms.MountStoreWithDB(fckCapKey, sdk.StoreTypeIAVL, db) + ms.MountStoreWithDB(keyParams, sdk.StoreTypeIAVL, db) + ms.MountStoreWithDB(tkeyParams, sdk.StoreTypeTransient, db) + ms.LoadLatestVersion() + + ps := subspace.NewSubspace(cdc, keyParams, tkeyParams, types.DefaultParamspace) + ak := NewAccountKeeper(cdc, authCapKey, ps, types.ProtoBaseAccount) + fck := types.NewFeeCollectionKeeper(cdc, fckCapKey) + ctx := sdk.NewContext(ms, abci.Header{ChainID: "test-chain-id"}, false, log.NewNopLogger()) + + ak.SetParams(ctx, types.DefaultParams()) + + return testInput{cdc: cdc, ctx: ctx, ak: ak, fck: fck} +} diff --git a/x/auth/account.go b/x/auth/types/account.go similarity index 99% rename from x/auth/account.go rename to x/auth/types/account.go index 99132d3ba26a..1924f079ccac 100644 --- a/x/auth/account.go +++ b/x/auth/types/account.go @@ -1,4 +1,4 @@ -package auth +package types import ( "errors" diff --git a/x/auth/account_test.go b/x/auth/types/account_test.go similarity index 97% rename from x/auth/account_test.go rename to x/auth/types/account_test.go index d8f7c6fa8ddd..581774c86fdd 100644 --- a/x/auth/account_test.go +++ b/x/auth/types/account_test.go @@ -1,4 +1,4 @@ -package auth +package types import ( "testing" @@ -18,8 +18,8 @@ var ( ) func TestBaseAddressPubKey(t *testing.T) { - _, pub1, addr1 := keyPubAddr() - _, pub2, addr2 := keyPubAddr() + _, pub1, addr1 := KeyTestPubAddr() + _, pub2, addr2 := KeyTestPubAddr() acc := NewBaseAccountWithAddress(addr1) // check the address (set) and pubkey (not set) @@ -51,7 +51,7 @@ func TestBaseAddressPubKey(t *testing.T) { } func TestBaseAccountCoins(t *testing.T) { - _, _, addr := keyPubAddr() + _, _, addr := KeyTestPubAddr() acc := NewBaseAccountWithAddress(addr) someCoins := sdk.Coins{sdk.NewInt64Coin("atom", 123), sdk.NewInt64Coin("eth", 246)} @@ -62,7 +62,7 @@ func TestBaseAccountCoins(t *testing.T) { } func TestBaseAccountSequence(t *testing.T) { - _, _, addr := keyPubAddr() + _, _, addr := KeyTestPubAddr() acc := NewBaseAccountWithAddress(addr) seq := uint64(7) @@ -73,7 +73,7 @@ func TestBaseAccountSequence(t *testing.T) { } func TestBaseAccountMarshal(t *testing.T) { - _, pub, addr := keyPubAddr() + _, pub, addr := KeyTestPubAddr() acc := NewBaseAccountWithAddress(addr) someCoins := sdk.Coins{sdk.NewInt64Coin("atom", 123), sdk.NewInt64Coin("eth", 246)} @@ -109,7 +109,7 @@ func TestGetVestedCoinsContVestingAcc(t *testing.T) { now := tmtime.Now() endTime := now.Add(24 * time.Hour) - _, _, addr := keyPubAddr() + _, _, addr := KeyTestPubAddr() origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)} bacc := NewBaseAccountWithAddress(addr) bacc.SetCoins(origCoins) @@ -136,7 +136,7 @@ func TestGetVestingCoinsContVestingAcc(t *testing.T) { now := tmtime.Now() endTime := now.Add(24 * time.Hour) - _, _, addr := keyPubAddr() + _, _, addr := KeyTestPubAddr() origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)} bacc := NewBaseAccountWithAddress(addr) bacc.SetCoins(origCoins) @@ -159,7 +159,7 @@ func TestSpendableCoinsContVestingAcc(t *testing.T) { now := tmtime.Now() endTime := now.Add(24 * time.Hour) - _, _, addr := keyPubAddr() + _, _, addr := KeyTestPubAddr() origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)} bacc := NewBaseAccountWithAddress(addr) bacc.SetCoins(origCoins) @@ -199,7 +199,7 @@ func TestTrackDelegationContVestingAcc(t *testing.T) { now := tmtime.Now() endTime := now.Add(24 * time.Hour) - _, _, addr := keyPubAddr() + _, _, addr := KeyTestPubAddr() origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)} bacc := NewBaseAccountWithAddress(addr) bacc.SetCoins(origCoins) @@ -246,7 +246,7 @@ func TestTrackUndelegationContVestingAcc(t *testing.T) { now := tmtime.Now() endTime := now.Add(24 * time.Hour) - _, _, addr := keyPubAddr() + _, _, addr := KeyTestPubAddr() origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)} bacc := NewBaseAccountWithAddress(addr) bacc.SetCoins(origCoins) @@ -302,7 +302,7 @@ func TestGetVestedCoinsDelVestingAcc(t *testing.T) { now := tmtime.Now() endTime := now.Add(24 * time.Hour) - _, _, addr := keyPubAddr() + _, _, addr := KeyTestPubAddr() origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)} bacc := NewBaseAccountWithAddress(addr) bacc.SetCoins(origCoins) @@ -321,7 +321,7 @@ func TestGetVestingCoinsDelVestingAcc(t *testing.T) { now := tmtime.Now() endTime := now.Add(24 * time.Hour) - _, _, addr := keyPubAddr() + _, _, addr := KeyTestPubAddr() origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)} bacc := NewBaseAccountWithAddress(addr) bacc.SetCoins(origCoins) @@ -340,7 +340,7 @@ func TestSpendableCoinsDelVestingAcc(t *testing.T) { now := tmtime.Now() endTime := now.Add(24 * time.Hour) - _, _, addr := keyPubAddr() + _, _, addr := KeyTestPubAddr() origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)} bacc := NewBaseAccountWithAddress(addr) bacc.SetCoins(origCoins) @@ -381,7 +381,7 @@ func TestTrackDelegationDelVestingAcc(t *testing.T) { now := tmtime.Now() endTime := now.Add(24 * time.Hour) - _, _, addr := keyPubAddr() + _, _, addr := KeyTestPubAddr() origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)} bacc := NewBaseAccountWithAddress(addr) bacc.SetCoins(origCoins) @@ -427,7 +427,7 @@ func TestTrackUndelegationDelVestingAcc(t *testing.T) { now := tmtime.Now() endTime := now.Add(24 * time.Hour) - _, _, addr := keyPubAddr() + _, _, addr := KeyTestPubAddr() origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)} bacc := NewBaseAccountWithAddress(addr) bacc.SetCoins(origCoins) diff --git a/x/auth/codec.go b/x/auth/types/codec.go similarity index 88% rename from x/auth/codec.go rename to x/auth/types/codec.go index 9b7b35204347..296c2b148356 100644 --- a/x/auth/codec.go +++ b/x/auth/types/codec.go @@ -1,4 +1,4 @@ -package auth +package types import ( "github.com/cosmos/cosmos-sdk/codec" @@ -26,9 +26,12 @@ func RegisterBaseAccount(cdc *codec.Codec) { codec.RegisterCrypto(cdc) } -var moduleCdc = codec.New() +// module wide codec +var ModuleCdc *codec.Codec func init() { - RegisterCodec(moduleCdc) - codec.RegisterCrypto(moduleCdc) + ModuleCdc = codec.New() + RegisterCodec(ModuleCdc) + codec.RegisterCrypto(ModuleCdc) + ModuleCdc.Seal() } diff --git a/x/auth/feekeeper.go b/x/auth/types/feekeeper.go similarity index 99% rename from x/auth/feekeeper.go rename to x/auth/types/feekeeper.go index bc6506b1764a..c0b37a150105 100644 --- a/x/auth/feekeeper.go +++ b/x/auth/types/feekeeper.go @@ -1,4 +1,4 @@ -package auth +package types import ( codec "github.com/cosmos/cosmos-sdk/codec" diff --git a/x/auth/feekeeper_test.go b/x/auth/types/feekeeper_test.go similarity index 99% rename from x/auth/feekeeper_test.go rename to x/auth/types/feekeeper_test.go index ab49305f1c73..5126aa446dd2 100644 --- a/x/auth/feekeeper_test.go +++ b/x/auth/types/feekeeper_test.go @@ -1,4 +1,4 @@ -package auth +package types import ( "testing" diff --git a/x/auth/types/genesis.go b/x/auth/types/genesis.go new file mode 100644 index 000000000000..d7239380463e --- /dev/null +++ b/x/auth/types/genesis.go @@ -0,0 +1,47 @@ +package types + +import ( + "fmt" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// GenesisState - all auth state that must be provided at genesis +type GenesisState struct { + CollectedFees sdk.Coins `json:"collected_fees"` + Params Params `json:"params"` +} + +// NewGenesisState - Create a new genesis state +func NewGenesisState(collectedFees sdk.Coins, params Params) GenesisState { + return GenesisState{ + CollectedFees: collectedFees, + Params: params, + } +} + +// DefaultGenesisState - Return a default genesis state +func DefaultGenesisState() GenesisState { + return NewGenesisState(sdk.NewCoins(), DefaultParams()) +} + +// ValidateGenesis performs basic validation of auth genesis data returning an +// error for any failed validation criteria. +func ValidateGenesis(data GenesisState) error { + if data.Params.TxSigLimit == 0 { + return fmt.Errorf("invalid tx signature limit: %d", data.Params.TxSigLimit) + } + if data.Params.SigVerifyCostED25519 == 0 { + return fmt.Errorf("invalid ED25519 signature verification cost: %d", data.Params.SigVerifyCostED25519) + } + if data.Params.SigVerifyCostSecp256k1 == 0 { + return fmt.Errorf("invalid SECK256k1 signature verification cost: %d", data.Params.SigVerifyCostSecp256k1) + } + if data.Params.MaxMemoCharacters == 0 { + return fmt.Errorf("invalid max memo characters: %d", data.Params.MaxMemoCharacters) + } + if data.Params.TxSizeCostPerByte == 0 { + return fmt.Errorf("invalid tx size cost per byte: %d", data.Params.TxSizeCostPerByte) + } + return nil +} diff --git a/x/auth/types/keys.go b/x/auth/types/keys.go new file mode 100644 index 000000000000..30cf80490bf7 --- /dev/null +++ b/x/auth/types/keys.go @@ -0,0 +1,30 @@ +package types + +import sdk "github.com/cosmos/cosmos-sdk/types" + +const ( + // module name + ModuleName = "auth" + + // StoreKey is string representation of the store key for auth + StoreKey = "acc" + + // FeeStoreKey is a string representation of the store key for fees + FeeStoreKey = "fee" + + // QuerierRoute is the querier route for acc + QuerierRoute = StoreKey +) + +var ( + // AddressStoreKeyPrefix prefix for account-by-address store + AddressStoreKeyPrefix = []byte{0x01} + + // param key for global account number + GlobalAccountNumberKey = []byte("globalAccountNumber") +) + +// AddressStoreKey turn an address to key used to get it from the account store +func AddressStoreKey(addr sdk.AccAddress) []byte { + return append(AddressStoreKeyPrefix, addr.Bytes()...) +} diff --git a/x/auth/params.go b/x/auth/types/params.go similarity index 92% rename from x/auth/params.go rename to x/auth/types/params.go index 971d76e25fb2..ed0f4881140c 100644 --- a/x/auth/params.go +++ b/x/auth/types/params.go @@ -1,11 +1,10 @@ -package auth +package types import ( "bytes" "fmt" "strings" - "github.com/cosmos/cosmos-sdk/x/params" "github.com/cosmos/cosmos-sdk/x/params/subspace" ) @@ -55,8 +54,8 @@ func NewParams(maxMemoCharacters, txSigLimit, txSizeCostPerByte, } // ParamKeyTable for auth module -func ParamKeyTable() params.KeyTable { - return params.NewKeyTable().RegisterParamSet(&Params{}) +func ParamKeyTable() subspace.KeyTable { + return subspace.NewKeyTable().RegisterParamSet(&Params{}) } // ParamSetPairs implements the ParamSet interface and returns all the key/value pairs @@ -74,8 +73,8 @@ func (p *Params) ParamSetPairs() subspace.ParamSetPairs { // Equal returns a boolean determining if two Params types are identical. func (p Params) Equal(p2 Params) bool { - bz1 := moduleCdc.MustMarshalBinaryLengthPrefixed(&p) - bz2 := moduleCdc.MustMarshalBinaryLengthPrefixed(&p2) + bz1 := ModuleCdc.MustMarshalBinaryLengthPrefixed(&p) + bz2 := ModuleCdc.MustMarshalBinaryLengthPrefixed(&p2) return bytes.Equal(bz1, bz2) } diff --git a/x/auth/params_test.go b/x/auth/types/params_test.go similarity index 94% rename from x/auth/params_test.go rename to x/auth/types/params_test.go index 67699c4304db..9929b8e06a1c 100644 --- a/x/auth/params_test.go +++ b/x/auth/types/params_test.go @@ -1,4 +1,4 @@ -package auth +package types import ( "testing" diff --git a/x/auth/types/querier.go b/x/auth/types/querier.go new file mode 100644 index 000000000000..e0b45fc7a80a --- /dev/null +++ b/x/auth/types/querier.go @@ -0,0 +1,21 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// query endpoints supported by the auth Querier +const ( + QueryAccount = "account" +) + +// defines the params for query: "custom/acc/account" +type QueryAccountParams struct { + Address sdk.AccAddress +} + +func NewQueryAccountParams(addr sdk.AccAddress) QueryAccountParams { + return QueryAccountParams{ + Address: addr, + } +} diff --git a/x/auth/types/stdsignmsg.go b/x/auth/types/stdsignmsg.go new file mode 100644 index 000000000000..889982811a46 --- /dev/null +++ b/x/auth/types/stdsignmsg.go @@ -0,0 +1,22 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// StdSignMsg is a convenience structure for passing along +// a Msg with the other requirements for a StdSignDoc before +// it is signed. For use in the CLI. +type StdSignMsg struct { + ChainID string `json:"chain_id"` + AccountNumber uint64 `json:"account_number"` + Sequence uint64 `json:"sequence"` + Fee StdFee `json:"fee"` + Msgs []sdk.Msg `json:"msgs"` + Memo string `json:"memo"` +} + +// get message bytes +func (msg StdSignMsg) Bytes() []byte { + return StdSignBytes(msg.ChainID, msg.AccountNumber, msg.Sequence, msg.Fee, msg.Msgs, msg.Memo) +} diff --git a/x/auth/stdtx.go b/x/auth/types/stdtx.go similarity index 96% rename from x/auth/stdtx.go rename to x/auth/types/stdtx.go index 2233752621c3..18cdfaf0a0f2 100644 --- a/x/auth/stdtx.go +++ b/x/auth/types/stdtx.go @@ -1,4 +1,4 @@ -package auth +package types import ( "encoding/json" @@ -59,8 +59,8 @@ func (tx StdTx) ValidateBasic() sdk.Error { return nil } -// countSubKeys counts the total number of keys for a multi-sig public key. -func countSubKeys(pub crypto.PubKey) int { +// CountSubKeys counts the total number of keys for a multi-sig public key. +func CountSubKeys(pub crypto.PubKey) int { v, ok := pub.(multisig.PubKeyMultisigThreshold) if !ok { return 1 @@ -68,7 +68,7 @@ func countSubKeys(pub crypto.PubKey) int { numKeys := 0 for _, subkey := range v.PubKeys { - numKeys += countSubKeys(subkey) + numKeys += CountSubKeys(subkey) } return numKeys @@ -133,7 +133,7 @@ func (fee StdFee) Bytes() []byte { if len(fee.Amount) == 0 { fee.Amount = sdk.NewCoins() } - bz, err := moduleCdc.MarshalJSON(fee) // TODO + bz, err := ModuleCdc.MarshalJSON(fee) // TODO if err != nil { panic(err) } @@ -171,7 +171,7 @@ func StdSignBytes(chainID string, accnum uint64, sequence uint64, fee StdFee, ms for _, msg := range msgs { msgsBytes = append(msgsBytes, json.RawMessage(msg.GetSignBytes())) } - bz, err := moduleCdc.MarshalJSON(StdSignDoc{ + bz, err := ModuleCdc.MarshalJSON(StdSignDoc{ AccountNumber: accnum, ChainID: chainID, Fee: json.RawMessage(fee.Bytes()), diff --git a/x/auth/stdtx_test.go b/x/auth/types/stdtx_test.go similarity index 85% rename from x/auth/stdtx_test.go rename to x/auth/types/stdtx_test.go index 1139407ad293..d6315d5fb9f7 100644 --- a/x/auth/stdtx_test.go +++ b/x/auth/types/stdtx_test.go @@ -1,4 +1,4 @@ -package auth +package types import ( "fmt" @@ -21,7 +21,7 @@ var ( func TestStdTx(t *testing.T) { msgs := []sdk.Msg{sdk.NewTestMsg(addr)} - fee := newStdFee() + fee := NewTestStdFee() sigs := []StdSignature{} tx := NewStdTx(msgs, fee, sigs, "") @@ -41,7 +41,7 @@ func TestStdSignBytes(t *testing.T) { msgs []sdk.Msg memo string } - defaultFee := newStdFee() + defaultFee := NewTestStdFee() tests := []struct { args args want string @@ -61,19 +61,19 @@ func TestTxValidateBasic(t *testing.T) { ctx := sdk.NewContext(nil, abci.Header{ChainID: "mychainid"}, false, log.NewNopLogger()) // keys and addresses - priv1, _, addr1 := keyPubAddr() - priv2, _, addr2 := keyPubAddr() + priv1, _, addr1 := KeyTestPubAddr() + priv2, _, addr2 := KeyTestPubAddr() // msg and signatures - msg1 := newTestMsg(addr1, addr2) - fee := newStdFee() + msg1 := NewTestMsg(addr1, addr2) + fee := NewTestStdFee() msgs := []sdk.Msg{msg1} // require to fail validation upon invalid fee - badFee := newStdFee() + badFee := NewTestStdFee() badFee.Amount[0].Amount = sdk.NewInt(-5) - tx := newTestTx(ctx, nil, nil, nil, nil, badFee) + tx := NewTestTx(ctx, nil, nil, nil, nil, badFee) err := tx.ValidateBasic() require.Error(t, err) @@ -81,7 +81,7 @@ func TestTxValidateBasic(t *testing.T) { // require to fail validation when no signatures exist privs, accNums, seqs := []crypto.PrivKey{}, []uint64{}, []uint64{} - tx = newTestTx(ctx, msgs, privs, accNums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accNums, seqs, fee) err = tx.ValidateBasic() require.Error(t, err) @@ -89,16 +89,16 @@ func TestTxValidateBasic(t *testing.T) { // require to fail validation when signatures do not match expected signers privs, accNums, seqs = []crypto.PrivKey{priv1}, []uint64{0, 1}, []uint64{0, 0} - tx = newTestTx(ctx, msgs, privs, accNums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accNums, seqs, fee) err = tx.ValidateBasic() require.Error(t, err) require.Equal(t, sdk.CodeUnauthorized, err.Result().Code) // require to fail with invalid gas supplied - badFee = newStdFee() + badFee = NewTestStdFee() badFee.Gas = 9223372036854775808 - tx = newTestTx(ctx, nil, nil, nil, nil, badFee) + tx = NewTestTx(ctx, nil, nil, nil, nil, badFee) err = tx.ValidateBasic() require.Error(t, err) @@ -106,7 +106,7 @@ func TestTxValidateBasic(t *testing.T) { // require to pass when above criteria are matched privs, accNums, seqs = []crypto.PrivKey{priv1, priv2}, []uint64{0, 1}, []uint64{0, 0} - tx = newTestTx(ctx, msgs, privs, accNums, seqs, fee) + tx = NewTestTx(ctx, msgs, privs, accNums, seqs, fee) err = tx.ValidateBasic() require.NoError(t, err) @@ -120,7 +120,7 @@ func TestDefaultTxEncoder(t *testing.T) { encoder := DefaultTxEncoder(cdc) msgs := []sdk.Msg{sdk.NewTestMsg(addr)} - fee := newStdFee() + fee := NewTestStdFee() sigs := []StdSignature{} tx := NewStdTx(msgs, fee, sigs, "") diff --git a/x/auth/test_utils.go b/x/auth/types/test_common.go similarity index 79% rename from x/auth/test_utils.go rename to x/auth/types/test_common.go index 88b002985d59..c6f4d26b1d62 100644 --- a/x/auth/test_utils.go +++ b/x/auth/types/test_common.go @@ -1,5 +1,5 @@ -// nolint -package auth +//nolint +package types import ( abci "github.com/tendermint/tendermint/abci/types" @@ -11,13 +11,13 @@ import ( "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/store" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/params/subspace" ) +//DONTCOVER + type testInput struct { cdc *codec.Codec ctx sdk.Context - ak AccountKeeper fck FeeCollectionKeeper } @@ -39,41 +39,37 @@ func setupTestInput() testInput { ms.MountStoreWithDB(tkeyParams, sdk.StoreTypeTransient, db) ms.LoadLatestVersion() - ps := subspace.NewSubspace(cdc, keyParams, tkeyParams, DefaultParamspace) - ak := NewAccountKeeper(cdc, authCapKey, ps, ProtoBaseAccount) fck := NewFeeCollectionKeeper(cdc, fckCapKey) ctx := sdk.NewContext(ms, abci.Header{ChainID: "test-chain-id"}, false, log.NewNopLogger()) - ak.SetParams(ctx, DefaultParams()) - - return testInput{cdc: cdc, ctx: ctx, ak: ak, fck: fck} + return testInput{cdc: cdc, ctx: ctx, fck: fck} } -func newTestMsg(addrs ...sdk.AccAddress) *sdk.TestMsg { +func NewTestMsg(addrs ...sdk.AccAddress) *sdk.TestMsg { return sdk.NewTestMsg(addrs...) } -func newStdFee() StdFee { +func NewTestStdFee() StdFee { return NewStdFee(50000, sdk.NewCoins(sdk.NewInt64Coin("atom", 150)), ) } // coins to more than cover the fee -func newCoins() sdk.Coins { +func NewTestCoins() sdk.Coins { return sdk.Coins{ sdk.NewInt64Coin("atom", 10000000), } } -func keyPubAddr() (crypto.PrivKey, crypto.PubKey, sdk.AccAddress) { +func KeyTestPubAddr() (crypto.PrivKey, crypto.PubKey, sdk.AccAddress) { key := secp256k1.GenPrivKey() pub := key.PubKey() addr := sdk.AccAddress(pub.Address()) return key, pub, addr } -func newTestTx(ctx sdk.Context, msgs []sdk.Msg, privs []crypto.PrivKey, accNums []uint64, seqs []uint64, fee StdFee) sdk.Tx { +func NewTestTx(ctx sdk.Context, msgs []sdk.Msg, privs []crypto.PrivKey, accNums []uint64, seqs []uint64, fee StdFee) sdk.Tx { sigs := make([]StdSignature, len(privs)) for i, priv := range privs { signBytes := StdSignBytes(ctx.ChainID(), accNums[i], seqs[i], fee, msgs, "") @@ -90,7 +86,7 @@ func newTestTx(ctx sdk.Context, msgs []sdk.Msg, privs []crypto.PrivKey, accNums return tx } -func newTestTxWithMemo(ctx sdk.Context, msgs []sdk.Msg, privs []crypto.PrivKey, accNums []uint64, seqs []uint64, fee StdFee, memo string) sdk.Tx { +func NewTestTxWithMemo(ctx sdk.Context, msgs []sdk.Msg, privs []crypto.PrivKey, accNums []uint64, seqs []uint64, fee StdFee, memo string) sdk.Tx { sigs := make([]StdSignature, len(privs)) for i, priv := range privs { signBytes := StdSignBytes(ctx.ChainID(), accNums[i], seqs[i], fee, msgs, memo) @@ -107,7 +103,7 @@ func newTestTxWithMemo(ctx sdk.Context, msgs []sdk.Msg, privs []crypto.PrivKey, return tx } -func newTestTxWithSignBytes(msgs []sdk.Msg, privs []crypto.PrivKey, accNums []uint64, seqs []uint64, fee StdFee, signBytes []byte, memo string) sdk.Tx { +func NewTestTxWithSignBytes(msgs []sdk.Msg, privs []crypto.PrivKey, accNums []uint64, seqs []uint64, fee StdFee, signBytes []byte, memo string) sdk.Tx { sigs := make([]StdSignature, len(privs)) for i, priv := range privs { sig, err := priv.Sign(signBytes) diff --git a/x/auth/client/txbuilder/txbuilder.go b/x/auth/types/txbuilder.go similarity index 91% rename from x/auth/client/txbuilder/txbuilder.go rename to x/auth/types/txbuilder.go index cc3a654392cb..b29d977fd468 100644 --- a/x/auth/client/txbuilder/txbuilder.go +++ b/x/auth/types/txbuilder.go @@ -1,4 +1,4 @@ -package context +package types import ( "errors" @@ -11,7 +11,6 @@ import ( "github.com/cosmos/cosmos-sdk/client/keys" crkeys "github.com/cosmos/cosmos-sdk/crypto/keys" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" ) // TxBuilder implements a transaction context created in SDK modules. @@ -203,7 +202,7 @@ func (bldr TxBuilder) BuildSignMsg(msgs []sdk.Msg) (StdSignMsg, error) { Sequence: bldr.sequence, Memo: bldr.memo, Msgs: msgs, - Fee: auth.NewStdFee(bldr.gas, fees), + Fee: NewStdFee(bldr.gas, fees), }, nil } @@ -215,7 +214,7 @@ func (bldr TxBuilder) Sign(name, passphrase string, msg StdSignMsg) ([]byte, err return nil, err } - return bldr.txEncoder(auth.NewStdTx(msg.Msgs, msg.Fee, []auth.StdSignature{sig}, msg.Memo)) + return bldr.txEncoder(NewStdTx(msg.Msgs, msg.Fee, []StdSignature{sig}, msg.Memo)) } // BuildAndSign builds a single message to be signed, and signs a transaction @@ -238,15 +237,15 @@ func (bldr TxBuilder) BuildTxForSim(msgs []sdk.Msg) ([]byte, error) { } // the ante handler will populate with a sentinel pubkey - sigs := []auth.StdSignature{{}} - return bldr.txEncoder(auth.NewStdTx(signMsg.Msgs, signMsg.Fee, sigs, signMsg.Memo)) + sigs := []StdSignature{{}} + return bldr.txEncoder(NewStdTx(signMsg.Msgs, signMsg.Fee, sigs, signMsg.Memo)) } // SignStdTx appends a signature to a StdTx and returns a copy of it. If append // is false, it replaces the signatures already attached with the new signature. -func (bldr TxBuilder) SignStdTx(name, passphrase string, stdTx auth.StdTx, appendSig bool) (signedStdTx auth.StdTx, err error) { +func (bldr TxBuilder) SignStdTx(name, passphrase string, stdTx StdTx, appendSig bool) (signedStdTx StdTx, err error) { if bldr.chainID == "" { - return auth.StdTx{}, fmt.Errorf("chain ID required but not specified") + return StdTx{}, fmt.Errorf("chain ID required but not specified") } stdSignature, err := MakeSignature(bldr.keybase, name, passphrase, StdSignMsg{ @@ -263,17 +262,17 @@ func (bldr TxBuilder) SignStdTx(name, passphrase string, stdTx auth.StdTx, appen sigs := stdTx.GetSignatures() if len(sigs) == 0 || !appendSig { - sigs = []auth.StdSignature{stdSignature} + sigs = []StdSignature{stdSignature} } else { sigs = append(sigs, stdSignature) } - signedStdTx = auth.NewStdTx(stdTx.GetMsgs(), stdTx.Fee, sigs, stdTx.GetMemo()) + signedStdTx = NewStdTx(stdTx.GetMsgs(), stdTx.Fee, sigs, stdTx.GetMemo()) return } // MakeSignature builds a StdSignature given keybase, key name, passphrase, and a StdSignMsg. func MakeSignature(keybase crkeys.Keybase, name, passphrase string, - msg StdSignMsg) (sig auth.StdSignature, err error) { + msg StdSignMsg) (sig StdSignature, err error) { if keybase == nil { keybase, err = keys.NewKeyBaseFromHomeFlag() if err != nil { @@ -285,7 +284,7 @@ func MakeSignature(keybase crkeys.Keybase, name, passphrase string, if err != nil { return } - return auth.StdSignature{ + return StdSignature{ PubKey: pubkey, Signature: sigBytes, }, nil diff --git a/x/auth/client/txbuilder/txbuilder_test.go b/x/auth/types/txbuilder_test.go similarity index 80% rename from x/auth/client/txbuilder/txbuilder_test.go rename to x/auth/types/txbuilder_test.go index 4ff4b0cec513..063401c8a4ba 100644 --- a/x/auth/client/txbuilder/txbuilder_test.go +++ b/x/auth/types/txbuilder_test.go @@ -1,4 +1,4 @@ -package context +package types import ( "reflect" @@ -6,16 +6,8 @@ import ( "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/crypto/ed25519" - "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" -) - -var ( - priv = ed25519.GenPrivKey() - addr = sdk.AccAddress(priv.PubKey().Address()) ) func TestTxBuilderBuild(t *testing.T) { @@ -42,7 +34,7 @@ func TestTxBuilderBuild(t *testing.T) { { "builder with fees", fields{ - TxEncoder: auth.DefaultTxEncoder(codec.New()), + TxEncoder: DefaultTxEncoder(codec.New()), AccountNumber: 1, Sequence: 1, Gas: 200000, @@ -59,14 +51,14 @@ func TestTxBuilderBuild(t *testing.T) { Sequence: 1, Memo: "hello from Voyager 1!", Msgs: defaultMsg, - Fee: auth.NewStdFee(200000, sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1))}), + Fee: NewStdFee(200000, sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1))}), }, false, }, { "builder with gas prices", fields{ - TxEncoder: auth.DefaultTxEncoder(codec.New()), + TxEncoder: DefaultTxEncoder(codec.New()), AccountNumber: 1, Sequence: 1, Gas: 200000, @@ -83,14 +75,14 @@ func TestTxBuilderBuild(t *testing.T) { Sequence: 1, Memo: "hello from Voyager 2!", Msgs: defaultMsg, - Fee: auth.NewStdFee(200000, sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1))}), + Fee: NewStdFee(200000, sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1))}), }, false, }, { "no chain-id supplied", fields{ - TxEncoder: auth.DefaultTxEncoder(codec.New()), + TxEncoder: DefaultTxEncoder(codec.New()), AccountNumber: 1, Sequence: 1, Gas: 200000, @@ -107,14 +99,14 @@ func TestTxBuilderBuild(t *testing.T) { Sequence: 1, Memo: "hello from Voyager 1!", Msgs: defaultMsg, - Fee: auth.NewStdFee(200000, sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1))}), + Fee: NewStdFee(200000, sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1))}), }, true, }, { "builder w/ fees and gas prices", fields{ - TxEncoder: auth.DefaultTxEncoder(codec.New()), + TxEncoder: DefaultTxEncoder(codec.New()), AccountNumber: 1, Sequence: 1, Gas: 200000, @@ -132,7 +124,7 @@ func TestTxBuilderBuild(t *testing.T) { Sequence: 1, Memo: "hello from Voyager 1!", Msgs: defaultMsg, - Fee: auth.NewStdFee(200000, sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1))}), + Fee: NewStdFee(200000, sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1))}), }, true, }, diff --git a/x/bank/alias.go b/x/bank/alias.go new file mode 100644 index 000000000000..595c3ab61425 --- /dev/null +++ b/x/bank/alias.go @@ -0,0 +1,45 @@ +// nolint +// autogenerated code using github.com/rigelrozanski/multitool +// aliases generated for the following subdirectories: +// ALIASGEN: github.com/cosmos/cosmos-sdk/x/bank/types +package bank + +import ( + "github.com/cosmos/cosmos-sdk/x/bank/types" +) + +const ( + DefaultCodespace = types.DefaultCodespace + CodeSendDisabled = types.CodeSendDisabled + CodeInvalidInputsOutputs = types.CodeInvalidInputsOutputs + ModuleName = types.ModuleName + RouterKey = types.RouterKey + DefaultParamspace = types.DefaultParamspace + DefaultSendEnabled = types.DefaultSendEnabled +) + +var ( + // functions aliases + RegisterCodec = types.RegisterCodec + ErrNoInputs = types.ErrNoInputs + ErrNoOutputs = types.ErrNoOutputs + ErrInputOutputMismatch = types.ErrInputOutputMismatch + ErrSendDisabled = types.ErrSendDisabled + NewMsgSend = types.NewMsgSend + NewMsgMultiSend = types.NewMsgMultiSend + NewInput = types.NewInput + NewOutput = types.NewOutput + ValidateInputsOutputs = types.ValidateInputsOutputs + ParamKeyTable = types.ParamKeyTable + + // variable aliases + ModuleCdc = types.ModuleCdc + ParamStoreKeySendEnabled = types.ParamStoreKeySendEnabled +) + +type ( + MsgSend = types.MsgSend + MsgMultiSend = types.MsgMultiSend + Input = types.Input + Output = types.Output +) diff --git a/x/bank/app_test.go b/x/bank/app_test.go index 951a1746932b..651021eadb9d 100644 --- a/x/bank/app_test.go +++ b/x/bank/app_test.go @@ -5,6 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/cosmos/cosmos-sdk/x/mock" "github.com/stretchr/testify/require" @@ -45,43 +46,43 @@ var ( manyCoins = sdk.Coins{sdk.NewInt64Coin("foocoin", 1), sdk.NewInt64Coin("barcoin", 1)} freeFee = auth.NewStdFee(100000, sdk.Coins{sdk.NewInt64Coin("foocoin", 0)}) - sendMsg1 = NewMsgSend(addr1, addr2, coins) + sendMsg1 = types.NewMsgSend(addr1, addr2, coins) - multiSendMsg1 = MsgMultiSend{ - Inputs: []Input{NewInput(addr1, coins)}, - Outputs: []Output{NewOutput(addr2, coins)}, + multiSendMsg1 = types.MsgMultiSend{ + Inputs: []types.Input{types.NewInput(addr1, coins)}, + Outputs: []types.Output{types.NewOutput(addr2, coins)}, } - multiSendMsg2 = MsgMultiSend{ - Inputs: []Input{NewInput(addr1, coins)}, - Outputs: []Output{ - NewOutput(addr2, halfCoins), - NewOutput(addr3, halfCoins), + multiSendMsg2 = types.MsgMultiSend{ + Inputs: []types.Input{types.NewInput(addr1, coins)}, + Outputs: []types.Output{ + types.NewOutput(addr2, halfCoins), + types.NewOutput(addr3, halfCoins), }, } - multiSendMsg3 = MsgMultiSend{ - Inputs: []Input{ - NewInput(addr1, coins), - NewInput(addr4, coins), + multiSendMsg3 = types.MsgMultiSend{ + Inputs: []types.Input{ + types.NewInput(addr1, coins), + types.NewInput(addr4, coins), }, - Outputs: []Output{ - NewOutput(addr2, coins), - NewOutput(addr3, coins), + Outputs: []types.Output{ + types.NewOutput(addr2, coins), + types.NewOutput(addr3, coins), }, } - multiSendMsg4 = MsgMultiSend{ - Inputs: []Input{ - NewInput(addr2, coins), + multiSendMsg4 = types.MsgMultiSend{ + Inputs: []types.Input{ + types.NewInput(addr2, coins), }, - Outputs: []Output{ - NewOutput(addr1, coins), + Outputs: []types.Output{ + types.NewOutput(addr1, coins), }, } - multiSendMsg5 = MsgMultiSend{ - Inputs: []Input{ - NewInput(addr1, manyCoins), + multiSendMsg5 = types.MsgMultiSend{ + Inputs: []types.Input{ + types.NewInput(addr1, manyCoins), }, - Outputs: []Output{ - NewOutput(addr2, manyCoins), + Outputs: []types.Output{ + types.NewOutput(addr2, manyCoins), }, } ) @@ -122,7 +123,7 @@ func TestSendNotEnoughBalance(t *testing.T) { origAccNum := res1.GetAccountNumber() origSeq := res1.GetSequence() - sendMsg := NewMsgSend(addr1, addr2, sdk.Coins{sdk.NewInt64Coin("foocoin", 100)}) + sendMsg := types.NewMsgSend(addr1, addr2, sdk.Coins{sdk.NewInt64Coin("foocoin", 100)}) header := abci.Header{Height: mapp.LastBlockHeight() + 1} mock.SignCheckDeliver(t, mapp.Cdc, mapp.BaseApp, header, []sdk.Msg{sendMsg}, []uint64{origAccNum}, []uint64{origSeq}, false, false, priv1) diff --git a/x/bank/bench_test.go b/x/bank/bench_test.go index 8425f0f93008..f4e5042805a2 100644 --- a/x/bank/bench_test.go +++ b/x/bank/bench_test.go @@ -3,11 +3,12 @@ package bank import ( "testing" + abci "github.com/tendermint/tendermint/abci/types" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/cosmos/cosmos-sdk/x/mock" - - abci "github.com/tendermint/tendermint/abci/types" ) // getBenchmarkMockApp initializes a mock application for this module, for purposes of benchmarking @@ -15,13 +16,13 @@ import ( func getBenchmarkMockApp() (*mock.App, error) { mapp := mock.NewApp() - RegisterCodec(mapp.Cdc) + types.RegisterCodec(mapp.Cdc) bankKeeper := NewBaseKeeper( mapp.AccountKeeper, - mapp.ParamsKeeper.Subspace(DefaultParamspace), - DefaultCodespace, + mapp.ParamsKeeper.Subspace(types.DefaultParamspace), + types.DefaultCodespace, ) - mapp.Router().AddRoute(RouterKey, NewHandler(bankKeeper)) + mapp.Router().AddRoute(types.RouterKey, NewHandler(bankKeeper)) mapp.SetInitChainer(getInitChainer(mapp, bankKeeper)) err := mapp.CompleteSetup() diff --git a/x/bank/client/cli/sendtx.go b/x/bank/client/cli/tx.go similarity index 63% rename from x/bank/client/cli/sendtx.go rename to x/bank/client/cli/tx.go index 094b5edcd7d1..86209a51fe64 100644 --- a/x/bank/client/cli/sendtx.go +++ b/x/bank/client/cli/tx.go @@ -1,15 +1,15 @@ package cli import ( + "github.com/spf13/cobra" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/utils" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" - "github.com/cosmos/cosmos-sdk/x/bank" - - "github.com/spf13/cobra" + auth "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/bank/types" ) const ( @@ -17,6 +17,21 @@ const ( flagAmount = "amount" ) +// GetTxCmd returns the transaction commands for this module +func GetTxCmd(cdc *codec.Codec) *cobra.Command { + txCmd := &cobra.Command{ + Use: types.ModuleName, + Short: "Bank transaction subcommands", + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: utils.ValidateCmd, + } + txCmd.AddCommand( + SendTxCmd(cdc), + ) + return txCmd +} + // SendTxCmd will create a send tx and sign it with the given key. func SendTxCmd(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ @@ -24,7 +39,7 @@ func SendTxCmd(cdc *codec.Codec) *cobra.Command { Short: "Create and sign a send tx", Args: cobra.ExactArgs(3), RunE: func(cmd *cobra.Command, args []string) error { - txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) cliCtx := context.NewCLIContextWithFrom(args[0]). WithCodec(cdc). WithAccountDecoder(cdc) @@ -41,7 +56,7 @@ func SendTxCmd(cdc *codec.Codec) *cobra.Command { } // build and sign the transaction, then broadcast to Tendermint - msg := bank.NewMsgSend(cliCtx.GetFromAddress(), to, coins) + msg := types.NewMsgSend(cliCtx.GetFromAddress(), to, coins) return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) }, } diff --git a/x/bank/client/rest/sendtx.go b/x/bank/client/rest/tx.go similarity index 80% rename from x/bank/client/rest/sendtx.go rename to x/bank/client/rest/tx.go index 3e634e551f61..57e0ec32e328 100644 --- a/x/bank/client/rest/sendtx.go +++ b/x/bank/client/rest/tx.go @@ -8,16 +8,15 @@ import ( "github.com/cosmos/cosmos-sdk/client/context" clientrest "github.com/cosmos/cosmos-sdk/client/rest" "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/crypto/keys" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/bank" + "github.com/cosmos/cosmos-sdk/x/bank/types" ) // RegisterRoutes - Central function to define routes that get registered by the main application -func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec, kb keys.Keybase) { - r.HandleFunc("/bank/accounts/{address}/transfers", SendRequestHandlerFn(cdc, kb, cliCtx)).Methods("POST") +func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec) { + r.HandleFunc("/bank/accounts/{address}/transfers", SendRequestHandlerFn(cdc, cliCtx)).Methods("POST") } // SendReq defines the properties of a send request's body. @@ -29,11 +28,11 @@ type SendReq struct { var moduleCdc = codec.New() func init() { - bank.RegisterCodec(moduleCdc) + types.RegisterCodec(moduleCdc) } // SendRequestHandlerFn - http request handler to send coins to a address. -func SendRequestHandlerFn(cdc *codec.Codec, kb keys.Keybase, cliCtx context.CLIContext) http.HandlerFunc { +func SendRequestHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) bech32Addr := vars["address"] @@ -60,7 +59,7 @@ func SendRequestHandlerFn(cdc *codec.Codec, kb keys.Keybase, cliCtx context.CLIC return } - msg := bank.NewMsgSend(fromAddr, toAddr, req.Amount) + msg := types.NewMsgSend(fromAddr, toAddr, req.Amount) clientrest.WriteGenerateStdTxResponse(w, cdc, cliCtx, req.BaseReq, []sdk.Msg{msg}) } } diff --git a/x/bank/handler.go b/x/bank/handler.go index 3afff836ae1f..040e440e3da7 100644 --- a/x/bank/handler.go +++ b/x/bank/handler.go @@ -5,16 +5,17 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/bank/tags" + "github.com/cosmos/cosmos-sdk/x/bank/types" ) // NewHandler returns a handler for "bank" type messages. func NewHandler(k Keeper) sdk.Handler { return func(ctx sdk.Context, msg sdk.Msg) sdk.Result { switch msg := msg.(type) { - case MsgSend: + case types.MsgSend: return handleMsgSend(ctx, k, msg) - case MsgMultiSend: + case types.MsgMultiSend: return handleMsgMultiSend(ctx, k, msg) default: @@ -25,9 +26,9 @@ func NewHandler(k Keeper) sdk.Handler { } // Handle MsgSend. -func handleMsgSend(ctx sdk.Context, k Keeper, msg MsgSend) sdk.Result { +func handleMsgSend(ctx sdk.Context, k Keeper, msg types.MsgSend) sdk.Result { if !k.GetSendEnabled(ctx) { - return ErrSendDisabled(k.Codespace()).Result() + return types.ErrSendDisabled(k.Codespace()).Result() } err := k.SendCoins(ctx, msg.FromAddress, msg.ToAddress, msg.Amount) if err != nil { @@ -46,10 +47,10 @@ func handleMsgSend(ctx sdk.Context, k Keeper, msg MsgSend) sdk.Result { } // Handle MsgMultiSend. -func handleMsgMultiSend(ctx sdk.Context, k Keeper, msg MsgMultiSend) sdk.Result { +func handleMsgMultiSend(ctx sdk.Context, k Keeper, msg types.MsgMultiSend) sdk.Result { // NOTE: totalIn == totalOut should already have been checked if !k.GetSendEnabled(ctx) { - return ErrSendDisabled(k.Codespace()).Result() + return types.ErrSendDisabled(k.Codespace()).Result() } resTags, err := k.InputOutputCoins(ctx, msg.Inputs, msg.Outputs) if err != nil { diff --git a/x/bank/invariants.go b/x/bank/invariants.go index a0e30db98372..bd1528aa6edf 100644 --- a/x/bank/invariants.go +++ b/x/bank/invariants.go @@ -6,11 +6,12 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/bank/types" ) // register bank invariants func RegisterInvariants(ir sdk.InvariantRouter, ak auth.AccountKeeper) { - ir.RegisterRoute(RouterKey, "nonnegative-outstanding", + ir.RegisterRoute(types.ModuleName, "nonnegative-outstanding", NonnegativeBalanceInvariant(ak)) } diff --git a/x/bank/keeper.go b/x/bank/keeper.go index 05a5b3d6e31d..730c96e070e7 100644 --- a/x/bank/keeper.go +++ b/x/bank/keeper.go @@ -7,6 +7,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/bank/tags" + "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/cosmos/cosmos-sdk/x/params" ) @@ -20,7 +21,7 @@ type Keeper interface { SetCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) sdk.Error SubtractCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) (sdk.Coins, sdk.Error) AddCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) (sdk.Coins, sdk.Error) - InputOutputCoins(ctx sdk.Context, inputs []Input, outputs []Output) (sdk.Tags, sdk.Error) + InputOutputCoins(ctx sdk.Context, inputs []types.Input, outputs []types.Output) (sdk.Tags, sdk.Error) DelegateCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) (sdk.Tags, sdk.Error) UndelegateCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) (sdk.Tags, sdk.Error) @@ -39,7 +40,7 @@ func NewBaseKeeper(ak auth.AccountKeeper, paramSpace params.Subspace, codespace sdk.CodespaceType) BaseKeeper { - ps := paramSpace.WithKeyTable(ParamKeyTable()) + ps := paramSpace.WithKeyTable(types.ParamKeyTable()) return BaseKeeper{ BaseSendKeeper: NewBaseSendKeeper(ak, ps, codespace), ak: ak, @@ -82,7 +83,7 @@ func (keeper BaseKeeper) AddCoins( // InputOutputCoins handles a list of inputs and outputs func (keeper BaseKeeper) InputOutputCoins( - ctx sdk.Context, inputs []Input, outputs []Output, + ctx sdk.Context, inputs []types.Input, outputs []types.Output, ) (sdk.Tags, sdk.Error) { return inputOutputCoins(ctx, keeper.ak, inputs, outputs) @@ -163,13 +164,13 @@ func (keeper BaseSendKeeper) SendCoins( // nolint: errcheck func (keeper BaseSendKeeper) GetSendEnabled(ctx sdk.Context) bool { var enabled bool - keeper.paramSpace.Get(ctx, ParamStoreKeySendEnabled, &enabled) + keeper.paramSpace.Get(ctx, types.ParamStoreKeySendEnabled, &enabled) return enabled } // SetSendEnabled sets the send enabled func (keeper BaseSendKeeper) SetSendEnabled(ctx sdk.Context, enabled bool) { - keeper.paramSpace.Set(ctx, ParamStoreKeySendEnabled, &enabled) + keeper.paramSpace.Set(ctx, types.ParamStoreKeySendEnabled, &enabled) } var _ ViewKeeper = (*BaseViewKeeper)(nil) @@ -323,10 +324,10 @@ func sendCoins(ctx sdk.Context, am auth.AccountKeeper, fromAddr sdk.AccAddress, // InputOutputCoins handles a list of inputs and outputs // NOTE: Make sure to revert state changes from tx on error -func inputOutputCoins(ctx sdk.Context, am auth.AccountKeeper, inputs []Input, outputs []Output) (sdk.Tags, sdk.Error) { +func inputOutputCoins(ctx sdk.Context, am auth.AccountKeeper, inputs []types.Input, outputs []types.Output) (sdk.Tags, sdk.Error) { // Safety check ensuring that when sending coins the keeper must maintain the // Check supply invariant and validity of Coins. - if err := ValidateInputsOutputs(inputs, outputs); err != nil { + if err := types.ValidateInputsOutputs(inputs, outputs); err != nil { return nil, err } diff --git a/x/bank/keeper_test.go b/x/bank/keeper_test.go index 7328b7af6e43..c658d5e46e9c 100644 --- a/x/bank/keeper_test.go +++ b/x/bank/keeper_test.go @@ -14,6 +14,7 @@ import ( "github.com/cosmos/cosmos-sdk/store" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/cosmos/cosmos-sdk/x/params" ) @@ -56,7 +57,7 @@ func setupTestInput() testInput { func TestKeeper(t *testing.T) { input := setupTestInput() ctx := input.ctx - bankKeeper := NewBaseKeeper(input.ak, input.pk.Subspace(DefaultParamspace), DefaultCodespace) + bankKeeper := NewBaseKeeper(input.ak, input.pk.Subspace(types.DefaultParamspace), types.DefaultCodespace) bankKeeper.SetSendEnabled(ctx, true) addr := sdk.AccAddress([]byte("addr1")) @@ -112,18 +113,18 @@ func TestKeeper(t *testing.T) { require.True(t, bankKeeper.GetCoins(ctx, addr2).IsEqual(sdk.NewCoins(sdk.NewInt64Coin("barcoin", 10), sdk.NewInt64Coin("foocoin", 10)))) // Test InputOutputCoins - input1 := NewInput(addr2, sdk.NewCoins(sdk.NewInt64Coin("foocoin", 2))) - output1 := NewOutput(addr, sdk.NewCoins(sdk.NewInt64Coin("foocoin", 2))) - bankKeeper.InputOutputCoins(ctx, []Input{input1}, []Output{output1}) + input1 := types.NewInput(addr2, sdk.NewCoins(sdk.NewInt64Coin("foocoin", 2))) + output1 := types.NewOutput(addr, sdk.NewCoins(sdk.NewInt64Coin("foocoin", 2))) + bankKeeper.InputOutputCoins(ctx, []types.Input{input1}, []types.Output{output1}) require.True(t, bankKeeper.GetCoins(ctx, addr).IsEqual(sdk.NewCoins(sdk.NewInt64Coin("barcoin", 20), sdk.NewInt64Coin("foocoin", 7)))) require.True(t, bankKeeper.GetCoins(ctx, addr2).IsEqual(sdk.NewCoins(sdk.NewInt64Coin("barcoin", 10), sdk.NewInt64Coin("foocoin", 8)))) - inputs := []Input{ + inputs := []types.Input{ NewInput(addr, sdk.NewCoins(sdk.NewInt64Coin("foocoin", 3))), - NewInput(addr2, sdk.NewCoins(sdk.NewInt64Coin("barcoin", 3), sdk.NewInt64Coin("foocoin", 2))), + types.NewInput(addr2, sdk.NewCoins(sdk.NewInt64Coin("barcoin", 3), sdk.NewInt64Coin("foocoin", 2))), } - outputs := []Output{ + outputs := []types.Output{ NewOutput(addr, sdk.NewCoins(sdk.NewInt64Coin("barcoin", 1))), NewOutput(addr3, sdk.NewCoins(sdk.NewInt64Coin("barcoin", 2), sdk.NewInt64Coin("foocoin", 5))), } @@ -136,8 +137,8 @@ func TestKeeper(t *testing.T) { func TestSendKeeper(t *testing.T) { input := setupTestInput() ctx := input.ctx - paramSpace := input.pk.Subspace(DefaultParamspace) - bankKeeper := NewBaseKeeper(input.ak, paramSpace, DefaultCodespace) + paramSpace := input.pk.Subspace(types.DefaultParamspace) + bankKeeper := NewBaseKeeper(input.ak, paramSpace, types.DefaultCodespace) sendKeeper := NewBaseSendKeeper(input.ak, paramSpace, DefaultCodespace) bankKeeper.SetSendEnabled(ctx, true) diff --git a/x/bank/module.go b/x/bank/module.go index 53be045fcdb2..75f84f6f927c 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -3,50 +3,69 @@ package bank import ( "encoding/json" + "github.com/gorilla/mux" + "github.com/spf13/cobra" + + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/auth" - abci "github.com/tendermint/tendermint/abci/types" + "github.com/cosmos/cosmos-sdk/x/bank/client/cli" + "github.com/cosmos/cosmos-sdk/x/bank/client/rest" + "github.com/cosmos/cosmos-sdk/x/bank/types" ) var ( - _ sdk.AppModule = AppModule{} - _ sdk.AppModuleBasic = AppModuleBasic{} + _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} ) -// name of this module -const ModuleName = "bank" - // app module basics object type AppModuleBasic struct{} -var _ sdk.AppModuleBasic = AppModuleBasic{} +var _ module.AppModuleBasic = AppModuleBasic{} // module name func (AppModuleBasic) Name() string { - return ModuleName + return types.ModuleName } // register module codec func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) { - RegisterCodec(cdc) + types.RegisterCodec(cdc) } // default genesis state func (AppModuleBasic) DefaultGenesis() json.RawMessage { - return moduleCdc.MustMarshalJSON(DefaultGenesisState()) + return types.ModuleCdc.MustMarshalJSON(DefaultGenesisState()) } // module validate genesis func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { var data GenesisState - err := moduleCdc.UnmarshalJSON(bz, &data) + err := types.ModuleCdc.UnmarshalJSON(bz, &data) if err != nil { return err } return ValidateGenesis(data) } +// register rest routes +func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router, cdc *codec.Codec) { + rest.RegisterRoutes(ctx, rtr, cdc) +} + +// get the root tx command of this module +func (AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command { + return cli.GetTxCmd(cdc) +} + +// get the root query command of this module +func (AppModuleBasic) GetQueryCmd(_ *codec.Codec) *cobra.Command { return nil } + //___________________________ // app module type AppModule struct { @@ -66,7 +85,7 @@ func NewAppModule(keeper Keeper, accountKeeper auth.AccountKeeper) AppModule { // module name func (AppModule) Name() string { - return ModuleName + return types.ModuleName } // register invariants @@ -76,7 +95,7 @@ func (am AppModule) RegisterInvariants(ir sdk.InvariantRouter) { // module message route name func (AppModule) Route() string { - return RouterKey + return types.RouterKey } // module handler @@ -93,7 +112,7 @@ func (AppModule) NewQuerierHandler() sdk.Querier { return nil } // module init-genesis func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate { var genesisState GenesisState - moduleCdc.MustUnmarshalJSON(data, &genesisState) + types.ModuleCdc.MustUnmarshalJSON(data, &genesisState) InitGenesis(ctx, am.keeper, genesisState) return []abci.ValidatorUpdate{} } @@ -101,7 +120,7 @@ func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.Va // module export genesis func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { gs := ExportGenesis(ctx, am.keeper) - return moduleCdc.MustMarshalJSON(gs) + return types.ModuleCdc.MustMarshalJSON(gs) } // module begin-block diff --git a/x/bank/codec.go b/x/bank/types/codec.go similarity index 69% rename from x/bank/codec.go rename to x/bank/types/codec.go index 2c2cc32a3387..6d4d49adc118 100644 --- a/x/bank/codec.go +++ b/x/bank/types/codec.go @@ -1,4 +1,4 @@ -package bank +package types import ( "github.com/cosmos/cosmos-sdk/codec" @@ -10,8 +10,11 @@ func RegisterCodec(cdc *codec.Codec) { cdc.RegisterConcrete(MsgMultiSend{}, "cosmos-sdk/MsgMultiSend", nil) } -var moduleCdc = codec.New() +// module codec +var ModuleCdc *codec.Codec func init() { - RegisterCodec(moduleCdc) + ModuleCdc = codec.New() + RegisterCodec(ModuleCdc) + ModuleCdc.Seal() } diff --git a/x/bank/errors.go b/x/bank/types/errors.go similarity index 98% rename from x/bank/errors.go rename to x/bank/types/errors.go index 5b579fabb28d..d9c0c7d11d1d 100644 --- a/x/bank/errors.go +++ b/x/bank/types/errors.go @@ -1,4 +1,4 @@ -package bank +package types import ( sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/bank/types/key.go b/x/bank/types/key.go new file mode 100644 index 000000000000..b894b78ed913 --- /dev/null +++ b/x/bank/types/key.go @@ -0,0 +1,6 @@ +package types + +const ( + // module name + ModuleName = "bank" +) diff --git a/x/bank/msgs.go b/x/bank/types/msgs.go similarity index 97% rename from x/bank/msgs.go rename to x/bank/types/msgs.go index 2953488673f2..0f3d8e1fef84 100644 --- a/x/bank/msgs.go +++ b/x/bank/types/msgs.go @@ -1,4 +1,4 @@ -package bank +package types import ( sdk "github.com/cosmos/cosmos-sdk/types" @@ -46,7 +46,7 @@ func (msg MsgSend) ValidateBasic() sdk.Error { // GetSignBytes Implements Msg. func (msg MsgSend) GetSignBytes() []byte { - return sdk.MustSortJSON(moduleCdc.MustMarshalJSON(msg)) + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) } // GetSigners Implements Msg. @@ -89,7 +89,7 @@ func (msg MsgMultiSend) ValidateBasic() sdk.Error { // GetSignBytes Implements Msg. func (msg MsgMultiSend) GetSignBytes() []byte { - return sdk.MustSortJSON(moduleCdc.MustMarshalJSON(msg)) + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) } // GetSigners Implements Msg. diff --git a/x/bank/msgs_test.go b/x/bank/types/msgs_test.go similarity index 99% rename from x/bank/msgs_test.go rename to x/bank/types/msgs_test.go index 3b7813e0d508..2a09c1b9f728 100644 --- a/x/bank/msgs_test.go +++ b/x/bank/types/msgs_test.go @@ -1,4 +1,4 @@ -package bank +package types import ( "fmt" diff --git a/x/bank/params.go b/x/bank/types/params.go similarity index 97% rename from x/bank/params.go rename to x/bank/types/params.go index 01602e52cceb..d232a975f0cb 100644 --- a/x/bank/params.go +++ b/x/bank/types/params.go @@ -1,4 +1,4 @@ -package bank +package types import ( "github.com/cosmos/cosmos-sdk/x/params" diff --git a/x/crisis/alias.go b/x/crisis/alias.go new file mode 100644 index 000000000000..be9fd5c54a1d --- /dev/null +++ b/x/crisis/alias.go @@ -0,0 +1,38 @@ +// nolint +// autogenerated code using github.com/rigelrozanski/multitool +// aliases generated for the following subdirectories: +// ALIASGEN: github.com/cosmos/cosmos-sdk/x/crisis/types +package crisis + +import ( + "github.com/cosmos/cosmos-sdk/x/crisis/types" +) + +const ( + DefaultCodespace = types.DefaultCodespace + CodeInvalidInput = types.CodeInvalidInput + ModuleName = types.ModuleName + DefaultParamspace = types.DefaultParamspace +) + +var ( + // functions aliases + RegisterCodec = types.RegisterCodec + ErrNilSender = types.ErrNilSender + ErrUnknownInvariant = types.ErrUnknownInvariant + NewGenesisState = types.NewGenesisState + DefaultGenesisState = types.DefaultGenesisState + NewMsgVerifyInvariant = types.NewMsgVerifyInvariant + ParamKeyTable = types.ParamKeyTable + NewInvarRoute = types.NewInvarRoute + + // variable aliases + ModuleCdc = types.ModuleCdc + ParamStoreKeyConstantFee = types.ParamStoreKeyConstantFee +) + +type ( + GenesisState = types.GenesisState + MsgVerifyInvariant = types.MsgVerifyInvariant + InvarRoute = types.InvarRoute +) diff --git a/x/crisis/client/cli/tx.go b/x/crisis/client/cli/tx.go index 8f1147793301..4cd41c4f1d8c 100644 --- a/x/crisis/client/cli/tx.go +++ b/x/crisis/client/cli/tx.go @@ -4,12 +4,13 @@ package cli import ( "github.com/spf13/cobra" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/utils" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" - "github.com/cosmos/cosmos-sdk/x/crisis" + auth "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/crisis/types" ) // command to replace a delegator's withdrawal address @@ -20,14 +21,30 @@ func GetCmdInvariantBroken(cdc *codec.Codec) *cobra.Command { Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { - txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) cliCtx := context.NewCLIContext().WithCodec(cdc).WithAccountDecoder(cdc) senderAddr := cliCtx.GetFromAddress() moduleName, route := args[0], args[1] - msg := crisis.NewMsgVerifyInvariant(senderAddr, moduleName, route) + msg := types.NewMsgVerifyInvariant(senderAddr, moduleName, route) return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) }, } return cmd } + +// GetTxCmd returns the transaction commands for this module +func GetTxCmd(cdc *codec.Codec) *cobra.Command { + txCmd := &cobra.Command{ + Use: types.ModuleName, + Short: "Crisis transactions subcommands", + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: utils.ValidateCmd, + } + + txCmd.AddCommand(client.PostCommands( + GetCmdInvariantBroken(cdc), + )...) + return txCmd +} diff --git a/x/crisis/client/module_client.go b/x/crisis/client/module_client.go deleted file mode 100644 index 2b477ef04e5f..000000000000 --- a/x/crisis/client/module_client.go +++ /dev/null @@ -1,46 +0,0 @@ -package client - -import ( - "github.com/spf13/cobra" - amino "github.com/tendermint/go-amino" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/utils" - "github.com/cosmos/cosmos-sdk/x/crisis" - "github.com/cosmos/cosmos-sdk/x/crisis/client/cli" -) - -// ModuleClient exports all client functionality from this module -type ModuleClient struct { - storeKey string - cdc *amino.Codec -} - -// NewModuleClient creates a new ModuleClient object -func NewModuleClient(storeKey string, cdc *amino.Codec) ModuleClient { - return ModuleClient{ - storeKey: storeKey, - cdc: cdc, - } -} - -// GetQueryCmd returns the cli query commands for this module -func (ModuleClient) GetQueryCmd() *cobra.Command { - return nil -} - -// GetTxCmd returns the transaction commands for this module -func (mc ModuleClient) GetTxCmd() *cobra.Command { - txCmd := &cobra.Command{ - Use: crisis.ModuleName, - Short: "crisis transactions subcommands", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: utils.ValidateCmd, - } - - txCmd.AddCommand(client.PostCommands( - cli.GetCmdInvariantBroken(mc.cdc), - )...) - return txCmd -} diff --git a/x/crisis/genesis.go b/x/crisis/genesis.go index 7cd702b8486b..58d2689e323f 100644 --- a/x/crisis/genesis.go +++ b/x/crisis/genesis.go @@ -2,39 +2,16 @@ package crisis import ( sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/crisis/types" ) -// GenesisState - crisis genesis state -type GenesisState struct { - ConstantFee sdk.Coin `json:"constant_fee"` -} - -// NewGenesisState creates a new GenesisState object -func NewGenesisState(constantFee sdk.Coin) GenesisState { - return GenesisState{ - ConstantFee: constantFee, - } -} - -// DefaultGenesisState creates a default GenesisState object -func DefaultGenesisState() GenesisState { - return GenesisState{ - ConstantFee: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1000)), - } -} - // new crisis genesis -func InitGenesis(ctx sdk.Context, keeper Keeper, data GenesisState) { +func InitGenesis(ctx sdk.Context, keeper Keeper, data types.GenesisState) { keeper.SetConstantFee(ctx, data.ConstantFee) } // ExportGenesis returns a GenesisState for a given context and keeper. -func ExportGenesis(ctx sdk.Context, keeper Keeper) GenesisState { +func ExportGenesis(ctx sdk.Context, keeper Keeper) types.GenesisState { constantFee := keeper.GetConstantFee(ctx) - return NewGenesisState(constantFee) -} - -// ValidateGenesis - placeholder function -func ValidateGenesis(data GenesisState) error { - return nil + return types.NewGenesisState(constantFee) } diff --git a/x/crisis/handler.go b/x/crisis/handler.go index 475ca8535c99..012b82edde99 100644 --- a/x/crisis/handler.go +++ b/x/crisis/handler.go @@ -5,6 +5,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/crisis/tags" + "github.com/cosmos/cosmos-sdk/x/crisis/types" ) // RouterKey @@ -13,7 +14,7 @@ const RouterKey = ModuleName func NewHandler(k Keeper) sdk.Handler { return func(ctx sdk.Context, msg sdk.Msg) sdk.Result { switch msg := msg.(type) { - case MsgVerifyInvariant: + case types.MsgVerifyInvariant: return handleMsgVerifyInvariant(ctx, msg, k) default: @@ -23,7 +24,7 @@ func NewHandler(k Keeper) sdk.Handler { } } -func handleMsgVerifyInvariant(ctx sdk.Context, msg MsgVerifyInvariant, k Keeper) sdk.Result { +func handleMsgVerifyInvariant(ctx sdk.Context, msg types.MsgVerifyInvariant, k Keeper) sdk.Result { // remove the constant fee constantFee := sdk.NewCoins(k.GetConstantFee(ctx)) @@ -47,7 +48,7 @@ func handleMsgVerifyInvariant(ctx sdk.Context, msg MsgVerifyInvariant, k Keeper) } } if !found { - return ErrUnknownInvariant(DefaultCodespace).Result() + return types.ErrUnknownInvariant(types.DefaultCodespace).Result() } if invarianceErr != nil { diff --git a/x/crisis/keeper.go b/x/crisis/keeper.go index 51a5abf6ec2f..7bb9d4aaa035 100644 --- a/x/crisis/keeper.go +++ b/x/crisis/keeper.go @@ -7,12 +7,13 @@ import ( "github.com/tendermint/tendermint/libs/log" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/crisis/types" "github.com/cosmos/cosmos-sdk/x/params" ) // Keeper - crisis keeper type Keeper struct { - routes []InvarRoute + routes []types.InvarRoute paramSpace params.Subspace invCheckPeriod uint @@ -27,8 +28,8 @@ func NewKeeper(paramSpace params.Subspace, invCheckPeriod uint, feeCollectionKeeper FeeCollectionKeeper) Keeper { return Keeper{ - routes: []InvarRoute{}, - paramSpace: paramSpace.WithKeyTable(ParamKeyTable()), + routes: []types.InvarRoute{}, + paramSpace: paramSpace.WithKeyTable(types.ParamKeyTable()), invCheckPeriod: invCheckPeriod, distrKeeper: distrKeeper, bankKeeper: bankKeeper, @@ -38,12 +39,12 @@ func NewKeeper(paramSpace params.Subspace, invCheckPeriod uint, // register routes for the func (k *Keeper) RegisterRoute(moduleName, route string, invar sdk.Invariant) { - invarRoute := NewInvarRoute(moduleName, route, invar) + invarRoute := types.NewInvarRoute(moduleName, route, invar) k.routes = append(k.routes, invarRoute) } // Routes - return the keeper's invariant routes -func (k Keeper) Routes() []InvarRoute { +func (k Keeper) Routes() []types.InvarRoute { return k.routes } diff --git a/x/crisis/module.go b/x/crisis/module.go index 7bb64f10714c..6491a23b820b 100644 --- a/x/crisis/module.go +++ b/x/crisis/module.go @@ -3,25 +3,28 @@ package crisis import ( "encoding/json" + "github.com/gorilla/mux" + "github.com/spf13/cobra" + + abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/libs/log" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - abci "github.com/tendermint/tendermint/abci/types" + "github.com/cosmos/cosmos-sdk/types/module" + "github.com/cosmos/cosmos-sdk/x/crisis/client/cli" ) var ( - _ sdk.AppModule = AppModule{} - _ sdk.AppModuleBasic = AppModuleBasic{} + _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} ) -// name of this module -const ModuleName = "crisis" - // app module basics object type AppModuleBasic struct{} -var _ sdk.AppModuleBasic = AppModuleBasic{} +var _ module.AppModuleBasic = AppModuleBasic{} // module name func (AppModuleBasic) Name() string { @@ -35,19 +38,27 @@ func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) { // default genesis state func (AppModuleBasic) DefaultGenesis() json.RawMessage { - return moduleCdc.MustMarshalJSON(DefaultGenesisState()) + return ModuleCdc.MustMarshalJSON(DefaultGenesisState()) } // module validate genesis func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { - var data GenesisState - err := moduleCdc.UnmarshalJSON(bz, &data) - if err != nil { - return err - } - return ValidateGenesis(data) + //TODO + return nil } +// register rest routes +func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router, cdc *codec.Codec) { +} + +// get the root tx command of this module +func (AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command { + return cli.GetTxCmd(cdc) +} + +// get the root query command of this module +func (AppModuleBasic) GetQueryCmd(_ *codec.Codec) *cobra.Command { return nil } + //___________________________ // app module for bank type AppModule struct { @@ -92,7 +103,7 @@ func (AppModule) NewQuerierHandler() sdk.Querier { return nil } // module init-genesis func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate { var genesisState GenesisState - moduleCdc.MustUnmarshalJSON(data, &genesisState) + ModuleCdc.MustUnmarshalJSON(data, &genesisState) InitGenesis(ctx, am.keeper, genesisState) am.keeper.AssertInvariants(ctx, am.logger) @@ -102,7 +113,7 @@ func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.Va // module export genesis func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { gs := ExportGenesis(ctx, am.keeper) - return moduleCdc.MustMarshalJSON(gs) + return ModuleCdc.MustMarshalJSON(gs) } // module begin-block diff --git a/x/crisis/params.go b/x/crisis/params.go index 14c8a2567315..e8f40759ddc5 100644 --- a/x/crisis/params.go +++ b/x/crisis/params.go @@ -2,33 +2,16 @@ package crisis import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/params" + "github.com/cosmos/cosmos-sdk/x/crisis/types" ) -// Default parameter namespace -const ( - DefaultParamspace = ModuleName -) - -var ( - // key for constant fee parameter - ParamStoreKeyConstantFee = []byte("ConstantFee") -) - -// type declaration for parameters -func ParamKeyTable() params.KeyTable { - return params.NewKeyTable( - ParamStoreKeyConstantFee, sdk.Coin{}, - ) -} - // GetConstantFee get's the constant fee from the paramSpace func (k Keeper) GetConstantFee(ctx sdk.Context) (constantFee sdk.Coin) { - k.paramSpace.Get(ctx, ParamStoreKeyConstantFee, &constantFee) + k.paramSpace.Get(ctx, types.ParamStoreKeyConstantFee, &constantFee) return } // GetConstantFee set's the constant fee in the paramSpace func (k Keeper) SetConstantFee(ctx sdk.Context, constantFee sdk.Coin) { - k.paramSpace.Set(ctx, ParamStoreKeyConstantFee, constantFee) + k.paramSpace.Set(ctx, types.ParamStoreKeyConstantFee, constantFee) } diff --git a/x/crisis/codec.go b/x/crisis/types/codec.go similarity index 66% rename from x/crisis/codec.go rename to x/crisis/types/codec.go index 9d35754139cf..92aeb130bce8 100644 --- a/x/crisis/codec.go +++ b/x/crisis/types/codec.go @@ -1,4 +1,4 @@ -package crisis +package types import ( "github.com/cosmos/cosmos-sdk/codec" @@ -10,11 +10,11 @@ func RegisterCodec(cdc *codec.Codec) { } // generic sealed codec to be used throughout module -var moduleCdc *codec.Codec +var ModuleCdc *codec.Codec func init() { - cdc := codec.New() - RegisterCodec(cdc) - codec.RegisterCrypto(cdc) - moduleCdc = cdc.Seal() + ModuleCdc = codec.New() + RegisterCodec(ModuleCdc) + codec.RegisterCrypto(ModuleCdc) + ModuleCdc.Seal() } diff --git a/x/crisis/errors.go b/x/crisis/types/errors.go similarity index 97% rename from x/crisis/errors.go rename to x/crisis/types/errors.go index 7a03134fd582..3b7392abfae6 100644 --- a/x/crisis/errors.go +++ b/x/crisis/types/errors.go @@ -1,4 +1,4 @@ -package crisis +package types import ( sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/crisis/types/genesis.go b/x/crisis/types/genesis.go new file mode 100644 index 000000000000..1a7e0f9ae072 --- /dev/null +++ b/x/crisis/types/genesis.go @@ -0,0 +1,24 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// GenesisState - crisis genesis state +type GenesisState struct { + ConstantFee sdk.Coin `json:"constant_fee"` +} + +// NewGenesisState creates a new GenesisState object +func NewGenesisState(constantFee sdk.Coin) GenesisState { + return GenesisState{ + ConstantFee: constantFee, + } +} + +// DefaultGenesisState creates a default GenesisState object +func DefaultGenesisState() GenesisState { + return GenesisState{ + ConstantFee: sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1000)), + } +} diff --git a/x/crisis/types/keys.go b/x/crisis/types/keys.go new file mode 100644 index 000000000000..8f009eda4148 --- /dev/null +++ b/x/crisis/types/keys.go @@ -0,0 +1,6 @@ +package types + +const ( + // module name + ModuleName = "crisis" +) diff --git a/x/crisis/msg.go b/x/crisis/types/msgs.go similarity index 96% rename from x/crisis/msg.go rename to x/crisis/types/msgs.go index f63623149410..e14b1528303a 100644 --- a/x/crisis/msg.go +++ b/x/crisis/types/msgs.go @@ -1,4 +1,4 @@ -package crisis +package types import ( sdk "github.com/cosmos/cosmos-sdk/types" @@ -34,7 +34,7 @@ func (msg MsgVerifyInvariant) GetSigners() []sdk.AccAddress { return []sdk.AccAd // GetSignBytes gets the sign bytes for the msg MsgVerifyInvariant func (msg MsgVerifyInvariant) GetSignBytes() []byte { - bz := moduleCdc.MustMarshalJSON(msg) + bz := ModuleCdc.MustMarshalJSON(msg) return sdk.MustSortJSON(bz) } diff --git a/x/crisis/types/params.go b/x/crisis/types/params.go new file mode 100644 index 000000000000..a0dbdf726783 --- /dev/null +++ b/x/crisis/types/params.go @@ -0,0 +1,23 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/params" +) + +// Default parameter namespace +const ( + DefaultParamspace = ModuleName +) + +var ( + // key for constant fee parameter + ParamStoreKeyConstantFee = []byte("ConstantFee") +) + +// type declaration for parameters +func ParamKeyTable() params.KeyTable { + return params.NewKeyTable( + ParamStoreKeyConstantFee, sdk.Coin{}, + ) +} diff --git a/x/crisis/route.go b/x/crisis/types/route.go similarity index 97% rename from x/crisis/route.go rename to x/crisis/types/route.go index 0f8808581c26..1096798e8c71 100644 --- a/x/crisis/route.go +++ b/x/crisis/types/route.go @@ -1,4 +1,4 @@ -package crisis +package types import ( sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/distribution/alias.go b/x/distribution/alias.go index e00d0075979b..619ae1d89e7f 100644 --- a/x/distribution/alias.go +++ b/x/distribution/alias.go @@ -14,19 +14,6 @@ import ( const ( DefaultParamspace = keeper.DefaultParamspace - QueryParams = keeper.QueryParams - QueryValidatorOutstandingRewards = keeper.QueryValidatorOutstandingRewards - QueryValidatorCommission = keeper.QueryValidatorCommission - QueryValidatorSlashes = keeper.QueryValidatorSlashes - QueryDelegationRewards = keeper.QueryDelegationRewards - QueryDelegatorTotalRewards = keeper.QueryDelegatorTotalRewards - QueryDelegatorValidators = keeper.QueryDelegatorValidators - QueryWithdrawAddr = keeper.QueryWithdrawAddr - QueryCommunityPool = keeper.QueryCommunityPool - ParamCommunityTax = keeper.ParamCommunityTax - ParamBaseProposerReward = keeper.ParamBaseProposerReward - ParamBonusProposerReward = keeper.ParamBonusProposerReward - ParamWithdrawAddrEnabled = keeper.ParamWithdrawAddrEnabled DefaultCodespace = types.DefaultCodespace CodeInvalidInput = types.CodeInvalidInput CodeNoDistributionInfo = types.CodeNoDistributionInfo @@ -37,6 +24,20 @@ const ( TStoreKey = types.TStoreKey RouterKey = types.RouterKey QuerierRoute = types.QuerierRoute + ProposalTypeCommunityPoolSpend = types.ProposalTypeCommunityPoolSpend + QueryParams = types.QueryParams + QueryValidatorOutstandingRewards = types.QueryValidatorOutstandingRewards + QueryValidatorCommission = types.QueryValidatorCommission + QueryValidatorSlashes = types.QueryValidatorSlashes + QueryDelegationRewards = types.QueryDelegationRewards + QueryDelegatorTotalRewards = types.QueryDelegatorTotalRewards + QueryDelegatorValidators = types.QueryDelegatorValidators + QueryWithdrawAddr = types.QueryWithdrawAddr + QueryCommunityPool = types.QueryCommunityPool + ParamCommunityTax = types.ParamCommunityTax + ParamBaseProposerReward = types.ParamBaseProposerReward + ParamBonusProposerReward = types.ParamBonusProposerReward + ParamWithdrawAddrEnabled = types.ParamWithdrawAddrEnabled ) var ( @@ -64,13 +65,8 @@ var ( GetValidatorSlashEventPrefix = keeper.GetValidatorSlashEventPrefix GetValidatorSlashEventKey = keeper.GetValidatorSlashEventKey ParamKeyTable = keeper.ParamKeyTable + HandleCommunityPoolSpendProposal = keeper.HandleCommunityPoolSpendProposal NewQuerier = keeper.NewQuerier - NewQueryValidatorOutstandingRewardsParams = keeper.NewQueryValidatorOutstandingRewardsParams - NewQueryValidatorCommissionParams = keeper.NewQueryValidatorCommissionParams - NewQueryValidatorSlashesParams = keeper.NewQueryValidatorSlashesParams - NewQueryDelegationRewardsParams = keeper.NewQueryDelegationRewardsParams - NewQueryDelegatorParams = keeper.NewQueryDelegatorParams - NewQueryDelegatorWithdrawAddrParams = keeper.NewQueryDelegatorWithdrawAddrParams MakeTestCodec = keeper.MakeTestCodec CreateTestInputDefault = keeper.CreateTestInputDefault CreateTestInputAdvanced = keeper.CreateTestInputAdvanced @@ -84,6 +80,8 @@ var ( ErrNoValidatorCommission = types.ErrNoValidatorCommission ErrSetWithdrawAddrDisabled = types.ErrSetWithdrawAddrDisabled ErrBadDistribution = types.ErrBadDistribution + ErrInvalidProposalAmount = types.ErrInvalidProposalAmount + ErrEmptyProposalRecipient = types.ErrEmptyProposalRecipient InitialFeePool = types.InitialFeePool NewGenesisState = types.NewGenesisState DefaultGenesisState = types.DefaultGenesisState @@ -91,13 +89,19 @@ var ( NewMsgSetWithdrawAddress = types.NewMsgSetWithdrawAddress NewMsgWithdrawDelegatorReward = types.NewMsgWithdrawDelegatorReward NewMsgWithdrawValidatorCommission = types.NewMsgWithdrawValidatorCommission + NewCommunityPoolSpendProposal = types.NewCommunityPoolSpendProposal + NewQueryValidatorOutstandingRewardsParams = types.NewQueryValidatorOutstandingRewardsParams + NewQueryValidatorCommissionParams = types.NewQueryValidatorCommissionParams + NewQueryValidatorSlashesParams = types.NewQueryValidatorSlashesParams + NewQueryDelegationRewardsParams = types.NewQueryDelegationRewardsParams + NewQueryDelegatorParams = types.NewQueryDelegatorParams + NewQueryDelegatorWithdrawAddrParams = types.NewQueryDelegatorWithdrawAddrParams NewQueryDelegatorTotalRewardsResponse = types.NewQueryDelegatorTotalRewardsResponse NewDelegationDelegatorReward = types.NewDelegationDelegatorReward NewValidatorHistoricalRewards = types.NewValidatorHistoricalRewards NewValidatorCurrentRewards = types.NewValidatorCurrentRewards InitialValidatorAccumulatedCommission = types.InitialValidatorAccumulatedCommission NewValidatorSlashEvent = types.NewValidatorSlashEvent - NewCommunityPoolSpendProposal = types.NewCommunityPoolSpendProposal // variable aliases FeePoolKey = keeper.FeePoolKey @@ -126,12 +130,6 @@ var ( type ( Hooks = keeper.Hooks Keeper = keeper.Keeper - QueryValidatorOutstandingRewardsParams = keeper.QueryValidatorOutstandingRewardsParams - QueryValidatorCommissionParams = keeper.QueryValidatorCommissionParams - QueryValidatorSlashesParams = keeper.QueryValidatorSlashesParams - QueryDelegationRewardsParams = keeper.QueryDelegationRewardsParams - QueryDelegatorParams = keeper.QueryDelegatorParams - QueryDelegatorWithdrawAddrParams = keeper.QueryDelegatorWithdrawAddrParams DummyFeeCollectionKeeper = keeper.DummyFeeCollectionKeeper DelegatorStartingInfo = types.DelegatorStartingInfo CodeType = types.CodeType @@ -146,11 +144,17 @@ type ( ValidatorCurrentRewardsRecord = types.ValidatorCurrentRewardsRecord DelegatorStartingInfoRecord = types.DelegatorStartingInfoRecord ValidatorSlashEventRecord = types.ValidatorSlashEventRecord - CommunityPoolSpendProposal = types.CommunityPoolSpendProposal GenesisState = types.GenesisState MsgSetWithdrawAddress = types.MsgSetWithdrawAddress MsgWithdrawDelegatorReward = types.MsgWithdrawDelegatorReward MsgWithdrawValidatorCommission = types.MsgWithdrawValidatorCommission + CommunityPoolSpendProposal = types.CommunityPoolSpendProposal + QueryValidatorOutstandingRewardsParams = types.QueryValidatorOutstandingRewardsParams + QueryValidatorCommissionParams = types.QueryValidatorCommissionParams + QueryValidatorSlashesParams = types.QueryValidatorSlashesParams + QueryDelegationRewardsParams = types.QueryDelegationRewardsParams + QueryDelegatorParams = types.QueryDelegatorParams + QueryDelegatorWithdrawAddrParams = types.QueryDelegatorWithdrawAddrParams QueryDelegatorTotalRewardsResponse = types.QueryDelegatorTotalRewardsResponse DelegationDelegatorReward = types.DelegationDelegatorReward ValidatorHistoricalRewards = types.ValidatorHistoricalRewards diff --git a/x/distribution/client/cli/query.go b/x/distribution/client/cli/query.go index 0013d3d08640..b1c1dd97be4f 100644 --- a/x/distribution/client/cli/query.go +++ b/x/distribution/client/cli/query.go @@ -7,15 +7,38 @@ import ( "github.com/spf13/cobra" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client/utils" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" - distr "github.com/cosmos/cosmos-sdk/x/distribution" "github.com/cosmos/cosmos-sdk/x/distribution/client/common" "github.com/cosmos/cosmos-sdk/x/distribution/types" ) +// GetQueryCmd returns the cli query commands for this module +func GetQueryCmd(queryRoute string, cdc *codec.Codec) *cobra.Command { + distQueryCmd := &cobra.Command{ + Use: types.ModuleName, + Short: "Querying commands for the distribution module", + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: utils.ValidateCmd, + } + + distQueryCmd.AddCommand(client.GetCommands( + GetCmdQueryParams(queryRoute, cdc), + GetCmdQueryValidatorOutstandingRewards(queryRoute, cdc), + GetCmdQueryValidatorCommission(queryRoute, cdc), + GetCmdQueryValidatorSlashes(queryRoute, cdc), + GetCmdQueryDelegatorRewards(queryRoute, cdc), + GetCmdQueryCommunityPool(queryRoute, cdc), + )...) + + return distQueryCmd +} + // GetCmdQueryParams implements the query params command. func GetCmdQueryParams(queryRoute string, cdc *codec.Codec) *cobra.Command { return &cobra.Command{ @@ -123,7 +146,7 @@ $ %s query distr slashes cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj 0 return fmt.Errorf("end-height %s not a valid uint, please input a valid end-height", args[2]) } - params := distr.NewQueryValidatorSlashesParams(validatorAddr, startHeight, endHeight) + params := types.NewQueryValidatorSlashesParams(validatorAddr, startHeight, endHeight) bz, err := cdc.MarshalJSON(params) if err != nil { return err @@ -178,7 +201,7 @@ $ %s query distr rewards cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p cosmosval return err } - var result distr.QueryDelegatorTotalRewardsResponse + var result types.QueryDelegatorTotalRewardsResponse cdc.MustUnmarshalJSON(resp, &result) return cliCtx.PrintOutput(result) }, diff --git a/x/distribution/client/cli/tx.go b/x/distribution/client/cli/tx.go index 44c737085417..83a5b2f24725 100644 --- a/x/distribution/client/cli/tx.go +++ b/x/distribution/client/cli/tx.go @@ -7,7 +7,6 @@ import ( "github.com/spf13/cobra" "github.com/spf13/viper" - amino "github.com/tendermint/go-amino" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/context" @@ -15,8 +14,8 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" - authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" - "github.com/cosmos/cosmos-sdk/x/gov" + auth "github.com/cosmos/cosmos-sdk/x/auth" + gov "github.com/cosmos/cosmos-sdk/x/gov" "github.com/cosmos/cosmos-sdk/x/distribution/client/common" "github.com/cosmos/cosmos-sdk/x/distribution/types" @@ -34,26 +33,30 @@ const ( ) // GetTxCmd returns the transaction commands for this module -func GetTxCmd(storeKey string, cdc *amino.Codec) *cobra.Command { +func GetTxCmd(storeKey string, cdc *codec.Codec) *cobra.Command { distTxCmd := &cobra.Command{ - Use: "dist", - Short: "Distribution transactions subcommands", + Use: types.ModuleName, + Short: "Distribution transactions subcommands", + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: utils.ValidateCmd, } distTxCmd.AddCommand(client.PostCommands( GetCmdWithdrawRewards(cdc), GetCmdSetWithdrawAddr(cdc), + GetCmdWithdrawAllRewards(cdc, storeKey), )...) return distTxCmd } -type generateOrBroadcastFunc func(context.CLIContext, authtxb.TxBuilder, []sdk.Msg) error +type generateOrBroadcastFunc func(context.CLIContext, auth.TxBuilder, []sdk.Msg) error func splitAndApply( generateOrBroadcast generateOrBroadcastFunc, cliCtx context.CLIContext, - txBldr authtxb.TxBuilder, + txBldr auth.TxBuilder, msgs []sdk.Msg, chunkSize int, ) error { @@ -98,7 +101,7 @@ $ %s tx distr withdraw-rewards cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqh ), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) cliCtx := context.NewCLIContext(). WithCodec(cdc). WithAccountDecoder(cdc) @@ -138,7 +141,7 @@ $ %s tx distr withdraw-all-rewards --from mykey Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) cliCtx := context.NewCLIContext(). WithCodec(cdc). WithAccountDecoder(cdc) @@ -174,7 +177,7 @@ $ %s tx set-withdraw-addr cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p --from m Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) cliCtx := context.NewCLIContext(). WithCodec(cdc). WithAccountDecoder(cdc) @@ -228,7 +231,7 @@ Where proposal.json contains: ), ), RunE: func(cmd *cobra.Command, args []string) error { - txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) cliCtx := context.NewCLIContext(). WithCodec(cdc). WithAccountDecoder(cdc) diff --git a/x/distribution/client/cli/tx_test.go b/x/distribution/client/cli/tx_test.go index c8f80f553f97..6996464086f2 100644 --- a/x/distribution/client/cli/tx_test.go +++ b/x/distribution/client/cli/tx_test.go @@ -1,19 +1,21 @@ package cli import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/tendermint/tendermint/crypto/secp256k1" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/utils" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" - "github.com/stretchr/testify/assert" - "github.com/tendermint/tendermint/crypto/secp256k1" - "testing" + auth "github.com/cosmos/cosmos-sdk/x/auth" ) -func createFakeTxBuilder() authtxb.TxBuilder { +func createFakeTxBuilder() auth.TxBuilder { cdc := codec.New() - return authtxb.NewTxBuilder( + return auth.NewTxBuilder( utils.GetTxEncoder(cdc), 123, 9876, @@ -55,8 +57,8 @@ func Test_splitAndCall_Splitting(t *testing.T) { callCount := 0 err := splitAndApply( - func(ctx context.CLIContext, txBldr authtxb.TxBuilder, msgs []sdk.Msg) error { - callCount += 1 + func(ctx context.CLIContext, txBldr auth.TxBuilder, msgs []sdk.Msg) error { + callCount++ assert.NotNil(t, ctx) assert.NotNil(t, txBldr) diff --git a/x/distribution/client/common/common.go b/x/distribution/client/common/common.go index 2f2f6b38b6c9..f1b8e4ef4698 100644 --- a/x/distribution/client/common/common.go +++ b/x/distribution/client/common/common.go @@ -6,31 +6,31 @@ import ( "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - distr "github.com/cosmos/cosmos-sdk/x/distribution" + "github.com/cosmos/cosmos-sdk/x/distribution/types" ) // QueryParams actually queries distribution params. func QueryParams(cliCtx context.CLIContext, queryRoute string) (PrettyParams, error) { - route := fmt.Sprintf("custom/%s/params/%s", queryRoute, distr.ParamCommunityTax) + route := fmt.Sprintf("custom/%s/params/%s", queryRoute, types.ParamCommunityTax) retCommunityTax, err := cliCtx.QueryWithData(route, []byte{}) if err != nil { return PrettyParams{}, err } - route = fmt.Sprintf("custom/%s/params/%s", queryRoute, distr.ParamBaseProposerReward) + route = fmt.Sprintf("custom/%s/params/%s", queryRoute, types.ParamBaseProposerReward) retBaseProposerReward, err := cliCtx.QueryWithData(route, []byte{}) if err != nil { return PrettyParams{}, err } - route = fmt.Sprintf("custom/%s/params/%s", queryRoute, distr.ParamBonusProposerReward) + route = fmt.Sprintf("custom/%s/params/%s", queryRoute, types.ParamBonusProposerReward) retBonusProposerReward, err := cliCtx.QueryWithData(route, []byte{}) if err != nil { return PrettyParams{}, err } - route = fmt.Sprintf("custom/%s/params/%s", queryRoute, distr.ParamWithdrawAddrEnabled) + route = fmt.Sprintf("custom/%s/params/%s", queryRoute, types.ParamWithdrawAddrEnabled) retWithdrawAddrEnabled, err := cliCtx.QueryWithData(route, []byte{}) if err != nil { return PrettyParams{}, err @@ -50,8 +50,8 @@ func QueryDelegatorTotalRewards(cliCtx context.CLIContext, cdc *codec.Codec, } return cliCtx.QueryWithData( - fmt.Sprintf("custom/%s/%s", queryRoute, distr.QueryDelegatorTotalRewards), - cdc.MustMarshalJSON(distr.NewQueryDelegatorParams(delegatorAddr)), + fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryDelegatorTotalRewards), + cdc.MustMarshalJSON(types.NewQueryDelegatorParams(delegatorAddr)), ) } @@ -69,8 +69,8 @@ func QueryDelegationRewards(cliCtx context.CLIContext, cdc *codec.Codec, } return cliCtx.QueryWithData( - fmt.Sprintf("custom/%s/%s", queryRoute, distr.QueryDelegationRewards), - cdc.MustMarshalJSON(distr.NewQueryDelegationRewardsParams(delegatorAddr, validatorAddr)), + fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryDelegationRewards), + cdc.MustMarshalJSON(types.NewQueryDelegationRewardsParams(delegatorAddr, validatorAddr)), ) } @@ -80,8 +80,8 @@ func QueryDelegatorValidators(cliCtx context.CLIContext, cdc *codec.Codec, queryRoute string, delegatorAddr sdk.AccAddress) ([]byte, error) { return cliCtx.QueryWithData( - fmt.Sprintf("custom/%s/%s", queryRoute, distr.QueryDelegatorValidators), - cdc.MustMarshalJSON(distr.NewQueryDelegatorParams(delegatorAddr)), + fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryDelegatorValidators), + cdc.MustMarshalJSON(types.NewQueryDelegatorParams(delegatorAddr)), ) } @@ -90,8 +90,8 @@ func QueryValidatorCommission(cliCtx context.CLIContext, cdc *codec.Codec, queryRoute string, validatorAddr sdk.ValAddress) ([]byte, error) { return cliCtx.QueryWithData( - fmt.Sprintf("custom/%s/%s", queryRoute, distr.QueryValidatorCommission), - cdc.MustMarshalJSON(distr.NewQueryValidatorCommissionParams(validatorAddr)), + fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryValidatorCommission), + cdc.MustMarshalJSON(types.NewQueryValidatorCommissionParams(validatorAddr)), ) } @@ -115,7 +115,7 @@ func WithdrawAllDelegatorRewards(cliCtx context.CLIContext, cdc *codec.Codec, // build multi-message transaction var msgs []sdk.Msg for _, valAddr := range validators { - msg := distr.NewMsgWithdrawDelegatorReward(delegatorAddr, valAddr) + msg := types.NewMsgWithdrawDelegatorReward(delegatorAddr, valAddr) if err := msg.ValidateBasic(); err != nil { return nil, err } @@ -129,13 +129,13 @@ func WithdrawAllDelegatorRewards(cliCtx context.CLIContext, cdc *codec.Codec, // used to withdraw both validation's commission and self-delegation reward. func WithdrawValidatorRewardsAndCommission(validatorAddr sdk.ValAddress) ([]sdk.Msg, error) { - commissionMsg := distr.NewMsgWithdrawValidatorCommission(validatorAddr) + commissionMsg := types.NewMsgWithdrawValidatorCommission(validatorAddr) if err := commissionMsg.ValidateBasic(); err != nil { return nil, err } // build and validate MsgWithdrawDelegatorReward - rewardMsg := distr.NewMsgWithdrawDelegatorReward( + rewardMsg := types.NewMsgWithdrawDelegatorReward( sdk.AccAddress(validatorAddr.Bytes()), validatorAddr) if err := rewardMsg.ValidateBasic(); err != nil { return nil, err diff --git a/x/distribution/client/module_client.go b/x/distribution/client/module_client.go deleted file mode 100644 index 5f3c874686c2..000000000000 --- a/x/distribution/client/module_client.go +++ /dev/null @@ -1,62 +0,0 @@ -package client - -import ( - "github.com/spf13/cobra" - amino "github.com/tendermint/go-amino" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/utils" - dist "github.com/cosmos/cosmos-sdk/x/distribution" - distCmds "github.com/cosmos/cosmos-sdk/x/distribution/client/cli" -) - -// ModuleClient exports all client functionality from this module -type ModuleClient struct { - storeKey string - cdc *amino.Codec -} - -func NewModuleClient(storeKey string, cdc *amino.Codec) ModuleClient { - return ModuleClient{storeKey, cdc} -} - -// GetQueryCmd returns the cli query commands for this module -func (mc ModuleClient) GetQueryCmd() *cobra.Command { - distQueryCmd := &cobra.Command{ - Use: dist.ModuleName, - Short: "Querying commands for the distribution module", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: utils.ValidateCmd, - } - - distQueryCmd.AddCommand(client.GetCommands( - distCmds.GetCmdQueryParams(mc.storeKey, mc.cdc), - distCmds.GetCmdQueryValidatorOutstandingRewards(mc.storeKey, mc.cdc), - distCmds.GetCmdQueryValidatorCommission(mc.storeKey, mc.cdc), - distCmds.GetCmdQueryValidatorSlashes(mc.storeKey, mc.cdc), - distCmds.GetCmdQueryDelegatorRewards(mc.storeKey, mc.cdc), - distCmds.GetCmdQueryCommunityPool(mc.storeKey, mc.cdc), - )...) - - return distQueryCmd -} - -// GetTxCmd returns the transaction commands for this module -func (mc ModuleClient) GetTxCmd() *cobra.Command { - distTxCmd := &cobra.Command{ - Use: dist.ModuleName, - Short: "Distribution transactions subcommands", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: utils.ValidateCmd, - } - - distTxCmd.AddCommand(client.PostCommands( - distCmds.GetCmdWithdrawRewards(mc.cdc), - distCmds.GetCmdSetWithdrawAddr(mc.cdc), - distCmds.GetCmdWithdrawAllRewards(mc.cdc, mc.storeKey), - )...) - - return distTxCmd -} diff --git a/x/distribution/client/proposal_handler.go b/x/distribution/client/proposal_handler.go new file mode 100644 index 000000000000..6514d8f5a242 --- /dev/null +++ b/x/distribution/client/proposal_handler.go @@ -0,0 +1,10 @@ +package client + +import ( + "github.com/cosmos/cosmos-sdk/x/distribution/client/cli" + "github.com/cosmos/cosmos-sdk/x/distribution/client/rest" + govclient "github.com/cosmos/cosmos-sdk/x/gov/client" +) + +// param change proposal handler +var ProposalHandler = govclient.NewProposalHandler(cli.GetCmdSubmitProposal, rest.ProposalRESTHandler) diff --git a/x/distribution/client/rest/query.go b/x/distribution/client/rest/query.go index 919574b5eece..a47b00018010 100644 --- a/x/distribution/client/rest/query.go +++ b/x/distribution/client/rest/query.go @@ -6,7 +6,6 @@ import ( "github.com/gorilla/mux" - "github.com/cosmos/cosmos-sdk/x/distribution" "github.com/cosmos/cosmos-sdk/x/distribution/client/common" "github.com/cosmos/cosmos-sdk/x/distribution/types" @@ -111,7 +110,7 @@ func delegatorWithdrawalAddrHandlerFn(cliCtx context.CLIContext, cdc *codec.Code return } - bz := cdc.MustMarshalJSON(distribution.NewQueryDelegatorWithdrawAddrParams(delegatorAddr)) + bz := cdc.MustMarshalJSON(types.NewQueryDelegatorWithdrawAddrParams(delegatorAddr)) res, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/withdraw_addr", queryRoute), bz) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) @@ -243,7 +242,7 @@ func outstandingRewardsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec, return } - bin := cdc.MustMarshalJSON(distribution.NewQueryValidatorOutstandingRewardsParams(validatorAddr)) + bin := cdc.MustMarshalJSON(types.NewQueryValidatorOutstandingRewardsParams(validatorAddr)) res, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/validator_outstanding_rewards", queryRoute), bin) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) diff --git a/x/distribution/client/rest/rest.go b/x/distribution/client/rest/rest.go index 49650c59d9c3..1468674c5583 100644 --- a/x/distribution/client/rest/rest.go +++ b/x/distribution/client/rest/rest.go @@ -1,15 +1,16 @@ package rest import ( - "github.com/gorilla/mux" "net/http" + "github.com/gorilla/mux" + "github.com/cosmos/cosmos-sdk/client/context" clientrest "github.com/cosmos/cosmos-sdk/client/rest" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/distribution" + "github.com/cosmos/cosmos-sdk/x/distribution/types" "github.com/cosmos/cosmos-sdk/x/gov" govrest "github.com/cosmos/cosmos-sdk/x/gov/client/rest" ) @@ -40,7 +41,7 @@ func postProposalHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.Han return } - content := distribution.NewCommunityPoolSpendProposal(req.Title, req.Description, req.Recipient, req.Amount) + content := types.NewCommunityPoolSpendProposal(req.Title, req.Description, req.Recipient, req.Amount) msg := gov.NewMsgSubmitProposal(content, req.Deposit, req.Proposer) if err := msg.ValidateBasic(); err != nil { diff --git a/x/distribution/keeper/proposal_handler.go b/x/distribution/keeper/proposal_handler.go index a8c3a4f596f7..70b0bebaa309 100644 --- a/x/distribution/keeper/proposal_handler.go +++ b/x/distribution/keeper/proposal_handler.go @@ -7,6 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/distribution/types" ) +// Handler for executing a passed community spend proposal func HandleCommunityPoolSpendProposal(ctx sdk.Context, k Keeper, p types.CommunityPoolSpendProposal) sdk.Error { feePool := k.GetFeePool(ctx) newPool, negative := feePool.CommunityPool.SafeSub(sdk.NewDecCoins(p.Amount)) diff --git a/x/distribution/keeper/querier.go b/x/distribution/keeper/querier.go index 200620674179..25bc5c846d68 100644 --- a/x/distribution/keeper/querier.go +++ b/x/distribution/keeper/querier.go @@ -12,52 +12,34 @@ import ( "github.com/cosmos/cosmos-sdk/x/staking/exported" ) -// nolint -const ( - QueryParams = "params" - QueryValidatorOutstandingRewards = "validator_outstanding_rewards" - QueryValidatorCommission = "validator_commission" - QueryValidatorSlashes = "validator_slashes" - QueryDelegationRewards = "delegation_rewards" - QueryDelegatorTotalRewards = "delegator_total_rewards" - QueryDelegatorValidators = "delegator_validators" - QueryWithdrawAddr = "withdraw_addr" - QueryCommunityPool = "community_pool" - - ParamCommunityTax = "community_tax" - ParamBaseProposerReward = "base_proposer_reward" - ParamBonusProposerReward = "bonus_proposer_reward" - ParamWithdrawAddrEnabled = "withdraw_addr_enabled" -) - func NewQuerier(k Keeper) sdk.Querier { return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, sdk.Error) { switch path[0] { - case QueryParams: + case types.QueryParams: return queryParams(ctx, path[1:], req, k) - case QueryValidatorOutstandingRewards: + case types.QueryValidatorOutstandingRewards: return queryValidatorOutstandingRewards(ctx, path[1:], req, k) - case QueryValidatorCommission: + case types.QueryValidatorCommission: return queryValidatorCommission(ctx, path[1:], req, k) - case QueryValidatorSlashes: + case types.QueryValidatorSlashes: return queryValidatorSlashes(ctx, path[1:], req, k) - case QueryDelegationRewards: + case types.QueryDelegationRewards: return queryDelegationRewards(ctx, path[1:], req, k) - case QueryDelegatorTotalRewards: + case types.QueryDelegatorTotalRewards: return queryDelegatorTotalRewards(ctx, path[1:], req, k) - case QueryDelegatorValidators: + case types.QueryDelegatorValidators: return queryDelegatorValidators(ctx, path[1:], req, k) - case QueryWithdrawAddr: + case types.QueryWithdrawAddr: return queryDelegatorWithdrawAddress(ctx, path[1:], req, k) - case QueryCommunityPool: + case types.QueryCommunityPool: return queryCommunityPool(ctx, path[1:], req, k) default: @@ -68,25 +50,25 @@ func NewQuerier(k Keeper) sdk.Querier { func queryParams(ctx sdk.Context, path []string, req abci.RequestQuery, k Keeper) ([]byte, sdk.Error) { switch path[0] { - case ParamCommunityTax: + case types.ParamCommunityTax: bz, err := codec.MarshalJSONIndent(k.cdc, k.GetCommunityTax(ctx)) if err != nil { return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could not marshal result to JSON", err.Error())) } return bz, nil - case ParamBaseProposerReward: + case types.ParamBaseProposerReward: bz, err := codec.MarshalJSONIndent(k.cdc, k.GetBaseProposerReward(ctx)) if err != nil { return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could not marshal result to JSON", err.Error())) } return bz, nil - case ParamBonusProposerReward: + case types.ParamBonusProposerReward: bz, err := codec.MarshalJSONIndent(k.cdc, k.GetBonusProposerReward(ctx)) if err != nil { return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could not marshal result to JSON", err.Error())) } return bz, nil - case ParamWithdrawAddrEnabled: + case types.ParamWithdrawAddrEnabled: bz, err := codec.MarshalJSONIndent(k.cdc, k.GetWithdrawAddrEnabled(ctx)) if err != nil { return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could not marshal result to JSON", err.Error())) @@ -97,20 +79,8 @@ func queryParams(ctx sdk.Context, path []string, req abci.RequestQuery, k Keeper } } -// params for query 'custom/distr/validator_outstanding_rewards' -type QueryValidatorOutstandingRewardsParams struct { - ValidatorAddress sdk.ValAddress `json:"validator_address"` -} - -// creates a new instance of QueryValidatorOutstandingRewardsParams -func NewQueryValidatorOutstandingRewardsParams(validatorAddr sdk.ValAddress) QueryValidatorOutstandingRewardsParams { - return QueryValidatorOutstandingRewardsParams{ - ValidatorAddress: validatorAddr, - } -} - func queryValidatorOutstandingRewards(ctx sdk.Context, path []string, req abci.RequestQuery, k Keeper) ([]byte, sdk.Error) { - var params QueryValidatorOutstandingRewardsParams + var params types.QueryValidatorOutstandingRewardsParams err := k.cdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { return nil, sdk.ErrUnknownRequest(sdk.AppendMsgToErr("incorrectly formatted request data", err.Error())) @@ -122,20 +92,8 @@ func queryValidatorOutstandingRewards(ctx sdk.Context, path []string, req abci.R return bz, nil } -// params for query 'custom/distr/validator_commission' -type QueryValidatorCommissionParams struct { - ValidatorAddress sdk.ValAddress `json:"validator_address"` -} - -// creates a new instance of QueryValidatorCommissionParams -func NewQueryValidatorCommissionParams(validatorAddr sdk.ValAddress) QueryValidatorCommissionParams { - return QueryValidatorCommissionParams{ - ValidatorAddress: validatorAddr, - } -} - func queryValidatorCommission(ctx sdk.Context, path []string, req abci.RequestQuery, k Keeper) ([]byte, sdk.Error) { - var params QueryValidatorCommissionParams + var params types.QueryValidatorCommissionParams err := k.cdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { return nil, sdk.ErrUnknownRequest(sdk.AppendMsgToErr("incorrectly formatted request data", err.Error())) @@ -148,24 +106,8 @@ func queryValidatorCommission(ctx sdk.Context, path []string, req abci.RequestQu return bz, nil } -// params for query 'custom/distr/validator_slashes' -type QueryValidatorSlashesParams struct { - ValidatorAddress sdk.ValAddress `json:"validator_address"` - StartingHeight uint64 `json:"starting_height"` - EndingHeight uint64 `json:"ending_height"` -} - -// creates a new instance of QueryValidatorSlashesParams -func NewQueryValidatorSlashesParams(validatorAddr sdk.ValAddress, startingHeight uint64, endingHeight uint64) QueryValidatorSlashesParams { - return QueryValidatorSlashesParams{ - ValidatorAddress: validatorAddr, - StartingHeight: startingHeight, - EndingHeight: endingHeight, - } -} - func queryValidatorSlashes(ctx sdk.Context, path []string, req abci.RequestQuery, k Keeper) ([]byte, sdk.Error) { - var params QueryValidatorSlashesParams + var params types.QueryValidatorSlashesParams err := k.cdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { return nil, sdk.ErrUnknownRequest(sdk.AppendMsgToErr("incorrectly formatted request data", err.Error())) @@ -184,22 +126,8 @@ func queryValidatorSlashes(ctx sdk.Context, path []string, req abci.RequestQuery return bz, nil } -// params for query 'custom/distr/delegation_rewards' -type QueryDelegationRewardsParams struct { - DelegatorAddress sdk.AccAddress `json:"delegator_address"` - ValidatorAddress sdk.ValAddress `json:"validator_address"` -} - -// creates a new instance of QueryDelegationRewardsParams -func NewQueryDelegationRewardsParams(delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress) QueryDelegationRewardsParams { - return QueryDelegationRewardsParams{ - DelegatorAddress: delegatorAddr, - ValidatorAddress: validatorAddr, - } -} - func queryDelegationRewards(ctx sdk.Context, _ []string, req abci.RequestQuery, k Keeper) ([]byte, sdk.Error) { - var params QueryDelegationRewardsParams + var params types.QueryDelegationRewardsParams err := k.cdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { return nil, sdk.ErrUnknownRequest(sdk.AppendMsgToErr("incorrectly formatted request data", err.Error())) @@ -231,20 +159,8 @@ func queryDelegationRewards(ctx sdk.Context, _ []string, req abci.RequestQuery, return bz, nil } -// params for query 'custom/distr/delegator_total_rewards' and 'custom/distr/delegator_validators' -type QueryDelegatorParams struct { - DelegatorAddress sdk.AccAddress `json:"delegator_address"` -} - -// creates a new instance of QueryDelegationRewardsParams -func NewQueryDelegatorParams(delegatorAddr sdk.AccAddress) QueryDelegatorParams { - return QueryDelegatorParams{ - DelegatorAddress: delegatorAddr, - } -} - func queryDelegatorTotalRewards(ctx sdk.Context, _ []string, req abci.RequestQuery, k Keeper) ([]byte, sdk.Error) { - var params QueryDelegatorParams + var params types.QueryDelegatorParams err := k.cdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { return nil, sdk.ErrUnknownRequest(sdk.AppendMsgToErr("incorrectly formatted request data", err.Error())) @@ -280,7 +196,7 @@ func queryDelegatorTotalRewards(ctx sdk.Context, _ []string, req abci.RequestQue } func queryDelegatorValidators(ctx sdk.Context, _ []string, req abci.RequestQuery, k Keeper) ([]byte, sdk.Error) { - var params QueryDelegatorParams + var params types.QueryDelegatorParams err := k.cdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { return nil, sdk.ErrUnknownRequest(sdk.AppendMsgToErr("incorrectly formatted request data", err.Error())) @@ -306,18 +222,8 @@ func queryDelegatorValidators(ctx sdk.Context, _ []string, req abci.RequestQuery return bz, nil } -// params for query 'custom/distr/withdraw_addr' -type QueryDelegatorWithdrawAddrParams struct { - DelegatorAddress sdk.AccAddress `json:"delegator_address"` -} - -// NewQueryDelegatorWithdrawAddrParams creates a new instance of QueryDelegatorWithdrawAddrParams. -func NewQueryDelegatorWithdrawAddrParams(delegatorAddr sdk.AccAddress) QueryDelegatorWithdrawAddrParams { - return QueryDelegatorWithdrawAddrParams{DelegatorAddress: delegatorAddr} -} - func queryDelegatorWithdrawAddress(ctx sdk.Context, _ []string, req abci.RequestQuery, k Keeper) ([]byte, sdk.Error) { - var params QueryDelegatorWithdrawAddrParams + var params types.QueryDelegatorWithdrawAddrParams err := k.cdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { return nil, sdk.ErrUnknownRequest(sdk.AppendMsgToErr("incorrectly formatted request data", err.Error())) diff --git a/x/distribution/keeper/querier_test.go b/x/distribution/keeper/querier_test.go index 9ef818f4d24c..1709a9cb5293 100644 --- a/x/distribution/keeper/querier_test.go +++ b/x/distribution/keeper/querier_test.go @@ -19,38 +19,38 @@ const custom = "custom" func getQueriedParams(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier) (communityTax sdk.Dec, baseProposerReward sdk.Dec, bonusProposerReward sdk.Dec, withdrawAddrEnabled bool) { query := abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, QueryParams, ParamCommunityTax}, "/"), + Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryParams, types.ParamCommunityTax}, "/"), Data: []byte{}, } - bz, err := querier(ctx, []string{QueryParams, ParamCommunityTax}, query) + bz, err := querier(ctx, []string{types.QueryParams, types.ParamCommunityTax}, query) require.Nil(t, err) require.Nil(t, cdc.UnmarshalJSON(bz, &communityTax)) query = abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, QueryParams, ParamBaseProposerReward}, "/"), + Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryParams, types.ParamBaseProposerReward}, "/"), Data: []byte{}, } - bz, err = querier(ctx, []string{QueryParams, ParamBaseProposerReward}, query) + bz, err = querier(ctx, []string{types.QueryParams, types.ParamBaseProposerReward}, query) require.Nil(t, err) require.Nil(t, cdc.UnmarshalJSON(bz, &baseProposerReward)) query = abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, QueryParams, ParamBonusProposerReward}, "/"), + Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryParams, types.ParamBonusProposerReward}, "/"), Data: []byte{}, } - bz, err = querier(ctx, []string{QueryParams, ParamBonusProposerReward}, query) + bz, err = querier(ctx, []string{types.QueryParams, types.ParamBonusProposerReward}, query) require.Nil(t, err) require.Nil(t, cdc.UnmarshalJSON(bz, &bonusProposerReward)) query = abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, QueryParams, ParamWithdrawAddrEnabled}, "/"), + Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryParams, types.ParamWithdrawAddrEnabled}, "/"), Data: []byte{}, } - bz, err = querier(ctx, []string{QueryParams, ParamWithdrawAddrEnabled}, query) + bz, err = querier(ctx, []string{types.QueryParams, types.ParamWithdrawAddrEnabled}, query) require.Nil(t, err) require.Nil(t, cdc.UnmarshalJSON(bz, &withdrawAddrEnabled)) @@ -59,11 +59,11 @@ func getQueriedParams(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier s func getQueriedValidatorOutstandingRewards(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier, validatorAddr sdk.ValAddress) (outstandingRewards sdk.DecCoins) { query := abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, QueryValidatorOutstandingRewards}, "/"), - Data: cdc.MustMarshalJSON(NewQueryValidatorOutstandingRewardsParams(validatorAddr)), + Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryValidatorOutstandingRewards}, "/"), + Data: cdc.MustMarshalJSON(types.NewQueryValidatorOutstandingRewardsParams(validatorAddr)), } - bz, err := querier(ctx, []string{QueryValidatorOutstandingRewards}, query) + bz, err := querier(ctx, []string{types.QueryValidatorOutstandingRewards}, query) require.Nil(t, err) require.Nil(t, cdc.UnmarshalJSON(bz, &outstandingRewards)) @@ -72,11 +72,11 @@ func getQueriedValidatorOutstandingRewards(t *testing.T, ctx sdk.Context, cdc *c func getQueriedValidatorCommission(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier, validatorAddr sdk.ValAddress) (validatorCommission sdk.DecCoins) { query := abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, QueryValidatorCommission}, "/"), - Data: cdc.MustMarshalJSON(NewQueryValidatorCommissionParams(validatorAddr)), + Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryValidatorCommission}, "/"), + Data: cdc.MustMarshalJSON(types.NewQueryValidatorCommissionParams(validatorAddr)), } - bz, err := querier(ctx, []string{QueryValidatorCommission}, query) + bz, err := querier(ctx, []string{types.QueryValidatorCommission}, query) require.Nil(t, err) require.Nil(t, cdc.UnmarshalJSON(bz, &validatorCommission)) @@ -85,11 +85,11 @@ func getQueriedValidatorCommission(t *testing.T, ctx sdk.Context, cdc *codec.Cod func getQueriedValidatorSlashes(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier, validatorAddr sdk.ValAddress, startHeight uint64, endHeight uint64) (slashes []types.ValidatorSlashEvent) { query := abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, QueryValidatorSlashes}, "/"), - Data: cdc.MustMarshalJSON(NewQueryValidatorSlashesParams(validatorAddr, startHeight, endHeight)), + Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryValidatorSlashes}, "/"), + Data: cdc.MustMarshalJSON(types.NewQueryValidatorSlashesParams(validatorAddr, startHeight, endHeight)), } - bz, err := querier(ctx, []string{QueryValidatorSlashes}, query) + bz, err := querier(ctx, []string{types.QueryValidatorSlashes}, query) require.Nil(t, err) require.Nil(t, cdc.UnmarshalJSON(bz, &slashes)) @@ -98,11 +98,11 @@ func getQueriedValidatorSlashes(t *testing.T, ctx sdk.Context, cdc *codec.Codec, func getQueriedDelegationRewards(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier, delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress) (rewards sdk.DecCoins) { query := abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, QueryDelegationRewards}, "/"), - Data: cdc.MustMarshalJSON(NewQueryDelegationRewardsParams(delegatorAddr, validatorAddr)), + Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryDelegationRewards}, "/"), + Data: cdc.MustMarshalJSON(types.NewQueryDelegationRewardsParams(delegatorAddr, validatorAddr)), } - bz, err := querier(ctx, []string{QueryDelegationRewards}, query) + bz, err := querier(ctx, []string{types.QueryDelegationRewards}, query) require.Nil(t, err) require.Nil(t, cdc.UnmarshalJSON(bz, &rewards)) @@ -111,11 +111,11 @@ func getQueriedDelegationRewards(t *testing.T, ctx sdk.Context, cdc *codec.Codec func getQueriedDelegatorTotalRewards(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier, delegatorAddr sdk.AccAddress) (response types.QueryDelegatorTotalRewardsResponse) { query := abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, QueryDelegatorTotalRewards}, "/"), - Data: cdc.MustMarshalJSON(NewQueryDelegatorParams(delegatorAddr)), + Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryDelegatorTotalRewards}, "/"), + Data: cdc.MustMarshalJSON(types.NewQueryDelegatorParams(delegatorAddr)), } - bz, err := querier(ctx, []string{QueryDelegatorTotalRewards}, query) + bz, err := querier(ctx, []string{types.QueryDelegatorTotalRewards}, query) require.Nil(t, err) require.Nil(t, cdc.UnmarshalJSON(bz, &response)) @@ -124,11 +124,11 @@ func getQueriedDelegatorTotalRewards(t *testing.T, ctx sdk.Context, cdc *codec.C func getQueriedCommunityPool(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier) (ptr []byte) { query := abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, QueryCommunityPool}, ""), + Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryCommunityPool}, ""), Data: []byte{}, } - cp, err := querier(ctx, []string{QueryCommunityPool}, query) + cp, err := querier(ctx, []string{types.QueryCommunityPool}, query) require.Nil(t, err) require.Nil(t, cdc.UnmarshalJSON(cp, &ptr)) diff --git a/x/distribution/module.go b/x/distribution/module.go index 03e7a5df1aa3..0d8b82d0827d 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -3,14 +3,22 @@ package distribution import ( "encoding/json" + "github.com/gorilla/mux" + "github.com/spf13/cobra" + + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - abci "github.com/tendermint/tendermint/abci/types" + "github.com/cosmos/cosmos-sdk/types/module" + "github.com/cosmos/cosmos-sdk/x/distribution/client/cli" + "github.com/cosmos/cosmos-sdk/x/distribution/client/rest" ) var ( - _ sdk.AppModule = AppModule{} - _ sdk.AppModuleBasic = AppModuleBasic{} + _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} ) // app module basics object @@ -41,6 +49,21 @@ func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { return ValidateGenesis(data) } +// register rest routes +func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router, cdc *codec.Codec) { + rest.RegisterRoutes(ctx, rtr, cdc, StoreKey) +} + +// get the root tx command of this module +func (AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command { + return cli.GetTxCmd(StoreKey, cdc) +} + +// get the root query command of this module +func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { + return cli.GetQueryCmd(StoreKey, cdc) +} + // app module type AppModule struct { AppModuleBasic diff --git a/x/distribution/types/codec.go b/x/distribution/types/codec.go index 269e01c4efbd..a2d4bf11eaae 100644 --- a/x/distribution/types/codec.go +++ b/x/distribution/types/codec.go @@ -16,8 +16,8 @@ func RegisterCodec(cdc *codec.Codec) { var ModuleCdc *codec.Codec func init() { - cdc := codec.New() - RegisterCodec(cdc) - codec.RegisterCrypto(cdc) - ModuleCdc = cdc.Seal() + ModuleCdc = codec.New() + RegisterCodec(ModuleCdc) + codec.RegisterCrypto(ModuleCdc) + ModuleCdc.Seal() } diff --git a/x/distribution/types/querier.go b/x/distribution/types/querier.go new file mode 100644 index 000000000000..1e4bf56dc6a0 --- /dev/null +++ b/x/distribution/types/querier.go @@ -0,0 +1,97 @@ +package types + +import sdk "github.com/cosmos/cosmos-sdk/types" + +// querier keys +const ( + QueryParams = "params" + QueryValidatorOutstandingRewards = "validator_outstanding_rewards" + QueryValidatorCommission = "validator_commission" + QueryValidatorSlashes = "validator_slashes" + QueryDelegationRewards = "delegation_rewards" + QueryDelegatorTotalRewards = "delegator_total_rewards" + QueryDelegatorValidators = "delegator_validators" + QueryWithdrawAddr = "withdraw_addr" + QueryCommunityPool = "community_pool" + + ParamCommunityTax = "community_tax" + ParamBaseProposerReward = "base_proposer_reward" + ParamBonusProposerReward = "bonus_proposer_reward" + ParamWithdrawAddrEnabled = "withdraw_addr_enabled" +) + +// params for query 'custom/distr/validator_outstanding_rewards' +type QueryValidatorOutstandingRewardsParams struct { + ValidatorAddress sdk.ValAddress `json:"validator_address"` +} + +// creates a new instance of QueryValidatorOutstandingRewardsParams +func NewQueryValidatorOutstandingRewardsParams(validatorAddr sdk.ValAddress) QueryValidatorOutstandingRewardsParams { + return QueryValidatorOutstandingRewardsParams{ + ValidatorAddress: validatorAddr, + } +} + +// params for query 'custom/distr/validator_commission' +type QueryValidatorCommissionParams struct { + ValidatorAddress sdk.ValAddress `json:"validator_address"` +} + +// creates a new instance of QueryValidatorCommissionParams +func NewQueryValidatorCommissionParams(validatorAddr sdk.ValAddress) QueryValidatorCommissionParams { + return QueryValidatorCommissionParams{ + ValidatorAddress: validatorAddr, + } +} + +// params for query 'custom/distr/validator_slashes' +type QueryValidatorSlashesParams struct { + ValidatorAddress sdk.ValAddress `json:"validator_address"` + StartingHeight uint64 `json:"starting_height"` + EndingHeight uint64 `json:"ending_height"` +} + +// creates a new instance of QueryValidatorSlashesParams +func NewQueryValidatorSlashesParams(validatorAddr sdk.ValAddress, startingHeight uint64, endingHeight uint64) QueryValidatorSlashesParams { + return QueryValidatorSlashesParams{ + ValidatorAddress: validatorAddr, + StartingHeight: startingHeight, + EndingHeight: endingHeight, + } +} + +// params for query 'custom/distr/delegation_rewards' +type QueryDelegationRewardsParams struct { + DelegatorAddress sdk.AccAddress `json:"delegator_address"` + ValidatorAddress sdk.ValAddress `json:"validator_address"` +} + +// creates a new instance of QueryDelegationRewardsParams +func NewQueryDelegationRewardsParams(delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress) QueryDelegationRewardsParams { + return QueryDelegationRewardsParams{ + DelegatorAddress: delegatorAddr, + ValidatorAddress: validatorAddr, + } +} + +// params for query 'custom/distr/delegator_total_rewards' and 'custom/distr/delegator_validators' +type QueryDelegatorParams struct { + DelegatorAddress sdk.AccAddress `json:"delegator_address"` +} + +// creates a new instance of QueryDelegationRewardsParams +func NewQueryDelegatorParams(delegatorAddr sdk.AccAddress) QueryDelegatorParams { + return QueryDelegatorParams{ + DelegatorAddress: delegatorAddr, + } +} + +// params for query 'custom/distr/withdraw_addr' +type QueryDelegatorWithdrawAddrParams struct { + DelegatorAddress sdk.AccAddress `json:"delegator_address"` +} + +// NewQueryDelegatorWithdrawAddrParams creates a new instance of QueryDelegatorWithdrawAddrParams. +func NewQueryDelegatorWithdrawAddrParams(delegatorAddr sdk.AccAddress) QueryDelegatorWithdrawAddrParams { + return QueryDelegatorWithdrawAddrParams{DelegatorAddress: delegatorAddr} +} diff --git a/x/genutil/client/cli/gentx.go b/x/genutil/client/cli/gentx.go index 859104d6d73a..bb04bc2ff638 100644 --- a/x/genutil/client/cli/gentx.go +++ b/x/genutil/client/cli/gentx.go @@ -24,9 +24,9 @@ import ( 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/types/module" "github.com/cosmos/cosmos-sdk/x/auth" - authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" "github.com/cosmos/cosmos-sdk/x/genutil" ) @@ -34,12 +34,12 @@ import ( 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) + BuildCreateValidatorMsg(cliCtx context.CLIContext, txBldr auth.TxBuilder) (auth.TxBuilder, sdk.Msg, error) } // GenTxCmd builds the application's gentx command. // nolint: errcheck -func GenTxCmd(ctx *server.Context, cdc *codec.Codec, mbm sdk.ModuleBasicManager, smbh StakingMsgBuildingHelpers, +func GenTxCmd(ctx *server.Context, cdc *codec.Codec, mbm module.BasicManager, smbh StakingMsgBuildingHelpers, genAccIterator genutil.GenesisAccountsIterator, defaultNodeHome, defaultCLIHome string) *cobra.Command { ipDefault, _ := server.ExternalIP() @@ -117,10 +117,10 @@ func GenTxCmd(ctx *server.Context, cdc *codec.Codec, mbm sdk.ModuleBasicManager, return err } - txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(client.GetTxEncoder(cdc)) + txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(client.GetTxEncoder(cdc)) cliCtx := client.NewCLIContext().WithCodec(cdc) - // XXX: Set the generate-only flag here after the CLI context has + // Set the generate-only flag here after the CLI context has // been created. This allows the from name/key to be correctly populated. // // TODO: Consider removing the manual setting of generate-only in diff --git a/x/genutil/client/cli/init.go b/x/genutil/client/cli/init.go index 0c2f04834e81..57ed063a4f74 100644 --- a/x/genutil/client/cli/init.go +++ b/x/genutil/client/cli/init.go @@ -16,7 +16,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/server" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/genutil" ) @@ -57,7 +57,7 @@ func displayInfo(cdc *codec.Codec, info printInfo) error { // InitCmd returns a command that initializes all files needed for Tendermint // and the respective application. -func InitCmd(ctx *server.Context, cdc *codec.Codec, mbm sdk.ModuleBasicManager, +func InitCmd(ctx *server.Context, cdc *codec.Codec, mbm module.BasicManager, defaultNodeHome string) *cobra.Command { // nolint: golint cmd := &cobra.Command{ Use: "init [moniker]", diff --git a/x/genutil/client/cli/init_test.go b/x/genutil/client/cli/init_test.go index f2f911db91d7..242646853279 100644 --- a/x/genutil/client/cli/init_test.go +++ b/x/genutil/client/cli/init_test.go @@ -20,10 +20,11 @@ import ( "github.com/cosmos/cosmos-sdk/server/mock" "github.com/cosmos/cosmos-sdk/tests" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/genutil" ) -var testMbm = sdk.NewModuleBasicManager(genutil.AppModuleBasic{}) +var testMbm = module.NewBasicManager(genutil.AppModuleBasic{}) func TestInitCmd(t *testing.T) { defer server.SetupViper(t)() diff --git a/x/genutil/client/cli/validate_genesis.go b/x/genutil/client/cli/validate_genesis.go index e7a1f850f572..f4baa5dc9df3 100644 --- a/x/genutil/client/cli/validate_genesis.go +++ b/x/genutil/client/cli/validate_genesis.go @@ -10,11 +10,11 @@ import ( "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/server" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" ) // Validate genesis command takes -func ValidateGenesisCmd(ctx *server.Context, cdc *codec.Codec, mbm sdk.ModuleBasicManager) *cobra.Command { +func ValidateGenesisCmd(ctx *server.Context, cdc *codec.Codec, mbm module.BasicManager) *cobra.Command { return &cobra.Command{ Use: "validate-genesis [file]", Args: cobra.RangeArgs(0, 1), diff --git a/x/genutil/codec.go b/x/genutil/codec.go index 80a3f6951ce4..a9752fa223c5 100644 --- a/x/genutil/codec.go +++ b/x/genutil/codec.go @@ -10,14 +10,13 @@ import ( // generic sealed codec to be used throughout this module var moduleCdc *codec.Codec +// TODO abstract genesis transactions registration back to staking +// required for genesis transactions func init() { - cdc := codec.New() - - // TODO abstract genesis transactions registration back to staking - // required for genesis transactions - staking.RegisterCodec(cdc) - auth.RegisterCodec(cdc) - sdk.RegisterCodec(cdc) - codec.RegisterCrypto(cdc) - moduleCdc = cdc.Seal() + moduleCdc = codec.New() + staking.RegisterCodec(moduleCdc) + auth.RegisterCodec(moduleCdc) + sdk.RegisterCodec(moduleCdc) + codec.RegisterCrypto(moduleCdc) + moduleCdc.Seal() } diff --git a/x/genutil/module.go b/x/genutil/module.go index ba69d4f54b7e..0b57912c8cc6 100644 --- a/x/genutil/module.go +++ b/x/genutil/module.go @@ -3,14 +3,20 @@ package genutil import ( "encoding/json" + "github.com/gorilla/mux" + "github.com/spf13/cobra" + + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - abci "github.com/tendermint/tendermint/abci/types" + "github.com/cosmos/cosmos-sdk/types/module" ) var ( - _ sdk.AppModuleGenesis = AppModule{} - _ sdk.AppModuleBasic = AppModuleBasic{} + _ module.AppModuleGenesis = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} ) // module name @@ -42,6 +48,16 @@ func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { return ValidateGenesis(data) } +// register rest routes +func (AppModuleBasic) RegisterRESTRoutes(_ context.CLIContext, _ *mux.Router, _ *codec.Codec) { +} + +// get the root tx command of this module +func (AppModuleBasic) GetTxCmd(_ *codec.Codec) *cobra.Command { return nil } + +// get the root query command of this module +func (AppModuleBasic) GetQueryCmd(_ *codec.Codec) *cobra.Command { return nil } + //___________________________ // app module type AppModule struct { @@ -53,9 +69,9 @@ type AppModule struct { // NewAppModule creates a new AppModule object func NewAppModule(accountKeeper AccountKeeper, - stakingKeeper StakingKeeper, deliverTx deliverTxfn) sdk.AppModule { + stakingKeeper StakingKeeper, deliverTx deliverTxfn) module.AppModule { - return sdk.NewGenesisOnlyAppModule(AppModule{ + return module.NewGenesisOnlyAppModule(AppModule{ AppModuleBasic: AppModuleBasic{}, accountKeeper: accountKeeper, stakingKeeper: stakingKeeper, diff --git a/x/gov/alias.go b/x/gov/alias.go index 766fa7914d97..9e3ed0ed070e 100644 --- a/x/gov/alias.go +++ b/x/gov/alias.go @@ -39,6 +39,17 @@ const ( StatusFailed = types.StatusFailed ProposalTypeText = types.ProposalTypeText ProposalTypeSoftwareUpgrade = types.ProposalTypeSoftwareUpgrade + QueryParams = types.QueryParams + QueryProposals = types.QueryProposals + QueryProposal = types.QueryProposal + QueryDeposits = types.QueryDeposits + QueryDeposit = types.QueryDeposit + QueryVotes = types.QueryVotes + QueryVote = types.QueryVote + QueryTally = types.QueryTally + ParamDeposit = types.ParamDeposit + ParamVoting = types.ParamVoting + ParamTallying = types.ParamTallying OptionEmpty = types.OptionEmpty OptionYes = types.OptionYes OptionAbstain = types.OptionAbstain @@ -79,6 +90,11 @@ var ( NewMsgSubmitProposal = types.NewMsgSubmitProposal NewMsgDeposit = types.NewMsgDeposit NewMsgVote = types.NewMsgVote + ParamKeyTable = types.ParamKeyTable + NewDepositParams = types.NewDepositParams + NewTallyParams = types.NewTallyParams + NewVotingParams = types.NewVotingParams + NewParams = types.NewParams NewProposal = types.NewProposal ProposalStatusFromString = types.ProposalStatusFromString ValidProposalStatus = types.ValidProposalStatus @@ -91,6 +107,10 @@ var ( ContentFromProposalType = types.ContentFromProposalType IsValidProposalType = types.IsValidProposalType ProposalHandler = types.ProposalHandler + NewQueryProposalParams = types.NewQueryProposalParams + NewQueryDepositParams = types.NewQueryDepositParams + NewQueryVoteParams = types.NewQueryVoteParams + NewQueryProposalsParams = types.NewQueryProposalsParams NewVote = types.NewVote VoteOptionFromString = types.VoteOptionFromString ValidVoteOption = types.ValidVoteOption @@ -103,6 +123,9 @@ var ( ProposalIDKey = types.ProposalIDKey DepositsKeyPrefix = types.DepositsKeyPrefix VotesKeyPrefix = types.VotesKeyPrefix + ParamStoreKeyDepositParams = types.ParamStoreKeyDepositParams + ParamStoreKeyVotingParams = types.ParamStoreKeyVotingParams + ParamStoreKeyTallyParams = types.ParamStoreKeyTallyParams ) type ( @@ -113,6 +136,10 @@ type ( MsgSubmitProposal = types.MsgSubmitProposal MsgDeposit = types.MsgDeposit MsgVote = types.MsgVote + DepositParams = types.DepositParams + TallyParams = types.TallyParams + VotingParams = types.VotingParams + Params = types.Params Proposal = types.Proposal Proposals = types.Proposals ProposalQueue = types.ProposalQueue @@ -120,6 +147,10 @@ type ( TallyResult = types.TallyResult TextProposal = types.TextProposal SoftwareUpgradeProposal = types.SoftwareUpgradeProposal + QueryProposalParams = types.QueryProposalParams + QueryDepositParams = types.QueryDepositParams + QueryVoteParams = types.QueryVoteParams + QueryProposalsParams = types.QueryProposalsParams Vote = types.Vote Votes = types.Votes VoteOption = types.VoteOption diff --git a/x/gov/client/cli/parse.go b/x/gov/client/cli/parse.go index f48aa34c5230..dd9415f18d19 100644 --- a/x/gov/client/cli/parse.go +++ b/x/gov/client/cli/parse.go @@ -7,7 +7,7 @@ import ( "github.com/spf13/viper" - govClientUtils "github.com/cosmos/cosmos-sdk/x/gov/client/utils" + govutils "github.com/cosmos/cosmos-sdk/x/gov/client/utils" ) func parseSubmitProposalFlags() (*proposal, error) { @@ -17,7 +17,7 @@ func parseSubmitProposalFlags() (*proposal, error) { if proposalFile == "" { proposal.Title = viper.GetString(FlagTitle) proposal.Description = viper.GetString(FlagDescription) - proposal.Type = govClientUtils.NormalizeProposalType(viper.GetString(flagProposalType)) + proposal.Type = govutils.NormalizeProposalType(viper.GetString(flagProposalType)) proposal.Deposit = viper.GetString(FlagDeposit) return proposal, nil } diff --git a/x/gov/client/cli/query.go b/x/gov/client/cli/query.go index fcb0eb636b09..c0418c1eb638 100644 --- a/x/gov/client/cli/query.go +++ b/x/gov/client/cli/query.go @@ -8,14 +8,42 @@ import ( "github.com/spf13/cobra" "github.com/spf13/viper" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client/utils" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" - "github.com/cosmos/cosmos-sdk/x/gov" gcutils "github.com/cosmos/cosmos-sdk/x/gov/client/utils" + "github.com/cosmos/cosmos-sdk/x/gov/types" ) +// GetQueryCmd returns the cli query commands for this module +func GetQueryCmd(queryRoute string, cdc *codec.Codec) *cobra.Command { + // Group gov queries under a subcommand + govQueryCmd := &cobra.Command{ + Use: types.ModuleName, + Short: "Querying commands for the governance module", + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: utils.ValidateCmd, + } + + govQueryCmd.AddCommand(client.GetCommands( + GetCmdQueryProposal(queryRoute, cdc), + GetCmdQueryProposals(queryRoute, cdc), + GetCmdQueryVote(queryRoute, cdc), + GetCmdQueryVotes(queryRoute, cdc), + GetCmdQueryParam(queryRoute, cdc), + GetCmdQueryParams(queryRoute, cdc), + GetCmdQueryProposer(queryRoute, cdc), + GetCmdQueryDeposit(queryRoute, cdc), + GetCmdQueryDeposits(queryRoute, cdc), + GetCmdQueryTally(queryRoute, cdc))...) + + return govQueryCmd +} + // GetCmdQueryProposal implements the query proposal command. func GetCmdQueryProposal(queryRoute string, cdc *codec.Codec) *cobra.Command { return &cobra.Command{ @@ -47,7 +75,7 @@ $ %s query gov proposal 1 return err } - var proposal gov.Proposal + var proposal types.Proposal cdc.MustUnmarshalJSON(res, &proposal) return cliCtx.PrintOutput(proposal) // nolint:errcheck }, @@ -78,9 +106,9 @@ $ %s query gov proposals --status (DepositPeriod|VotingPeriod|Passed|Rejected) var depositorAddr sdk.AccAddress var voterAddr sdk.AccAddress - var proposalStatus gov.ProposalStatus + var proposalStatus types.ProposalStatus - params := gov.NewQueryProposalsParams(proposalStatus, numLimit, voterAddr, depositorAddr) + params := types.NewQueryProposalsParams(proposalStatus, numLimit, voterAddr, depositorAddr) if len(bechDepositorAddr) != 0 { depositorAddr, err := sdk.AccAddressFromBech32(bechDepositorAddr) @@ -99,7 +127,7 @@ $ %s query gov proposals --status (DepositPeriod|VotingPeriod|Passed|Rejected) } if len(strProposalStatus) != 0 { - proposalStatus, err := gov.ProposalStatusFromString(gcutils.NormalizeProposalStatus(strProposalStatus)) + proposalStatus, err := types.ProposalStatusFromString(gcutils.NormalizeProposalStatus(strProposalStatus)) if err != nil { return err } @@ -118,7 +146,7 @@ $ %s query gov proposals --status (DepositPeriod|VotingPeriod|Passed|Rejected) return err } - var matchingProposals gov.Proposals + var matchingProposals types.Proposals err = cdc.UnmarshalJSON(res, &matchingProposals) if err != nil { return err @@ -176,7 +204,7 @@ $ %s query gov vote 1 cosmos1skjwj5whet0lpe65qaq4rpq03hjxlwd9nf39lk return err } - params := gov.NewQueryVoteParams(proposalID, voterAddr) + params := types.NewQueryVoteParams(proposalID, voterAddr) bz, err := cdc.MarshalJSON(params) if err != nil { return err @@ -187,7 +215,7 @@ $ %s query gov vote 1 cosmos1skjwj5whet0lpe65qaq4rpq03hjxlwd9nf39lk return err } - var vote gov.Vote + var vote types.Vote if err := cdc.UnmarshalJSON(res, &vote); err != nil { return err } @@ -231,7 +259,7 @@ $ %s query gov votes 1 return fmt.Errorf("proposal-id %s not a valid int, please input a valid proposal-id", args[0]) } - params := gov.NewQueryProposalParams(proposalID) + params := types.NewQueryProposalParams(proposalID) bz, err := cdc.MarshalJSON(params) if err != nil { return err @@ -243,11 +271,11 @@ $ %s query gov votes 1 return fmt.Errorf("failed to fetch proposal-id %d: %s", proposalID, err) } - var proposal gov.Proposal + var proposal types.Proposal cdc.MustUnmarshalJSON(res, &proposal) propStatus := proposal.Status - if !(propStatus == gov.StatusVotingPeriod || propStatus == gov.StatusDepositPeriod) { + if !(propStatus == types.StatusVotingPeriod || propStatus == types.StatusDepositPeriod) { res, err = gcutils.QueryVotesByTxQuery(cdc, cliCtx, params) } else { res, err = cliCtx.QueryWithData(fmt.Sprintf("custom/%s/votes", queryRoute), bz) @@ -257,7 +285,7 @@ $ %s query gov votes 1 return err } - var votes gov.Votes + var votes types.Votes cdc.MustUnmarshalJSON(res, &votes) return cliCtx.PrintOutput(votes) }, @@ -300,7 +328,7 @@ $ %s query gov deposit 1 cosmos1skjwj5whet0lpe65qaq4rpq03hjxlwd9nf39lk return err } - params := gov.NewQueryDepositParams(proposalID, depositorAddr) + params := types.NewQueryDepositParams(proposalID, depositorAddr) bz, err := cdc.MarshalJSON(params) if err != nil { return err @@ -311,7 +339,7 @@ $ %s query gov deposit 1 cosmos1skjwj5whet0lpe65qaq4rpq03hjxlwd9nf39lk return err } - var deposit gov.Deposit + var deposit types.Deposit cdc.MustUnmarshalJSON(res, &deposit) if deposit.Empty() { @@ -352,7 +380,7 @@ $ %s query gov deposits 1 return fmt.Errorf("proposal-id %s not a valid uint, please input a valid proposal-id", args[0]) } - params := gov.NewQueryProposalParams(proposalID) + params := types.NewQueryProposalParams(proposalID) bz, err := cdc.MarshalJSON(params) if err != nil { return err @@ -364,11 +392,11 @@ $ %s query gov deposits 1 return fmt.Errorf("failed to fetch proposal with id %d: %s", proposalID, err) } - var proposal gov.Proposal + var proposal types.Proposal cdc.MustUnmarshalJSON(res, &proposal) propStatus := proposal.Status - if !(propStatus == gov.StatusVotingPeriod || propStatus == gov.StatusDepositPeriod) { + if !(propStatus == types.StatusVotingPeriod || propStatus == types.StatusDepositPeriod) { res, err = gcutils.QueryDepositsByTxQuery(cdc, cliCtx, params) } else { res, err = cliCtx.QueryWithData(fmt.Sprintf("custom/%s/deposits", queryRoute), bz) @@ -378,7 +406,7 @@ $ %s query gov deposits 1 return err } - var dep gov.Deposits + var dep types.Deposits cdc.MustUnmarshalJSON(res, &dep) return cliCtx.PrintOutput(dep) }, @@ -417,7 +445,7 @@ $ %s query gov tally 1 } // Construct query - params := gov.NewQueryProposalParams(proposalID) + params := types.NewQueryProposalParams(proposalID) bz, err := cdc.MarshalJSON(params) if err != nil { return err @@ -429,7 +457,7 @@ $ %s query gov tally 1 return err } - var tally gov.TallyResult + var tally types.TallyResult cdc.MustUnmarshalJSON(res, &tally) return cliCtx.PrintOutput(tally) }, @@ -466,14 +494,14 @@ $ %s query gov params return err } - var tallyParams gov.TallyParams + var tallyParams types.TallyParams cdc.MustUnmarshalJSON(tp, &tallyParams) - var depositParams gov.DepositParams + var depositParams types.DepositParams cdc.MustUnmarshalJSON(dp, &depositParams) - var votingParams gov.VotingParams + var votingParams types.VotingParams cdc.MustUnmarshalJSON(vp, &votingParams) - return cliCtx.PrintOutput(gov.NewParams(votingParams, tallyParams, depositParams)) + return cliCtx.PrintOutput(types.NewParams(votingParams, tallyParams, depositParams)) }, } } @@ -506,15 +534,15 @@ $ %s query gov param deposit var out fmt.Stringer switch args[0] { case "voting": - var param gov.VotingParams + var param types.VotingParams cdc.MustUnmarshalJSON(res, ¶m) out = param case "tallying": - var param gov.TallyParams + var param types.TallyParams cdc.MustUnmarshalJSON(res, ¶m) out = param case "deposit": - var param gov.DepositParams + var param types.DepositParams cdc.MustUnmarshalJSON(res, ¶m) out = param default: diff --git a/x/gov/client/cli/tx.go b/x/gov/client/cli/tx.go index de1b662eed52..144085688cee 100644 --- a/x/gov/client/cli/tx.go +++ b/x/gov/client/cli/tx.go @@ -3,20 +3,19 @@ package cli import ( "fmt" "strconv" + "strings" + + "github.com/spf13/cobra" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/utils" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" - authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" - "github.com/cosmos/cosmos-sdk/x/gov" - - "strings" - - "github.com/spf13/cobra" - - govClientUtils "github.com/cosmos/cosmos-sdk/x/gov/client/utils" + "github.com/cosmos/cosmos-sdk/x/auth" + govutils "github.com/cosmos/cosmos-sdk/x/gov/client/utils" + "github.com/cosmos/cosmos-sdk/x/gov/types" ) // Proposal flags @@ -49,6 +48,34 @@ var ProposalFlags = []string{ FlagDeposit, } +// GetTxCmd returns the transaction commands for this module +// governance ModuleClient is slightly different from other ModuleClients in that +// it contains a slice of "proposal" child commands. These commands are respective +// to proposal type handlers that are implemented in other modules but are mounted +// under the governance CLI (eg. parameter change proposals). +func GetTxCmd(storeKey string, cdc *codec.Codec, pcmds []*cobra.Command) *cobra.Command { + govTxCmd := &cobra.Command{ + Use: types.ModuleName, + Short: "Governance transactions subcommands", + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: utils.ValidateCmd, + } + + cmdSubmitProp := GetCmdSubmitProposal(cdc) + for _, pcmd := range pcmds { + cmdSubmitProp.AddCommand(client.PostCommands(pcmd)[0]) + } + + govTxCmd.AddCommand(client.PostCommands( + GetCmdDeposit(cdc), + GetCmdVote(cdc), + cmdSubmitProp, + )...) + + return govTxCmd +} + // GetCmdSubmitProposal implements submitting a proposal transaction command. func GetCmdSubmitProposal(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ @@ -78,7 +105,7 @@ $ %s tx gov submit-proposal --title="Test Proposal" --description="My awesome pr ), ), RunE: func(cmd *cobra.Command, args []string) error { - txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) cliCtx := context.NewCLIContext(). WithCodec(cdc). WithAccountDecoder(cdc) @@ -93,9 +120,9 @@ $ %s tx gov submit-proposal --title="Test Proposal" --description="My awesome pr return err } - content := gov.ContentFromProposalType(proposal.Title, proposal.Description, proposal.Type) + content := types.ContentFromProposalType(proposal.Title, proposal.Description, proposal.Type) - msg := gov.NewMsgSubmitProposal(content, amount, cliCtx.GetFromAddress()) + msg := types.NewMsgSubmitProposal(content, amount, cliCtx.GetFromAddress()) if err := msg.ValidateBasic(); err != nil { return err } @@ -130,7 +157,7 @@ $ %s tx gov deposit 1 10stake --from mykey ), ), RunE: func(cmd *cobra.Command, args []string) error { - txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) cliCtx := context.NewCLIContext(). WithCodec(cdc). WithAccountDecoder(cdc) @@ -150,7 +177,7 @@ $ %s tx gov deposit 1 10stake --from mykey return err } - msg := gov.NewMsgDeposit(from, proposalID, amount) + msg := types.NewMsgDeposit(from, proposalID, amount) err = msg.ValidateBasic() if err != nil { return err @@ -179,7 +206,7 @@ $ %s tx gov vote 1 yes --from mykey ), ), RunE: func(cmd *cobra.Command, args []string) error { - txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) cliCtx := context.NewCLIContext(). WithCodec(cdc). WithAccountDecoder(cdc) @@ -194,13 +221,13 @@ $ %s tx gov vote 1 yes --from mykey } // Find out which vote option user chose - byteVoteOption, err := gov.VoteOptionFromString(govClientUtils.NormalizeVoteOption(args[1])) + byteVoteOption, err := types.VoteOptionFromString(govutils.NormalizeVoteOption(args[1])) if err != nil { return err } // Build vote message and run basic validation - msg := gov.NewMsgVote(from, proposalID, byteVoteOption) + msg := types.NewMsgVote(from, proposalID, byteVoteOption) err = msg.ValidateBasic() if err != nil { return err diff --git a/x/gov/client/module_client.go b/x/gov/client/module_client.go deleted file mode 100644 index 60dd7f931639..000000000000 --- a/x/gov/client/module_client.go +++ /dev/null @@ -1,76 +0,0 @@ -package client - -import ( - "github.com/spf13/cobra" - amino "github.com/tendermint/go-amino" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/utils" - "github.com/cosmos/cosmos-sdk/x/gov" - govCli "github.com/cosmos/cosmos-sdk/x/gov/client/cli" -) - -// ModuleClient exports all client functionality from the governance module. The -// governance ModuleClient is slightly different from other ModuleClients in that -// it contains a slice of "proposal" child commands. These commands are respective -// to proposal type handlers that are implemented in other modules but are mounted -// under the governance CLI (eg. parameter change proposals). -type ModuleClient struct { - storeKey string - cdc *amino.Codec - pcmds []*cobra.Command -} - -func NewModuleClient(storeKey string, cdc *amino.Codec, pcmds ...*cobra.Command) ModuleClient { - return ModuleClient{storeKey, cdc, pcmds} -} - -// GetQueryCmd returns the cli query commands for this module -func (mc ModuleClient) GetQueryCmd() *cobra.Command { - // Group gov queries under a subcommand - govQueryCmd := &cobra.Command{ - Use: gov.ModuleName, - Short: "Querying commands for the governance module", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: utils.ValidateCmd, - } - - govQueryCmd.AddCommand(client.GetCommands( - govCli.GetCmdQueryProposal(mc.storeKey, mc.cdc), - govCli.GetCmdQueryProposals(mc.storeKey, mc.cdc), - govCli.GetCmdQueryVote(mc.storeKey, mc.cdc), - govCli.GetCmdQueryVotes(mc.storeKey, mc.cdc), - govCli.GetCmdQueryParam(mc.storeKey, mc.cdc), - govCli.GetCmdQueryParams(mc.storeKey, mc.cdc), - govCli.GetCmdQueryProposer(mc.storeKey, mc.cdc), - govCli.GetCmdQueryDeposit(mc.storeKey, mc.cdc), - govCli.GetCmdQueryDeposits(mc.storeKey, mc.cdc), - govCli.GetCmdQueryTally(mc.storeKey, mc.cdc))...) - - return govQueryCmd -} - -// GetTxCmd returns the transaction commands for this module -func (mc ModuleClient) GetTxCmd() *cobra.Command { - govTxCmd := &cobra.Command{ - Use: gov.ModuleName, - Short: "Governance transactions subcommands", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: utils.ValidateCmd, - } - - cmdSubmitProp := govCli.GetCmdSubmitProposal(mc.cdc) - for _, pcmd := range mc.pcmds { - cmdSubmitProp.AddCommand(client.PostCommands(pcmd)[0]) - } - - govTxCmd.AddCommand(client.PostCommands( - govCli.GetCmdDeposit(mc.cdc), - govCli.GetCmdVote(mc.cdc), - cmdSubmitProp, - )...) - - return govTxCmd -} diff --git a/x/gov/client/proposal_handler.go b/x/gov/client/proposal_handler.go new file mode 100644 index 000000000000..c3297ee56d8f --- /dev/null +++ b/x/gov/client/proposal_handler.go @@ -0,0 +1,29 @@ +package client + +import ( + "github.com/spf13/cobra" + + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/x/gov/client/rest" +) + +// function to create the rest handler +type RESTHandlerFn func(context.CLIContext, *codec.Codec) rest.ProposalRESTHandler + +// function to create the cli handler +type CLIHandlerFn func(*codec.Codec) *cobra.Command + +// The combined type for a proposal handler for both cli and rest +type ProposalHandler struct { + CLIHandler CLIHandlerFn + RESTHandler RESTHandlerFn +} + +// NewProposalHandler creates a new ProposalHandler object +func NewProposalHandler(cliHandler CLIHandlerFn, restHandler RESTHandlerFn) ProposalHandler { + return ProposalHandler{ + CLIHandler: cliHandler, + RESTHandler: restHandler, + } +} diff --git a/x/gov/client/rest/rest.go b/x/gov/client/rest/rest.go index 701600357312..d62bcacc1ccd 100644 --- a/x/gov/client/rest/rest.go +++ b/x/gov/client/rest/rest.go @@ -12,8 +12,8 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/gov" gcutils "github.com/cosmos/cosmos-sdk/x/gov/client/utils" + "github.com/cosmos/cosmos-sdk/x/gov/types" ) // REST Variable names @@ -35,7 +35,7 @@ type ProposalRESTHandler struct { } // RegisterRoutes - Central function to define routes that get registered by the main application -func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec, phs ...ProposalRESTHandler) { +func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec, phs []ProposalRESTHandler) { propSubRtr := r.PathPrefix("/gov/proposals").Subrouter() for _, ph := range phs { propSubRtr.HandleFunc(fmt.Sprintf("/%s", ph.SubRoute), ph.Handler).Methods("POST") @@ -100,9 +100,9 @@ func postProposalHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.Han } proposalType := gcutils.NormalizeProposalType(req.ProposalType) - content := gov.ContentFromProposalType(req.Title, req.Description, proposalType) + content := types.ContentFromProposalType(req.Title, req.Description, proposalType) - msg := gov.NewMsgSubmitProposal(content, req.InitialDeposit, req.Proposer) + msg := types.NewMsgSubmitProposal(content, req.InitialDeposit, req.Proposer) if err := msg.ValidateBasic(); err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return @@ -139,7 +139,7 @@ func depositHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerF } // create the message - msg := gov.NewMsgDeposit(req.Depositor, proposalID, req.Amount) + msg := types.NewMsgDeposit(req.Depositor, proposalID, req.Amount) if err := msg.ValidateBasic(); err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return @@ -175,14 +175,14 @@ func voteHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc return } - voteOption, err := gov.VoteOptionFromString(gcutils.NormalizeVoteOption(req.Option)) + voteOption, err := types.VoteOptionFromString(gcutils.NormalizeVoteOption(req.Option)) if err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } // create the message - msg := gov.NewMsgVote(req.Voter, proposalID, voteOption) + msg := types.NewMsgVote(req.Voter, proposalID, voteOption) if err := msg.ValidateBasic(); err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return @@ -197,7 +197,7 @@ func queryParamsHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.Hand vars := mux.Vars(r) paramType := vars[RestParamsType] - res, err := cliCtx.QueryWithData(fmt.Sprintf("custom/gov/%s/%s", gov.QueryParams, paramType), nil) + res, err := cliCtx.QueryWithData(fmt.Sprintf("custom/gov/%s/%s", types.QueryParams, paramType), nil) if err != nil { rest.WriteErrorResponse(w, http.StatusNotFound, err.Error()) return @@ -223,7 +223,7 @@ func queryProposalHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.Ha return } - params := gov.NewQueryProposalParams(proposalID) + params := types.NewQueryProposalParams(proposalID) bz, err := cdc.MarshalJSON(params) if err != nil { @@ -251,7 +251,7 @@ func queryDepositsHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.Ha return } - params := gov.NewQueryProposalParams(proposalID) + params := types.NewQueryProposalParams(proposalID) bz, err := cdc.MarshalJSON(params) if err != nil { @@ -265,7 +265,7 @@ func queryDepositsHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.Ha return } - var proposal gov.Proposal + var proposal types.Proposal if err := cdc.UnmarshalJSON(res, &proposal); err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return @@ -274,7 +274,7 @@ func queryDepositsHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.Ha // For inactive proposals we must query the txs directly to get the deposits // as they're no longer in state. propStatus := proposal.Status - if !(propStatus == gov.StatusVotingPeriod || propStatus == gov.StatusDepositPeriod) { + if !(propStatus == types.StatusVotingPeriod || propStatus == types.StatusDepositPeriod) { res, err = gcutils.QueryDepositsByTxQuery(cdc, cliCtx, params) } else { res, err = cliCtx.QueryWithData("custom/gov/deposits", bz) @@ -338,7 +338,7 @@ func queryDepositHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.Han return } - params := gov.NewQueryDepositParams(proposalID, depositorAddr) + params := types.NewQueryDepositParams(proposalID, depositorAddr) bz, err := cdc.MarshalJSON(params) if err != nil { @@ -352,7 +352,7 @@ func queryDepositHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.Han return } - var deposit gov.Deposit + var deposit types.Deposit if err := cdc.UnmarshalJSON(res, &deposit); err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return @@ -362,7 +362,7 @@ func queryDepositHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.Han // which case the deposit would be removed from state and should be queried // for directly via a txs query. if deposit.Empty() { - bz, err := cdc.MarshalJSON(gov.NewQueryProposalParams(proposalID)) + bz, err := cdc.MarshalJSON(types.NewQueryProposalParams(proposalID)) if err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return @@ -415,7 +415,7 @@ func queryVoteHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.Handle return } - params := gov.NewQueryVoteParams(proposalID, voterAddr) + params := types.NewQueryVoteParams(proposalID, voterAddr) bz, err := cdc.MarshalJSON(params) if err != nil { @@ -429,7 +429,7 @@ func queryVoteHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.Handle return } - var vote gov.Vote + var vote types.Vote if err := cdc.UnmarshalJSON(res, &vote); err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return @@ -439,7 +439,7 @@ func queryVoteHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.Handle // which case the vote would be removed from state and should be queried for // directly via a txs query. if vote.Empty() { - bz, err := cdc.MarshalJSON(gov.NewQueryProposalParams(proposalID)) + bz, err := cdc.MarshalJSON(types.NewQueryProposalParams(proposalID)) if err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return @@ -480,7 +480,7 @@ func queryVotesOnProposalHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) return } - params := gov.NewQueryProposalParams(proposalID) + params := types.NewQueryProposalParams(proposalID) bz, err := cdc.MarshalJSON(params) if err != nil { @@ -494,7 +494,7 @@ func queryVotesOnProposalHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) return } - var proposal gov.Proposal + var proposal types.Proposal if err := cdc.UnmarshalJSON(res, &proposal); err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return @@ -503,7 +503,7 @@ func queryVotesOnProposalHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) // For inactive proposals we must query the txs directly to get the votes // as they're no longer in state. propStatus := proposal.Status - if !(propStatus == gov.StatusVotingPeriod || propStatus == gov.StatusDepositPeriod) { + if !(propStatus == types.StatusVotingPeriod || propStatus == types.StatusDepositPeriod) { res, err = gcutils.QueryVotesByTxQuery(cdc, cliCtx, params) } else { res, err = cliCtx.QueryWithData("custom/gov/votes", bz) @@ -526,7 +526,7 @@ func queryProposalsWithParameterFn(cdc *codec.Codec, cliCtx context.CLIContext) strProposalStatus := r.URL.Query().Get(RestProposalStatus) strNumLimit := r.URL.Query().Get(RestNumLimit) - params := gov.QueryProposalsParams{} + params := types.QueryProposalsParams{} if len(bechVoterAddr) != 0 { voterAddr, err := sdk.AccAddressFromBech32(bechVoterAddr) @@ -547,7 +547,7 @@ func queryProposalsWithParameterFn(cdc *codec.Codec, cliCtx context.CLIContext) } if len(strProposalStatus) != 0 { - proposalStatus, err := gov.ProposalStatusFromString(gcutils.NormalizeProposalStatus(strProposalStatus)) + proposalStatus, err := types.ProposalStatusFromString(gcutils.NormalizeProposalStatus(strProposalStatus)) if err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return @@ -595,7 +595,7 @@ func queryTallyOnProposalHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) return } - params := gov.NewQueryProposalParams(proposalID) + params := types.NewQueryProposalParams(proposalID) bz, err := cdc.MarshalJSON(params) if err != nil { diff --git a/x/gov/client/utils/query.go b/x/gov/client/utils/query.go index 28e996981897..afbb605e6c68 100644 --- a/x/gov/client/utils/query.go +++ b/x/gov/client/utils/query.go @@ -6,8 +6,8 @@ import ( "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/tx" "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/x/gov" "github.com/cosmos/cosmos-sdk/x/gov/tags" + "github.com/cosmos/cosmos-sdk/x/gov/types" ) const ( @@ -38,11 +38,11 @@ func (p Proposer) String() string { // NOTE: SearchTxs is used to facilitate the txs query which does not currently // support configurable pagination. func QueryDepositsByTxQuery( - cdc *codec.Codec, cliCtx context.CLIContext, params gov.QueryProposalParams, + cdc *codec.Codec, cliCtx context.CLIContext, params types.QueryProposalParams, ) ([]byte, error) { tags := []string{ - fmt.Sprintf("%s='%s'", tags.Action, gov.MsgDeposit{}.Type()), + fmt.Sprintf("%s='%s'", tags.Action, types.MsgDeposit{}.Type()), fmt.Sprintf("%s='%s'", tags.ProposalID, []byte(fmt.Sprintf("%d", params.ProposalID))), } @@ -53,14 +53,14 @@ func QueryDepositsByTxQuery( return nil, err } - var deposits []gov.Deposit + var deposits []types.Deposit for _, info := range searchResult.Txs { for _, msg := range info.Tx.GetMsgs() { - if msg.Type() == gov.TypeMsgDeposit { - depMsg := msg.(gov.MsgDeposit) + if msg.Type() == types.TypeMsgDeposit { + depMsg := msg.(types.MsgDeposit) - deposits = append(deposits, gov.Deposit{ + deposits = append(deposits, types.Deposit{ Depositor: depMsg.Depositor, ProposalID: params.ProposalID, Amount: depMsg.Amount, @@ -83,11 +83,11 @@ func QueryDepositsByTxQuery( // NOTE: SearchTxs is used to facilitate the txs query which does not currently // support configurable pagination. func QueryVotesByTxQuery( - cdc *codec.Codec, cliCtx context.CLIContext, params gov.QueryProposalParams, + cdc *codec.Codec, cliCtx context.CLIContext, params types.QueryProposalParams, ) ([]byte, error) { tags := []string{ - fmt.Sprintf("%s='%s'", tags.Action, gov.MsgVote{}.Type()), + fmt.Sprintf("%s='%s'", tags.Action, types.MsgVote{}.Type()), fmt.Sprintf("%s='%s'", tags.ProposalID, []byte(fmt.Sprintf("%d", params.ProposalID))), } @@ -98,14 +98,14 @@ func QueryVotesByTxQuery( return nil, err } - var votes []gov.Vote + var votes []types.Vote for _, info := range searchResult.Txs { for _, msg := range info.Tx.GetMsgs() { - if msg.Type() == gov.TypeMsgVote { - voteMsg := msg.(gov.MsgVote) + if msg.Type() == types.TypeMsgVote { + voteMsg := msg.(types.MsgVote) - votes = append(votes, gov.Vote{ + votes = append(votes, types.Vote{ Voter: voteMsg.Voter, ProposalID: params.ProposalID, Option: voteMsg.Option, @@ -123,11 +123,11 @@ func QueryVotesByTxQuery( // QueryVoteByTxQuery will query for a single vote via a direct txs tags query. func QueryVoteByTxQuery( - cdc *codec.Codec, cliCtx context.CLIContext, params gov.QueryVoteParams, + cdc *codec.Codec, cliCtx context.CLIContext, params types.QueryVoteParams, ) ([]byte, error) { tags := []string{ - fmt.Sprintf("%s='%s'", tags.Action, gov.MsgVote{}.Type()), + fmt.Sprintf("%s='%s'", tags.Action, types.MsgVote{}.Type()), fmt.Sprintf("%s='%s'", tags.ProposalID, []byte(fmt.Sprintf("%d", params.ProposalID))), fmt.Sprintf("%s='%s'", tags.Sender, []byte(params.Voter.String())), } @@ -142,10 +142,10 @@ func QueryVoteByTxQuery( for _, info := range searchResult.Txs { for _, msg := range info.Tx.GetMsgs() { // there should only be a single vote under the given conditions - if msg.Type() == gov.TypeMsgVote { - voteMsg := msg.(gov.MsgVote) + if msg.Type() == types.TypeMsgVote { + voteMsg := msg.(types.MsgVote) - vote := gov.Vote{ + vote := types.Vote{ Voter: voteMsg.Voter, ProposalID: params.ProposalID, Option: voteMsg.Option, @@ -166,11 +166,11 @@ func QueryVoteByTxQuery( // QueryDepositByTxQuery will query for a single deposit via a direct txs tags // query. func QueryDepositByTxQuery( - cdc *codec.Codec, cliCtx context.CLIContext, params gov.QueryDepositParams, + cdc *codec.Codec, cliCtx context.CLIContext, params types.QueryDepositParams, ) ([]byte, error) { tags := []string{ - fmt.Sprintf("%s='%s'", tags.Action, gov.MsgDeposit{}.Type()), + fmt.Sprintf("%s='%s'", tags.Action, types.MsgDeposit{}.Type()), fmt.Sprintf("%s='%s'", tags.ProposalID, []byte(fmt.Sprintf("%d", params.ProposalID))), fmt.Sprintf("%s='%s'", tags.Sender, []byte(params.Depositor.String())), } @@ -185,10 +185,10 @@ func QueryDepositByTxQuery( for _, info := range searchResult.Txs { for _, msg := range info.Tx.GetMsgs() { // there should only be a single deposit under the given conditions - if msg.Type() == gov.TypeMsgDeposit { - depMsg := msg.(gov.MsgDeposit) + if msg.Type() == types.TypeMsgDeposit { + depMsg := msg.(types.MsgDeposit) - deposit := gov.Deposit{ + deposit := types.Deposit{ Depositor: depMsg.Depositor, ProposalID: params.ProposalID, Amount: depMsg.Amount, @@ -213,7 +213,7 @@ func QueryProposerByTxQuery( ) (Proposer, error) { tags := []string{ - fmt.Sprintf("%s='%s'", tags.Action, gov.MsgSubmitProposal{}.Type()), + fmt.Sprintf("%s='%s'", tags.Action, types.MsgSubmitProposal{}.Type()), fmt.Sprintf("%s='%s'", tags.ProposalID, []byte(fmt.Sprintf("%d", proposalID))), } @@ -227,8 +227,8 @@ func QueryProposerByTxQuery( for _, info := range searchResult.Txs { for _, msg := range info.Tx.GetMsgs() { // there should only be a single proposal under the given conditions - if msg.Type() == gov.TypeMsgSubmitProposal { - subMsg := msg.(gov.MsgSubmitProposal) + if msg.Type() == types.TypeMsgSubmitProposal { + subMsg := msg.(types.MsgSubmitProposal) return NewProposer(proposalID, subMsg.Proposer.String()), nil } } @@ -238,7 +238,7 @@ func QueryProposerByTxQuery( // QueryProposalByID takes a proposalID and returns a proposal func QueryProposalByID(proposalID uint64, cliCtx context.CLIContext, cdc *codec.Codec, queryRoute string) ([]byte, error) { - params := gov.NewQueryProposalParams(proposalID) + params := types.NewQueryProposalParams(proposalID) bz, err := cdc.MarshalJSON(params) if err != nil { return nil, err diff --git a/x/gov/client/utils/utils.go b/x/gov/client/utils/utils.go index 612d82906c98..e23aa3ca1e85 100644 --- a/x/gov/client/utils/utils.go +++ b/x/gov/client/utils/utils.go @@ -1,21 +1,21 @@ package utils -import "github.com/cosmos/cosmos-sdk/x/gov" +import "github.com/cosmos/cosmos-sdk/x/gov/types" // NormalizeVoteOption - normalize user specified vote option func NormalizeVoteOption(option string) string { switch option { case "Yes", "yes": - return gov.OptionYes.String() + return types.OptionYes.String() case "Abstain", "abstain": - return gov.OptionAbstain.String() + return types.OptionAbstain.String() case "No", "no": - return gov.OptionNo.String() + return types.OptionNo.String() case "NoWithVeto", "no_with_veto": - return gov.OptionNoWithVeto.String() + return types.OptionNoWithVeto.String() default: return "" @@ -26,10 +26,10 @@ func NormalizeVoteOption(option string) string { func NormalizeProposalType(proposalType string) string { switch proposalType { case "Text", "text": - return gov.ProposalTypeText + return types.ProposalTypeText case "SoftwareUpgrade", "software_upgrade": - return gov.ProposalTypeSoftwareUpgrade + return types.ProposalTypeSoftwareUpgrade default: return "" diff --git a/x/gov/keeper.go b/x/gov/keeper.go index 6d1ef798b1e7..e6d53945e1af 100644 --- a/x/gov/keeper.go +++ b/x/gov/keeper.go @@ -13,6 +13,7 @@ import ( "github.com/tendermint/tendermint/libs/log" ) +// special governance addresses var ( // TODO: Find another way to implement this without using accounts, or find a cleaner way to implement it using accounts. DepositedCoinsAccAddr = sdk.AccAddress(crypto.AddressHash([]byte("govDepositedCoins"))) diff --git a/x/gov/module.go b/x/gov/module.go index 7db8824a0db5..6e9a37755952 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -3,21 +3,39 @@ package gov import ( "encoding/json" + "github.com/gorilla/mux" + "github.com/spf13/cobra" + + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + "github.com/cosmos/cosmos-sdk/x/gov/client" + "github.com/cosmos/cosmos-sdk/x/gov/client/cli" + "github.com/cosmos/cosmos-sdk/x/gov/client/rest" "github.com/cosmos/cosmos-sdk/x/gov/types" - abci "github.com/tendermint/tendermint/abci/types" ) var ( - _ sdk.AppModule = AppModule{} - _ sdk.AppModuleBasic = AppModuleBasic{} + _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} ) // app module basics object -type AppModuleBasic struct{} +type AppModuleBasic struct { + proposalHandlers []client.ProposalHandler // proposal handlers which live in governance cli and rest +} -var _ sdk.AppModuleBasic = AppModuleBasic{} +// NewAppModuleBasic creates a new AppModuleBasic object +func NewAppModuleBasic(proposalHandlers ...client.ProposalHandler) AppModuleBasic { + return AppModuleBasic{ + proposalHandlers: proposalHandlers, + } +} + +var _ module.AppModuleBasic = AppModuleBasic{} // module name func (AppModuleBasic) Name() string { @@ -44,6 +62,33 @@ func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { return ValidateGenesis(data) } +// register rest routes +func (a AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router, cdc *codec.Codec) { + + var proposalRESTHandlers []rest.ProposalRESTHandler + for _, proposalHandler := range a.proposalHandlers { + proposalRESTHandlers = append(proposalRESTHandlers, proposalHandler.RESTHandler(ctx, cdc)) + } + + rest.RegisterRoutes(ctx, rtr, cdc, proposalRESTHandlers) +} + +// get the root tx command of this module +func (a AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command { + + var proposalCLIHandlers []*cobra.Command + for _, proposalHandler := range a.proposalHandlers { + proposalCLIHandlers = append(proposalCLIHandlers, proposalHandler.CLIHandler(cdc)) + } + + return cli.GetTxCmd(StoreKey, cdc, proposalCLIHandlers) +} + +// get the root query command of this module +func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { + return cli.GetQueryCmd(StoreKey, cdc) +} + //___________________________ // app module type AppModule struct { diff --git a/x/gov/querier.go b/x/gov/querier.go index 0aff0a0dd738..03e37c84a13b 100644 --- a/x/gov/querier.go +++ b/x/gov/querier.go @@ -7,28 +7,13 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" -) - -// query endpoints supported by the governance Querier -const ( - QueryParams = "params" - QueryProposals = "proposals" - QueryProposal = "proposal" - QueryDeposits = "deposits" - QueryDeposit = "deposit" - QueryVotes = "votes" - QueryVote = "vote" - QueryTally = "tally" - - ParamDeposit = "deposit" - ParamVoting = "voting" - ParamTallying = "tallying" + "github.com/cosmos/cosmos-sdk/x/gov/types" ) func NewQuerier(keeper Keeper) sdk.Querier { return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, sdk.Error) { switch path[0] { - case QueryParams: + case types.QueryParams: return queryParams(ctx, path[1:], req, keeper) case QueryProposals: return queryProposals(ctx, path[1:], req, keeper) @@ -75,22 +60,6 @@ func queryParams(ctx sdk.Context, path []string, req abci.RequestQuery, keeper K } } -// Params for queries: -// - 'custom/gov/proposal' -// - 'custom/gov/deposits' -// - 'custom/gov/tally' -// - 'custom/gov/votes' -type QueryProposalParams struct { - ProposalID uint64 -} - -// creates a new instance of QueryProposalParams -func NewQueryProposalParams(proposalID uint64) QueryProposalParams { - return QueryProposalParams{ - ProposalID: proposalID, - } -} - // nolint: unparam func queryProposal(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper) ([]byte, sdk.Error) { var params QueryProposalParams @@ -111,20 +80,6 @@ func queryProposal(ctx sdk.Context, path []string, req abci.RequestQuery, keeper return bz, nil } -// Params for query 'custom/gov/deposit' -type QueryDepositParams struct { - ProposalID uint64 - Depositor sdk.AccAddress -} - -// creates a new instance of QueryDepositParams -func NewQueryDepositParams(proposalID uint64, depositor sdk.AccAddress) QueryDepositParams { - return QueryDepositParams{ - ProposalID: proposalID, - Depositor: depositor, - } -} - // nolint: unparam func queryDeposit(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper) ([]byte, sdk.Error) { var params QueryDepositParams @@ -141,20 +96,6 @@ func queryDeposit(ctx sdk.Context, path []string, req abci.RequestQuery, keeper return bz, nil } -// Params for query 'custom/gov/vote' -type QueryVoteParams struct { - ProposalID uint64 - Voter sdk.AccAddress -} - -// creates a new instance of QueryVoteParams -func NewQueryVoteParams(proposalID uint64, voter sdk.AccAddress) QueryVoteParams { - return QueryVoteParams{ - ProposalID: proposalID, - Voter: voter, - } -} - // nolint: unparam func queryVote(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper) ([]byte, sdk.Error) { var params QueryVoteParams @@ -239,24 +180,6 @@ func queryVotes(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Ke return bz, nil } -// Params for query 'custom/gov/proposals' -type QueryProposalsParams struct { - Voter sdk.AccAddress - Depositor sdk.AccAddress - ProposalStatus ProposalStatus - Limit uint64 -} - -// creates a new instance of QueryProposalsParams -func NewQueryProposalsParams(status ProposalStatus, limit uint64, voter, depositor sdk.AccAddress) QueryProposalsParams { - return QueryProposalsParams{ - Voter: voter, - Depositor: depositor, - ProposalStatus: status, - Limit: limit, - } -} - // nolint: unparam func queryProposals(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper) ([]byte, sdk.Error) { var params QueryProposalsParams diff --git a/x/gov/types/codec.go b/x/gov/types/codec.go index bec23cce0c5b..32d4900785af 100644 --- a/x/gov/types/codec.go +++ b/x/gov/types/codec.go @@ -27,6 +27,7 @@ func RegisterProposalTypeCodec(o interface{}, name string) { ModuleCdc.RegisterConcrete(o, name, nil) } +// TODO determine a good place to seal this codec func init() { RegisterCodec(ModuleCdc) } diff --git a/x/gov/params.go b/x/gov/types/params.go similarity index 97% rename from x/gov/params.go rename to x/gov/types/params.go index d12658967a6f..9a766452b54f 100644 --- a/x/gov/params.go +++ b/x/gov/types/params.go @@ -1,11 +1,11 @@ -package gov +package types import ( "fmt" "time" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/params" + params "github.com/cosmos/cosmos-sdk/x/params/subspace" ) // Parameter store key diff --git a/x/gov/types/querier.go b/x/gov/types/querier.go new file mode 100644 index 000000000000..cfe0abc4d328 --- /dev/null +++ b/x/gov/types/querier.go @@ -0,0 +1,83 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// query endpoints supported by the governance Querier +const ( + QueryParams = "params" + QueryProposals = "proposals" + QueryProposal = "proposal" + QueryDeposits = "deposits" + QueryDeposit = "deposit" + QueryVotes = "votes" + QueryVote = "vote" + QueryTally = "tally" + + ParamDeposit = "deposit" + ParamVoting = "voting" + ParamTallying = "tallying" +) + +// Params for queries: +// - 'custom/gov/proposal' +// - 'custom/gov/deposits' +// - 'custom/gov/tally' +// - 'custom/gov/votes' +type QueryProposalParams struct { + ProposalID uint64 +} + +// creates a new instance of QueryProposalParams +func NewQueryProposalParams(proposalID uint64) QueryProposalParams { + return QueryProposalParams{ + ProposalID: proposalID, + } +} + +// Params for query 'custom/gov/deposit' +type QueryDepositParams struct { + ProposalID uint64 + Depositor sdk.AccAddress +} + +// creates a new instance of QueryDepositParams +func NewQueryDepositParams(proposalID uint64, depositor sdk.AccAddress) QueryDepositParams { + return QueryDepositParams{ + ProposalID: proposalID, + Depositor: depositor, + } +} + +// Params for query 'custom/gov/vote' +type QueryVoteParams struct { + ProposalID uint64 + Voter sdk.AccAddress +} + +// creates a new instance of QueryVoteParams +func NewQueryVoteParams(proposalID uint64, voter sdk.AccAddress) QueryVoteParams { + return QueryVoteParams{ + ProposalID: proposalID, + Voter: voter, + } +} + +// Params for query 'custom/gov/proposals' +type QueryProposalsParams struct { + Voter sdk.AccAddress + Depositor sdk.AccAddress + ProposalStatus ProposalStatus + Limit uint64 +} + +// creates a new instance of QueryProposalsParams +func NewQueryProposalsParams(status ProposalStatus, limit uint64, voter, depositor sdk.AccAddress) QueryProposalsParams { + return QueryProposalsParams{ + Voter: voter, + Depositor: depositor, + ProposalStatus: status, + Limit: limit, + } +} diff --git a/x/ibc/client/cli/ibctx.go b/x/ibc/client/cli/ibctx.go index 9a5ac05ee661..0b706cbed1d7 100644 --- a/x/ibc/client/cli/ibctx.go +++ b/x/ibc/client/cli/ibctx.go @@ -8,7 +8,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/utils" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" + auth "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/ibc" "github.com/spf13/cobra" @@ -26,7 +26,7 @@ func IBCTransferCmd(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "transfer", RunE: func(cmd *cobra.Command, args []string) error { - txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) cliCtx := context.NewCLIContext(). WithCodec(cdc). WithAccountDecoder(cdc) diff --git a/x/ibc/client/cli/relay.go b/x/ibc/client/cli/relay.go index c1c45611eb3f..577dcc0d18c3 100644 --- a/x/ibc/client/cli/relay.go +++ b/x/ibc/client/cli/relay.go @@ -12,7 +12,6 @@ import ( "github.com/cosmos/cosmos-sdk/codec" 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/ibc" "github.com/spf13/cobra" @@ -197,7 +196,7 @@ func (c relayCommander) refine(bz []byte, ibcSeq, accSeq uint64, passphrase stri Sequence: ibcSeq, } - txBldr := authtxb.NewTxBuilderFromCLI().WithSequence(accSeq).WithTxEncoder(utils.GetTxEncoder(c.cdc)) + txBldr := auth.NewTxBuilderFromCLI().WithSequence(accSeq).WithTxEncoder(utils.GetTxEncoder(c.cdc)) cliCtx := context.NewCLIContext() name := cliCtx.GetFromName() diff --git a/x/mint/alias.go b/x/mint/alias.go new file mode 100644 index 000000000000..c285c6a7e182 --- /dev/null +++ b/x/mint/alias.go @@ -0,0 +1,46 @@ +// nolint +// autogenerated code using github.com/rigelrozanski/multitool +// aliases generated for the following subdirectories: +// ALIASGEN: github.com/cosmos/cosmos-sdk/x/mint/types +package mint + +import ( + "github.com/cosmos/cosmos-sdk/x/mint/types" +) + +const ( + ModuleName = types.ModuleName + DefaultParamspace = types.DefaultParamspace + StoreKey = types.StoreKey + QuerierRoute = types.QuerierRoute + QueryParameters = types.QueryParameters + QueryInflation = types.QueryInflation + QueryAnnualProvisions = types.QueryAnnualProvisions +) + +var ( + // functions aliases + NewMinter = types.NewMinter + InitialMinter = types.InitialMinter + DefaultInitialMinter = types.DefaultInitialMinter + ValidateMinter = types.ValidateMinter + ParamKeyTable = types.ParamKeyTable + NewParams = types.NewParams + DefaultParams = types.DefaultParams + ValidateParams = types.ValidateParams + + // variable aliases + ModuleCdc = types.ModuleCdc + MinterKey = types.MinterKey + KeyMintDenom = types.KeyMintDenom + KeyInflationRateChange = types.KeyInflationRateChange + KeyInflationMax = types.KeyInflationMax + KeyInflationMin = types.KeyInflationMin + KeyGoalBonded = types.KeyGoalBonded + KeyBlocksPerYear = types.KeyBlocksPerYear +) + +type ( + Minter = types.Minter + Params = types.Params +) diff --git a/x/mint/client/cli/query.go b/x/mint/client/cli/query.go index 65bde6adeb32..f5fc80a6aaaf 100644 --- a/x/mint/client/cli/query.go +++ b/x/mint/client/cli/query.go @@ -5,12 +5,35 @@ import ( "github.com/spf13/cobra" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client/utils" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/mint" + "github.com/cosmos/cosmos-sdk/x/mint/types" ) +// GetQueryCmd returns the cli query commands for the minting module. +func GetQueryCmd(cdc *codec.Codec) *cobra.Command { + mintingQueryCmd := &cobra.Command{ + Use: types.ModuleName, + Short: "Querying commands for the minting module", + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: utils.ValidateCmd, + } + + mintingQueryCmd.AddCommand( + client.GetCommands( + GetCmdQueryParams(cdc), + GetCmdQueryInflation(cdc), + GetCmdQueryAnnualProvisions(cdc), + )..., + ) + + return mintingQueryCmd +} + // GetCmdQueryParams implements a command to return the current minting // parameters. func GetCmdQueryParams(cdc *codec.Codec) *cobra.Command { @@ -21,13 +44,13 @@ func GetCmdQueryParams(cdc *codec.Codec) *cobra.Command { RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) - route := fmt.Sprintf("custom/%s/%s", mint.QuerierRoute, mint.QueryParameters) + route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryParameters) res, err := cliCtx.QueryWithData(route, nil) if err != nil { return err } - var params mint.Params + var params types.Params if err := cdc.UnmarshalJSON(res, ¶ms); err != nil { return err } @@ -47,7 +70,7 @@ func GetCmdQueryInflation(cdc *codec.Codec) *cobra.Command { RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) - route := fmt.Sprintf("custom/%s/%s", mint.QuerierRoute, mint.QueryInflation) + route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryInflation) res, err := cliCtx.QueryWithData(route, nil) if err != nil { return err @@ -73,7 +96,7 @@ func GetCmdQueryAnnualProvisions(cdc *codec.Codec) *cobra.Command { RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) - route := fmt.Sprintf("custom/%s/%s", mint.QuerierRoute, mint.QueryAnnualProvisions) + route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryAnnualProvisions) res, err := cliCtx.QueryWithData(route, nil) if err != nil { return err diff --git a/x/mint/client/module_client.go b/x/mint/client/module_client.go deleted file mode 100644 index d76cdd1315a3..000000000000 --- a/x/mint/client/module_client.go +++ /dev/null @@ -1,54 +0,0 @@ -package client - -import ( - "github.com/spf13/cobra" - amino "github.com/tendermint/go-amino" - - sdkclient "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/utils" - "github.com/cosmos/cosmos-sdk/x/mint" - "github.com/cosmos/cosmos-sdk/x/mint/client/cli" -) - -type ModuleClient struct { - storeKey string - cdc *amino.Codec -} - -func NewModuleClient(storeKey string, cdc *amino.Codec) ModuleClient { - return ModuleClient{storeKey, cdc} -} - -// GetQueryCmd returns the cli query commands for the minting module. -func (mc ModuleClient) GetQueryCmd() *cobra.Command { - mintingQueryCmd := &cobra.Command{ - Use: mint.ModuleName, - Short: "Querying commands for the minting module", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: utils.ValidateCmd, - } - - mintingQueryCmd.AddCommand( - sdkclient.GetCommands( - cli.GetCmdQueryParams(mc.cdc), - cli.GetCmdQueryInflation(mc.cdc), - cli.GetCmdQueryAnnualProvisions(mc.cdc), - )..., - ) - - return mintingQueryCmd -} - -// GetTxCmd returns the transaction commands for the minting module. -func (mc ModuleClient) GetTxCmd() *cobra.Command { - mintTxCmd := &cobra.Command{ - Use: mint.ModuleName, - Short: "Minting transaction subcommands", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: utils.ValidateCmd, - } - - return mintTxCmd -} diff --git a/x/mint/client/rest/query.go b/x/mint/client/rest/query.go index 2d3cd4a0fea0..171204f79330 100644 --- a/x/mint/client/rest/query.go +++ b/x/mint/client/rest/query.go @@ -9,7 +9,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/mint" + "github.com/cosmos/cosmos-sdk/x/mint/types" ) func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec) { @@ -31,7 +31,7 @@ func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Co func queryParamsHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - route := fmt.Sprintf("custom/%s/%s", mint.QuerierRoute, mint.QueryParameters) + route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryParameters) res, err := cliCtx.QueryWithData(route, nil) if err != nil { @@ -45,7 +45,7 @@ func queryParamsHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.Hand func queryInflationHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - route := fmt.Sprintf("custom/%s/%s", mint.QuerierRoute, mint.QueryInflation) + route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryInflation) res, err := cliCtx.QueryWithData(route, nil) if err != nil { @@ -59,7 +59,7 @@ func queryInflationHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.H func queryAnnualProvisionsHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - route := fmt.Sprintf("custom/%s/%s", mint.QuerierRoute, mint.QueryAnnualProvisions) + route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryAnnualProvisions) res, err := cliCtx.QueryWithData(route, nil) if err != nil { diff --git a/x/mint/genesis.go b/x/mint/genesis.go index 11f96c6f90bb..a2e66da3ed0e 100644 --- a/x/mint/genesis.go +++ b/x/mint/genesis.go @@ -2,12 +2,13 @@ package mint import ( sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/mint/types" ) // GenesisState - minter state type GenesisState struct { - Minter Minter `json:"minter"` // minter object - Params Params `json:"params"` // inflation params + Minter Minter `json:"minter"` // minter object + Params types.Params `json:"params"` // inflation params } // NewGenesisState creates a new GenesisState object @@ -43,11 +44,11 @@ func ExportGenesis(ctx sdk.Context, keeper Keeper) GenesisState { // ValidateGenesis validates the provided genesis state to ensure the // expected invariants holds. func ValidateGenesis(data GenesisState) error { - err := validateParams(data.Params) + err := ValidateParams(data.Params) if err != nil { return err } - err = validateMinter(data.Minter) + err = ValidateMinter(data.Minter) if err != nil { return err } diff --git a/x/mint/keeper.go b/x/mint/keeper.go index f298b51611cc..798c64765e09 100644 --- a/x/mint/keeper.go +++ b/x/mint/keeper.go @@ -6,19 +6,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/params" ) -var minterKey = []byte{0x00} // the one key to use for the keeper store - -const ( - // default paramspace for params keeper - DefaultParamspace = ModuleName - - // StoreKey is the default store key for mint - StoreKey = ModuleName - - // QuerierRoute is the querier route for the minting store. - QuerierRoute = StoreKey -) - // keeper of the staking store type Keeper struct { storeKey sdk.StoreKey @@ -46,7 +33,7 @@ func NewKeeper(cdc *codec.Codec, key sdk.StoreKey, // get the minter func (k Keeper) GetMinter(ctx sdk.Context) (minter Minter) { store := ctx.KVStore(k.storeKey) - b := store.Get(minterKey) + b := store.Get(MinterKey) if b == nil { panic("stored minter should not have been nil") } @@ -58,7 +45,7 @@ func (k Keeper) GetMinter(ctx sdk.Context) (minter Minter) { func (k Keeper) SetMinter(ctx sdk.Context, minter Minter) { store := ctx.KVStore(k.storeKey) b := k.cdc.MustMarshalBinaryLengthPrefixed(minter) - store.Set(minterKey, b) + store.Set(MinterKey, b) } //______________________________________________________________________ diff --git a/x/mint/module.go b/x/mint/module.go index d645624fa09f..061e848f503a 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -3,23 +3,28 @@ package mint import ( "encoding/json" + "github.com/gorilla/mux" + "github.com/spf13/cobra" + + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - abci "github.com/tendermint/tendermint/abci/types" + "github.com/cosmos/cosmos-sdk/types/module" + "github.com/cosmos/cosmos-sdk/x/mint/client/cli" + "github.com/cosmos/cosmos-sdk/x/mint/client/rest" ) var ( - _ sdk.AppModule = AppModule{} - _ sdk.AppModuleBasic = AppModuleBasic{} + _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} ) -// name of this module -const ModuleName = "mint" - // app module basics object type AppModuleBasic struct{} -var _ sdk.AppModuleBasic = AppModuleBasic{} +var _ module.AppModuleBasic = AppModuleBasic{} // module name func (AppModuleBasic) Name() string { @@ -31,19 +36,32 @@ func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) {} // default genesis state func (AppModuleBasic) DefaultGenesis() json.RawMessage { - return moduleCdc.MustMarshalJSON(DefaultGenesisState()) + return ModuleCdc.MustMarshalJSON(DefaultGenesisState()) } // module validate genesis func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { var data GenesisState - err := moduleCdc.UnmarshalJSON(bz, &data) + err := ModuleCdc.UnmarshalJSON(bz, &data) if err != nil { return err } return ValidateGenesis(data) } +// register rest routes +func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router, cdc *codec.Codec) { + rest.RegisterRoutes(ctx, rtr, cdc) +} + +// get the root tx command of this module +func (AppModuleBasic) GetTxCmd(_ *codec.Codec) *cobra.Command { return nil } + +// get the root query command of this module +func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { + return cli.GetQueryCmd(cdc) +} + //___________________________ // app module type AppModule struct { @@ -86,7 +104,7 @@ func (am AppModule) NewQuerierHandler() sdk.Querier { // module init-genesis func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate { var genesisState GenesisState - moduleCdc.MustUnmarshalJSON(data, &genesisState) + ModuleCdc.MustUnmarshalJSON(data, &genesisState) InitGenesis(ctx, am.keeper, genesisState) return []abci.ValidatorUpdate{} } @@ -94,7 +112,7 @@ func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.Va // module export genesis func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { gs := ExportGenesis(ctx, am.keeper) - return moduleCdc.MustMarshalJSON(gs) + return ModuleCdc.MustMarshalJSON(gs) } // module begin-block diff --git a/x/mint/querier.go b/x/mint/querier.go index 4de3fdeeb526..e33b04f8e62d 100644 --- a/x/mint/querier.go +++ b/x/mint/querier.go @@ -7,26 +7,20 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" -) - -// Query endpoints supported by the minting querier -const ( - QueryParameters = "parameters" - QueryInflation = "inflation" - QueryAnnualProvisions = "annual_provisions" + "github.com/cosmos/cosmos-sdk/x/mint/types" ) // NewQuerier returns a minting Querier handler. func NewQuerier(k Keeper) sdk.Querier { return func(ctx sdk.Context, path []string, _ abci.RequestQuery) ([]byte, sdk.Error) { switch path[0] { - case QueryParameters: + case types.QueryParameters: return queryParams(ctx, k) - case QueryInflation: + case types.QueryInflation: return queryInflation(ctx, k) - case QueryAnnualProvisions: + case types.QueryAnnualProvisions: return queryAnnualProvisions(ctx, k) default: diff --git a/x/mint/test_common.go b/x/mint/test_common.go index d3615bdb3db5..71dddc01fc46 100644 --- a/x/mint/test_common.go +++ b/x/mint/test_common.go @@ -49,15 +49,15 @@ func newTestInput(t *testing.T) testInput { err := ms.LoadLatestVersion() require.Nil(t, err) - paramsKeeper := params.NewKeeper(moduleCdc, keyParams, tkeyParams, params.DefaultCodespace) - feeCollectionKeeper := auth.NewFeeCollectionKeeper(moduleCdc, keyFeeCollection) - accountKeeper := auth.NewAccountKeeper(moduleCdc, keyAcc, paramsKeeper.Subspace(auth.DefaultParamspace), auth.ProtoBaseAccount) + paramsKeeper := params.NewKeeper(ModuleCdc, keyParams, tkeyParams, params.DefaultCodespace) + feeCollectionKeeper := auth.NewFeeCollectionKeeper(ModuleCdc, keyFeeCollection) + accountKeeper := auth.NewAccountKeeper(ModuleCdc, keyAcc, paramsKeeper.Subspace(auth.DefaultParamspace), auth.ProtoBaseAccount) bankKeeper := bank.NewBaseKeeper(accountKeeper, paramsKeeper.Subspace(bank.DefaultParamspace), bank.DefaultCodespace) stakingKeeper := staking.NewKeeper( - moduleCdc, keyStaking, tkeyStaking, bankKeeper, paramsKeeper.Subspace(staking.DefaultParamspace), staking.DefaultCodespace, + ModuleCdc, keyStaking, tkeyStaking, bankKeeper, paramsKeeper.Subspace(staking.DefaultParamspace), staking.DefaultCodespace, ) mintKeeper := NewKeeper( - moduleCdc, keyMint, paramsKeeper.Subspace(DefaultParamspace), &stakingKeeper, feeCollectionKeeper, + ModuleCdc, keyMint, paramsKeeper.Subspace(DefaultParamspace), &stakingKeeper, feeCollectionKeeper, ) ctx := sdk.NewContext(ms, abci.Header{Time: time.Unix(0, 0)}, false, log.NewTMLogger(os.Stdout)) @@ -65,5 +65,5 @@ func newTestInput(t *testing.T) testInput { mintKeeper.SetParams(ctx, DefaultParams()) mintKeeper.SetMinter(ctx, DefaultInitialMinter()) - return testInput{ctx, moduleCdc, mintKeeper} + return testInput{ctx, ModuleCdc, mintKeeper} } diff --git a/x/mint/codec.go b/x/mint/types/codec.go similarity index 51% rename from x/mint/codec.go rename to x/mint/types/codec.go index e704d29f6054..5787f242adfe 100644 --- a/x/mint/codec.go +++ b/x/mint/types/codec.go @@ -1,14 +1,14 @@ -package mint +package types import ( "github.com/cosmos/cosmos-sdk/codec" ) // generic sealed codec to be used throughout this module -var moduleCdc *codec.Codec +var ModuleCdc *codec.Codec func init() { - cdc := codec.New() - codec.RegisterCrypto(cdc) - moduleCdc = cdc.Seal() + ModuleCdc = codec.New() + codec.RegisterCrypto(ModuleCdc) + ModuleCdc.Seal() } diff --git a/x/mint/types/keys.go b/x/mint/types/keys.go new file mode 100644 index 000000000000..cf395bc44ee3 --- /dev/null +++ b/x/mint/types/keys.go @@ -0,0 +1,24 @@ +package types + +// the one key to use for the keeper store +var MinterKey = []byte{0x00} + +// nolint +const ( + // module name + ModuleName = "mint" + + // default paramspace for params keeper + DefaultParamspace = ModuleName + + // StoreKey is the default store key for mint + StoreKey = ModuleName + + // QuerierRoute is the querier route for the minting store. + QuerierRoute = StoreKey + + // Query endpoints supported by the minting querier + QueryParameters = "parameters" + QueryInflation = "inflation" + QueryAnnualProvisions = "annual_provisions" +) diff --git a/x/mint/minter.go b/x/mint/types/minter.go similarity index 97% rename from x/mint/minter.go rename to x/mint/types/minter.go index eff30785faf1..ee7ca7c662b0 100644 --- a/x/mint/minter.go +++ b/x/mint/types/minter.go @@ -1,4 +1,4 @@ -package mint +package types import ( "fmt" @@ -37,7 +37,8 @@ func DefaultInitialMinter() Minter { ) } -func validateMinter(minter Minter) error { +// validate minter +func ValidateMinter(minter Minter) error { if minter.Inflation.LT(sdk.ZeroDec()) { return fmt.Errorf("mint parameter Inflation should be positive, is %s", minter.Inflation.String()) diff --git a/x/mint/minter_test.go b/x/mint/types/minter_test.go similarity index 99% rename from x/mint/minter_test.go rename to x/mint/types/minter_test.go index 0245c71972fb..8760a66f4466 100644 --- a/x/mint/minter_test.go +++ b/x/mint/types/minter_test.go @@ -1,4 +1,4 @@ -package mint +package types import ( "math/rand" diff --git a/x/mint/params.go b/x/mint/types/params.go similarity index 97% rename from x/mint/params.go rename to x/mint/types/params.go index d51d46fff952..28e07300069c 100644 --- a/x/mint/params.go +++ b/x/mint/types/params.go @@ -1,4 +1,4 @@ -package mint +package types import ( "fmt" @@ -57,7 +57,8 @@ func DefaultParams() Params { } } -func validateParams(params Params) error { +// validate params +func ValidateParams(params Params) error { if params.GoalBonded.LT(sdk.ZeroDec()) { return fmt.Errorf("mint parameter GoalBonded should be positive, is %s ", params.GoalBonded.String()) } diff --git a/x/params/client/cli/tx.go b/x/params/client/cli/tx.go index 71c1d797388b..d974f02b94a3 100644 --- a/x/params/client/cli/tx.go +++ b/x/params/client/cli/tx.go @@ -11,10 +11,10 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" - authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" + auth "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/gov" - "github.com/cosmos/cosmos-sdk/x/params" paramscutils "github.com/cosmos/cosmos-sdk/x/params/client/utils" + "github.com/cosmos/cosmos-sdk/x/params/types" ) // GetCmdSubmitProposal implements a command handler for submitting a parameter @@ -64,7 +64,7 @@ Where proposal.json contains: ), ), RunE: func(cmd *cobra.Command, args []string) error { - txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) cliCtx := context.NewCLIContext(). WithCodec(cdc). WithAccountDecoder(cdc) @@ -75,7 +75,7 @@ Where proposal.json contains: } from := cliCtx.GetFromAddress() - content := params.NewParameterChangeProposal(proposal.Title, proposal.Description, proposal.Changes.ToParamChanges()) + content := types.NewParameterChangeProposal(proposal.Title, proposal.Description, proposal.Changes.ToParamChanges()) msg := gov.NewMsgSubmitProposal(content, proposal.Deposit, from) if err := msg.ValidateBasic(); err != nil { diff --git a/x/params/client/proposal_handler.go b/x/params/client/proposal_handler.go new file mode 100644 index 000000000000..040bebdf448f --- /dev/null +++ b/x/params/client/proposal_handler.go @@ -0,0 +1,10 @@ +package client + +import ( + govclient "github.com/cosmos/cosmos-sdk/x/gov/client" + "github.com/cosmos/cosmos-sdk/x/params/client/cli" + "github.com/cosmos/cosmos-sdk/x/params/client/rest" +) + +// param change proposal handler +var ProposalHandler = govclient.NewProposalHandler(cli.GetCmdSubmitProposal, rest.ProposalRESTHandler) diff --git a/x/params/module.go b/x/params/module.go index 1749dfc5a82e..f1ebed97af09 100644 --- a/x/params/module.go +++ b/x/params/module.go @@ -3,13 +3,17 @@ package params import ( "encoding/json" + "github.com/gorilla/mux" + "github.com/spf13/cobra" + + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/params/types" ) var ( - _ sdk.AppModuleBasic = AppModuleBasic{} + _ module.AppModuleBasic = AppModuleBasic{} ) const moduleName = "params" @@ -32,3 +36,12 @@ func (AppModuleBasic) DefaultGenesis() json.RawMessage { return nil } // module validate genesis func (AppModuleBasic) ValidateGenesis(_ json.RawMessage) error { return nil } + +// register rest routes +func (AppModuleBasic) RegisterRESTRoutes(_ context.CLIContext, _ *mux.Router, _ *codec.Codec) {} + +// get the root tx command of this module +func (AppModuleBasic) GetTxCmd(_ *codec.Codec) *cobra.Command { return nil } + +// get the root query command of this module +func (AppModuleBasic) GetQueryCmd(_ *codec.Codec) *cobra.Command { return nil } diff --git a/x/params/types/codec.go b/x/params/types/codec.go index fbbc5ffd7da3..525836346f90 100644 --- a/x/params/types/codec.go +++ b/x/params/types/codec.go @@ -4,10 +4,13 @@ import ( "github.com/cosmos/cosmos-sdk/codec" ) -var msgCdc = codec.New() +// module codec +var ModuleCdc *codec.Codec func init() { - RegisterCodec(msgCdc) + ModuleCdc = codec.New() + RegisterCodec(ModuleCdc) + ModuleCdc.Seal() } // RegisterCodec registers all necessary param module types with a given codec. diff --git a/x/slashing/tick.go b/x/slashing/abci_app.go similarity index 89% rename from x/slashing/tick.go rename to x/slashing/abci_app.go index 14e07d6509a8..c9ca3116babe 100644 --- a/x/slashing/tick.go +++ b/x/slashing/abci_app.go @@ -16,7 +16,7 @@ func BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock, sk Keeper) sdk.Ta // store whether or not they have actually signed it and slash/unbond any // which have missed too many blocks in a row (downtime slashing) for _, voteInfo := range req.LastCommitInfo.GetVotes() { - sk.handleValidatorSignature(ctx, voteInfo.Validator.Address, voteInfo.Validator.Power, voteInfo.SignedLastBlock) + sk.HandleValidatorSignature(ctx, voteInfo.Validator.Address, voteInfo.Validator.Power, voteInfo.SignedLastBlock) } // Iterate through any newly discovered evidence of infraction @@ -25,7 +25,7 @@ func BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock, sk Keeper) sdk.Ta for _, evidence := range req.ByzantineValidators { switch evidence.Type { case tmtypes.ABCIEvidenceTypeDuplicateVote: - sk.handleDoubleSign(ctx, evidence.Validator.Address, evidence.Height, evidence.Time, evidence.Validator.Power) + sk.HandleDoubleSign(ctx, evidence.Validator.Address, evidence.Height, evidence.Time, evidence.Validator.Power) default: sk.Logger(ctx).Error(fmt.Sprintf("ignored unknown evidence type: %s", evidence.Type)) } diff --git a/x/slashing/tick_test.go b/x/slashing/abci_app_test.go similarity index 100% rename from x/slashing/tick_test.go rename to x/slashing/abci_app_test.go diff --git a/x/slashing/alias.go b/x/slashing/alias.go new file mode 100644 index 000000000000..a3129e7fae93 --- /dev/null +++ b/x/slashing/alias.go @@ -0,0 +1,89 @@ +// nolint +// autogenerated code using github.com/rigelrozanski/multitool +// aliases generated for the following subdirectories: +// ALIASGEN: github.com/cosmos/cosmos-sdk/x/slashing/types +package slashing + +import ( + "github.com/cosmos/cosmos-sdk/x/slashing/types" +) + +const ( + DefaultCodespace = types.DefaultCodespace + CodeInvalidValidator = types.CodeInvalidValidator + CodeValidatorJailed = types.CodeValidatorJailed + CodeValidatorNotJailed = types.CodeValidatorNotJailed + CodeMissingSelfDelegation = types.CodeMissingSelfDelegation + CodeSelfDelegationTooLow = types.CodeSelfDelegationTooLow + CodeMissingSigningInfo = types.CodeMissingSigningInfo + ModuleName = types.ModuleName + StoreKey = types.StoreKey + RouterKey = types.RouterKey + QuerierRoute = types.QuerierRoute + QueryParameters = types.QueryParameters + QuerySigningInfo = types.QuerySigningInfo + QuerySigningInfos = types.QuerySigningInfos + DefaultParamspace = types.DefaultParamspace + DefaultMaxEvidenceAge = types.DefaultMaxEvidenceAge + DefaultSignedBlocksWindow = types.DefaultSignedBlocksWindow + DefaultDowntimeJailDuration = types.DefaultDowntimeJailDuration +) + +var ( + // functions aliases + RegisterCodec = types.RegisterCodec + ErrNoValidatorForAddress = types.ErrNoValidatorForAddress + ErrBadValidatorAddr = types.ErrBadValidatorAddr + ErrValidatorJailed = types.ErrValidatorJailed + ErrValidatorNotJailed = types.ErrValidatorNotJailed + ErrMissingSelfDelegation = types.ErrMissingSelfDelegation + ErrSelfDelegationTooLowToUnjail = types.ErrSelfDelegationTooLowToUnjail + ErrNoSigningInfoFound = types.ErrNoSigningInfoFound + NewGenesisState = types.NewGenesisState + DefaultGenesisState = types.DefaultGenesisState + ValidateGenesis = types.ValidateGenesis + GetValidatorSigningInfoKey = types.GetValidatorSigningInfoKey + GetValidatorSigningInfoAddress = types.GetValidatorSigningInfoAddress + GetValidatorMissedBlockBitArrayPrefixKey = types.GetValidatorMissedBlockBitArrayPrefixKey + GetValidatorMissedBlockBitArrayKey = types.GetValidatorMissedBlockBitArrayKey + GetValidatorSlashingPeriodPrefix = types.GetValidatorSlashingPeriodPrefix + GetValidatorSlashingPeriodKey = types.GetValidatorSlashingPeriodKey + GetAddrPubkeyRelationKey = types.GetAddrPubkeyRelationKey + NewMsgUnjail = types.NewMsgUnjail + ParamKeyTable = types.ParamKeyTable + NewParams = types.NewParams + DefaultParams = types.DefaultParams + NewQuerySigningInfoParams = types.NewQuerySigningInfoParams + NewQuerySigningInfosParams = types.NewQuerySigningInfosParams + NewValidatorSigningInfo = types.NewValidatorSigningInfo + + // variable aliases + ModuleCdc = types.ModuleCdc + ValidatorSigningInfoKey = types.ValidatorSigningInfoKey + ValidatorMissedBlockBitArrayKey = types.ValidatorMissedBlockBitArrayKey + ValidatorSlashingPeriodKey = types.ValidatorSlashingPeriodKey + AddrPubkeyRelationKey = types.AddrPubkeyRelationKey + DoubleSignJailEndTime = types.DoubleSignJailEndTime + DefaultMinSignedPerWindow = types.DefaultMinSignedPerWindow + DefaultSlashFractionDoubleSign = types.DefaultSlashFractionDoubleSign + DefaultSlashFractionDowntime = types.DefaultSlashFractionDowntime + KeyMaxEvidenceAge = types.KeyMaxEvidenceAge + KeySignedBlocksWindow = types.KeySignedBlocksWindow + KeyMinSignedPerWindow = types.KeyMinSignedPerWindow + KeyDowntimeJailDuration = types.KeyDowntimeJailDuration + KeySlashFractionDoubleSign = types.KeySlashFractionDoubleSign + KeySlashFractionDowntime = types.KeySlashFractionDowntime +) + +type ( + CodeType = types.CodeType + StakingKeeper = types.StakingKeeper + AccountKeeper = types.AccountKeeper + GenesisState = types.GenesisState + MissedBlock = types.MissedBlock + MsgUnjail = types.MsgUnjail + Params = types.Params + QuerySigningInfoParams = types.QuerySigningInfoParams + QuerySigningInfosParams = types.QuerySigningInfosParams + ValidatorSigningInfo = types.ValidatorSigningInfo +) diff --git a/x/slashing/client/cli/query.go b/x/slashing/client/cli/query.go index a92c5525d0b2..de149a79dc56 100644 --- a/x/slashing/client/cli/query.go +++ b/x/slashing/client/cli/query.go @@ -6,12 +6,37 @@ import ( "github.com/spf13/cobra" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/context" - "github.com/cosmos/cosmos-sdk/codec" // XXX fix + "github.com/cosmos/cosmos-sdk/client/utils" + "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/slashing" + + "github.com/cosmos/cosmos-sdk/x/slashing/types" ) +// GetQueryCmd returns the cli query commands for this module +func GetQueryCmd(queryRoute string, cdc *codec.Codec) *cobra.Command { + // Group slashing queries under a subcommand + slashingQueryCmd := &cobra.Command{ + Use: types.ModuleName, + Short: "Querying commands for the slashing module", + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: utils.ValidateCmd, + } + + slashingQueryCmd.AddCommand( + client.GetCommands( + GetCmdQuerySigningInfo(queryRoute, cdc), + GetCmdQueryParams(cdc), + )..., + ) + + return slashingQueryCmd + +} + // GetCmdQuerySigningInfo implements the command to query signing info. func GetCmdQuerySigningInfo(storeName string, cdc *codec.Codec) *cobra.Command { return &cobra.Command{ @@ -31,7 +56,7 @@ $ query slashing signing-info cosmosvalconspub1zcjduepqfhvwcmt7p06fvdge } consAddr := sdk.ConsAddress(pk.Address()) - key := slashing.GetValidatorSigningInfoKey(consAddr) + key := types.GetValidatorSigningInfoKey(consAddr) res, err := cliCtx.QueryStore(key, storeName) if err != nil { @@ -42,7 +67,7 @@ $ query slashing signing-info cosmosvalconspub1zcjduepqfhvwcmt7p06fvdge return fmt.Errorf("Validator %s not found in slashing store", consAddr) } - var signingInfo slashing.ValidatorSigningInfo + var signingInfo types.ValidatorSigningInfo cdc.MustUnmarshalBinaryLengthPrefixed(res, &signingInfo) return cliCtx.PrintOutput(signingInfo) }, @@ -62,13 +87,13 @@ $ query slashing params RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) - route := fmt.Sprintf("custom/%s/parameters", slashing.QuerierRoute) + route := fmt.Sprintf("custom/%s/parameters", types.QuerierRoute) res, err := cliCtx.QueryWithData(route, nil) if err != nil { return err } - var params slashing.Params + var params types.Params cdc.MustUnmarshalJSON(res, ¶ms) return cliCtx.PrintOutput(params) }, diff --git a/x/slashing/client/cli/tx.go b/x/slashing/client/cli/tx.go index c049ca3afac7..01663254a197 100644 --- a/x/slashing/client/cli/tx.go +++ b/x/slashing/client/cli/tx.go @@ -1,16 +1,34 @@ package cli import ( + "github.com/spf13/cobra" + + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/utils" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" - "github.com/cosmos/cosmos-sdk/x/slashing" - - "github.com/spf13/cobra" + "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/slashing/types" ) +// GetTxCmd returns the transaction commands for this module +func GetTxCmd(cdc *codec.Codec) *cobra.Command { + slashingTxCmd := &cobra.Command{ + Use: types.ModuleName, + Short: "Slashing transactions subcommands", + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: utils.ValidateCmd, + } + + slashingTxCmd.AddCommand(client.PostCommands( + GetCmdUnjail(cdc), + )...) + + return slashingTxCmd +} + // GetCmdUnjail implements the create unjail validator command. func GetCmdUnjail(cdc *codec.Codec) *cobra.Command { return &cobra.Command{ @@ -22,14 +40,14 @@ func GetCmdUnjail(cdc *codec.Codec) *cobra.Command { $ tx slashing unjail --from mykey `, RunE: func(cmd *cobra.Command, args []string) error { - txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) cliCtx := context.NewCLIContext(). WithCodec(cdc). WithAccountDecoder(cdc) valAddr := cliCtx.GetFromAddress() - msg := slashing.NewMsgUnjail(sdk.ValAddress(valAddr)) + msg := types.NewMsgUnjail(sdk.ValAddress(valAddr)) return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) }, } diff --git a/x/slashing/client/module_client.go b/x/slashing/client/module_client.go deleted file mode 100644 index 97071d785d63..000000000000 --- a/x/slashing/client/module_client.go +++ /dev/null @@ -1,60 +0,0 @@ -package client - -import ( - "github.com/spf13/cobra" - amino "github.com/tendermint/go-amino" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/utils" - "github.com/cosmos/cosmos-sdk/x/slashing" - "github.com/cosmos/cosmos-sdk/x/slashing/client/cli" -) - -// ModuleClient exports all client functionality from this module -type ModuleClient struct { - storeKey string - cdc *amino.Codec -} - -func NewModuleClient(storeKey string, cdc *amino.Codec) ModuleClient { - return ModuleClient{storeKey, cdc} -} - -// GetQueryCmd returns the cli query commands for this module -func (mc ModuleClient) GetQueryCmd() *cobra.Command { - // Group slashing queries under a subcommand - slashingQueryCmd := &cobra.Command{ - Use: slashing.ModuleName, - Short: "Querying commands for the slashing module", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: utils.ValidateCmd, - } - - slashingQueryCmd.AddCommand( - client.GetCommands( - cli.GetCmdQuerySigningInfo(mc.storeKey, mc.cdc), - cli.GetCmdQueryParams(mc.cdc), - )..., - ) - - return slashingQueryCmd - -} - -// GetTxCmd returns the transaction commands for this module -func (mc ModuleClient) GetTxCmd() *cobra.Command { - slashingTxCmd := &cobra.Command{ - Use: slashing.ModuleName, - Short: "Slashing transactions subcommands", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: utils.ValidateCmd, - } - - slashingTxCmd.AddCommand(client.PostCommands( - cli.GetCmdUnjail(mc.cdc), - )...) - - return slashingTxCmd -} diff --git a/x/slashing/client/rest/query.go b/x/slashing/client/rest/query.go index c17b61053e4f..5b673d5cb94a 100644 --- a/x/slashing/client/rest/query.go +++ b/x/slashing/client/rest/query.go @@ -10,7 +10,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/slashing" + "github.com/cosmos/cosmos-sdk/x/slashing/types" ) func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec) { @@ -40,7 +40,7 @@ func signingInfoHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.Hand return } - params := slashing.NewQuerySigningInfoParams(sdk.ConsAddress(pk.Address())) + params := types.NewQuerySigningInfoParams(sdk.ConsAddress(pk.Address())) bz, err := cdc.MarshalJSON(params) if err != nil { @@ -48,7 +48,7 @@ func signingInfoHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.Hand return } - route := fmt.Sprintf("custom/%s/%s", slashing.QuerierRoute, slashing.QuerySigningInfo) + route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QuerySigningInfo) res, err := cliCtx.QueryWithData(route, bz) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) @@ -68,14 +68,14 @@ func signingInfoHandlerListFn(cliCtx context.CLIContext, cdc *codec.Codec) http. return } - params := slashing.NewQuerySigningInfosParams(page, limit) + params := types.NewQuerySigningInfosParams(page, limit) bz, err := cdc.MarshalJSON(params) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return } - route := fmt.Sprintf("custom/%s/%s", slashing.QuerierRoute, slashing.QuerySigningInfos) + route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QuerySigningInfos) res, err := cliCtx.QueryWithData(route, bz) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) @@ -88,7 +88,7 @@ func signingInfoHandlerListFn(cliCtx context.CLIContext, cdc *codec.Codec) http. func queryParamsHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - route := fmt.Sprintf("custom/%s/parameters", slashing.QuerierRoute) + route := fmt.Sprintf("custom/%s/parameters", types.QuerierRoute) res, err := cliCtx.QueryWithData(route, nil) if err != nil { diff --git a/x/slashing/client/rest/rest.go b/x/slashing/client/rest/rest.go index d06cd719df20..d3bfc07350b9 100644 --- a/x/slashing/client/rest/rest.go +++ b/x/slashing/client/rest/rest.go @@ -5,11 +5,10 @@ import ( "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/crypto/keys" ) // RegisterRoutes registers staking-related REST handlers to a router -func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec, kb keys.Keybase) { +func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec) { registerQueryRoutes(cliCtx, r, cdc) - registerTxRoutes(cliCtx, r, cdc, kb) + registerTxRoutes(cliCtx, r, cdc) } diff --git a/x/slashing/client/rest/tx.go b/x/slashing/client/rest/tx.go index 95b93740b0ac..4e1941818a20 100644 --- a/x/slashing/client/rest/tx.go +++ b/x/slashing/client/rest/tx.go @@ -9,16 +9,15 @@ import ( "github.com/cosmos/cosmos-sdk/client/context" clientrest "github.com/cosmos/cosmos-sdk/client/rest" "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/crypto/keys" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/slashing" + "github.com/cosmos/cosmos-sdk/x/slashing/types" ) -func registerTxRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec, kb keys.Keybase) { +func registerTxRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec) { r.HandleFunc( "/slashing/validators/{validatorAddr}/unjail", - unjailRequestHandlerFn(cdc, kb, cliCtx), + unjailRequestHandlerFn(cdc, cliCtx), ).Methods("POST") } @@ -27,7 +26,7 @@ type UnjailReq struct { BaseReq rest.BaseReq `json:"base_req"` } -func unjailRequestHandlerFn(cdc *codec.Codec, kb keys.Keybase, cliCtx context.CLIContext) http.HandlerFunc { +func unjailRequestHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) @@ -60,7 +59,7 @@ func unjailRequestHandlerFn(cdc *codec.Codec, kb keys.Keybase, cliCtx context.CL return } - msg := slashing.NewMsgUnjail(valAddr) + msg := types.NewMsgUnjail(valAddr) err = msg.ValidateBasic() if err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) diff --git a/x/slashing/genesis.go b/x/slashing/genesis.go index ab9f0a0ef814..c39010c670c5 100644 --- a/x/slashing/genesis.go +++ b/x/slashing/genesis.go @@ -1,84 +1,14 @@ package slashing import ( - "fmt" - "time" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/slashing/types" "github.com/cosmos/cosmos-sdk/x/staking/exported" ) -// GenesisState - all slashing state that must be provided at genesis -type GenesisState struct { - Params Params `json:"params"` - SigningInfos map[string]ValidatorSigningInfo `json:"signing_infos"` - MissedBlocks map[string][]MissedBlock `json:"missed_blocks"` -} - -// NewGenesisState creates a new GenesisState object -func NewGenesisState(params Params, signingInfos map[string]ValidatorSigningInfo, - missedBlocks map[string][]MissedBlock) GenesisState { - - return GenesisState{ - Params: params, - SigningInfos: signingInfos, - MissedBlocks: missedBlocks, - } -} - -// MissedBlock -type MissedBlock struct { - Index int64 `json:"index"` - Missed bool `json:"missed"` -} - -// DefaultGenesisState - default GenesisState used by Cosmos Hub -func DefaultGenesisState() GenesisState { - return GenesisState{ - Params: DefaultParams(), - SigningInfos: make(map[string]ValidatorSigningInfo), - MissedBlocks: make(map[string][]MissedBlock), - } -} - -// ValidateGenesis validates the slashing genesis parameters -func ValidateGenesis(data GenesisState) error { - downtime := data.Params.SlashFractionDowntime - if downtime.IsNegative() || downtime.GT(sdk.OneDec()) { - return fmt.Errorf("Slashing fraction downtime should be less than or equal to one and greater than zero, is %s", downtime.String()) - } - - dblSign := data.Params.SlashFractionDoubleSign - if dblSign.IsNegative() || dblSign.GT(sdk.OneDec()) { - return fmt.Errorf("Slashing fraction double sign should be less than or equal to one and greater than zero, is %s", dblSign.String()) - } - - minSign := data.Params.MinSignedPerWindow - if minSign.IsNegative() || minSign.GT(sdk.OneDec()) { - return fmt.Errorf("Min signed per window should be less than or equal to one and greater than zero, is %s", minSign.String()) - } - - maxEvidence := data.Params.MaxEvidenceAge - if maxEvidence < 1*time.Minute { - return fmt.Errorf("Max evidence age must be at least 1 minute, is %s", maxEvidence.String()) - } - - downtimeJail := data.Params.DowntimeJailDuration - if downtimeJail < 1*time.Minute { - return fmt.Errorf("Downtime unblond duration must be at least 1 minute, is %s", downtimeJail.String()) - } - - signedWindow := data.Params.SignedBlocksWindow - if signedWindow < 10 { - return fmt.Errorf("Signed blocks window must be at least 10, is %d", signedWindow) - } - - return nil -} - // InitGenesis initialize default parameters // and the keeper's address to pubkey map -func InitGenesis(ctx sdk.Context, keeper Keeper, stakingKeeper StakingKeeper, data GenesisState) { +func InitGenesis(ctx sdk.Context, keeper Keeper, stakingKeeper types.StakingKeeper, data types.GenesisState) { stakingKeeper.IterateValidators(ctx, func(index int64, validator exported.ValidatorI) bool { keeper.addPubkey(ctx, validator.GetConsPubKey()) @@ -110,19 +40,19 @@ func InitGenesis(ctx sdk.Context, keeper Keeper, stakingKeeper StakingKeeper, da // ExportGenesis writes the current store values // to a genesis file, which can be imported again // with InitGenesis -func ExportGenesis(ctx sdk.Context, keeper Keeper) (data GenesisState) { - var params Params +func ExportGenesis(ctx sdk.Context, keeper Keeper) (data types.GenesisState) { + var params types.Params keeper.paramspace.GetParamSet(ctx, ¶ms) - signingInfos := make(map[string]ValidatorSigningInfo) - missedBlocks := make(map[string][]MissedBlock) - keeper.IterateValidatorSigningInfos(ctx, func(address sdk.ConsAddress, info ValidatorSigningInfo) (stop bool) { + signingInfos := make(map[string]types.ValidatorSigningInfo) + missedBlocks := make(map[string][]types.MissedBlock) + keeper.IterateValidatorSigningInfos(ctx, func(address sdk.ConsAddress, info types.ValidatorSigningInfo) (stop bool) { bechAddr := address.String() signingInfos[bechAddr] = info - localMissedBlocks := []MissedBlock{} + localMissedBlocks := []types.MissedBlock{} keeper.IterateValidatorMissedBlockBitArray(ctx, address, func(index int64, missed bool) (stop bool) { - localMissedBlocks = append(localMissedBlocks, MissedBlock{index, missed}) + localMissedBlocks = append(localMissedBlocks, types.MissedBlock{index, missed}) return false }) missedBlocks[bechAddr] = localMissedBlocks @@ -130,7 +60,7 @@ func ExportGenesis(ctx sdk.Context, keeper Keeper) (data GenesisState) { return false }) - return GenesisState{ + return types.GenesisState{ Params: params, SigningInfos: signingInfos, MissedBlocks: missedBlocks, diff --git a/x/slashing/hooks.go b/x/slashing/hooks.go index 78ac98974008..7535ab4acb10 100644 --- a/x/slashing/hooks.go +++ b/x/slashing/hooks.go @@ -7,13 +7,14 @@ import ( "github.com/tendermint/tendermint/crypto" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/slashing/types" ) func (k Keeper) AfterValidatorBonded(ctx sdk.Context, address sdk.ConsAddress, _ sdk.ValAddress) { // Update the signing info start height or create a new signing info _, found := k.getValidatorSigningInfo(ctx, address) if !found { - signingInfo := NewValidatorSigningInfo( + signingInfo := types.NewValidatorSigningInfo( address, ctx.BlockHeight(), 0, @@ -43,7 +44,7 @@ type Hooks struct { k Keeper } -var _ StakingHooks = Hooks{} +var _ types.StakingHooks = Hooks{} // Return the wrapper struct func (k Keeper) Hooks() Hooks { diff --git a/x/slashing/keeper.go b/x/slashing/keeper.go index 6e29f0ab28ac..e0e4d83113a8 100644 --- a/x/slashing/keeper.go +++ b/x/slashing/keeper.go @@ -10,6 +10,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/params" + "github.com/cosmos/cosmos-sdk/x/slashing/types" ) // Keeper of the slashing store @@ -40,7 +41,7 @@ func (k Keeper) Logger(ctx sdk.Context) log.Logger { return ctx.Logger().With("m // handle a validator signing two blocks at the same height // power: power of the double-signing validator at the height of infraction -func (k Keeper) handleDoubleSign(ctx sdk.Context, addr crypto.Address, infractionHeight int64, timestamp time.Time, power int64) { +func (k Keeper) HandleDoubleSign(ctx sdk.Context, addr crypto.Address, infractionHeight int64, timestamp time.Time, power int64) { logger := k.Logger(ctx) // calculate the age of the evidence @@ -120,7 +121,7 @@ func (k Keeper) handleDoubleSign(ctx sdk.Context, addr crypto.Address, infractio signInfo.Tombstoned = true // Set jailed until to be forever (max time) - signInfo.JailedUntil = DoubleSignJailEndTime + signInfo.JailedUntil = types.DoubleSignJailEndTime // Set validator signing info k.SetValidatorSigningInfo(ctx, consAddr, signInfo) @@ -128,7 +129,7 @@ func (k Keeper) handleDoubleSign(ctx sdk.Context, addr crypto.Address, infractio // handle a validator signature, must be called once per validator per block // TODO refactor to take in a consensus address, additionally should maybe just take in the pubkey too -func (k Keeper) handleValidatorSignature(ctx sdk.Context, addr crypto.Address, power int64, signed bool) { +func (k Keeper) HandleValidatorSignature(ctx sdk.Context, addr crypto.Address, power int64, signed bool) { logger := k.Logger(ctx) height := ctx.BlockHeight() consAddr := sdk.ConsAddress(addr) @@ -215,7 +216,7 @@ func (k Keeper) addPubkey(ctx sdk.Context, pubkey crypto.PubKey) { func (k Keeper) getPubkey(ctx sdk.Context, address crypto.Address) (crypto.PubKey, error) { store := ctx.KVStore(k.storeKey) var pubkey crypto.PubKey - err := k.cdc.UnmarshalBinaryLengthPrefixed(store.Get(getAddrPubkeyRelationKey(address)), &pubkey) + err := k.cdc.UnmarshalBinaryLengthPrefixed(store.Get(types.GetAddrPubkeyRelationKey(address)), &pubkey) if err != nil { return nil, fmt.Errorf("address %v not found", address) } @@ -225,10 +226,10 @@ func (k Keeper) getPubkey(ctx sdk.Context, address crypto.Address) (crypto.PubKe func (k Keeper) setAddrPubkeyRelation(ctx sdk.Context, addr crypto.Address, pubkey crypto.PubKey) { store := ctx.KVStore(k.storeKey) bz := k.cdc.MustMarshalBinaryLengthPrefixed(pubkey) - store.Set(getAddrPubkeyRelationKey(addr), bz) + store.Set(types.GetAddrPubkeyRelationKey(addr), bz) } func (k Keeper) deleteAddrPubkeyRelation(ctx sdk.Context, addr crypto.Address) { store := ctx.KVStore(k.storeKey) - store.Delete(getAddrPubkeyRelationKey(addr)) + store.Delete(types.GetAddrPubkeyRelationKey(addr)) } diff --git a/x/slashing/keeper_test.go b/x/slashing/keeper_test.go index bfb48b8b85d9..4d8654f38eaf 100644 --- a/x/slashing/keeper_test.go +++ b/x/slashing/keeper_test.go @@ -8,13 +8,14 @@ import ( abci "github.com/tendermint/tendermint/abci/types" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/slashing/types" "github.com/cosmos/cosmos-sdk/x/staking" ) // Have to change these parameters for tests // lest the tests take forever -func keeperTestParams() Params { - params := DefaultParams() +func keeperTestParams() types.Params { + params := types.DefaultParams() params.SignedBlocksWindow = 1000 params.DowntimeJailDuration = 60 * 60 return params @@ -43,12 +44,12 @@ func TestHandleDoubleSign(t *testing.T) { require.Equal(t, amt, sk.Validator(ctx, operatorAddr).GetBondedTokens()) // handle a signature to set signing info - keeper.handleValidatorSignature(ctx, val.Address(), amt.Int64(), true) + keeper.HandleValidatorSignature(ctx, val.Address(), amt.Int64(), true) oldTokens := sk.Validator(ctx, operatorAddr).GetTokens() // double sign less than max age - keeper.handleDoubleSign(ctx, val.Address(), 0, time.Unix(0, 0), power) + keeper.HandleDoubleSign(ctx, val.Address(), 0, time.Unix(0, 0), power) // should be jailed require.True(t, sk.Validator(ctx, operatorAddr).IsJailed()) @@ -58,7 +59,7 @@ func TestHandleDoubleSign(t *testing.T) { require.True(t, newTokens.LT(oldTokens)) // New evidence - keeper.handleDoubleSign(ctx, val.Address(), 0, time.Unix(0, 0), power) + keeper.HandleDoubleSign(ctx, val.Address(), 0, time.Unix(0, 0), power) // tokens should be the same (capped slash) require.True(t, sk.Validator(ctx, operatorAddr).GetTokens().Equal(newTokens)) @@ -67,7 +68,7 @@ func TestHandleDoubleSign(t *testing.T) { ctx = ctx.WithBlockHeader(abci.Header{Time: time.Unix(1, 0).Add(sk.GetParams(ctx).UnbondingTime)}) // Still shouldn't be able to unjail - msgUnjail := NewMsgUnjail(operatorAddr) + msgUnjail := types.NewMsgUnjail(operatorAddr) res := handleMsgUnjail(ctx, msgUnjail, keeper) require.False(t, res.IsOK()) @@ -104,14 +105,14 @@ func TestPastMaxEvidenceAge(t *testing.T) { require.Equal(t, amt, sk.Validator(ctx, operatorAddr).GetBondedTokens()) // handle a signature to set signing info - keeper.handleValidatorSignature(ctx, val.Address(), power, true) + keeper.HandleValidatorSignature(ctx, val.Address(), power, true) ctx = ctx.WithBlockHeader(abci.Header{Time: time.Unix(1, 0).Add(keeper.MaxEvidenceAge(ctx))}) oldPower := sk.Validator(ctx, operatorAddr).GetTendermintPower() // double sign past max age - keeper.handleDoubleSign(ctx, val.Address(), 0, time.Unix(0, 0), power) + keeper.HandleDoubleSign(ctx, val.Address(), 0, time.Unix(0, 0), power) // should still be bonded require.True(t, sk.Validator(ctx, operatorAddr).IsBonded()) @@ -153,7 +154,7 @@ func TestHandleAbsentValidator(t *testing.T) { // 1000 first blocks OK for ; height < keeper.SignedBlocksWindow(ctx); height++ { ctx = ctx.WithBlockHeight(height) - keeper.handleValidatorSignature(ctx, val.Address(), power, true) + keeper.HandleValidatorSignature(ctx, val.Address(), power, true) } info, found = keeper.getValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address())) require.True(t, found) @@ -163,7 +164,7 @@ func TestHandleAbsentValidator(t *testing.T) { // 500 blocks missed for ; height < keeper.SignedBlocksWindow(ctx)+(keeper.SignedBlocksWindow(ctx)-keeper.MinSignedPerWindow(ctx)); height++ { ctx = ctx.WithBlockHeight(height) - keeper.handleValidatorSignature(ctx, val.Address(), power, false) + keeper.HandleValidatorSignature(ctx, val.Address(), power, false) } info, found = keeper.getValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address())) require.True(t, found) @@ -178,7 +179,7 @@ func TestHandleAbsentValidator(t *testing.T) { // 501st block missed ctx = ctx.WithBlockHeight(height) - keeper.handleValidatorSignature(ctx, val.Address(), power, false) + keeper.HandleValidatorSignature(ctx, val.Address(), power, false) info, found = keeper.getValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address())) require.True(t, found) require.Equal(t, int64(0), info.StartHeight) @@ -200,7 +201,7 @@ func TestHandleAbsentValidator(t *testing.T) { // 502nd block *also* missed (since the LastCommit would have still included the just-unbonded validator) height++ ctx = ctx.WithBlockHeight(height) - keeper.handleValidatorSignature(ctx, val.Address(), power, false) + keeper.HandleValidatorSignature(ctx, val.Address(), power, false) info, found = keeper.getValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address())) require.True(t, found) require.Equal(t, int64(0), info.StartHeight) @@ -243,7 +244,7 @@ func TestHandleAbsentValidator(t *testing.T) { // validator should not be immediately jailed again height++ ctx = ctx.WithBlockHeight(height) - keeper.handleValidatorSignature(ctx, val.Address(), power, false) + keeper.HandleValidatorSignature(ctx, val.Address(), power, false) validator, _ = sk.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(val)) require.Equal(t, sdk.Bonded, validator.GetStatus()) @@ -251,7 +252,7 @@ func TestHandleAbsentValidator(t *testing.T) { nextHeight := height + keeper.MinSignedPerWindow(ctx) + 1 for ; height < nextHeight; height++ { ctx = ctx.WithBlockHeight(height) - keeper.handleValidatorSignature(ctx, val.Address(), power, false) + keeper.HandleValidatorSignature(ctx, val.Address(), power, false) } // end block @@ -261,7 +262,7 @@ func TestHandleAbsentValidator(t *testing.T) { nextHeight = height + keeper.MinSignedPerWindow(ctx) + 1 for ; height <= nextHeight; height++ { ctx = ctx.WithBlockHeight(height) - keeper.handleValidatorSignature(ctx, val.Address(), power, false) + keeper.HandleValidatorSignature(ctx, val.Address(), power, false) } // end block @@ -296,9 +297,9 @@ func TestHandleNewValidator(t *testing.T) { require.Equal(t, amt, sk.Validator(ctx, addr).GetBondedTokens()) // Now a validator, for two blocks - keeper.handleValidatorSignature(ctx, val.Address(), 100, true) + keeper.HandleValidatorSignature(ctx, val.Address(), 100, true) ctx = ctx.WithBlockHeight(keeper.SignedBlocksWindow(ctx) + 2) - keeper.handleValidatorSignature(ctx, val.Address(), 100, false) + keeper.HandleValidatorSignature(ctx, val.Address(), 100, false) info, found := keeper.getValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address())) require.True(t, found) @@ -333,13 +334,13 @@ func TestHandleAlreadyJailed(t *testing.T) { height := int64(0) for ; height < keeper.SignedBlocksWindow(ctx); height++ { ctx = ctx.WithBlockHeight(height) - keeper.handleValidatorSignature(ctx, val.Address(), power, true) + keeper.HandleValidatorSignature(ctx, val.Address(), power, true) } // 501 blocks missed for ; height < keeper.SignedBlocksWindow(ctx)+(keeper.SignedBlocksWindow(ctx)-keeper.MinSignedPerWindow(ctx))+1; height++ { ctx = ctx.WithBlockHeight(height) - keeper.handleValidatorSignature(ctx, val.Address(), power, false) + keeper.HandleValidatorSignature(ctx, val.Address(), power, false) } // end block @@ -355,7 +356,7 @@ func TestHandleAlreadyJailed(t *testing.T) { // another block missed ctx = ctx.WithBlockHeight(height) - keeper.handleValidatorSignature(ctx, val.Address(), power, false) + keeper.HandleValidatorSignature(ctx, val.Address(), power, false) // validator should not have been slashed twice validator, _ = sk.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(val)) @@ -387,7 +388,7 @@ func TestValidatorDippingInAndOut(t *testing.T) { height := int64(0) for ; height < int64(100); height++ { ctx = ctx.WithBlockHeight(height) - keeper.handleValidatorSignature(ctx, val.Address(), power, true) + keeper.HandleValidatorSignature(ctx, val.Address(), power, true) } // validator kicked out of validator set @@ -414,7 +415,7 @@ func TestValidatorDippingInAndOut(t *testing.T) { newPower := int64(103) // validator misses a block - keeper.handleValidatorSignature(ctx, val.Address(), newPower, false) + keeper.HandleValidatorSignature(ctx, val.Address(), newPower, false) height++ // shouldn't be jailed/kicked yet @@ -425,7 +426,7 @@ func TestValidatorDippingInAndOut(t *testing.T) { latest := height for ; height < latest+500; height++ { ctx = ctx.WithBlockHeight(height) - keeper.handleValidatorSignature(ctx, val.Address(), newPower, false) + keeper.HandleValidatorSignature(ctx, val.Address(), newPower, false) } // should now be jailed & kicked @@ -450,7 +451,7 @@ func TestValidatorDippingInAndOut(t *testing.T) { // validator rejoins and starts signing again sk.Unjail(ctx, consAddr) - keeper.handleValidatorSignature(ctx, val.Address(), newPower, true) + keeper.HandleValidatorSignature(ctx, val.Address(), newPower, true) height++ // validator should not be kicked since we reset counter/array when it was jailed @@ -462,7 +463,7 @@ func TestValidatorDippingInAndOut(t *testing.T) { latest = height for ; height < latest+501; height++ { ctx = ctx.WithBlockHeight(height) - keeper.handleValidatorSignature(ctx, val.Address(), newPower, false) + keeper.HandleValidatorSignature(ctx, val.Address(), newPower, false) } // validator should now be jailed & kicked diff --git a/x/slashing/module.go b/x/slashing/module.go index 15caaf6bb429..6d5561d0802a 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -3,27 +3,33 @@ package slashing import ( "encoding/json" + "github.com/gorilla/mux" + "github.com/spf13/cobra" + + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - abci "github.com/tendermint/tendermint/abci/types" + "github.com/cosmos/cosmos-sdk/types/module" + "github.com/cosmos/cosmos-sdk/x/slashing/client/cli" + "github.com/cosmos/cosmos-sdk/x/slashing/client/rest" + "github.com/cosmos/cosmos-sdk/x/slashing/types" ) var ( - _ sdk.AppModule = AppModule{} - _ sdk.AppModuleBasic = AppModuleBasic{} + _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} ) -// name of this module -const ModuleName = "slashing" - // app module basics object type AppModuleBasic struct{} -var _ sdk.AppModuleBasic = AppModuleBasic{} +var _ module.AppModuleBasic = AppModuleBasic{} // module name func (AppModuleBasic) Name() string { - return ModuleName + return types.ModuleName } // register module codec @@ -33,19 +39,34 @@ func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) { // default genesis state func (AppModuleBasic) DefaultGenesis() json.RawMessage { - return moduleCdc.MustMarshalJSON(DefaultGenesisState()) + return ModuleCdc.MustMarshalJSON(DefaultGenesisState()) } // module validate genesis func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { var data GenesisState - err := moduleCdc.UnmarshalJSON(bz, &data) + err := ModuleCdc.UnmarshalJSON(bz, &data) if err != nil { return err } return ValidateGenesis(data) } +// register rest routes +func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router, cdc *codec.Codec) { + rest.RegisterRoutes(ctx, rtr, cdc) +} + +// get the root tx command of this module +func (AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command { + return cli.GetTxCmd(cdc) +} + +// get the root query command of this module +func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { + return cli.GetQueryCmd(StoreKey, cdc) +} + //___________________________ // app module type AppModule struct { @@ -94,7 +115,7 @@ func (am AppModule) NewQuerierHandler() sdk.Querier { // module init-genesis func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate { var genesisState GenesisState - moduleCdc.MustUnmarshalJSON(data, &genesisState) + ModuleCdc.MustUnmarshalJSON(data, &genesisState) InitGenesis(ctx, am.keeper, am.stakingKeeper, genesisState) return []abci.ValidatorUpdate{} } @@ -102,7 +123,7 @@ func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.Va // module export genesis func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { gs := ExportGenesis(ctx, am.keeper) - return moduleCdc.MustMarshalJSON(gs) + return ModuleCdc.MustMarshalJSON(gs) } // module begin-block diff --git a/x/slashing/params.go b/x/slashing/params.go index 98cae397fe6f..dfe676a88a0d 100644 --- a/x/slashing/params.go +++ b/x/slashing/params.go @@ -1,122 +1,28 @@ package slashing import ( - "fmt" "time" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/params" + "github.com/cosmos/cosmos-sdk/x/slashing/types" ) -// Default parameter namespace -const ( - DefaultParamspace = ModuleName - DefaultMaxEvidenceAge time.Duration = 60 * 2 * time.Second - DefaultSignedBlocksWindow int64 = 100 - DefaultDowntimeJailDuration time.Duration = 60 * 10 * time.Second -) - -// The Double Sign Jail period ends at Max Time supported by Amino (Dec 31, 9999 - 23:59:59 GMT) -var ( - DoubleSignJailEndTime = time.Unix(253402300799, 0) - DefaultMinSignedPerWindow = sdk.NewDecWithPrec(5, 1) - DefaultSlashFractionDoubleSign = sdk.NewDec(1).Quo(sdk.NewDec(20)) - DefaultSlashFractionDowntime = sdk.NewDec(1).Quo(sdk.NewDec(100)) -) - -// Parameter store keys -var ( - KeyMaxEvidenceAge = []byte("MaxEvidenceAge") - KeySignedBlocksWindow = []byte("SignedBlocksWindow") - KeyMinSignedPerWindow = []byte("MinSignedPerWindow") - KeyDowntimeJailDuration = []byte("DowntimeJailDuration") - KeySlashFractionDoubleSign = []byte("SlashFractionDoubleSign") - KeySlashFractionDowntime = []byte("SlashFractionDowntime") -) - -// ParamKeyTable for slashing module -func ParamKeyTable() params.KeyTable { - return params.NewKeyTable().RegisterParamSet(&Params{}) -} - -// Params - used for initializing default parameter for slashing at genesis -type Params struct { - MaxEvidenceAge time.Duration `json:"max_evidence_age"` - SignedBlocksWindow int64 `json:"signed_blocks_window"` - MinSignedPerWindow sdk.Dec `json:"min_signed_per_window"` - DowntimeJailDuration time.Duration `json:"downtime_jail_duration"` - SlashFractionDoubleSign sdk.Dec `json:"slash_fraction_double_sign"` - SlashFractionDowntime sdk.Dec `json:"slash_fraction_downtime"` -} - -// NewParams creates a new Params object -func NewParams(maxEvidenceAge time.Duration, signedBlocksWindow int64, - minSignedPerWindow sdk.Dec, downtimeJailDuration time.Duration, - slashFractionDoubleSign sdk.Dec, slashFractionDowntime sdk.Dec) Params { - - return Params{ - MaxEvidenceAge: maxEvidenceAge, - SignedBlocksWindow: signedBlocksWindow, - MinSignedPerWindow: minSignedPerWindow, - DowntimeJailDuration: downtimeJailDuration, - SlashFractionDoubleSign: slashFractionDoubleSign, - SlashFractionDowntime: slashFractionDowntime, - } -} - -func (p Params) String() string { - return fmt.Sprintf(`Slashing Params: - MaxEvidenceAge: %s - SignedBlocksWindow: %d - MinSignedPerWindow: %s - DowntimeJailDuration: %s - SlashFractionDoubleSign: %s - SlashFractionDowntime: %s`, p.MaxEvidenceAge, - p.SignedBlocksWindow, p.MinSignedPerWindow, - p.DowntimeJailDuration, p.SlashFractionDoubleSign, - p.SlashFractionDowntime) -} - -// Implements params.ParamSet -func (p *Params) ParamSetPairs() params.ParamSetPairs { - return params.ParamSetPairs{ - {KeyMaxEvidenceAge, &p.MaxEvidenceAge}, - {KeySignedBlocksWindow, &p.SignedBlocksWindow}, - {KeyMinSignedPerWindow, &p.MinSignedPerWindow}, - {KeyDowntimeJailDuration, &p.DowntimeJailDuration}, - {KeySlashFractionDoubleSign, &p.SlashFractionDoubleSign}, - {KeySlashFractionDowntime, &p.SlashFractionDowntime}, - } -} - -// Default parameters for this module -func DefaultParams() Params { - return Params{ - MaxEvidenceAge: DefaultMaxEvidenceAge, - SignedBlocksWindow: DefaultSignedBlocksWindow, - MinSignedPerWindow: DefaultMinSignedPerWindow, - DowntimeJailDuration: DefaultDowntimeJailDuration, - SlashFractionDoubleSign: DefaultSlashFractionDoubleSign, - SlashFractionDowntime: DefaultSlashFractionDowntime, - } -} - // MaxEvidenceAge - max age for evidence func (k Keeper) MaxEvidenceAge(ctx sdk.Context) (res time.Duration) { - k.paramspace.Get(ctx, KeyMaxEvidenceAge, &res) + k.paramspace.Get(ctx, types.KeyMaxEvidenceAge, &res) return } // SignedBlocksWindow - sliding window for downtime slashing func (k Keeper) SignedBlocksWindow(ctx sdk.Context) (res int64) { - k.paramspace.Get(ctx, KeySignedBlocksWindow, &res) + k.paramspace.Get(ctx, types.KeySignedBlocksWindow, &res) return } // Downtime slashing threshold func (k Keeper) MinSignedPerWindow(ctx sdk.Context) int64 { var minSignedPerWindow sdk.Dec - k.paramspace.Get(ctx, KeyMinSignedPerWindow, &minSignedPerWindow) + k.paramspace.Get(ctx, types.KeyMinSignedPerWindow, &minSignedPerWindow) signedBlocksWindow := k.SignedBlocksWindow(ctx) // NOTE: RoundInt64 will never panic as minSignedPerWindow is @@ -126,24 +32,24 @@ func (k Keeper) MinSignedPerWindow(ctx sdk.Context) int64 { // Downtime unbond duration func (k Keeper) DowntimeJailDuration(ctx sdk.Context) (res time.Duration) { - k.paramspace.Get(ctx, KeyDowntimeJailDuration, &res) + k.paramspace.Get(ctx, types.KeyDowntimeJailDuration, &res) return } // SlashFractionDoubleSign func (k Keeper) SlashFractionDoubleSign(ctx sdk.Context) (res sdk.Dec) { - k.paramspace.Get(ctx, KeySlashFractionDoubleSign, &res) + k.paramspace.Get(ctx, types.KeySlashFractionDoubleSign, &res) return } // SlashFractionDowntime func (k Keeper) SlashFractionDowntime(ctx sdk.Context) (res sdk.Dec) { - k.paramspace.Get(ctx, KeySlashFractionDowntime, &res) + k.paramspace.Get(ctx, types.KeySlashFractionDowntime, &res) return } // GetParams returns the total set of slashing parameters. -func (k Keeper) GetParams(ctx sdk.Context) (params Params) { +func (k Keeper) GetParams(ctx sdk.Context) (params types.Params) { k.paramspace.GetParamSet(ctx, ¶ms) return params } diff --git a/x/slashing/querier.go b/x/slashing/querier.go index e937f88a99b3..fa4b56aefcca 100644 --- a/x/slashing/querier.go +++ b/x/slashing/querier.go @@ -9,13 +9,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -// Query endpoints supported by the slashing querier -const ( - QueryParameters = "parameters" - QuerySigningInfo = "signingInfo" - QuerySigningInfos = "signingInfos" -) - // NewQuerier creates a new querier for slashing clients. func NewQuerier(k Keeper) sdk.Querier { return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, sdk.Error) { @@ -35,7 +28,7 @@ func NewQuerier(k Keeper) sdk.Querier { func queryParams(ctx sdk.Context, k Keeper) ([]byte, sdk.Error) { params := k.GetParams(ctx) - res, err := codec.MarshalJSONIndent(moduleCdc, params) + res, err := codec.MarshalJSONIndent(ModuleCdc, params) if err != nil { return nil, sdk.ErrInternal(sdk.AppendMsgToErr("failed to marshal JSON", err.Error())) } @@ -43,20 +36,10 @@ func queryParams(ctx sdk.Context, k Keeper) ([]byte, sdk.Error) { return res, nil } -// QuerySigningInfoParams defines the params for the following queries: -// - 'custom/slashing/signingInfo' -type QuerySigningInfoParams struct { - ConsAddress sdk.ConsAddress -} - -func NewQuerySigningInfoParams(consAddr sdk.ConsAddress) QuerySigningInfoParams { - return QuerySigningInfoParams{consAddr} -} - func querySigningInfo(ctx sdk.Context, req abci.RequestQuery, k Keeper) ([]byte, sdk.Error) { var params QuerySigningInfoParams - err := moduleCdc.UnmarshalJSON(req.Data, ¶ms) + err := ModuleCdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { return nil, sdk.ErrInternal(fmt.Sprintf("failed to parse params: %s", err)) } @@ -66,7 +49,7 @@ func querySigningInfo(ctx sdk.Context, req abci.RequestQuery, k Keeper) ([]byte, return nil, ErrNoSigningInfoFound(DefaultCodespace, params.ConsAddress) } - res, err := codec.MarshalJSONIndent(moduleCdc, signingInfo) + res, err := codec.MarshalJSONIndent(ModuleCdc, signingInfo) if err != nil { return nil, sdk.ErrInternal(sdk.AppendMsgToErr("failed to JSON marshal result: %s", err.Error())) } @@ -74,20 +57,10 @@ func querySigningInfo(ctx sdk.Context, req abci.RequestQuery, k Keeper) ([]byte, return res, nil } -// QuerySigningInfosParams defines the params for the following queries: -// - 'custom/slashing/signingInfos' -type QuerySigningInfosParams struct { - Page, Limit int -} - -func NewQuerySigningInfosParams(page, limit int) QuerySigningInfosParams { - return QuerySigningInfosParams{page, limit} -} - func querySigningInfos(ctx sdk.Context, req abci.RequestQuery, k Keeper) ([]byte, sdk.Error) { var params QuerySigningInfosParams - err := moduleCdc.UnmarshalJSON(req.Data, ¶ms) + err := ModuleCdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { return nil, sdk.ErrInternal(fmt.Sprintf("failed to parse params: %s", err)) } @@ -118,7 +91,7 @@ func querySigningInfos(ctx sdk.Context, req abci.RequestQuery, k Keeper) ([]byte signingInfos = signingInfos[start:end] } - res, err := codec.MarshalJSONIndent(moduleCdc, signingInfos) + res, err := codec.MarshalJSONIndent(ModuleCdc, signingInfos) if err != nil { return nil, sdk.ErrInternal(sdk.AppendMsgToErr("failed to JSON marshal result: %s", err.Error())) } diff --git a/x/slashing/signing_info.go b/x/slashing/signing_info.go index 01f967fd6046..f9cce43ac85e 100644 --- a/x/slashing/signing_info.go +++ b/x/slashing/signing_info.go @@ -1,16 +1,14 @@ package slashing import ( - "fmt" - "time" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/slashing/types" ) // Stored by *validator* address (not operator address) -func (k Keeper) getValidatorSigningInfo(ctx sdk.Context, address sdk.ConsAddress) (info ValidatorSigningInfo, found bool) { +func (k Keeper) getValidatorSigningInfo(ctx sdk.Context, address sdk.ConsAddress) (info types.ValidatorSigningInfo, found bool) { store := ctx.KVStore(k.storeKey) - bz := store.Get(GetValidatorSigningInfoKey(address)) + bz := store.Get(types.GetValidatorSigningInfoKey(address)) if bz == nil { found = false return @@ -21,13 +19,15 @@ func (k Keeper) getValidatorSigningInfo(ctx sdk.Context, address sdk.ConsAddress } // Stored by *validator* address (not operator address) -func (k Keeper) IterateValidatorSigningInfos(ctx sdk.Context, handler func(address sdk.ConsAddress, info ValidatorSigningInfo) (stop bool)) { +func (k Keeper) IterateValidatorSigningInfos(ctx sdk.Context, + handler func(address sdk.ConsAddress, info types.ValidatorSigningInfo) (stop bool)) { + store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, ValidatorSigningInfoKey) + iter := sdk.KVStorePrefixIterator(store, types.ValidatorSigningInfoKey) defer iter.Close() for ; iter.Valid(); iter.Next() { - address := GetValidatorSigningInfoAddress(iter.Key()) - var info ValidatorSigningInfo + address := types.GetValidatorSigningInfoAddress(iter.Key()) + var info types.ValidatorSigningInfo k.cdc.MustUnmarshalBinaryLengthPrefixed(iter.Value(), &info) if handler(address, info) { break @@ -36,16 +36,16 @@ func (k Keeper) IterateValidatorSigningInfos(ctx sdk.Context, handler func(addre } // Stored by *validator* address (not operator address) -func (k Keeper) SetValidatorSigningInfo(ctx sdk.Context, address sdk.ConsAddress, info ValidatorSigningInfo) { +func (k Keeper) SetValidatorSigningInfo(ctx sdk.Context, address sdk.ConsAddress, info types.ValidatorSigningInfo) { store := ctx.KVStore(k.storeKey) bz := k.cdc.MustMarshalBinaryLengthPrefixed(info) - store.Set(GetValidatorSigningInfoKey(address), bz) + store.Set(types.GetValidatorSigningInfoKey(address), bz) } // Stored by *validator* address (not operator address) func (k Keeper) getValidatorMissedBlockBitArray(ctx sdk.Context, address sdk.ConsAddress, index int64) (missed bool) { store := ctx.KVStore(k.storeKey) - bz := store.Get(GetValidatorMissedBlockBitArrayKey(address, index)) + bz := store.Get(types.GetValidatorMissedBlockBitArrayKey(address, index)) if bz == nil { // lazy: treat empty key as not missed missed = false @@ -56,13 +56,15 @@ func (k Keeper) getValidatorMissedBlockBitArray(ctx sdk.Context, address sdk.Con } // Stored by *validator* address (not operator address) -func (k Keeper) IterateValidatorMissedBlockBitArray(ctx sdk.Context, address sdk.ConsAddress, handler func(index int64, missed bool) (stop bool)) { +func (k Keeper) IterateValidatorMissedBlockBitArray(ctx sdk.Context, + address sdk.ConsAddress, handler func(index int64, missed bool) (stop bool)) { + store := ctx.KVStore(k.storeKey) index := int64(0) // Array may be sparse for ; index < k.SignedBlocksWindow(ctx); index++ { var missed bool - bz := store.Get(GetValidatorMissedBlockBitArrayKey(address, index)) + bz := store.Get(types.GetValidatorMissedBlockBitArrayKey(address, index)) if bz == nil { continue } @@ -77,54 +79,15 @@ func (k Keeper) IterateValidatorMissedBlockBitArray(ctx sdk.Context, address sdk func (k Keeper) setValidatorMissedBlockBitArray(ctx sdk.Context, address sdk.ConsAddress, index int64, missed bool) { store := ctx.KVStore(k.storeKey) bz := k.cdc.MustMarshalBinaryLengthPrefixed(missed) - store.Set(GetValidatorMissedBlockBitArrayKey(address, index), bz) + store.Set(types.GetValidatorMissedBlockBitArrayKey(address, index), bz) } // Stored by *validator* address (not operator address) func (k Keeper) clearValidatorMissedBlockBitArray(ctx sdk.Context, address sdk.ConsAddress) { store := ctx.KVStore(k.storeKey) - iter := sdk.KVStorePrefixIterator(store, GetValidatorMissedBlockBitArrayPrefixKey(address)) + iter := sdk.KVStorePrefixIterator(store, types.GetValidatorMissedBlockBitArrayPrefixKey(address)) defer iter.Close() for ; iter.Valid(); iter.Next() { store.Delete(iter.Key()) } } - -// Signing info for a validator -type ValidatorSigningInfo struct { - Address sdk.ConsAddress `json:"address"` // validator consensus address - StartHeight int64 `json:"start_height"` // height at which validator was first a candidate OR was unjailed - IndexOffset int64 `json:"index_offset"` // index offset into signed block bit array - JailedUntil time.Time `json:"jailed_until"` // timestamp validator cannot be unjailed until - Tombstoned bool `json:"tombstoned"` // whether or not a validator has been tombstoned (killed out of validator set) - MissedBlocksCounter int64 `json:"missed_blocks_counter"` // missed blocks counter (to avoid scanning the array every time) -} - -// Construct a new `ValidatorSigningInfo` struct -func NewValidatorSigningInfo( - condAddr sdk.ConsAddress, startHeight, indexOffset int64, - jailedUntil time.Time, tombstoned bool, missedBlocksCounter int64, -) ValidatorSigningInfo { - - return ValidatorSigningInfo{ - Address: condAddr, - StartHeight: startHeight, - IndexOffset: indexOffset, - JailedUntil: jailedUntil, - Tombstoned: tombstoned, - MissedBlocksCounter: missedBlocksCounter, - } -} - -// Return human readable signing info -func (i ValidatorSigningInfo) String() string { - return fmt.Sprintf(`Validator Signing Info: - Address: %s - Start Height: %d - Index Offset: %d - Jailed Until: %v - Tombstoned: %t - Missed Blocks Counter: %d`, - i.Address, i.StartHeight, i.IndexOffset, i.JailedUntil, - i.Tombstoned, i.MissedBlocksCounter) -} diff --git a/x/slashing/codec.go b/x/slashing/types/codec.go similarity index 57% rename from x/slashing/codec.go rename to x/slashing/types/codec.go index f48ce6fc6afa..1a4d62c4e190 100644 --- a/x/slashing/codec.go +++ b/x/slashing/types/codec.go @@ -1,4 +1,4 @@ -package slashing +package types import ( "github.com/cosmos/cosmos-sdk/codec" @@ -9,11 +9,12 @@ func RegisterCodec(cdc *codec.Codec) { cdc.RegisterConcrete(MsgUnjail{}, "cosmos-sdk/MsgUnjail", nil) } -var moduleCdc = codec.New() +// module codec +var ModuleCdc *codec.Codec func init() { - cdc := codec.New() - RegisterCodec(cdc) - codec.RegisterCrypto(cdc) - moduleCdc = cdc.Seal() + ModuleCdc = codec.New() + RegisterCodec(ModuleCdc) + codec.RegisterCrypto(ModuleCdc) + ModuleCdc.Seal() } diff --git a/x/slashing/errors.go b/x/slashing/types/errors.go similarity index 99% rename from x/slashing/errors.go rename to x/slashing/types/errors.go index 47a52159213d..2e0fa8349333 100644 --- a/x/slashing/errors.go +++ b/x/slashing/types/errors.go @@ -1,5 +1,5 @@ //nolint -package slashing +package types import ( "fmt" diff --git a/x/slashing/expected_keepers.go b/x/slashing/types/expected_keepers.go similarity index 99% rename from x/slashing/expected_keepers.go rename to x/slashing/types/expected_keepers.go index 0c2f20a6fbe9..94b6276c0424 100644 --- a/x/slashing/expected_keepers.go +++ b/x/slashing/types/expected_keepers.go @@ -1,4 +1,4 @@ -package slashing +package types import ( sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/slashing/types/genesis.go b/x/slashing/types/genesis.go new file mode 100644 index 000000000000..a375235b798b --- /dev/null +++ b/x/slashing/types/genesis.go @@ -0,0 +1,76 @@ +package types + +import ( + "fmt" + "time" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// GenesisState - all slashing state that must be provided at genesis +type GenesisState struct { + Params Params `json:"params"` + SigningInfos map[string]ValidatorSigningInfo `json:"signing_infos"` + MissedBlocks map[string][]MissedBlock `json:"missed_blocks"` +} + +// NewGenesisState creates a new GenesisState object +func NewGenesisState(params Params, signingInfos map[string]ValidatorSigningInfo, + missedBlocks map[string][]MissedBlock) GenesisState { + + return GenesisState{ + Params: params, + SigningInfos: signingInfos, + MissedBlocks: missedBlocks, + } +} + +// MissedBlock +type MissedBlock struct { + Index int64 `json:"index"` + Missed bool `json:"missed"` +} + +// DefaultGenesisState - default GenesisState used by Cosmos Hub +func DefaultGenesisState() GenesisState { + return GenesisState{ + Params: DefaultParams(), + SigningInfos: make(map[string]ValidatorSigningInfo), + MissedBlocks: make(map[string][]MissedBlock), + } +} + +// ValidateGenesis validates the slashing genesis parameters +func ValidateGenesis(data GenesisState) error { + downtime := data.Params.SlashFractionDowntime + if downtime.IsNegative() || downtime.GT(sdk.OneDec()) { + return fmt.Errorf("Slashing fraction downtime should be less than or equal to one and greater than zero, is %s", downtime.String()) + } + + dblSign := data.Params.SlashFractionDoubleSign + if dblSign.IsNegative() || dblSign.GT(sdk.OneDec()) { + return fmt.Errorf("Slashing fraction double sign should be less than or equal to one and greater than zero, is %s", dblSign.String()) + } + + minSign := data.Params.MinSignedPerWindow + if minSign.IsNegative() || minSign.GT(sdk.OneDec()) { + return fmt.Errorf("Min signed per window should be less than or equal to one and greater than zero, is %s", minSign.String()) + } + + maxEvidence := data.Params.MaxEvidenceAge + if maxEvidence < 1*time.Minute { + return fmt.Errorf("Max evidence age must be at least 1 minute, is %s", maxEvidence.String()) + } + + downtimeJail := data.Params.DowntimeJailDuration + if downtimeJail < 1*time.Minute { + return fmt.Errorf("Downtime unblond duration must be at least 1 minute, is %s", downtimeJail.String()) + } + + signedWindow := data.Params.SignedBlocksWindow + if signedWindow < 10 { + return fmt.Errorf("Signed blocks window must be at least 10, is %d", signedWindow) + } + + return nil +} diff --git a/x/slashing/keys.go b/x/slashing/types/keys.go similarity index 86% rename from x/slashing/keys.go rename to x/slashing/types/keys.go index 009a31b4aa48..65e52a12786a 100644 --- a/x/slashing/keys.go +++ b/x/slashing/types/keys.go @@ -1,4 +1,4 @@ -package slashing +package types import ( "encoding/binary" @@ -7,6 +7,9 @@ import ( ) const ( + // module name + ModuleName = "slashing" + // StoreKey is the store key string for slashing StoreKey = ModuleName @@ -17,6 +20,13 @@ const ( QuerierRoute = ModuleName ) +// Query endpoints supported by the slashing querier +const ( + QueryParameters = "parameters" + QuerySigningInfo = "signingInfo" + QuerySigningInfos = "signingInfos" +) + // key prefix bytes var ( ValidatorSigningInfoKey = []byte{0x01} // Prefix for signing info @@ -64,6 +74,7 @@ func GetValidatorSlashingPeriodKey(v sdk.ConsAddress, startHeight int64) []byte return append(GetValidatorSlashingPeriodPrefix(v), b...) } -func getAddrPubkeyRelationKey(address []byte) []byte { +// get pubkey relation key used to get the pubkey from the address +func GetAddrPubkeyRelationKey(address []byte) []byte { return append(AddrPubkeyRelationKey, address...) } diff --git a/x/slashing/msg.go b/x/slashing/types/msg.go similarity index 94% rename from x/slashing/msg.go rename to x/slashing/types/msg.go index 5e49969f8732..2988cb7dcc36 100644 --- a/x/slashing/msg.go +++ b/x/slashing/types/msg.go @@ -1,4 +1,4 @@ -package slashing +package types import ( sdk "github.com/cosmos/cosmos-sdk/types" @@ -27,7 +27,7 @@ func (msg MsgUnjail) GetSigners() []sdk.AccAddress { // get the bytes for the message signer to sign on func (msg MsgUnjail) GetSignBytes() []byte { - bz := moduleCdc.MustMarshalJSON(msg) + bz := ModuleCdc.MustMarshalJSON(msg) return sdk.MustSortJSON(bz) } diff --git a/x/slashing/msg_test.go b/x/slashing/types/msg_test.go similarity index 95% rename from x/slashing/msg_test.go rename to x/slashing/types/msg_test.go index f0e19fc54294..31f7a70e75db 100644 --- a/x/slashing/msg_test.go +++ b/x/slashing/types/msg_test.go @@ -1,4 +1,4 @@ -package slashing +package types import ( "testing" diff --git a/x/slashing/types/params.go b/x/slashing/types/params.go new file mode 100644 index 000000000000..6173effe016c --- /dev/null +++ b/x/slashing/types/params.go @@ -0,0 +1,102 @@ +package types + +import ( + "fmt" + "time" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/params" +) + +// Default parameter namespace +const ( + DefaultParamspace = ModuleName + DefaultMaxEvidenceAge time.Duration = 60 * 2 * time.Second + DefaultSignedBlocksWindow int64 = 100 + DefaultDowntimeJailDuration time.Duration = 60 * 10 * time.Second +) + +// The Double Sign Jail period ends at Max Time supported by Amino (Dec 31, 9999 - 23:59:59 GMT) +var ( + DoubleSignJailEndTime = time.Unix(253402300799, 0) + DefaultMinSignedPerWindow = sdk.NewDecWithPrec(5, 1) + DefaultSlashFractionDoubleSign = sdk.NewDec(1).Quo(sdk.NewDec(20)) + DefaultSlashFractionDowntime = sdk.NewDec(1).Quo(sdk.NewDec(100)) +) + +// Parameter store keys +var ( + KeyMaxEvidenceAge = []byte("MaxEvidenceAge") + KeySignedBlocksWindow = []byte("SignedBlocksWindow") + KeyMinSignedPerWindow = []byte("MinSignedPerWindow") + KeyDowntimeJailDuration = []byte("DowntimeJailDuration") + KeySlashFractionDoubleSign = []byte("SlashFractionDoubleSign") + KeySlashFractionDowntime = []byte("SlashFractionDowntime") +) + +// ParamKeyTable for slashing module +func ParamKeyTable() params.KeyTable { + return params.NewKeyTable().RegisterParamSet(&Params{}) +} + +// Params - used for initializing default parameter for slashing at genesis +type Params struct { + MaxEvidenceAge time.Duration `json:"max_evidence_age"` + SignedBlocksWindow int64 `json:"signed_blocks_window"` + MinSignedPerWindow sdk.Dec `json:"min_signed_per_window"` + DowntimeJailDuration time.Duration `json:"downtime_jail_duration"` + SlashFractionDoubleSign sdk.Dec `json:"slash_fraction_double_sign"` + SlashFractionDowntime sdk.Dec `json:"slash_fraction_downtime"` +} + +// NewParams creates a new Params object +func NewParams(maxEvidenceAge time.Duration, signedBlocksWindow int64, + minSignedPerWindow sdk.Dec, downtimeJailDuration time.Duration, + slashFractionDoubleSign sdk.Dec, slashFractionDowntime sdk.Dec) Params { + + return Params{ + MaxEvidenceAge: maxEvidenceAge, + SignedBlocksWindow: signedBlocksWindow, + MinSignedPerWindow: minSignedPerWindow, + DowntimeJailDuration: downtimeJailDuration, + SlashFractionDoubleSign: slashFractionDoubleSign, + SlashFractionDowntime: slashFractionDowntime, + } +} + +func (p Params) String() string { + return fmt.Sprintf(`Slashing Params: + MaxEvidenceAge: %s + SignedBlocksWindow: %d + MinSignedPerWindow: %s + DowntimeJailDuration: %s + SlashFractionDoubleSign: %s + SlashFractionDowntime: %s`, p.MaxEvidenceAge, + p.SignedBlocksWindow, p.MinSignedPerWindow, + p.DowntimeJailDuration, p.SlashFractionDoubleSign, + p.SlashFractionDowntime) +} + +// Implements params.ParamSet +func (p *Params) ParamSetPairs() params.ParamSetPairs { + return params.ParamSetPairs{ + {KeyMaxEvidenceAge, &p.MaxEvidenceAge}, + {KeySignedBlocksWindow, &p.SignedBlocksWindow}, + {KeyMinSignedPerWindow, &p.MinSignedPerWindow}, + {KeyDowntimeJailDuration, &p.DowntimeJailDuration}, + {KeySlashFractionDoubleSign, &p.SlashFractionDoubleSign}, + {KeySlashFractionDowntime, &p.SlashFractionDowntime}, + } +} + +// Default parameters for this module +func DefaultParams() Params { + return Params{ + MaxEvidenceAge: DefaultMaxEvidenceAge, + SignedBlocksWindow: DefaultSignedBlocksWindow, + MinSignedPerWindow: DefaultMinSignedPerWindow, + DowntimeJailDuration: DefaultDowntimeJailDuration, + SlashFractionDoubleSign: DefaultSlashFractionDoubleSign, + SlashFractionDowntime: DefaultSlashFractionDowntime, + } +} diff --git a/x/slashing/types/querier.go b/x/slashing/types/querier.go new file mode 100644 index 000000000000..d8850b0b2678 --- /dev/null +++ b/x/slashing/types/querier.go @@ -0,0 +1,25 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// QuerySigningInfoParams defines the params for the following queries: +// - 'custom/slashing/signingInfo' +type QuerySigningInfoParams struct { + ConsAddress sdk.ConsAddress +} + +func NewQuerySigningInfoParams(consAddr sdk.ConsAddress) QuerySigningInfoParams { + return QuerySigningInfoParams{consAddr} +} + +// QuerySigningInfosParams defines the params for the following queries: +// - 'custom/slashing/signingInfos' +type QuerySigningInfosParams struct { + Page, Limit int +} + +func NewQuerySigningInfosParams(page, limit int) QuerySigningInfosParams { + return QuerySigningInfosParams{page, limit} +} diff --git a/x/slashing/types/signing_info.go b/x/slashing/types/signing_info.go new file mode 100644 index 000000000000..dba9e434c30c --- /dev/null +++ b/x/slashing/types/signing_info.go @@ -0,0 +1,47 @@ +package types + +import ( + "fmt" + "time" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// Signing info for a validator +type ValidatorSigningInfo struct { + Address sdk.ConsAddress `json:"address"` // validator consensus address + StartHeight int64 `json:"start_height"` // height at which validator was first a candidate OR was unjailed + IndexOffset int64 `json:"index_offset"` // index offset into signed block bit array + JailedUntil time.Time `json:"jailed_until"` // timestamp validator cannot be unjailed until + Tombstoned bool `json:"tombstoned"` // whether or not a validator has been tombstoned (killed out of validator set) + MissedBlocksCounter int64 `json:"missed_blocks_counter"` // missed blocks counter (to avoid scanning the array every time) +} + +// Construct a new `ValidatorSigningInfo` struct +func NewValidatorSigningInfo( + condAddr sdk.ConsAddress, startHeight, indexOffset int64, + jailedUntil time.Time, tombstoned bool, missedBlocksCounter int64, +) ValidatorSigningInfo { + + return ValidatorSigningInfo{ + Address: condAddr, + StartHeight: startHeight, + IndexOffset: indexOffset, + JailedUntil: jailedUntil, + Tombstoned: tombstoned, + MissedBlocksCounter: missedBlocksCounter, + } +} + +// Return human readable signing info +func (i ValidatorSigningInfo) String() string { + return fmt.Sprintf(`Validator Signing Info: + Address: %s + Start Height: %d + Index Offset: %d + Jailed Until: %v + Tombstoned: %t + Missed Blocks Counter: %d`, + i.Address, i.StartHeight, i.IndexOffset, i.JailedUntil, + i.Tombstoned, i.MissedBlocksCounter) +} diff --git a/x/staking/alias.go b/x/staking/alias.go index 97ced648be50..18c8f0ce668c 100644 --- a/x/staking/alias.go +++ b/x/staking/alias.go @@ -2,32 +2,18 @@ // autogenerated code using github.com/rigelrozanski/multitool // aliases generated for the following subdirectories: // ALIASGEN: github.com/cosmos/cosmos-sdk/x/staking/keeper -// ALIASGEN: github.com/cosmos/cosmos-sdk/x/staking/querier // ALIASGEN: github.com/cosmos/cosmos-sdk/x/staking/types +// ALIASGEN: github.com/cosmos/cosmos-sdk/x/staking/exported package staking import ( + "github.com/cosmos/cosmos-sdk/x/staking/exported" "github.com/cosmos/cosmos-sdk/x/staking/keeper" - "github.com/cosmos/cosmos-sdk/x/staking/querier" "github.com/cosmos/cosmos-sdk/x/staking/types" ) const ( DefaultParamspace = keeper.DefaultParamspace - QueryValidators = querier.QueryValidators - QueryValidator = querier.QueryValidator - QueryDelegatorDelegations = querier.QueryDelegatorDelegations - QueryDelegatorUnbondingDelegations = querier.QueryDelegatorUnbondingDelegations - QueryRedelegations = querier.QueryRedelegations - QueryValidatorDelegations = querier.QueryValidatorDelegations - QueryValidatorRedelegations = querier.QueryValidatorRedelegations - QueryValidatorUnbondingDelegations = querier.QueryValidatorUnbondingDelegations - QueryDelegation = querier.QueryDelegation - QueryUnbondingDelegation = querier.QueryUnbondingDelegation - QueryDelegatorValidators = querier.QueryDelegatorValidators - QueryDelegatorValidator = querier.QueryDelegatorValidator - QueryPool = querier.QueryPool - QueryParameters = querier.QueryParameters DefaultCodespace = types.DefaultCodespace CodeInvalidValidator = types.CodeInvalidValidator CodeInvalidDelegation = types.CodeInvalidDelegation @@ -45,6 +31,20 @@ const ( DefaultUnbondingTime = types.DefaultUnbondingTime DefaultMaxValidators = types.DefaultMaxValidators DefaultMaxEntries = types.DefaultMaxEntries + QueryValidators = types.QueryValidators + QueryValidator = types.QueryValidator + QueryDelegatorDelegations = types.QueryDelegatorDelegations + QueryDelegatorUnbondingDelegations = types.QueryDelegatorUnbondingDelegations + QueryRedelegations = types.QueryRedelegations + QueryValidatorDelegations = types.QueryValidatorDelegations + QueryValidatorRedelegations = types.QueryValidatorRedelegations + QueryValidatorUnbondingDelegations = types.QueryValidatorUnbondingDelegations + QueryDelegation = types.QueryDelegation + QueryUnbondingDelegation = types.QueryUnbondingDelegation + QueryDelegatorValidators = types.QueryDelegatorValidators + QueryDelegatorValidator = types.QueryDelegatorValidator + QueryPool = types.QueryPool + QueryParameters = types.QueryParameters MaxMonikerLength = types.MaxMonikerLength MaxIdentityLength = types.MaxIdentityLength MaxWebsiteLength = types.MaxWebsiteLength @@ -62,6 +62,7 @@ var ( DelegatorSharesInvariant = keeper.DelegatorSharesInvariant NewKeeper = keeper.NewKeeper ParamKeyTable = keeper.ParamKeyTable + NewQuerier = keeper.NewQuerier ValEq = keeper.ValEq MakeTestCodec = keeper.MakeTestCodec CreateTestInput = keeper.CreateTestInput @@ -71,12 +72,6 @@ var ( TestingUpdateValidator = keeper.TestingUpdateValidator RandomValidator = keeper.RandomValidator RandomBondedValidator = keeper.RandomBondedValidator - NewQuerier = querier.NewQuerier - NewQueryDelegatorParams = querier.NewQueryDelegatorParams - NewQueryValidatorParams = querier.NewQueryValidatorParams - NewQueryBondsParams = querier.NewQueryBondsParams - NewQueryRedelegationParams = querier.NewQueryRedelegationParams - NewQueryValidatorsParams = querier.NewQueryValidatorsParams RegisterCodec = types.RegisterCodec NewCommissionRates = types.NewCommissionRates NewCommission = types.NewCommission @@ -183,6 +178,11 @@ var ( InitialPool = types.InitialPool MustUnmarshalPool = types.MustUnmarshalPool UnmarshalPool = types.UnmarshalPool + NewQueryDelegatorParams = types.NewQueryDelegatorParams + NewQueryValidatorParams = types.NewQueryValidatorParams + NewQueryBondsParams = types.NewQueryBondsParams + NewQueryRedelegationParams = types.NewQueryRedelegationParams + NewQueryValidatorsParams = types.NewQueryValidatorsParams NewValidator = types.NewValidator MustMarshalValidator = types.MustMarshalValidator MustUnmarshalValidator = types.MustUnmarshalValidator @@ -216,11 +216,6 @@ var ( type ( Keeper = keeper.Keeper - QueryDelegatorParams = querier.QueryDelegatorParams - QueryValidatorParams = querier.QueryValidatorParams - QueryBondsParams = querier.QueryBondsParams - QueryRedelegationParams = querier.QueryRedelegationParams - QueryValidatorsParams = querier.QueryValidatorsParams Commission = types.Commission CommissionRates = types.CommissionRates DVPair = types.DVPair @@ -243,6 +238,9 @@ type ( FeeCollectionKeeper = types.FeeCollectionKeeper BankKeeper = types.BankKeeper AccountKeeper = types.AccountKeeper + ValidatorSet = types.ValidatorSet + DelegationSet = types.DelegationSet + StakingHooks = types.StakingHooks GenesisState = types.GenesisState LastValidatorPower = types.LastValidatorPower MultiStakingHooks = types.MultiStakingHooks @@ -253,7 +251,14 @@ type ( MsgUndelegate = types.MsgUndelegate Params = types.Params Pool = types.Pool + QueryDelegatorParams = types.QueryDelegatorParams + QueryValidatorParams = types.QueryValidatorParams + QueryBondsParams = types.QueryBondsParams + QueryRedelegationParams = types.QueryRedelegationParams + QueryValidatorsParams = types.QueryValidatorsParams Validator = types.Validator Validators = types.Validators Description = types.Description + DelegationI = exported.DelegationI + ValidatorI = exported.ValidatorI ) diff --git a/x/staking/client/cli/query.go b/x/staking/client/cli/query.go index f829d9b87c6e..f9ea5314ec86 100644 --- a/x/staking/client/cli/query.go +++ b/x/staking/client/cli/query.go @@ -6,14 +6,43 @@ import ( "github.com/spf13/cobra" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client/utils" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" - "github.com/cosmos/cosmos-sdk/x/staking/querier" "github.com/cosmos/cosmos-sdk/x/staking/types" ) +// GetQueryCmd returns the cli query commands for this module +func GetQueryCmd(queryRoute string, cdc *codec.Codec) *cobra.Command { + stakingQueryCmd := &cobra.Command{ + Use: types.ModuleName, + Short: "Querying commands for the staking module", + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: utils.ValidateCmd, + } + stakingQueryCmd.AddCommand(client.GetCommands( + GetCmdQueryDelegation(queryRoute, cdc), + GetCmdQueryDelegations(queryRoute, cdc), + GetCmdQueryUnbondingDelegation(queryRoute, cdc), + GetCmdQueryUnbondingDelegations(queryRoute, cdc), + GetCmdQueryRedelegation(queryRoute, cdc), + GetCmdQueryRedelegations(queryRoute, cdc), + GetCmdQueryValidator(queryRoute, cdc), + GetCmdQueryValidators(queryRoute, cdc), + GetCmdQueryValidatorDelegations(queryRoute, cdc), + GetCmdQueryValidatorUnbondingDelegations(queryRoute, cdc), + GetCmdQueryValidatorRedelegations(queryRoute, cdc), + GetCmdQueryParams(queryRoute, cdc), + GetCmdQueryPool(queryRoute, cdc))...) + + return stakingQueryCmd + +} + // GetCmdQueryValidator implements the validator query command. func GetCmdQueryValidator(storeName string, cdc *codec.Codec) *cobra.Command { return &cobra.Command{ @@ -85,7 +114,7 @@ $ %s query staking validators } // GetCmdQueryValidatorUnbondingDelegations implements the query all unbonding delegatations from a validator command. -func GetCmdQueryValidatorUnbondingDelegations(storeKey string, cdc *codec.Codec) *cobra.Command { +func GetCmdQueryValidatorUnbondingDelegations(queryRoute string, cdc *codec.Codec) *cobra.Command { return &cobra.Command{ Use: "unbonding-delegations-from [validator-addr]", Short: "Query all unbonding delegatations from a validator", @@ -107,12 +136,12 @@ $ %s query staking unbonding-delegations-from cosmosvaloper1gghjut3ccd8ay0zduzj6 return err } - bz, err := cdc.MarshalJSON(querier.NewQueryValidatorParams(valAddr)) + bz, err := cdc.MarshalJSON(types.NewQueryValidatorParams(valAddr)) if err != nil { return err } - route := fmt.Sprintf("custom/%s/%s", storeKey, querier.QueryValidatorUnbondingDelegations) + route := fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryValidatorUnbondingDelegations) res, err := cliCtx.QueryWithData(route, bz) if err != nil { return err @@ -127,7 +156,7 @@ $ %s query staking unbonding-delegations-from cosmosvaloper1gghjut3ccd8ay0zduzj6 // GetCmdQueryValidatorRedelegations implements the query all redelegatations // from a validator command. -func GetCmdQueryValidatorRedelegations(storeKey string, cdc *codec.Codec) *cobra.Command { +func GetCmdQueryValidatorRedelegations(queryRoute string, cdc *codec.Codec) *cobra.Command { return &cobra.Command{ Use: "redelegations-from [validator-addr]", Short: "Query all outgoing redelegatations from a validator", @@ -149,12 +178,12 @@ $ %s query staking redelegations-from cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fx return err } - bz, err := cdc.MarshalJSON(querier.QueryRedelegationParams{SrcValidatorAddr: valSrcAddr}) + bz, err := cdc.MarshalJSON(types.QueryRedelegationParams{SrcValidatorAddr: valSrcAddr}) if err != nil { return err } - route := fmt.Sprintf("custom/%s/%s", storeKey, querier.QueryRedelegations) + route := fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryRedelegations) res, err := cliCtx.QueryWithData(route, bz) if err != nil { return err @@ -171,7 +200,7 @@ $ %s query staking redelegations-from cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fx } // GetCmdQueryDelegation the query delegation command. -func GetCmdQueryDelegation(storeKey string, cdc *codec.Codec) *cobra.Command { +func GetCmdQueryDelegation(queryRoute string, cdc *codec.Codec) *cobra.Command { return &cobra.Command{ Use: "delegation [delegator-addr] [validator-addr]", Short: "Query a delegation based on address and validator address", @@ -198,12 +227,12 @@ $ %s query staking delegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p cosm return err } - bz, err := cdc.MarshalJSON(querier.NewQueryBondsParams(delAddr, valAddr)) + bz, err := cdc.MarshalJSON(types.NewQueryBondsParams(delAddr, valAddr)) if err != nil { return err } - route := fmt.Sprintf("custom/%s/%s", storeKey, querier.QueryDelegation) + route := fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryDelegation) res, err := cliCtx.QueryWithData(route, bz) if err != nil { return err @@ -221,7 +250,7 @@ $ %s query staking delegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p cosm // GetCmdQueryDelegations implements the command to query all the delegations // made from one delegator. -func GetCmdQueryDelegations(storeKey string, cdc *codec.Codec) *cobra.Command { +func GetCmdQueryDelegations(queryRoute string, cdc *codec.Codec) *cobra.Command { return &cobra.Command{ Use: "delegations [delegator-addr]", Short: "Query all delegations made by one delegator", @@ -243,12 +272,12 @@ $ %s query staking delegations cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p return err } - bz, err := cdc.MarshalJSON(querier.NewQueryDelegatorParams(delAddr)) + bz, err := cdc.MarshalJSON(types.NewQueryDelegatorParams(delAddr)) if err != nil { return err } - route := fmt.Sprintf("custom/%s/%s", storeKey, querier.QueryDelegatorDelegations) + route := fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryDelegatorDelegations) res, err := cliCtx.QueryWithData(route, bz) if err != nil { return err @@ -266,7 +295,7 @@ $ %s query staking delegations cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p // GetCmdQueryValidatorDelegations implements the command to query all the // delegations to a specific validator. -func GetCmdQueryValidatorDelegations(storeKey string, cdc *codec.Codec) *cobra.Command { +func GetCmdQueryValidatorDelegations(queryRoute string, cdc *codec.Codec) *cobra.Command { return &cobra.Command{ Use: "delegations-to [validator-addr]", Short: "Query all delegations made to one validator", @@ -288,12 +317,12 @@ $ %s query staking delegations-to cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ld return err } - bz, err := cdc.MarshalJSON(querier.NewQueryValidatorParams(valAddr)) + bz, err := cdc.MarshalJSON(types.NewQueryValidatorParams(valAddr)) if err != nil { return err } - route := fmt.Sprintf("custom/%s/%s", storeKey, querier.QueryValidatorDelegations) + route := fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryValidatorDelegations) res, err := cliCtx.QueryWithData(route, bz) if err != nil { return err @@ -311,7 +340,7 @@ $ %s query staking delegations-to cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ld // GetCmdQueryUnbondingDelegation implements the command to query a single // unbonding-delegation record. -func GetCmdQueryUnbondingDelegation(storeKey string, cdc *codec.Codec) *cobra.Command { +func GetCmdQueryUnbondingDelegation(queryRoute string, cdc *codec.Codec) *cobra.Command { return &cobra.Command{ Use: "unbonding-delegation [delegator-addr] [validator-addr]", Short: "Query an unbonding-delegation record based on delegator and validator address", @@ -338,12 +367,12 @@ $ %s query staking unbonding-delegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld7 return err } - bz, err := cdc.MarshalJSON(querier.NewQueryBondsParams(delAddr, valAddr)) + bz, err := cdc.MarshalJSON(types.NewQueryBondsParams(delAddr, valAddr)) if err != nil { return err } - route := fmt.Sprintf("custom/%s/%s", storeKey, querier.QueryUnbondingDelegation) + route := fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryUnbondingDelegation) res, err := cliCtx.QueryWithData(route, bz) if err != nil { return err @@ -356,7 +385,7 @@ $ %s query staking unbonding-delegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld7 // GetCmdQueryUnbondingDelegations implements the command to query all the // unbonding-delegation records for a delegator. -func GetCmdQueryUnbondingDelegations(storeKey string, cdc *codec.Codec) *cobra.Command { +func GetCmdQueryUnbondingDelegations(queryRoute string, cdc *codec.Codec) *cobra.Command { return &cobra.Command{ Use: "unbonding-delegations [delegator-addr]", Short: "Query all unbonding-delegations records for one delegator", @@ -378,12 +407,12 @@ $ %s query staking unbonding-delegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld7 return err } - bz, err := cdc.MarshalJSON(querier.NewQueryDelegatorParams(delegatorAddr)) + bz, err := cdc.MarshalJSON(types.NewQueryDelegatorParams(delegatorAddr)) if err != nil { return err } - route := fmt.Sprintf("custom/%s/%s", storeKey, querier.QueryDelegatorUnbondingDelegations) + route := fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryDelegatorUnbondingDelegations) res, err := cliCtx.QueryWithData(route, bz) if err != nil { return err @@ -401,7 +430,7 @@ $ %s query staking unbonding-delegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld7 // GetCmdQueryRedelegation implements the command to query a single // redelegation record. -func GetCmdQueryRedelegation(storeKey string, cdc *codec.Codec) *cobra.Command { +func GetCmdQueryRedelegation(queryRoute string, cdc *codec.Codec) *cobra.Command { return &cobra.Command{ Use: "redelegation [delegator-addr] [src-validator-addr] [dst-validator-addr]", Short: "Query a redelegation record based on delegator and a source and destination validator address", @@ -433,12 +462,12 @@ $ %s query staking redelegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p co return err } - bz, err := cdc.MarshalJSON(querier.NewQueryRedelegationParams(delAddr, valSrcAddr, valDstAddr)) + bz, err := cdc.MarshalJSON(types.NewQueryRedelegationParams(delAddr, valSrcAddr, valDstAddr)) if err != nil { return err } - route := fmt.Sprintf("custom/%s/%s", storeKey, querier.QueryRedelegations) + route := fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryRedelegations) res, err := cliCtx.QueryWithData(route, bz) if err != nil { return err @@ -456,7 +485,7 @@ $ %s query staking redelegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p co // GetCmdQueryRedelegations implements the command to query all the // redelegation records for a delegator. -func GetCmdQueryRedelegations(storeKey string, cdc *codec.Codec) *cobra.Command { +func GetCmdQueryRedelegations(queryRoute string, cdc *codec.Codec) *cobra.Command { return &cobra.Command{ Use: "redelegations [delegator-addr]", Args: cobra.ExactArgs(1), @@ -478,12 +507,12 @@ $ %s query staking redelegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p return err } - bz, err := cdc.MarshalJSON(querier.QueryRedelegationParams{DelegatorAddr: delAddr}) + bz, err := cdc.MarshalJSON(types.QueryRedelegationParams{DelegatorAddr: delAddr}) if err != nil { return err } - route := fmt.Sprintf("custom/%s/%s", storeKey, querier.QueryRedelegations) + route := fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryRedelegations) res, err := cliCtx.QueryWithData(route, bz) if err != nil { return err @@ -545,7 +574,7 @@ $ %s query staking params RunE: func(cmd *cobra.Command, args []string) error { cliCtx := context.NewCLIContext().WithCodec(cdc) - route := fmt.Sprintf("custom/%s/%s", storeName, querier.QueryParameters) + route := fmt.Sprintf("custom/%s/%s", storeName, types.QueryParameters) bz, err := cliCtx.QueryWithData(route, nil) if err != nil { return err diff --git a/x/staking/client/cli/tx.go b/x/staking/client/cli/tx.go index fe9e5d2d723d..665b6428f0bd 100644 --- a/x/staking/client/cli/tx.go +++ b/x/staking/client/cli/tx.go @@ -19,17 +19,37 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" "github.com/cosmos/cosmos-sdk/x/auth" - authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" "github.com/cosmos/cosmos-sdk/x/staking/types" ) +// GetTxCmd returns the transaction commands for this module +func GetTxCmd(storeKey string, cdc *codec.Codec) *cobra.Command { + stakingTxCmd := &cobra.Command{ + Use: types.ModuleName, + Short: "Staking transaction subcommands", + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: utils.ValidateCmd, + } + + stakingTxCmd.AddCommand(client.PostCommands( + GetCmdCreateValidator(cdc), + GetCmdEditValidator(cdc), + GetCmdDelegate(cdc), + GetCmdRedelegate(storeKey, cdc), + GetCmdUnbond(storeKey, cdc), + )...) + + return stakingTxCmd +} + // GetCmdCreateValidator implements the create validator command handler. func GetCmdCreateValidator(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "create-validator", Short: "create new validator initialized with a self-delegation to it", RunE: func(cmd *cobra.Command, args []string) error { - txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) cliCtx := context.NewCLIContext(). WithCodec(cdc). WithAccountDecoder(cdc) @@ -67,7 +87,7 @@ func GetCmdEditValidator(cdc *codec.Codec) *cobra.Command { Use: "edit-validator", Short: "edit an existing validator account", RunE: func(cmd *cobra.Command, args []string) error { - txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(auth.DefaultTxEncoder(cdc)) + txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(auth.DefaultTxEncoder(cdc)) cliCtx := context.NewCLIContext(). WithCodec(cdc). WithAccountDecoder(cdc) @@ -132,7 +152,7 @@ $ %s tx staking delegate cosmosvaloper1l2rsakp388kuv9k8qzq6lrm9taddae7fpx59wm 10 ), ), RunE: func(cmd *cobra.Command, args []string) error { - txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(auth.DefaultTxEncoder(cdc)) + txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(auth.DefaultTxEncoder(cdc)) cliCtx := context.NewCLIContext(). WithCodec(cdc). WithAccountDecoder(cdc) @@ -170,7 +190,7 @@ $ %s tx staking redelegate cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj ), ), RunE: func(cmd *cobra.Command, args []string) error { - txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(auth.DefaultTxEncoder(cdc)) + txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(auth.DefaultTxEncoder(cdc)) cliCtx := context.NewCLIContext(). WithCodec(cdc). WithAccountDecoder(cdc) @@ -213,7 +233,7 @@ $ %s tx staking unbond cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj 100s ), ), RunE: func(cmd *cobra.Command, args []string) error { - txBldr := authtxb.NewTxBuilderFromCLI().WithTxEncoder(auth.DefaultTxEncoder(cdc)) + txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(auth.DefaultTxEncoder(cdc)) cliCtx := context.NewCLIContext(). WithCodec(cdc). WithAccountDecoder(cdc) @@ -320,7 +340,7 @@ func PrepareFlagsForTxCreateValidator( } // BuildCreateValidatorMsg makes a new MsgCreateValidator. -func BuildCreateValidatorMsg(cliCtx context.CLIContext, txBldr authtxb.TxBuilder) (authtxb.TxBuilder, sdk.Msg, error) { +func BuildCreateValidatorMsg(cliCtx context.CLIContext, txBldr auth.TxBuilder) (auth.TxBuilder, sdk.Msg, error) { amounstStr := viper.GetString(FlagAmount) amount, err := sdk.ParseCoin(amounstStr) if err != nil { diff --git a/x/staking/client/module_client.go b/x/staking/client/module_client.go deleted file mode 100644 index 71c3940e6511..000000000000 --- a/x/staking/client/module_client.go +++ /dev/null @@ -1,70 +0,0 @@ -package client - -import ( - "github.com/spf13/cobra" - amino "github.com/tendermint/go-amino" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/utils" - "github.com/cosmos/cosmos-sdk/x/staking/client/cli" - "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -// ModuleClient exports all client functionality from this module -type ModuleClient struct { - storeKey string - cdc *amino.Codec -} - -func NewModuleClient(storeKey string, cdc *amino.Codec) ModuleClient { - return ModuleClient{storeKey, cdc} -} - -// GetQueryCmd returns the cli query commands for this module -func (mc ModuleClient) GetQueryCmd() *cobra.Command { - stakingQueryCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "Querying commands for the staking module", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: utils.ValidateCmd, - } - stakingQueryCmd.AddCommand(client.GetCommands( - cli.GetCmdQueryDelegation(mc.storeKey, mc.cdc), - cli.GetCmdQueryDelegations(mc.storeKey, mc.cdc), - cli.GetCmdQueryUnbondingDelegation(mc.storeKey, mc.cdc), - cli.GetCmdQueryUnbondingDelegations(mc.storeKey, mc.cdc), - cli.GetCmdQueryRedelegation(mc.storeKey, mc.cdc), - cli.GetCmdQueryRedelegations(mc.storeKey, mc.cdc), - cli.GetCmdQueryValidator(mc.storeKey, mc.cdc), - cli.GetCmdQueryValidators(mc.storeKey, mc.cdc), - cli.GetCmdQueryValidatorDelegations(mc.storeKey, mc.cdc), - cli.GetCmdQueryValidatorUnbondingDelegations(mc.storeKey, mc.cdc), - cli.GetCmdQueryValidatorRedelegations(mc.storeKey, mc.cdc), - cli.GetCmdQueryParams(mc.storeKey, mc.cdc), - cli.GetCmdQueryPool(mc.storeKey, mc.cdc))...) - - return stakingQueryCmd - -} - -// GetTxCmd returns the transaction commands for this module -func (mc ModuleClient) GetTxCmd() *cobra.Command { - stakingTxCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "Staking transaction subcommands", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: utils.ValidateCmd, - } - - stakingTxCmd.AddCommand(client.PostCommands( - cli.GetCmdCreateValidator(mc.cdc), - cli.GetCmdEditValidator(mc.cdc), - cli.GetCmdDelegate(mc.cdc), - cli.GetCmdRedelegate(mc.storeKey, mc.cdc), - cli.GetCmdUnbond(mc.storeKey, mc.cdc), - )...) - - return stakingTxCmd -} diff --git a/x/staking/client/rest/query.go b/x/staking/client/rest/query.go index 19c52026c713..14173a6d07fd 100644 --- a/x/staking/client/rest/query.go +++ b/x/staking/client/rest/query.go @@ -5,13 +5,13 @@ import ( "net/http" "strings" + "github.com/gorilla/mux" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/staking" - - "github.com/gorilla/mux" + "github.com/cosmos/cosmos-sdk/x/staking/types" ) func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec) { @@ -103,7 +103,7 @@ func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Co // HTTP request handler to query a delegator delegations func delegatorDelegationsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { - return queryDelegator(cliCtx, cdc, fmt.Sprintf("custom/%s/%s", staking.QuerierRoute, staking.QueryDelegatorDelegations)) + return queryDelegator(cliCtx, cdc, fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryDelegatorDelegations)) } // HTTP request handler to query a delegator unbonding delegations @@ -139,15 +139,15 @@ func delegatorTxsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.Han switch { case isBondTx: - actions = append(actions, staking.MsgDelegate{}.Type()) + actions = append(actions, types.MsgDelegate{}.Type()) case isUnbondTx: - actions = append(actions, staking.MsgUndelegate{}.Type()) + actions = append(actions, types.MsgUndelegate{}.Type()) case isRedTx: - actions = append(actions, staking.MsgBeginRedelegate{}.Type()) + actions = append(actions, types.MsgBeginRedelegate{}.Type()) case noQuery: - actions = append(actions, staking.MsgDelegate{}.Type()) - actions = append(actions, staking.MsgUndelegate{}.Type()) - actions = append(actions, staking.MsgBeginRedelegate{}.Type()) + actions = append(actions, types.MsgDelegate{}.Type()) + actions = append(actions, types.MsgUndelegate{}.Type()) + actions = append(actions, types.MsgBeginRedelegate{}.Type()) default: w.WriteHeader(http.StatusNoContent) return @@ -178,7 +178,7 @@ func unbondingDelegationHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) h // HTTP request handler to query redelegations func redelegationsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - var params staking.QueryRedelegationParams + var params types.QueryRedelegationParams bechDelegatorAddr := r.URL.Query().Get("delegator") bechSrcValidatorAddr := r.URL.Query().Get("validator_from") @@ -228,7 +228,7 @@ func redelegationsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.Ha // HTTP request handler to query a delegation func delegationHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { - return queryBonds(cliCtx, cdc, fmt.Sprintf("custom/%s/%s", staking.QuerierRoute, staking.QueryDelegation)) + return queryBonds(cliCtx, cdc, fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryDelegation)) } // HTTP request handler to query all delegator bonded validators @@ -255,14 +255,14 @@ func validatorsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.Handl status = sdk.BondStatusBonded } - params := staking.NewQueryValidatorsParams(page, limit, status) + params := types.NewQueryValidatorsParams(page, limit, status) bz, err := cdc.MarshalJSON(params) if err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } - route := fmt.Sprintf("custom/%s/%s", staking.QuerierRoute, staking.QueryValidators) + route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryValidators) res, err := cliCtx.QueryWithData(route, bz) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) @@ -279,7 +279,7 @@ func validatorHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.Handle // HTTP request handler to query all unbonding delegations from a validator func validatorDelegationsHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.HandlerFunc { - return queryValidator(cliCtx, cdc, fmt.Sprintf("custom/%s/%s", staking.QuerierRoute, staking.QueryValidatorDelegations)) + return queryValidator(cliCtx, cdc, fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryValidatorDelegations)) } // HTTP request handler to query all unbonding delegations from a validator diff --git a/x/staking/client/rest/rest.go b/x/staking/client/rest/rest.go index 507fcb517fc4..d3bfc07350b9 100644 --- a/x/staking/client/rest/rest.go +++ b/x/staking/client/rest/rest.go @@ -1,15 +1,14 @@ package rest import ( + "github.com/gorilla/mux" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/crypto/keys" - - "github.com/gorilla/mux" ) // RegisterRoutes registers staking-related REST handlers to a router -func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec, kb keys.Keybase) { +func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec) { registerQueryRoutes(cliCtx, r, cdc) - registerTxRoutes(cliCtx, r, cdc, kb) + registerTxRoutes(cliCtx, r, cdc) } diff --git a/x/staking/client/rest/tx.go b/x/staking/client/rest/tx.go index f42a90c9d02a..84b7e4750bbc 100644 --- a/x/staking/client/rest/tx.go +++ b/x/staking/client/rest/tx.go @@ -9,24 +9,23 @@ import ( "github.com/cosmos/cosmos-sdk/client/context" clientrest "github.com/cosmos/cosmos-sdk/client/rest" "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/crypto/keys" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/staking" + "github.com/cosmos/cosmos-sdk/x/staking/types" ) -func registerTxRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec, kb keys.Keybase) { +func registerTxRoutes(cliCtx context.CLIContext, r *mux.Router, cdc *codec.Codec) { r.HandleFunc( "/staking/delegators/{delegatorAddr}/delegations", - postDelegationsHandlerFn(cdc, kb, cliCtx), + postDelegationsHandlerFn(cdc, cliCtx), ).Methods("POST") r.HandleFunc( "/staking/delegators/{delegatorAddr}/unbonding_delegations", - postUnbondingDelegationsHandlerFn(cdc, kb, cliCtx), + postUnbondingDelegationsHandlerFn(cdc, cliCtx), ).Methods("POST") r.HandleFunc( "/staking/delegators/{delegatorAddr}/redelegations", - postRedelegationsHandlerFn(cdc, kb, cliCtx), + postRedelegationsHandlerFn(cdc, cliCtx), ).Methods("POST") } @@ -57,7 +56,7 @@ type ( } ) -func postDelegationsHandlerFn(cdc *codec.Codec, kb keys.Keybase, cliCtx context.CLIContext) http.HandlerFunc { +func postDelegationsHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req DelegateRequest @@ -70,7 +69,7 @@ func postDelegationsHandlerFn(cdc *codec.Codec, kb keys.Keybase, cliCtx context. return } - msg := staking.NewMsgDelegate(req.DelegatorAddress, req.ValidatorAddress, req.Amount) + msg := types.NewMsgDelegate(req.DelegatorAddress, req.ValidatorAddress, req.Amount) if err := msg.ValidateBasic(); err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return @@ -91,7 +90,7 @@ func postDelegationsHandlerFn(cdc *codec.Codec, kb keys.Keybase, cliCtx context. } } -func postRedelegationsHandlerFn(cdc *codec.Codec, kb keys.Keybase, cliCtx context.CLIContext) http.HandlerFunc { +func postRedelegationsHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req RedelegateRequest @@ -104,7 +103,7 @@ func postRedelegationsHandlerFn(cdc *codec.Codec, kb keys.Keybase, cliCtx contex return } - msg := staking.NewMsgBeginRedelegate(req.DelegatorAddress, req.ValidatorSrcAddress, req.ValidatorDstAddress, req.Amount) + msg := types.NewMsgBeginRedelegate(req.DelegatorAddress, req.ValidatorSrcAddress, req.ValidatorDstAddress, req.Amount) if err := msg.ValidateBasic(); err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return @@ -125,7 +124,7 @@ func postRedelegationsHandlerFn(cdc *codec.Codec, kb keys.Keybase, cliCtx contex } } -func postUnbondingDelegationsHandlerFn(cdc *codec.Codec, kb keys.Keybase, cliCtx context.CLIContext) http.HandlerFunc { +func postUnbondingDelegationsHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req UndelegateRequest @@ -138,7 +137,7 @@ func postUnbondingDelegationsHandlerFn(cdc *codec.Codec, kb keys.Keybase, cliCtx return } - msg := staking.NewMsgUndelegate(req.DelegatorAddress, req.ValidatorAddress, req.Amount) + msg := types.NewMsgUndelegate(req.DelegatorAddress, req.ValidatorAddress, req.Amount) if err := msg.ValidateBasic(); err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return diff --git a/x/staking/client/rest/utils.go b/x/staking/client/rest/utils.go index 0bb363aa55a4..d5ad533814f0 100644 --- a/x/staking/client/rest/utils.go +++ b/x/staking/client/rest/utils.go @@ -11,8 +11,8 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/staking" "github.com/cosmos/cosmos-sdk/x/staking/tags" + "github.com/cosmos/cosmos-sdk/x/staking/types" ) // contains checks if the a given query contains one of the tx types @@ -50,7 +50,7 @@ func queryBonds(cliCtx context.CLIContext, cdc *codec.Codec, endpoint string) ht return } - params := staking.NewQueryBondsParams(delegatorAddr, validatorAddr) + params := types.NewQueryBondsParams(delegatorAddr, validatorAddr) bz, err := cdc.MarshalJSON(params) if err != nil { @@ -78,7 +78,7 @@ func queryDelegator(cliCtx context.CLIContext, cdc *codec.Codec, endpoint string return } - params := staking.NewQueryDelegatorParams(delegatorAddr) + params := types.NewQueryDelegatorParams(delegatorAddr) bz, err := cdc.MarshalJSON(params) if err != nil { @@ -106,7 +106,7 @@ func queryValidator(cliCtx context.CLIContext, cdc *codec.Codec, endpoint string return } - params := staking.NewQueryValidatorParams(validatorAddr) + params := types.NewQueryValidatorParams(validatorAddr) bz, err := cdc.MarshalJSON(params) if err != nil { diff --git a/x/staking/querier/querier.go b/x/staking/keeper/querier.go similarity index 65% rename from x/staking/querier/querier.go rename to x/staking/keeper/querier.go index d3eca7a48c9c..d68e9679bdbd 100644 --- a/x/staking/querier/querier.go +++ b/x/staking/keeper/querier.go @@ -1,4 +1,4 @@ -package querier +package keeper import ( "fmt" @@ -8,57 +8,38 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - keep "github.com/cosmos/cosmos-sdk/x/staking/keeper" "github.com/cosmos/cosmos-sdk/x/staking/types" ) -// query endpoints supported by the staking Querier -const ( - QueryValidators = "validators" - QueryValidator = "validator" - QueryDelegatorDelegations = "delegatorDelegations" - QueryDelegatorUnbondingDelegations = "delegatorUnbondingDelegations" - QueryRedelegations = "redelegations" - QueryValidatorDelegations = "validatorDelegations" - QueryValidatorRedelegations = "validatorRedelegations" - QueryValidatorUnbondingDelegations = "validatorUnbondingDelegations" - QueryDelegation = "delegation" - QueryUnbondingDelegation = "unbondingDelegation" - QueryDelegatorValidators = "delegatorValidators" - QueryDelegatorValidator = "delegatorValidator" - QueryPool = "pool" - QueryParameters = "parameters" -) - // creates a querier for staking REST endpoints -func NewQuerier(k keep.Keeper) sdk.Querier { +func NewQuerier(k Keeper) sdk.Querier { return func(ctx sdk.Context, path []string, req abci.RequestQuery) (res []byte, err sdk.Error) { switch path[0] { - case QueryValidators: + case types.QueryValidators: return queryValidators(ctx, req, k) - case QueryValidator: + case types.QueryValidator: return queryValidator(ctx, req, k) - case QueryValidatorDelegations: + case types.QueryValidatorDelegations: return queryValidatorDelegations(ctx, req, k) - case QueryValidatorUnbondingDelegations: + case types.QueryValidatorUnbondingDelegations: return queryValidatorUnbondingDelegations(ctx, req, k) - case QueryDelegation: + case types.QueryDelegation: return queryDelegation(ctx, req, k) - case QueryUnbondingDelegation: + case types.QueryUnbondingDelegation: return queryUnbondingDelegation(ctx, req, k) - case QueryDelegatorDelegations: + case types.QueryDelegatorDelegations: return queryDelegatorDelegations(ctx, req, k) - case QueryDelegatorUnbondingDelegations: + case types.QueryDelegatorUnbondingDelegations: return queryDelegatorUnbondingDelegations(ctx, req, k) - case QueryRedelegations: + case types.QueryRedelegations: return queryRedelegations(ctx, req, k) - case QueryDelegatorValidators: + case types.QueryDelegatorValidators: return queryDelegatorValidators(ctx, req, k) - case QueryDelegatorValidator: + case types.QueryDelegatorValidator: return queryDelegatorValidator(ctx, req, k) - case QueryPool: + case types.QueryPool: return queryPool(ctx, k) - case QueryParameters: + case types.QueryParameters: return queryParameters(ctx, k) default: return nil, sdk.ErrUnknownRequest("unknown staking query endpoint") @@ -66,70 +47,8 @@ func NewQuerier(k keep.Keeper) sdk.Querier { } } -// defines the params for the following queries: -// - 'custom/staking/delegatorDelegations' -// - 'custom/staking/delegatorUnbondingDelegations' -// - 'custom/staking/delegatorRedelegations' -// - 'custom/staking/delegatorValidators' -type QueryDelegatorParams struct { - DelegatorAddr sdk.AccAddress -} - -func NewQueryDelegatorParams(delegatorAddr sdk.AccAddress) QueryDelegatorParams { - return QueryDelegatorParams{ - DelegatorAddr: delegatorAddr, - } -} - -// defines the params for the following queries: -// - 'custom/staking/validator' -// - 'custom/staking/validatorDelegations' -// - 'custom/staking/validatorUnbondingDelegations' -// - 'custom/staking/validatorRedelegations' -type QueryValidatorParams struct { - ValidatorAddr sdk.ValAddress -} - -func NewQueryValidatorParams(validatorAddr sdk.ValAddress) QueryValidatorParams { - return QueryValidatorParams{ - ValidatorAddr: validatorAddr, - } -} - -// defines the params for the following queries: -// - 'custom/staking/delegation' -// - 'custom/staking/unbondingDelegation' -// - 'custom/staking/delegatorValidator' -type QueryBondsParams struct { - DelegatorAddr sdk.AccAddress - ValidatorAddr sdk.ValAddress -} - -func NewQueryBondsParams(delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress) QueryBondsParams { - return QueryBondsParams{ - DelegatorAddr: delegatorAddr, - ValidatorAddr: validatorAddr, - } -} - -// defines the params for the following queries: -// - 'custom/staking/redelegation' -type QueryRedelegationParams struct { - DelegatorAddr sdk.AccAddress - SrcValidatorAddr sdk.ValAddress - DstValidatorAddr sdk.ValAddress -} - -func NewQueryRedelegationParams(delegatorAddr sdk.AccAddress, srcValidatorAddr sdk.ValAddress, dstValidatorAddr sdk.ValAddress) QueryRedelegationParams { - return QueryRedelegationParams{ - DelegatorAddr: delegatorAddr, - SrcValidatorAddr: srcValidatorAddr, - DstValidatorAddr: dstValidatorAddr, - } -} - -func queryValidators(ctx sdk.Context, req abci.RequestQuery, k keep.Keeper) ([]byte, sdk.Error) { - var params QueryValidatorsParams +func queryValidators(ctx sdk.Context, req abci.RequestQuery, k Keeper) ([]byte, sdk.Error) { + var params types.QueryValidatorsParams err := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { @@ -172,8 +91,8 @@ func queryValidators(ctx sdk.Context, req abci.RequestQuery, k keep.Keeper) ([]b return res, nil } -func queryValidator(ctx sdk.Context, req abci.RequestQuery, k keep.Keeper) ([]byte, sdk.Error) { - var params QueryValidatorParams +func queryValidator(ctx sdk.Context, req abci.RequestQuery, k Keeper) ([]byte, sdk.Error) { + var params types.QueryValidatorParams err := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { @@ -193,8 +112,8 @@ func queryValidator(ctx sdk.Context, req abci.RequestQuery, k keep.Keeper) ([]by return res, nil } -func queryValidatorDelegations(ctx sdk.Context, req abci.RequestQuery, k keep.Keeper) ([]byte, sdk.Error) { - var params QueryValidatorParams +func queryValidatorDelegations(ctx sdk.Context, req abci.RequestQuery, k Keeper) ([]byte, sdk.Error) { + var params types.QueryValidatorParams err := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { @@ -215,8 +134,8 @@ func queryValidatorDelegations(ctx sdk.Context, req abci.RequestQuery, k keep.Ke return res, nil } -func queryValidatorUnbondingDelegations(ctx sdk.Context, req abci.RequestQuery, k keep.Keeper) ([]byte, sdk.Error) { - var params QueryValidatorParams +func queryValidatorUnbondingDelegations(ctx sdk.Context, req abci.RequestQuery, k Keeper) ([]byte, sdk.Error) { + var params types.QueryValidatorParams err := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { @@ -233,8 +152,8 @@ func queryValidatorUnbondingDelegations(ctx sdk.Context, req abci.RequestQuery, return res, nil } -func queryDelegatorDelegations(ctx sdk.Context, req abci.RequestQuery, k keep.Keeper) ([]byte, sdk.Error) { - var params QueryDelegatorParams +func queryDelegatorDelegations(ctx sdk.Context, req abci.RequestQuery, k Keeper) ([]byte, sdk.Error) { + var params types.QueryDelegatorParams err := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { @@ -255,8 +174,8 @@ func queryDelegatorDelegations(ctx sdk.Context, req abci.RequestQuery, k keep.Ke return res, nil } -func queryDelegatorUnbondingDelegations(ctx sdk.Context, req abci.RequestQuery, k keep.Keeper) ([]byte, sdk.Error) { - var params QueryDelegatorParams +func queryDelegatorUnbondingDelegations(ctx sdk.Context, req abci.RequestQuery, k Keeper) ([]byte, sdk.Error) { + var params types.QueryDelegatorParams err := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { @@ -273,8 +192,8 @@ func queryDelegatorUnbondingDelegations(ctx sdk.Context, req abci.RequestQuery, return res, nil } -func queryDelegatorValidators(ctx sdk.Context, req abci.RequestQuery, k keep.Keeper) ([]byte, sdk.Error) { - var params QueryDelegatorParams +func queryDelegatorValidators(ctx sdk.Context, req abci.RequestQuery, k Keeper) ([]byte, sdk.Error) { + var params types.QueryDelegatorParams stakingParams := k.GetParams(ctx) @@ -293,8 +212,8 @@ func queryDelegatorValidators(ctx sdk.Context, req abci.RequestQuery, k keep.Kee return res, nil } -func queryDelegatorValidator(ctx sdk.Context, req abci.RequestQuery, k keep.Keeper) ([]byte, sdk.Error) { - var params QueryBondsParams +func queryDelegatorValidator(ctx sdk.Context, req abci.RequestQuery, k Keeper) ([]byte, sdk.Error) { + var params types.QueryBondsParams err := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { @@ -314,8 +233,8 @@ func queryDelegatorValidator(ctx sdk.Context, req abci.RequestQuery, k keep.Keep return res, nil } -func queryDelegation(ctx sdk.Context, req abci.RequestQuery, k keep.Keeper) ([]byte, sdk.Error) { - var params QueryBondsParams +func queryDelegation(ctx sdk.Context, req abci.RequestQuery, k Keeper) ([]byte, sdk.Error) { + var params types.QueryBondsParams err := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { @@ -340,8 +259,8 @@ func queryDelegation(ctx sdk.Context, req abci.RequestQuery, k keep.Keeper) ([]b return res, nil } -func queryUnbondingDelegation(ctx sdk.Context, req abci.RequestQuery, k keep.Keeper) ([]byte, sdk.Error) { - var params QueryBondsParams +func queryUnbondingDelegation(ctx sdk.Context, req abci.RequestQuery, k Keeper) ([]byte, sdk.Error) { + var params types.QueryBondsParams err := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { @@ -361,8 +280,8 @@ func queryUnbondingDelegation(ctx sdk.Context, req abci.RequestQuery, k keep.Kee return res, nil } -func queryRedelegations(ctx sdk.Context, req abci.RequestQuery, k keep.Keeper) ([]byte, sdk.Error) { - var params QueryRedelegationParams +func queryRedelegations(ctx sdk.Context, req abci.RequestQuery, k Keeper) ([]byte, sdk.Error) { + var params types.QueryRedelegationParams err := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { @@ -397,7 +316,7 @@ func queryRedelegations(ctx sdk.Context, req abci.RequestQuery, k keep.Keeper) ( return res, nil } -func queryPool(ctx sdk.Context, k keep.Keeper) ([]byte, sdk.Error) { +func queryPool(ctx sdk.Context, k Keeper) ([]byte, sdk.Error) { pool := k.GetPool(ctx) res, err := codec.MarshalJSONIndent(types.ModuleCdc, pool) @@ -408,7 +327,7 @@ func queryPool(ctx sdk.Context, k keep.Keeper) ([]byte, sdk.Error) { return res, nil } -func queryParameters(ctx sdk.Context, k keep.Keeper) ([]byte, sdk.Error) { +func queryParameters(ctx sdk.Context, k Keeper) ([]byte, sdk.Error) { params := k.GetParams(ctx) res, err := codec.MarshalJSONIndent(types.ModuleCdc, params) @@ -419,13 +338,69 @@ func queryParameters(ctx sdk.Context, k keep.Keeper) ([]byte, sdk.Error) { return res, nil } -// QueryValidatorsParams defines the params for the following queries: -// - 'custom/staking/validators' -type QueryValidatorsParams struct { - Page, Limit int - Status string +//______________________________________________________ +// util + +func delegationToDelegationResponse(ctx sdk.Context, k Keeper, del types.Delegation) (types.DelegationResponse, sdk.Error) { + val, found := k.GetValidator(ctx, del.ValidatorAddress) + if !found { + return types.DelegationResponse{}, types.ErrNoValidatorFound(types.DefaultCodespace) + } + + return types.NewDelegationResp( + del.DelegatorAddress, + del.ValidatorAddress, + del.Shares, + val.TokensFromShares(del.Shares).TruncateInt(), + ), nil +} + +func delegationsToDelegationResponses( + ctx sdk.Context, k Keeper, delegations types.Delegations, +) (types.DelegationResponses, sdk.Error) { + + resp := make(types.DelegationResponses, len(delegations), len(delegations)) + for i, del := range delegations { + delResp, err := delegationToDelegationResponse(ctx, k, del) + if err != nil { + return nil, err + } + + resp[i] = delResp + } + + return resp, nil } -func NewQueryValidatorsParams(page, limit int, status string) QueryValidatorsParams { - return QueryValidatorsParams{page, limit, status} +func redelegationsToRedelegationResponses( + ctx sdk.Context, k Keeper, redels types.Redelegations, +) (types.RedelegationResponses, sdk.Error) { + + resp := make(types.RedelegationResponses, len(redels), len(redels)) + for i, redel := range redels { + val, found := k.GetValidator(ctx, redel.ValidatorDstAddress) + if !found { + return nil, types.ErrNoValidatorFound(types.DefaultCodespace) + } + + entryResponses := make([]types.RedelegationEntryResponse, len(redel.Entries), len(redel.Entries)) + for j, entry := range redel.Entries { + entryResponses[j] = types.NewRedelegationEntryResponse( + entry.CreationHeight, + entry.CompletionTime, + entry.SharesDst, + entry.InitialBalance, + val.TokensFromShares(entry.SharesDst).TruncateInt(), + ) + } + + resp[i] = types.NewRedelegationResponse( + redel.DelegatorAddress, + redel.ValidatorSrcAddress, + redel.ValidatorDstAddress, + entryResponses, + ) + } + + return resp, nil } diff --git a/x/staking/querier/querier_test.go b/x/staking/keeper/querier_test.go similarity index 72% rename from x/staking/querier/querier_test.go rename to x/staking/keeper/querier_test.go index 5a199c1dcca3..9e938a26387d 100644 --- a/x/staking/querier/querier_test.go +++ b/x/staking/keeper/querier_test.go @@ -1,4 +1,4 @@ -package querier +package keeper import ( "fmt" @@ -9,37 +9,36 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - keep "github.com/cosmos/cosmos-sdk/x/staking/keeper" "github.com/cosmos/cosmos-sdk/x/staking/types" ) var ( - addrAcc1, addrAcc2 = keep.Addrs[0], keep.Addrs[1] - addrVal1, addrVal2 = sdk.ValAddress(keep.Addrs[0]), sdk.ValAddress(keep.Addrs[1]) - pk1, pk2 = keep.PKs[0], keep.PKs[1] + addrAcc1, addrAcc2 = Addrs[0], Addrs[1] + addrVal1, addrVal2 = sdk.ValAddress(Addrs[0]), sdk.ValAddress(Addrs[1]) + pk1, pk2 = PKs[0], PKs[1] ) func TestNewQuerier(t *testing.T) { cdc := codec.New() - ctx, _, keeper := keep.CreateTestInput(t, false, 1000) - pool := keeper.GetPool(ctx) + ctx, _, r := CreateTestInput(t, false, 1000) + pool := r.GetPool(ctx) // Create Validators amts := []sdk.Int{sdk.NewInt(9), sdk.NewInt(8)} var validators [2]types.Validator for i, amt := range amts { - validators[i] = types.NewValidator(sdk.ValAddress(keep.Addrs[i]), keep.PKs[i], types.Description{}) + validators[i] = types.NewValidator(sdk.ValAddress(Addrs[i]), PKs[i], types.Description{}) validators[i], pool, _ = validators[i].AddTokensFromDel(pool, amt) - keeper.SetValidator(ctx, validators[i]) - keeper.SetValidatorByPowerIndex(ctx, validators[i]) + r.SetValidator(ctx, validators[i]) + r.SetValidatorByPowerIndex(ctx, validators[i]) } - keeper.SetPool(ctx, pool) + r.SetPool(ctx, pool) query := abci.RequestQuery{ Path: "", Data: []byte{}, } - querier := NewQuerier(keeper) + querier := NewQuerier(r) bz, err := querier(ctx, []string{"other"}, query) require.NotNil(t, err) @@ -51,7 +50,7 @@ func TestNewQuerier(t *testing.T) { _, err = querier(ctx, []string{"parameters"}, query) require.Nil(t, err) - queryValParams := NewQueryValidatorParams(addrVal1) + queryValParams := types.NewQueryValidatorParams(addrVal1) bz, errRes := cdc.MarshalJSON(queryValParams) require.Nil(t, errRes) @@ -67,7 +66,7 @@ func TestNewQuerier(t *testing.T) { _, err = querier(ctx, []string{"validatorUnbondingDelegations"}, query) require.Nil(t, err) - queryDelParams := NewQueryDelegatorParams(addrAcc2) + queryDelParams := types.NewQueryDelegatorParams(addrAcc2) bz, errRes = cdc.MarshalJSON(queryDelParams) require.Nil(t, errRes) @@ -83,7 +82,7 @@ func TestNewQuerier(t *testing.T) { _, err = querier(ctx, []string{"delegatorValidators"}, query) require.Nil(t, err) - bz, errRes = cdc.MarshalJSON(NewQueryRedelegationParams(nil, nil, nil)) + bz, errRes = cdc.MarshalJSON(types.NewQueryRedelegationParams(nil, nil, nil)) require.Nil(t, errRes) query.Data = bz @@ -93,60 +92,60 @@ func TestNewQuerier(t *testing.T) { func TestQueryParametersPool(t *testing.T) { cdc := codec.New() - ctx, _, keeper := keep.CreateTestInput(t, false, 1000) + ctx, _, r := CreateTestInput(t, false, 1000) - res, err := queryParameters(ctx, keeper) + res, err := queryParameters(ctx, r) require.Nil(t, err) var params types.Params errRes := cdc.UnmarshalJSON(res, ¶ms) require.Nil(t, errRes) - require.Equal(t, keeper.GetParams(ctx), params) + require.Equal(t, r.GetParams(ctx), params) - res, err = queryPool(ctx, keeper) + res, err = queryPool(ctx, r) require.Nil(t, err) var pool types.Pool errRes = cdc.UnmarshalJSON(res, &pool) require.Nil(t, errRes) - require.Equal(t, keeper.GetPool(ctx), pool) + require.Equal(t, r.GetPool(ctx), pool) } func TestQueryValidators(t *testing.T) { cdc := codec.New() - ctx, _, keeper := keep.CreateTestInput(t, false, 10000) - pool := keeper.GetPool(ctx) - params := keeper.GetParams(ctx) + ctx, _, r := CreateTestInput(t, false, 10000) + pool := r.GetPool(ctx) + params := r.GetParams(ctx) // Create Validators amts := []sdk.Int{sdk.NewInt(9), sdk.NewInt(8), sdk.NewInt(7)} status := []sdk.BondStatus{sdk.Bonded, sdk.Unbonded, sdk.Unbonding} var validators [3]types.Validator for i, amt := range amts { - validators[i] = types.NewValidator(sdk.ValAddress(keep.Addrs[i]), keep.PKs[i], types.Description{}) + validators[i] = types.NewValidator(sdk.ValAddress(Addrs[i]), PKs[i], types.Description{}) validators[i], pool, _ = validators[i].AddTokensFromDel(pool, amt) validators[i], pool = validators[i].UpdateStatus(pool, status[i]) } - keeper.SetPool(ctx, pool) - keeper.SetValidator(ctx, validators[0]) - keeper.SetValidator(ctx, validators[1]) - keeper.SetValidator(ctx, validators[2]) + r.SetPool(ctx, pool) + r.SetValidator(ctx, validators[0]) + r.SetValidator(ctx, validators[1]) + r.SetValidator(ctx, validators[2]) // Query Validators - queriedValidators := keeper.GetValidators(ctx, params.MaxValidators) + queriedValidators := r.GetValidators(ctx, params.MaxValidators) for i, s := range status { - queryValsParams := NewQueryValidatorsParams(1, int(params.MaxValidators), s.String()) + queryValsParams := types.NewQueryValidatorsParams(1, int(params.MaxValidators), s.String()) bz, err := cdc.MarshalJSON(queryValsParams) require.Nil(t, err) req := abci.RequestQuery{ - Path: fmt.Sprintf("/custom/%s/%s", types.QuerierRoute, QueryValidators), + Path: fmt.Sprintf("/custom/%s/%s", types.QuerierRoute, types.QueryValidators), Data: bz, } - res, err := queryValidators(ctx, req, keeper) + res, err := queryValidators(ctx, req, r) require.Nil(t, err) var validatorsResp []types.Validator @@ -159,7 +158,7 @@ func TestQueryValidators(t *testing.T) { } // Query each validator - queryParams := NewQueryValidatorParams(addrVal1) + queryParams := types.NewQueryValidatorParams(addrVal1) bz, err := cdc.MarshalJSON(queryParams) require.Nil(t, err) @@ -167,7 +166,7 @@ func TestQueryValidators(t *testing.T) { Path: "/custom/staking/validator", Data: bz, } - res, err := queryValidator(ctx, query, keeper) + res, err := queryValidator(ctx, query, r) require.Nil(t, err) var validator types.Validator @@ -179,26 +178,26 @@ func TestQueryValidators(t *testing.T) { func TestQueryDelegation(t *testing.T) { cdc := codec.New() - ctx, _, keeper := keep.CreateTestInput(t, false, 10000) - params := keeper.GetParams(ctx) + ctx, _, r := CreateTestInput(t, false, 10000) + params := r.GetParams(ctx) // Create Validators and Delegation val1 := types.NewValidator(addrVal1, pk1, types.Description{}) - keeper.SetValidator(ctx, val1) - keeper.SetValidatorByPowerIndex(ctx, val1) + r.SetValidator(ctx, val1) + r.SetValidatorByPowerIndex(ctx, val1) val2 := types.NewValidator(addrVal2, pk2, types.Description{}) - keeper.SetValidator(ctx, val2) - keeper.SetValidatorByPowerIndex(ctx, val2) + r.SetValidator(ctx, val2) + r.SetValidatorByPowerIndex(ctx, val2) delTokens := sdk.TokensFromTendermintPower(20) - keeper.Delegate(ctx, addrAcc2, delTokens, val1, true) + r.Delegate(ctx, addrAcc2, delTokens, val1, true) // apply TM updates - keeper.ApplyAndReturnValidatorSetUpdates(ctx) + r.ApplyAndReturnValidatorSetUpdates(ctx) // Query Delegator bonded validators - queryParams := NewQueryDelegatorParams(addrAcc2) + queryParams := types.NewQueryDelegatorParams(addrAcc2) bz, errRes := cdc.MarshalJSON(queryParams) require.Nil(t, errRes) @@ -207,9 +206,9 @@ func TestQueryDelegation(t *testing.T) { Data: bz, } - delValidators := keeper.GetDelegatorValidators(ctx, addrAcc2, params.MaxValidators) + delValidators := r.GetDelegatorValidators(ctx, addrAcc2, params.MaxValidators) - res, err := queryDelegatorValidators(ctx, query, keeper) + res, err := queryDelegatorValidators(ctx, query, r) require.Nil(t, err) var validatorsResp []types.Validator @@ -222,11 +221,11 @@ func TestQueryDelegation(t *testing.T) { // error unknown request query.Data = bz[:len(bz)-1] - _, err = queryDelegatorValidators(ctx, query, keeper) + _, err = queryDelegatorValidators(ctx, query, r) require.NotNil(t, err) // Query bonded validator - queryBondParams := NewQueryBondsParams(addrAcc2, addrVal1) + queryBondParams := types.NewQueryBondsParams(addrAcc2, addrVal1) bz, errRes = cdc.MarshalJSON(queryBondParams) require.Nil(t, errRes) @@ -235,7 +234,7 @@ func TestQueryDelegation(t *testing.T) { Data: bz, } - res, err = queryDelegatorValidator(ctx, query, keeper) + res, err = queryDelegatorValidator(ctx, query, r) require.Nil(t, err) var validator types.Validator @@ -247,7 +246,7 @@ func TestQueryDelegation(t *testing.T) { // error unknown request query.Data = bz[:len(bz)-1] - _, err = queryDelegatorValidator(ctx, query, keeper) + _, err = queryDelegatorValidator(ctx, query, r) require.NotNil(t, err) // Query delegation @@ -257,10 +256,10 @@ func TestQueryDelegation(t *testing.T) { Data: bz, } - delegation, found := keeper.GetDelegation(ctx, addrAcc2, addrVal1) + delegation, found := r.GetDelegation(ctx, addrAcc2, addrVal1) require.True(t, found) - res, err = queryDelegation(ctx, query, keeper) + res, err = queryDelegation(ctx, query, r) require.Nil(t, err) var delegationRes types.DelegationResponse @@ -277,7 +276,7 @@ func TestQueryDelegation(t *testing.T) { Data: bz, } - res, err = queryDelegatorDelegations(ctx, query, keeper) + res, err = queryDelegatorDelegations(ctx, query, r) require.Nil(t, err) var delegatorDelegations types.DelegationResponses @@ -291,12 +290,12 @@ func TestQueryDelegation(t *testing.T) { // error unknown request query.Data = bz[:len(bz)-1] - _, err = queryDelegation(ctx, query, keeper) + _, err = queryDelegation(ctx, query, r) require.NotNil(t, err) // Query validator delegations - bz, errRes = cdc.MarshalJSON(NewQueryValidatorParams(addrVal1)) + bz, errRes = cdc.MarshalJSON(types.NewQueryValidatorParams(addrVal1)) require.Nil(t, errRes) query = abci.RequestQuery{ @@ -304,7 +303,7 @@ func TestQueryDelegation(t *testing.T) { Data: bz, } - res, err = queryValidatorDelegations(ctx, query, keeper) + res, err = queryValidatorDelegations(ctx, query, r) require.Nil(t, err) var delegationsRes types.DelegationResponses @@ -317,10 +316,10 @@ func TestQueryDelegation(t *testing.T) { // Query unbonging delegation unbondingTokens := sdk.TokensFromTendermintPower(10) - _, err = keeper.Undelegate(ctx, addrAcc2, val1.OperatorAddress, unbondingTokens.ToDec()) + _, err = r.Undelegate(ctx, addrAcc2, val1.OperatorAddress, unbondingTokens.ToDec()) require.Nil(t, err) - queryBondParams = NewQueryBondsParams(addrAcc2, addrVal1) + queryBondParams = types.NewQueryBondsParams(addrAcc2, addrVal1) bz, errRes = cdc.MarshalJSON(queryBondParams) require.Nil(t, errRes) @@ -329,10 +328,10 @@ func TestQueryDelegation(t *testing.T) { Data: bz, } - unbond, found := keeper.GetUnbondingDelegation(ctx, addrAcc2, addrVal1) + unbond, found := r.GetUnbondingDelegation(ctx, addrAcc2, addrVal1) require.True(t, found) - res, err = queryUnbondingDelegation(ctx, query, keeper) + res, err = queryUnbondingDelegation(ctx, query, r) require.Nil(t, err) var unbondRes types.UnbondingDelegation @@ -344,7 +343,7 @@ func TestQueryDelegation(t *testing.T) { // error unknown request query.Data = bz[:len(bz)-1] - _, err = queryUnbondingDelegation(ctx, query, keeper) + _, err = queryUnbondingDelegation(ctx, query, r) require.NotNil(t, err) // Query Delegator Delegations @@ -354,7 +353,7 @@ func TestQueryDelegation(t *testing.T) { Data: bz, } - res, err = queryDelegatorUnbondingDelegations(ctx, query, keeper) + res, err = queryDelegatorUnbondingDelegations(ctx, query, r) require.Nil(t, err) var delegatorUbds []types.UnbondingDelegation @@ -365,18 +364,18 @@ func TestQueryDelegation(t *testing.T) { // error unknown request query.Data = bz[:len(bz)-1] - _, err = queryDelegatorUnbondingDelegations(ctx, query, keeper) + _, err = queryDelegatorUnbondingDelegations(ctx, query, r) require.NotNil(t, err) // Query redelegation redelegationTokens := sdk.TokensFromTendermintPower(10) - _, err = keeper.BeginRedelegation(ctx, addrAcc2, val1.OperatorAddress, + _, err = r.BeginRedelegation(ctx, addrAcc2, val1.OperatorAddress, val2.OperatorAddress, redelegationTokens.ToDec()) require.Nil(t, err) - redel, found := keeper.GetRedelegation(ctx, addrAcc2, val1.OperatorAddress, val2.OperatorAddress) + redel, found := r.GetRedelegation(ctx, addrAcc2, val1.OperatorAddress, val2.OperatorAddress) require.True(t, found) - bz, errRes = cdc.MarshalJSON(NewQueryRedelegationParams(addrAcc2, val1.OperatorAddress, val2.OperatorAddress)) + bz, errRes = cdc.MarshalJSON(types.NewQueryRedelegationParams(addrAcc2, val1.OperatorAddress, val2.OperatorAddress)) require.Nil(t, errRes) query = abci.RequestQuery{ @@ -384,7 +383,7 @@ func TestQueryDelegation(t *testing.T) { Data: bz, } - res, err = queryRedelegations(ctx, query, keeper) + res, err = queryRedelegations(ctx, query, r) require.Nil(t, err) var redelRes types.RedelegationResponses @@ -399,27 +398,27 @@ func TestQueryDelegation(t *testing.T) { func TestQueryRedelegations(t *testing.T) { cdc := codec.New() - ctx, _, keeper := keep.CreateTestInput(t, false, 10000) + ctx, _, r := CreateTestInput(t, false, 10000) // Create Validators and Delegation val1 := types.NewValidator(addrVal1, pk1, types.Description{}) val2 := types.NewValidator(addrVal2, pk2, types.Description{}) - keeper.SetValidator(ctx, val1) - keeper.SetValidator(ctx, val2) + r.SetValidator(ctx, val1) + r.SetValidator(ctx, val2) delAmount := sdk.TokensFromTendermintPower(100) - keeper.Delegate(ctx, addrAcc2, delAmount, val1, true) - _ = keeper.ApplyAndReturnValidatorSetUpdates(ctx) + r.Delegate(ctx, addrAcc2, delAmount, val1, true) + _ = r.ApplyAndReturnValidatorSetUpdates(ctx) rdAmount := sdk.TokensFromTendermintPower(20) - keeper.BeginRedelegation(ctx, addrAcc2, val1.GetOperator(), val2.GetOperator(), rdAmount.ToDec()) - keeper.ApplyAndReturnValidatorSetUpdates(ctx) + r.BeginRedelegation(ctx, addrAcc2, val1.GetOperator(), val2.GetOperator(), rdAmount.ToDec()) + r.ApplyAndReturnValidatorSetUpdates(ctx) - redel, found := keeper.GetRedelegation(ctx, addrAcc2, val1.OperatorAddress, val2.OperatorAddress) + redel, found := r.GetRedelegation(ctx, addrAcc2, val1.OperatorAddress, val2.OperatorAddress) require.True(t, found) // delegator redelegations - queryDelegatorParams := NewQueryDelegatorParams(addrAcc2) + queryDelegatorParams := types.NewQueryDelegatorParams(addrAcc2) bz, errRes := cdc.MarshalJSON(queryDelegatorParams) require.Nil(t, errRes) @@ -428,7 +427,7 @@ func TestQueryRedelegations(t *testing.T) { Data: bz, } - res, err := queryRedelegations(ctx, query, keeper) + res, err := queryRedelegations(ctx, query, r) require.Nil(t, err) var redelRes types.RedelegationResponses @@ -441,7 +440,7 @@ func TestQueryRedelegations(t *testing.T) { require.Len(t, redel.Entries, len(redelRes[0].Entries)) // validator redelegations - queryValidatorParams := NewQueryValidatorParams(val1.GetOperator()) + queryValidatorParams := types.NewQueryValidatorParams(val1.GetOperator()) bz, errRes = cdc.MarshalJSON(queryValidatorParams) require.Nil(t, errRes) @@ -450,7 +449,7 @@ func TestQueryRedelegations(t *testing.T) { Data: bz, } - res, err = queryRedelegations(ctx, query, keeper) + res, err = queryRedelegations(ctx, query, r) require.Nil(t, err) errRes = cdc.UnmarshalJSON(res, &redelRes) @@ -464,7 +463,7 @@ func TestQueryRedelegations(t *testing.T) { func TestQueryUnbondingDelegation(t *testing.T) { cdc := codec.New() - ctx, _, keeper := keep.CreateTestInput(t, false, 10000) + ctx, _, keeper := CreateTestInput(t, false, 10000) // Create Validators and Delegation val1 := types.NewValidator(addrVal1, pk1, types.Description{}) @@ -488,7 +487,7 @@ func TestQueryUnbondingDelegation(t *testing.T) { // // found: query unbonding delegation by delegator and validator // - queryValidatorParams := NewQueryBondsParams(addrAcc1, val1.GetOperator()) + queryValidatorParams := types.NewQueryBondsParams(addrAcc1, val1.GetOperator()) bz, errRes := cdc.MarshalJSON(queryValidatorParams) require.Nil(t, errRes) query := abci.RequestQuery{ @@ -507,7 +506,7 @@ func TestQueryUnbondingDelegation(t *testing.T) { // // not found: query unbonding delegation by delegator and validator // - queryValidatorParams = NewQueryBondsParams(addrAcc2, val1.GetOperator()) + queryValidatorParams = types.NewQueryBondsParams(addrAcc2, val1.GetOperator()) bz, errRes = cdc.MarshalJSON(queryValidatorParams) require.Nil(t, errRes) query = abci.RequestQuery{ @@ -520,7 +519,7 @@ func TestQueryUnbondingDelegation(t *testing.T) { // // found: query unbonding delegation by delegator and validator // - queryDelegatorParams := NewQueryDelegatorParams(addrAcc1) + queryDelegatorParams := types.NewQueryDelegatorParams(addrAcc1) bz, errRes = cdc.MarshalJSON(queryDelegatorParams) require.Nil(t, errRes) query = abci.RequestQuery{ @@ -539,7 +538,7 @@ func TestQueryUnbondingDelegation(t *testing.T) { // // not found: query unbonding delegation by delegator and validator // - queryDelegatorParams = NewQueryDelegatorParams(addrAcc2) + queryDelegatorParams = types.NewQueryDelegatorParams(addrAcc2) bz, errRes = cdc.MarshalJSON(queryDelegatorParams) require.Nil(t, errRes) query = abci.RequestQuery{ diff --git a/x/staking/module.go b/x/staking/module.go index aebb11401f40..8a540cb25fb0 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -3,6 +3,8 @@ package staking import ( "encoding/json" + "github.com/gorilla/mux" + "github.com/spf13/cobra" flag "github.com/spf13/pflag" abci "github.com/tendermint/tendermint/abci/types" @@ -12,20 +14,22 @@ import ( "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" + "github.com/cosmos/cosmos-sdk/types/module" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/cosmos/cosmos-sdk/x/staking/client/cli" + "github.com/cosmos/cosmos-sdk/x/staking/client/rest" "github.com/cosmos/cosmos-sdk/x/staking/types" ) var ( - _ sdk.AppModule = AppModule{} - _ sdk.AppModuleBasic = AppModuleBasic{} + _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} ) // app module basics object type AppModuleBasic struct{} -var _ sdk.AppModuleBasic = AppModuleBasic{} +var _ module.AppModuleBasic = AppModuleBasic{} // module name func (AppModuleBasic) Name() string { @@ -52,6 +56,21 @@ func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { return ValidateGenesis(data) } +// register rest routes +func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router, cdc *codec.Codec) { + rest.RegisterRoutes(ctx, rtr, cdc) +} + +// get the root tx command of this module +func (AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command { + return cli.GetTxCmd(StoreKey, cdc) +} + +// get the root query command of this module +func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { + return cli.GetQueryCmd(StoreKey, cdc) +} + //_____________________________________ // extra helpers @@ -69,7 +88,7 @@ func (AppModuleBasic) PrepareFlagsForTxCreateValidator(config *cfg.Config, nodeI // BuildCreateValidatorMsg - used for gen-tx func (AppModuleBasic) BuildCreateValidatorMsg(cliCtx context.CLIContext, - txBldr authtxb.TxBuilder) (authtxb.TxBuilder, sdk.Msg, error) { + txBldr authtypes.TxBuilder) (authtypes.TxBuilder, sdk.Msg, error) { return cli.BuildCreateValidatorMsg(cliCtx, txBldr) } diff --git a/x/staking/querier/utils.go b/x/staking/querier/utils.go deleted file mode 100644 index 391464af5c92..000000000000 --- a/x/staking/querier/utils.go +++ /dev/null @@ -1,71 +0,0 @@ -package querier - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/staking/keeper" - "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -func delegationToDelegationResponse(ctx sdk.Context, k keeper.Keeper, del types.Delegation) (types.DelegationResponse, sdk.Error) { - val, found := k.GetValidator(ctx, del.ValidatorAddress) - if !found { - return types.DelegationResponse{}, types.ErrNoValidatorFound(types.DefaultCodespace) - } - - return types.NewDelegationResp( - del.DelegatorAddress, - del.ValidatorAddress, - del.Shares, - val.TokensFromShares(del.Shares).TruncateInt(), - ), nil -} - -func delegationsToDelegationResponses( - ctx sdk.Context, k keeper.Keeper, delegations types.Delegations, -) (types.DelegationResponses, sdk.Error) { - - resp := make(types.DelegationResponses, len(delegations), len(delegations)) - for i, del := range delegations { - delResp, err := delegationToDelegationResponse(ctx, k, del) - if err != nil { - return nil, err - } - - resp[i] = delResp - } - - return resp, nil -} - -func redelegationsToRedelegationResponses( - ctx sdk.Context, k keeper.Keeper, redels types.Redelegations, -) (types.RedelegationResponses, sdk.Error) { - - resp := make(types.RedelegationResponses, len(redels), len(redels)) - for i, redel := range redels { - val, found := k.GetValidator(ctx, redel.ValidatorDstAddress) - if !found { - return nil, types.ErrNoValidatorFound(types.DefaultCodespace) - } - - entryResponses := make([]types.RedelegationEntryResponse, len(redel.Entries), len(redel.Entries)) - for j, entry := range redel.Entries { - entryResponses[j] = types.NewRedelegationEntryResponse( - entry.CreationHeight, - entry.CompletionTime, - entry.SharesDst, - entry.InitialBalance, - val.TokensFromShares(entry.SharesDst).TruncateInt(), - ) - } - - resp[i] = types.NewRedelegationResponse( - redel.DelegatorAddress, - redel.ValidatorSrcAddress, - redel.ValidatorDstAddress, - entryResponses, - ) - } - - return resp, nil -} diff --git a/x/staking/types/codec.go b/x/staking/types/codec.go index d4f3ad594aff..6fadfd9a68f9 100644 --- a/x/staking/types/codec.go +++ b/x/staking/types/codec.go @@ -17,8 +17,8 @@ func RegisterCodec(cdc *codec.Codec) { var ModuleCdc *codec.Codec func init() { - cdc := codec.New() - RegisterCodec(cdc) - codec.RegisterCrypto(cdc) - ModuleCdc = cdc.Seal() + ModuleCdc = codec.New() + RegisterCodec(ModuleCdc) + codec.RegisterCrypto(ModuleCdc) + ModuleCdc.Seal() } diff --git a/x/staking/types/querier.go b/x/staking/types/querier.go new file mode 100644 index 000000000000..ba38a55742f5 --- /dev/null +++ b/x/staking/types/querier.go @@ -0,0 +1,98 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// query endpoints supported by the staking Querier +const ( + QueryValidators = "validators" + QueryValidator = "validator" + QueryDelegatorDelegations = "delegatorDelegations" + QueryDelegatorUnbondingDelegations = "delegatorUnbondingDelegations" + QueryRedelegations = "redelegations" + QueryValidatorDelegations = "validatorDelegations" + QueryValidatorRedelegations = "validatorRedelegations" + QueryValidatorUnbondingDelegations = "validatorUnbondingDelegations" + QueryDelegation = "delegation" + QueryUnbondingDelegation = "unbondingDelegation" + QueryDelegatorValidators = "delegatorValidators" + QueryDelegatorValidator = "delegatorValidator" + QueryPool = "pool" + QueryParameters = "parameters" +) + +// defines the params for the following queries: +// - 'custom/staking/delegatorDelegations' +// - 'custom/staking/delegatorUnbondingDelegations' +// - 'custom/staking/delegatorRedelegations' +// - 'custom/staking/delegatorValidators' +type QueryDelegatorParams struct { + DelegatorAddr sdk.AccAddress +} + +func NewQueryDelegatorParams(delegatorAddr sdk.AccAddress) QueryDelegatorParams { + return QueryDelegatorParams{ + DelegatorAddr: delegatorAddr, + } +} + +// defines the params for the following queries: +// - 'custom/staking/validator' +// - 'custom/staking/validatorDelegations' +// - 'custom/staking/validatorUnbondingDelegations' +// - 'custom/staking/validatorRedelegations' +type QueryValidatorParams struct { + ValidatorAddr sdk.ValAddress +} + +func NewQueryValidatorParams(validatorAddr sdk.ValAddress) QueryValidatorParams { + return QueryValidatorParams{ + ValidatorAddr: validatorAddr, + } +} + +// defines the params for the following queries: +// - 'custom/staking/delegation' +// - 'custom/staking/unbondingDelegation' +// - 'custom/staking/delegatorValidator' +type QueryBondsParams struct { + DelegatorAddr sdk.AccAddress + ValidatorAddr sdk.ValAddress +} + +func NewQueryBondsParams(delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress) QueryBondsParams { + return QueryBondsParams{ + DelegatorAddr: delegatorAddr, + ValidatorAddr: validatorAddr, + } +} + +// defines the params for the following queries: +// - 'custom/staking/redelegation' +type QueryRedelegationParams struct { + DelegatorAddr sdk.AccAddress + SrcValidatorAddr sdk.ValAddress + DstValidatorAddr sdk.ValAddress +} + +func NewQueryRedelegationParams(delegatorAddr sdk.AccAddress, + srcValidatorAddr, dstValidatorAddr sdk.ValAddress) QueryRedelegationParams { + + return QueryRedelegationParams{ + DelegatorAddr: delegatorAddr, + SrcValidatorAddr: srcValidatorAddr, + DstValidatorAddr: dstValidatorAddr, + } +} + +// QueryValidatorsParams defines the params for the following queries: +// - 'custom/staking/validators' +type QueryValidatorsParams struct { + Page, Limit int + Status string +} + +func NewQueryValidatorsParams(page, limit int, status string) QueryValidatorsParams { + return QueryValidatorsParams{page, limit, status} +}