From 62cb0571f0aaf9e0070363d29ce665de12ed51e1 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Tue, 2 Jul 2019 17:05:56 +0200 Subject: [PATCH 01/36] reestructure gov module according to spec --- x/gov/{endblocker.go => abci.go} | 2 +- x/gov/{endblocker_test.go => abci_test.go} | 0 x/gov/alias.go | 6 +- x/gov/client/rest/query.go | 500 +++++++++++++++ x/gov/client/rest/rest.go | 602 +----------------- x/gov/client/rest/tx.go | 133 ++++ x/gov/genesis.go | 81 --- x/gov/genesis_test.go | 57 -- x/gov/{ => internal/keeper}/deposit.go | 4 +- x/gov/{ => internal/keeper}/invariants.go | 4 +- x/gov/{ => internal/keeper}/keeper.go | 10 +- x/gov/{ => internal/keeper}/keeper_test.go | 2 +- x/gov/{ => internal/keeper}/proposal.go | 4 +- x/gov/{ => internal/keeper}/querier.go | 5 +- x/gov/{ => internal/keeper}/querier_test.go | 4 +- x/gov/{ => internal/keeper}/tally.go | 29 +- x/gov/{ => internal/keeper}/tally_test.go | 2 +- x/gov/{ => internal/keeper}/vote.go | 4 +- x/gov/{ => internal}/types/codec.go | 0 x/gov/{ => internal}/types/content.go | 0 x/gov/{ => internal}/types/deposit.go | 0 x/gov/{ => internal}/types/errors.go | 2 +- x/gov/{ => internal}/types/events.go | 0 .../{ => internal/types}/expected_keepers.go | 2 +- x/gov/internal/types/genesis.go | 90 +++ x/gov/internal/types/genesis_test.go | 66 ++ x/gov/{ => internal}/types/keys.go | 0 x/gov/{ => internal}/types/keys_test.go | 0 x/gov/{ => internal}/types/msgs.go | 0 x/gov/{ => internal}/types/msgs_test.go | 0 x/gov/{ => internal}/types/params.go | 0 x/gov/{ => internal}/types/proposal.go | 51 -- x/gov/{ => internal}/types/proposals_test.go | 0 x/gov/{ => internal}/types/querier.go | 0 x/gov/internal/types/tally.go | 76 +++ x/gov/{ => internal}/types/vote.go | 0 x/gov/{simulation/msgs.go => simulation.go} | 43 +- 37 files changed, 921 insertions(+), 858 deletions(-) rename x/gov/{endblocker.go => abci.go} (97%) rename x/gov/{endblocker_test.go => abci_test.go} (100%) create mode 100644 x/gov/client/rest/query.go create mode 100644 x/gov/client/rest/tx.go rename x/gov/{ => internal/keeper}/deposit.go (98%) rename x/gov/{ => internal/keeper}/invariants.go (94%) rename x/gov/{ => internal/keeper}/keeper.go (97%) rename x/gov/{ => internal/keeper}/keeper_test.go (99%) rename x/gov/{ => internal/keeper}/proposal.go (98%) rename x/gov/{ => internal/keeper}/querier.go (98%) rename x/gov/{ => internal/keeper}/querier_test.go (99%) rename x/gov/{ => internal/keeper}/tally.go (78%) rename x/gov/{ => internal/keeper}/tally_test.go (99%) rename x/gov/{ => internal/keeper}/vote.go (97%) rename x/gov/{ => internal}/types/codec.go (100%) rename x/gov/{ => internal}/types/content.go (100%) rename x/gov/{ => internal}/types/deposit.go (100%) rename x/gov/{ => internal}/types/errors.go (98%) rename x/gov/{ => internal}/types/events.go (100%) rename x/gov/{ => internal/types}/expected_keepers.go (99%) create mode 100644 x/gov/internal/types/genesis.go create mode 100644 x/gov/internal/types/genesis_test.go rename x/gov/{ => internal}/types/keys.go (100%) rename x/gov/{ => internal}/types/keys_test.go (100%) rename x/gov/{ => internal}/types/msgs.go (100%) rename x/gov/{ => internal}/types/msgs_test.go (100%) rename x/gov/{ => internal}/types/params.go (100%) rename x/gov/{ => internal}/types/proposal.go (86%) rename x/gov/{ => internal}/types/proposals_test.go (100%) rename x/gov/{ => internal}/types/querier.go (100%) create mode 100644 x/gov/internal/types/tally.go rename x/gov/{ => internal}/types/vote.go (100%) rename x/gov/{simulation/msgs.go => simulation.go} (81%) diff --git a/x/gov/endblocker.go b/x/gov/abci.go similarity index 97% rename from x/gov/endblocker.go rename to x/gov/abci.go index d9d7933e05bd..730e4d3a4d29 100644 --- a/x/gov/endblocker.go +++ b/x/gov/abci.go @@ -39,7 +39,7 @@ func EndBlocker(ctx sdk.Context, keeper Keeper) { keeper.IterateActiveProposalsQueue(ctx, ctx.BlockHeader().Time, func(proposal Proposal) bool { var tagValue, logMsg string - passes, burnDeposits, tallyResults := tally(ctx, keeper, proposal) + passes, burnDeposits, tallyResults := keeper.Tally(ctx, proposal) if burnDeposits { keeper.DeleteDeposits(ctx, proposal.ProposalID) diff --git a/x/gov/endblocker_test.go b/x/gov/abci_test.go similarity index 100% rename from x/gov/endblocker_test.go rename to x/gov/abci_test.go diff --git a/x/gov/alias.go b/x/gov/alias.go index 9e3ed0ed070e..d4d99f2c44b5 100644 --- a/x/gov/alias.go +++ b/x/gov/alias.go @@ -1,11 +1,13 @@ // nolint // autogenerated code using github.com/rigelrozanski/multitool // aliases generated for the following subdirectories: -// ALIASGEN: github.com/cosmos/cosmos-sdk/x/gov/types +// ALIASGEN: github.com/cosmos/cosmos-sdk/x/gov/internal/keeper +// ALIASGEN: github.com/cosmos/cosmos-sdk/x/gov/internal/types package gov import ( - "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/cosmos/cosmos-sdk/x/gov/internal/keeper" + "github.com/cosmos/cosmos-sdk/x/gov/internal/types" ) const ( diff --git a/x/gov/client/rest/query.go b/x/gov/client/rest/query.go new file mode 100644 index 000000000000..23f471f027ea --- /dev/null +++ b/x/gov/client/rest/query.go @@ -0,0 +1,500 @@ +package rest + +import ( + "errors" + "fmt" + "net/http" + + "github.com/gorilla/mux" + + "github.com/cosmos/cosmos-sdk/client/context" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/rest" + "github.com/cosmos/cosmos-sdk/x/auth/client/utils" + gcutils "github.com/cosmos/cosmos-sdk/x/gov/client/utils" + "github.com/cosmos/cosmos-sdk/x/gov/types" +) + + +func registerQueryRoutes() { + r.HandleFunc(fmt.Sprintf("/gov/parameters/{%s}", RestParamsType), queryParamsHandlerFn(cliCtx)).Methods("GET") + r.HandleFunc("/gov/proposals", queryProposalsWithParameterFn(cliCtx)).Methods("GET") + r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}", RestProposalID), queryProposalHandlerFn(cliCtx)).Methods("GET") + r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/proposer", RestProposalID), queryProposerHandlerFn(cliCtx)).Methods("GET") + r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/deposits", RestProposalID), queryDepositsHandlerFn(cliCtx)).Methods("GET") + r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/deposits/{%s}", RestProposalID, RestDepositor), queryDepositHandlerFn(cliCtx)).Methods("GET") + r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/tally", RestProposalID), queryTallyOnProposalHandlerFn(cliCtx)).Methods("GET") + r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/votes", RestProposalID), queryVotesOnProposalHandlerFn(cliCtx)).Methods("GET") + r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/votes/{%s}", RestProposalID, RestVoter), queryVoteHandlerFn(cliCtx)).Methods("GET") +} + + +func queryParamsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + paramType := vars[RestParamsType] + + cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + if !ok { + return + } + + res, height, err := cliCtx.QueryWithData(fmt.Sprintf("custom/gov/%s/%s", types.QueryParams, paramType), nil) + if err != nil { + rest.WriteErrorResponse(w, http.StatusNotFound, err.Error()) + return + } + + cliCtx = cliCtx.WithHeight(height) + rest.PostProcessResponse(w, cliCtx, res) + } +} + +func queryProposalHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + strProposalID := vars[RestProposalID] + + if len(strProposalID) == 0 { + err := errors.New("proposalId required but not specified") + rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + proposalID, ok := rest.ParseUint64OrReturnBadRequest(w, strProposalID) + if !ok { + return + } + + cliCtx, ok = rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + if !ok { + return + } + + params := types.NewQueryProposalParams(proposalID) + + bz, err := cliCtx.Codec.MarshalJSON(params) + if err != nil { + rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + res, height, err := cliCtx.QueryWithData("custom/gov/proposal", bz) + if err != nil { + rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } + + cliCtx = cliCtx.WithHeight(height) + rest.PostProcessResponse(w, cliCtx, res) + } +} + +func queryDepositsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + strProposalID := vars[RestProposalID] + + proposalID, ok := rest.ParseUint64OrReturnBadRequest(w, strProposalID) + if !ok { + return + } + + cliCtx, ok = rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + if !ok { + return + } + + params := types.NewQueryProposalParams(proposalID) + + bz, err := cliCtx.Codec.MarshalJSON(params) + if err != nil { + rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + res, _, err := cliCtx.QueryWithData("custom/gov/proposal", bz) + if err != nil { + rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } + + var proposal types.Proposal + if err := cliCtx.Codec.UnmarshalJSON(res, &proposal); err != nil { + rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } + + // 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 == types.StatusVotingPeriod || propStatus == types.StatusDepositPeriod) { + res, err = gcutils.QueryDepositsByTxQuery(cliCtx, params) + } else { + res, _, err = cliCtx.QueryWithData("custom/gov/deposits", bz) + } + + if err != nil { + rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } + + rest.PostProcessResponse(w, cliCtx, res) + } +} + +func queryProposerHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + strProposalID := vars[RestProposalID] + + proposalID, ok := rest.ParseUint64OrReturnBadRequest(w, strProposalID) + if !ok { + return + } + + cliCtx, ok = rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + if !ok { + return + } + + res, err := gcutils.QueryProposerByTxQuery(cliCtx, proposalID) + if err != nil { + rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } + + rest.PostProcessResponse(w, cliCtx, res) + } +} + +func queryDepositHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + strProposalID := vars[RestProposalID] + bechDepositorAddr := vars[RestDepositor] + + if len(strProposalID) == 0 { + err := errors.New("proposalId required but not specified") + rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + proposalID, ok := rest.ParseUint64OrReturnBadRequest(w, strProposalID) + if !ok { + return + } + + if len(bechDepositorAddr) == 0 { + err := errors.New("depositor address required but not specified") + rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + depositorAddr, err := sdk.AccAddressFromBech32(bechDepositorAddr) + if err != nil { + rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + cliCtx, ok = rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + if !ok { + return + } + + params := types.NewQueryDepositParams(proposalID, depositorAddr) + + bz, err := cliCtx.Codec.MarshalJSON(params) + if err != nil { + rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + res, _, err := cliCtx.QueryWithData("custom/gov/deposit", bz) + if err != nil { + rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } + + var deposit types.Deposit + if err := cliCtx.Codec.UnmarshalJSON(res, &deposit); err != nil { + rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + // For an empty deposit, either the proposal does not exist or is inactive in + // which case the deposit would be removed from state and should be queried + // for directly via a txs query. + if deposit.Empty() { + bz, err := cliCtx.Codec.MarshalJSON(types.NewQueryProposalParams(proposalID)) + if err != nil { + rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + res, _, err = cliCtx.QueryWithData("custom/gov/proposal", bz) + if err != nil || len(res) == 0 { + err := fmt.Errorf("proposalID %d does not exist", proposalID) + rest.WriteErrorResponse(w, http.StatusNotFound, err.Error()) + return + } + + res, err = gcutils.QueryDepositByTxQuery(cliCtx, params) + if err != nil { + rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } + } + + rest.PostProcessResponse(w, cliCtx, res) + } +} + +func queryVoteHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + strProposalID := vars[RestProposalID] + bechVoterAddr := vars[RestVoter] + + if len(strProposalID) == 0 { + err := errors.New("proposalId required but not specified") + rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + proposalID, ok := rest.ParseUint64OrReturnBadRequest(w, strProposalID) + if !ok { + return + } + + if len(bechVoterAddr) == 0 { + err := errors.New("voter address required but not specified") + rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + voterAddr, err := sdk.AccAddressFromBech32(bechVoterAddr) + if err != nil { + rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + cliCtx, ok = rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + if !ok { + return + } + + params := types.NewQueryVoteParams(proposalID, voterAddr) + + bz, err := cliCtx.Codec.MarshalJSON(params) + if err != nil { + rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + res, _, err := cliCtx.QueryWithData("custom/gov/vote", bz) + if err != nil { + rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } + + var vote types.Vote + if err := cliCtx.Codec.UnmarshalJSON(res, &vote); err != nil { + rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + // For an empty vote, either the proposal does not exist or is inactive in + // which case the vote would be removed from state and should be queried for + // directly via a txs query. + if vote.Empty() { + bz, err := cliCtx.Codec.MarshalJSON(types.NewQueryProposalParams(proposalID)) + if err != nil { + rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + res, _, err = cliCtx.QueryWithData("custom/gov/proposal", bz) + if err != nil || len(res) == 0 { + err := fmt.Errorf("proposalID %d does not exist", proposalID) + rest.WriteErrorResponse(w, http.StatusNotFound, err.Error()) + return + } + + res, err = gcutils.QueryVoteByTxQuery(cliCtx, params) + if err != nil { + rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } + } + + rest.PostProcessResponse(w, cliCtx, res) + } +} + +// todo: Split this functionality into helper functions to remove the above +func queryVotesOnProposalHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + strProposalID := vars[RestProposalID] + + if len(strProposalID) == 0 { + err := errors.New("proposalId required but not specified") + rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + proposalID, ok := rest.ParseUint64OrReturnBadRequest(w, strProposalID) + if !ok { + return + } + + cliCtx, ok = rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + if !ok { + return + } + + params := types.NewQueryProposalParams(proposalID) + + bz, err := cliCtx.Codec.MarshalJSON(params) + if err != nil { + rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + res, _, err := cliCtx.QueryWithData("custom/gov/proposal", bz) + if err != nil { + rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } + + var proposal types.Proposal + if err := cliCtx.Codec.UnmarshalJSON(res, &proposal); err != nil { + rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } + + // 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 == types.StatusVotingPeriod || propStatus == types.StatusDepositPeriod) { + res, err = gcutils.QueryVotesByTxQuery(cliCtx, params) + } else { + res, _, err = cliCtx.QueryWithData("custom/gov/votes", bz) + } + + if err != nil { + rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } + + rest.PostProcessResponse(w, cliCtx, res) + } +} + +// todo: Split this functionality into helper functions to remove the above +func queryProposalsWithParameterFn(cliCtx context.CLIContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + bechVoterAddr := r.URL.Query().Get(RestVoter) + bechDepositorAddr := r.URL.Query().Get(RestDepositor) + strProposalStatus := r.URL.Query().Get(RestProposalStatus) + strNumLimit := r.URL.Query().Get(RestNumLimit) + + params := types.QueryProposalsParams{} + + if len(bechVoterAddr) != 0 { + voterAddr, err := sdk.AccAddressFromBech32(bechVoterAddr) + if err != nil { + rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + params.Voter = voterAddr + } + + if len(bechDepositorAddr) != 0 { + depositorAddr, err := sdk.AccAddressFromBech32(bechDepositorAddr) + if err != nil { + rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + params.Depositor = depositorAddr + } + + if len(strProposalStatus) != 0 { + proposalStatus, err := types.ProposalStatusFromString(gcutils.NormalizeProposalStatus(strProposalStatus)) + if err != nil { + rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + params.ProposalStatus = proposalStatus + } + if len(strNumLimit) != 0 { + numLimit, ok := rest.ParseUint64OrReturnBadRequest(w, strNumLimit) + if !ok { + return + } + params.Limit = numLimit + } + + cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + if !ok { + return + } + + bz, err := cliCtx.Codec.MarshalJSON(params) + if err != nil { + rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + res, height, err := cliCtx.QueryWithData("custom/gov/proposals", bz) + if err != nil { + rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } + + cliCtx = cliCtx.WithHeight(height) + rest.PostProcessResponse(w, cliCtx, res) + } +} + +// todo: Split this functionality into helper functions to remove the above +func queryTallyOnProposalHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + strProposalID := vars[RestProposalID] + + if len(strProposalID) == 0 { + err := errors.New("proposalId required but not specified") + rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + proposalID, ok := rest.ParseUint64OrReturnBadRequest(w, strProposalID) + if !ok { + return + } + + cliCtx, ok = rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + if !ok { + return + } + + params := types.NewQueryProposalParams(proposalID) + + bz, err := cliCtx.Codec.MarshalJSON(params) + if err != nil { + rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + res, height, err := cliCtx.QueryWithData("custom/gov/tally", bz) + if err != nil { + rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) + return + } + + cliCtx = cliCtx.WithHeight(height) + rest.PostProcessResponse(w, cliCtx, res) + } +} diff --git a/x/gov/client/rest/rest.go b/x/gov/client/rest/rest.go index 79121d33f741..58a054c1a7c5 100644 --- a/x/gov/client/rest/rest.go +++ b/x/gov/client/rest/rest.go @@ -35,31 +35,8 @@ type ProposalRESTHandler struct { // RegisterRoutes - Central function to define routes that get registered by the main application func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router, phs []ProposalRESTHandler) { - propSubRtr := r.PathPrefix("/gov/proposals").Subrouter() - for _, ph := range phs { - propSubRtr.HandleFunc(fmt.Sprintf("/%s", ph.SubRoute), ph.Handler).Methods("POST") - } - - r.HandleFunc("/gov/proposals", postProposalHandlerFn(cliCtx)).Methods("POST") - r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/deposits", RestProposalID), depositHandlerFn(cliCtx)).Methods("POST") - r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/votes", RestProposalID), voteHandlerFn(cliCtx)).Methods("POST") - - r.HandleFunc( - fmt.Sprintf("/gov/parameters/{%s}", RestParamsType), - queryParamsHandlerFn(cliCtx), - ).Methods("GET") - - r.HandleFunc("/gov/proposals", queryProposalsWithParameterFn(cliCtx)).Methods("GET") - r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}", RestProposalID), queryProposalHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc( - fmt.Sprintf("/gov/proposals/{%s}/proposer", RestProposalID), - queryProposerHandlerFn(cliCtx), - ).Methods("GET") - r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/deposits", RestProposalID), queryDepositsHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/deposits/{%s}", RestProposalID, RestDepositor), queryDepositHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/tally", RestProposalID), queryTallyOnProposalHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/votes", RestProposalID), queryVotesOnProposalHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/votes/{%s}", RestProposalID, RestVoter), queryVoteHandlerFn(cliCtx)).Methods("GET") + registerQueryRoutes(cliCtx, r) + registerTxRoutes(cliCtx, r, phs) } // PostProposalReq defines the properties of a proposal request's body. @@ -85,578 +62,3 @@ type VoteReq struct { Voter sdk.AccAddress `json:"voter"` // address of the voter Option string `json:"option"` // option from OptionSet chosen by the voter } - -func postProposalHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - var req PostProposalReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { - return - } - - req.BaseReq = req.BaseReq.Sanitize() - if !req.BaseReq.ValidateBasic(w) { - return - } - - proposalType := gcutils.NormalizeProposalType(req.ProposalType) - content := types.ContentFromProposalType(req.Title, req.Description, proposalType) - - msg := types.NewMsgSubmitProposal(content, req.InitialDeposit, req.Proposer) - if err := msg.ValidateBasic(); err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - utils.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) - } -} - -func depositHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - strProposalID := vars[RestProposalID] - - if len(strProposalID) == 0 { - err := errors.New("proposalId required but not specified") - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - proposalID, ok := rest.ParseUint64OrReturnBadRequest(w, strProposalID) - if !ok { - return - } - - var req DepositReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { - return - } - - req.BaseReq = req.BaseReq.Sanitize() - if !req.BaseReq.ValidateBasic(w) { - return - } - - // create the message - msg := types.NewMsgDeposit(req.Depositor, proposalID, req.Amount) - if err := msg.ValidateBasic(); err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - utils.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) - } -} - -func voteHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - strProposalID := vars[RestProposalID] - - if len(strProposalID) == 0 { - err := errors.New("proposalId required but not specified") - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - proposalID, ok := rest.ParseUint64OrReturnBadRequest(w, strProposalID) - if !ok { - return - } - - var req VoteReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { - return - } - - req.BaseReq = req.BaseReq.Sanitize() - if !req.BaseReq.ValidateBasic(w) { - return - } - - voteOption, err := types.VoteOptionFromString(gcutils.NormalizeVoteOption(req.Option)) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - // create the message - msg := types.NewMsgVote(req.Voter, proposalID, voteOption) - if err := msg.ValidateBasic(); err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - utils.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) - } -} - -func queryParamsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - paramType := vars[RestParamsType] - - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) - if !ok { - return - } - - res, height, err := cliCtx.QueryWithData(fmt.Sprintf("custom/gov/%s/%s", types.QueryParams, paramType), nil) - if err != nil { - rest.WriteErrorResponse(w, http.StatusNotFound, err.Error()) - return - } - - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, res) - } -} - -func queryProposalHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - strProposalID := vars[RestProposalID] - - if len(strProposalID) == 0 { - err := errors.New("proposalId required but not specified") - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - proposalID, ok := rest.ParseUint64OrReturnBadRequest(w, strProposalID) - if !ok { - return - } - - cliCtx, ok = rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) - if !ok { - return - } - - params := types.NewQueryProposalParams(proposalID) - - bz, err := cliCtx.Codec.MarshalJSON(params) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - res, height, err := cliCtx.QueryWithData("custom/gov/proposal", bz) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, res) - } -} - -func queryDepositsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - strProposalID := vars[RestProposalID] - - proposalID, ok := rest.ParseUint64OrReturnBadRequest(w, strProposalID) - if !ok { - return - } - - cliCtx, ok = rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) - if !ok { - return - } - - params := types.NewQueryProposalParams(proposalID) - - bz, err := cliCtx.Codec.MarshalJSON(params) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - res, _, err := cliCtx.QueryWithData("custom/gov/proposal", bz) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - var proposal types.Proposal - if err := cliCtx.Codec.UnmarshalJSON(res, &proposal); err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - // 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 == types.StatusVotingPeriod || propStatus == types.StatusDepositPeriod) { - res, err = gcutils.QueryDepositsByTxQuery(cliCtx, params) - } else { - res, _, err = cliCtx.QueryWithData("custom/gov/deposits", bz) - } - - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - rest.PostProcessResponse(w, cliCtx, res) - } -} - -func queryProposerHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - strProposalID := vars[RestProposalID] - - proposalID, ok := rest.ParseUint64OrReturnBadRequest(w, strProposalID) - if !ok { - return - } - - cliCtx, ok = rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) - if !ok { - return - } - - res, err := gcutils.QueryProposerByTxQuery(cliCtx, proposalID) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - rest.PostProcessResponse(w, cliCtx, res) - } -} - -func queryDepositHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - strProposalID := vars[RestProposalID] - bechDepositorAddr := vars[RestDepositor] - - if len(strProposalID) == 0 { - err := errors.New("proposalId required but not specified") - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - proposalID, ok := rest.ParseUint64OrReturnBadRequest(w, strProposalID) - if !ok { - return - } - - if len(bechDepositorAddr) == 0 { - err := errors.New("depositor address required but not specified") - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - depositorAddr, err := sdk.AccAddressFromBech32(bechDepositorAddr) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - cliCtx, ok = rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) - if !ok { - return - } - - params := types.NewQueryDepositParams(proposalID, depositorAddr) - - bz, err := cliCtx.Codec.MarshalJSON(params) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - res, _, err := cliCtx.QueryWithData("custom/gov/deposit", bz) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - var deposit types.Deposit - if err := cliCtx.Codec.UnmarshalJSON(res, &deposit); err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - // For an empty deposit, either the proposal does not exist or is inactive in - // which case the deposit would be removed from state and should be queried - // for directly via a txs query. - if deposit.Empty() { - bz, err := cliCtx.Codec.MarshalJSON(types.NewQueryProposalParams(proposalID)) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - res, _, err = cliCtx.QueryWithData("custom/gov/proposal", bz) - if err != nil || len(res) == 0 { - err := fmt.Errorf("proposalID %d does not exist", proposalID) - rest.WriteErrorResponse(w, http.StatusNotFound, err.Error()) - return - } - - res, err = gcutils.QueryDepositByTxQuery(cliCtx, params) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - } - - rest.PostProcessResponse(w, cliCtx, res) - } -} - -func queryVoteHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - strProposalID := vars[RestProposalID] - bechVoterAddr := vars[RestVoter] - - if len(strProposalID) == 0 { - err := errors.New("proposalId required but not specified") - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - proposalID, ok := rest.ParseUint64OrReturnBadRequest(w, strProposalID) - if !ok { - return - } - - if len(bechVoterAddr) == 0 { - err := errors.New("voter address required but not specified") - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - voterAddr, err := sdk.AccAddressFromBech32(bechVoterAddr) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - cliCtx, ok = rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) - if !ok { - return - } - - params := types.NewQueryVoteParams(proposalID, voterAddr) - - bz, err := cliCtx.Codec.MarshalJSON(params) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - res, _, err := cliCtx.QueryWithData("custom/gov/vote", bz) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - var vote types.Vote - if err := cliCtx.Codec.UnmarshalJSON(res, &vote); err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - // For an empty vote, either the proposal does not exist or is inactive in - // which case the vote would be removed from state and should be queried for - // directly via a txs query. - if vote.Empty() { - bz, err := cliCtx.Codec.MarshalJSON(types.NewQueryProposalParams(proposalID)) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - res, _, err = cliCtx.QueryWithData("custom/gov/proposal", bz) - if err != nil || len(res) == 0 { - err := fmt.Errorf("proposalID %d does not exist", proposalID) - rest.WriteErrorResponse(w, http.StatusNotFound, err.Error()) - return - } - - res, err = gcutils.QueryVoteByTxQuery(cliCtx, params) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - } - - rest.PostProcessResponse(w, cliCtx, res) - } -} - -// todo: Split this functionality into helper functions to remove the above -func queryVotesOnProposalHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - strProposalID := vars[RestProposalID] - - if len(strProposalID) == 0 { - err := errors.New("proposalId required but not specified") - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - proposalID, ok := rest.ParseUint64OrReturnBadRequest(w, strProposalID) - if !ok { - return - } - - cliCtx, ok = rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) - if !ok { - return - } - - params := types.NewQueryProposalParams(proposalID) - - bz, err := cliCtx.Codec.MarshalJSON(params) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - res, _, err := cliCtx.QueryWithData("custom/gov/proposal", bz) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - var proposal types.Proposal - if err := cliCtx.Codec.UnmarshalJSON(res, &proposal); err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - // 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 == types.StatusVotingPeriod || propStatus == types.StatusDepositPeriod) { - res, err = gcutils.QueryVotesByTxQuery(cliCtx, params) - } else { - res, _, err = cliCtx.QueryWithData("custom/gov/votes", bz) - } - - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - rest.PostProcessResponse(w, cliCtx, res) - } -} - -// todo: Split this functionality into helper functions to remove the above -func queryProposalsWithParameterFn(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - bechVoterAddr := r.URL.Query().Get(RestVoter) - bechDepositorAddr := r.URL.Query().Get(RestDepositor) - strProposalStatus := r.URL.Query().Get(RestProposalStatus) - strNumLimit := r.URL.Query().Get(RestNumLimit) - - params := types.QueryProposalsParams{} - - if len(bechVoterAddr) != 0 { - voterAddr, err := sdk.AccAddressFromBech32(bechVoterAddr) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - params.Voter = voterAddr - } - - if len(bechDepositorAddr) != 0 { - depositorAddr, err := sdk.AccAddressFromBech32(bechDepositorAddr) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - params.Depositor = depositorAddr - } - - if len(strProposalStatus) != 0 { - proposalStatus, err := types.ProposalStatusFromString(gcutils.NormalizeProposalStatus(strProposalStatus)) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - params.ProposalStatus = proposalStatus - } - if len(strNumLimit) != 0 { - numLimit, ok := rest.ParseUint64OrReturnBadRequest(w, strNumLimit) - if !ok { - return - } - params.Limit = numLimit - } - - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) - if !ok { - return - } - - bz, err := cliCtx.Codec.MarshalJSON(params) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - res, height, err := cliCtx.QueryWithData("custom/gov/proposals", bz) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, res) - } -} - -// todo: Split this functionality into helper functions to remove the above -func queryTallyOnProposalHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - strProposalID := vars[RestProposalID] - - if len(strProposalID) == 0 { - err := errors.New("proposalId required but not specified") - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - proposalID, ok := rest.ParseUint64OrReturnBadRequest(w, strProposalID) - if !ok { - return - } - - cliCtx, ok = rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) - if !ok { - return - } - - params := types.NewQueryProposalParams(proposalID) - - bz, err := cliCtx.Codec.MarshalJSON(params) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - res, height, err := cliCtx.QueryWithData("custom/gov/tally", bz) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, res) - } -} diff --git a/x/gov/client/rest/tx.go b/x/gov/client/rest/tx.go new file mode 100644 index 000000000000..764cb7943fa4 --- /dev/null +++ b/x/gov/client/rest/tx.go @@ -0,0 +1,133 @@ +package rest + +import ( + "errors" + "fmt" + "net/http" + + "github.com/gorilla/mux" + + "github.com/cosmos/cosmos-sdk/client/context" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/rest" + "github.com/cosmos/cosmos-sdk/x/auth/client/utils" + gcutils "github.com/cosmos/cosmos-sdk/x/gov/client/utils" + "github.com/cosmos/cosmos-sdk/x/gov/types" +) + +func registerTxRoutes(cliCtx, r, phs []ProposalRESTHandler) { + propSubRtr := r.PathPrefix("/gov/proposals").Subrouter() + for _, ph := range phs { + propSubRtr.HandleFunc(fmt.Sprintf("/%s", ph.SubRoute), ph.Handler).Methods("POST") + } + + r.HandleFunc("/gov/proposals", postProposalHandlerFn(cliCtx)).Methods("POST") + r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/deposits", RestProposalID), depositHandlerFn(cliCtx)).Methods("POST") + r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/votes", RestProposalID), voteHandlerFn(cliCtx)).Methods("POST") +} + + +func postProposalHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req PostProposalReq + if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + return + } + + req.BaseReq = req.BaseReq.Sanitize() + if !req.BaseReq.ValidateBasic(w) { + return + } + + proposalType := gcutils.NormalizeProposalType(req.ProposalType) + content := types.ContentFromProposalType(req.Title, req.Description, proposalType) + + msg := types.NewMsgSubmitProposal(content, req.InitialDeposit, req.Proposer) + if err := msg.ValidateBasic(); err != nil { + rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + utils.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) + } +} + +func depositHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + strProposalID := vars[RestProposalID] + + if len(strProposalID) == 0 { + err := errors.New("proposalId required but not specified") + rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + proposalID, ok := rest.ParseUint64OrReturnBadRequest(w, strProposalID) + if !ok { + return + } + + var req DepositReq + if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + return + } + + req.BaseReq = req.BaseReq.Sanitize() + if !req.BaseReq.ValidateBasic(w) { + return + } + + // create the message + msg := types.NewMsgDeposit(req.Depositor, proposalID, req.Amount) + if err := msg.ValidateBasic(); err != nil { + rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + utils.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) + } +} + +func voteHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + strProposalID := vars[RestProposalID] + + if len(strProposalID) == 0 { + err := errors.New("proposalId required but not specified") + rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + proposalID, ok := rest.ParseUint64OrReturnBadRequest(w, strProposalID) + if !ok { + return + } + + var req VoteReq + if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + return + } + + req.BaseReq = req.BaseReq.Sanitize() + if !req.BaseReq.ValidateBasic(w) { + return + } + + voteOption, err := types.VoteOptionFromString(gcutils.NormalizeVoteOption(req.Option)) + if err != nil { + rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + // create the message + msg := types.NewMsgVote(req.Voter, proposalID, voteOption) + if err := msg.ValidateBasic(); err != nil { + rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + utils.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) + } +} \ No newline at end of file diff --git a/x/gov/genesis.go b/x/gov/genesis.go index ea87444da7ce..a633f45d5f46 100644 --- a/x/gov/genesis.go +++ b/x/gov/genesis.go @@ -9,87 +9,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/gov/types" ) -const ( - // Default period for deposits & voting - DefaultPeriod time.Duration = 86400 * 2 * time.Second // 2 days -) - -// GenesisState - all staking state that must be provided at genesis -type GenesisState struct { - StartingProposalID uint64 `json:"starting_proposal_id"` - Deposits Deposits `json:"deposits"` - Votes Votes `json:"votes"` - Proposals []Proposal `json:"proposals"` - DepositParams DepositParams `json:"deposit_params"` - VotingParams VotingParams `json:"voting_params"` - TallyParams TallyParams `json:"tally_params"` -} - -// NewGenesisState creates a new genesis state for the governance module -func NewGenesisState(startingProposalID uint64, dp DepositParams, vp VotingParams, tp TallyParams) GenesisState { - return GenesisState{ - StartingProposalID: startingProposalID, - DepositParams: dp, - VotingParams: vp, - TallyParams: tp, - } -} - -// get raw genesis raw message for testing -func DefaultGenesisState() GenesisState { - minDepositTokens := sdk.TokensFromConsensusPower(10) - return GenesisState{ - StartingProposalID: 1, - DepositParams: DepositParams{ - MinDeposit: sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, minDepositTokens)}, - MaxDepositPeriod: DefaultPeriod, - }, - VotingParams: VotingParams{ - VotingPeriod: DefaultPeriod, - }, - TallyParams: TallyParams{ - Quorum: sdk.NewDecWithPrec(334, 3), - Threshold: sdk.NewDecWithPrec(5, 1), - Veto: sdk.NewDecWithPrec(334, 3), - }, - } -} - -// Checks whether 2 GenesisState structs are equivalent. -func (data GenesisState) Equal(data2 GenesisState) bool { - b1 := types.ModuleCdc.MustMarshalBinaryBare(data) - b2 := types.ModuleCdc.MustMarshalBinaryBare(data2) - return bytes.Equal(b1, b2) -} - -// Returns if a GenesisState is empty or has data in it -func (data GenesisState) IsEmpty() bool { - emptyGenState := GenesisState{} - return data.Equal(emptyGenState) -} - -// ValidateGenesis checks if parameters are within valid ranges -func ValidateGenesis(data GenesisState) error { - threshold := data.TallyParams.Threshold - if threshold.IsNegative() || threshold.GT(sdk.OneDec()) { - return fmt.Errorf("Governance vote threshold should be positive and less or equal to one, is %s", - threshold.String()) - } - - veto := data.TallyParams.Veto - if veto.IsNegative() || veto.GT(sdk.OneDec()) { - return fmt.Errorf("Governance vote veto threshold should be positive and less or equal to one, is %s", - veto.String()) - } - - if !data.DepositParams.MinDeposit.IsValid() { - return fmt.Errorf("Governance deposit amount must be a valid sdk.Coins amount, is %s", - data.DepositParams.MinDeposit.String()) - } - - return nil -} - // InitGenesis - store genesis parameters func InitGenesis(ctx sdk.Context, k Keeper, supplyKeeper SupplyKeeper, data GenesisState) { diff --git a/x/gov/genesis_test.go b/x/gov/genesis_test.go index 692a77b6a46a..37ce0619155f 100644 --- a/x/gov/genesis_test.go +++ b/x/gov/genesis_test.go @@ -8,63 +8,6 @@ import ( abci "github.com/tendermint/tendermint/abci/types" ) -func TestEqualProposalID(t *testing.T) { - state1 := GenesisState{} - state2 := GenesisState{} - require.Equal(t, state1, state2) - - // Proposals - state1.StartingProposalID = 1 - require.NotEqual(t, state1, state2) - require.False(t, state1.Equal(state2)) - - state2.StartingProposalID = 1 - require.Equal(t, state1, state2) - require.True(t, state1.Equal(state2)) -} - -func TestEqualProposals(t *testing.T) { - // Generate mock app and keepers - input := getMockApp(t, 2, GenesisState{}, nil) - SortAddresses(input.addrs) - - header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} - input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) - - ctx := input.mApp.BaseApp.NewContext(false, abci.Header{}) - - // Submit two proposals - proposal := testProposal() - proposal1, err := input.keeper.SubmitProposal(ctx, proposal) - require.NoError(t, err) - proposal2, err := input.keeper.SubmitProposal(ctx, proposal) - require.NoError(t, err) - - // They are similar but their IDs should be different - require.NotEqual(t, proposal1, proposal2) - require.False(t, ProposalEqual(proposal1, proposal2)) - - // Now create two genesis blocks - state1 := GenesisState{Proposals: []Proposal{proposal1}} - state2 := GenesisState{Proposals: []Proposal{proposal2}} - require.NotEqual(t, state1, state2) - require.False(t, state1.Equal(state2)) - - // Now make proposals identical by setting both IDs to 55 - proposal1.ProposalID = 55 - proposal2.ProposalID = 55 - require.Equal(t, proposal1, proposal1) - require.True(t, ProposalEqual(proposal1, proposal2)) - - // Reassign proposals into state - state1.Proposals[0] = proposal1 - state2.Proposals[0] = proposal2 - - // State should be identical now.. - require.Equal(t, state1, state2) - require.True(t, state1.Equal(state2)) -} - func TestImportExportQueues(t *testing.T) { // Generate mock app and keepers input := getMockApp(t, 2, GenesisState{}, nil) diff --git a/x/gov/deposit.go b/x/gov/internal/keeper/deposit.go similarity index 98% rename from x/gov/deposit.go rename to x/gov/internal/keeper/deposit.go index 0059d693d6f2..d327b4dd87d0 100644 --- a/x/gov/deposit.go +++ b/x/gov/internal/keeper/deposit.go @@ -1,10 +1,10 @@ -package gov +package keeper import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/cosmos/cosmos-sdk/x/gov/internal/types" ) // GetDeposit gets the deposit of a specific depositor on a specific proposal diff --git a/x/gov/invariants.go b/x/gov/internal/keeper/invariants.go similarity index 94% rename from x/gov/invariants.go rename to x/gov/internal/keeper/invariants.go index 1e9454978e8b..1fa9cdbad656 100644 --- a/x/gov/invariants.go +++ b/x/gov/internal/keeper/invariants.go @@ -1,10 +1,10 @@ -package gov +package keeper import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/cosmos/cosmos-sdk/x/gov/internal/types" ) // RegisterInvariants registers all governance invariants diff --git a/x/gov/keeper.go b/x/gov/internal/keeper/keeper.go similarity index 97% rename from x/gov/keeper.go rename to x/gov/internal/keeper/keeper.go index 826ef83cd77f..d196892cd8d1 100644 --- a/x/gov/keeper.go +++ b/x/gov/internal/keeper/keeper.go @@ -1,4 +1,4 @@ -package gov +package keeper import ( "fmt" @@ -6,7 +6,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/cosmos/cosmos-sdk/x/gov/internal/types" "github.com/cosmos/cosmos-sdk/x/params" "github.com/cosmos/cosmos-sdk/x/supply/exported" @@ -22,10 +22,10 @@ type Keeper struct { paramSpace params.Subspace // The SupplyKeeper to reduce the supply of the network - supplyKeeper SupplyKeeper + supplyKeeper types.SupplyKeeper // The reference to the DelegationSet and ValidatorSet to get information about validators and delegators - sk StakingKeeper + sk types.StakingKeeper // The (unexposed) keys used to access the stores from the Context. storeKey sdk.StoreKey @@ -47,7 +47,7 @@ type Keeper struct { // - and tallying the result of the vote. func NewKeeper( cdc *codec.Codec, key sdk.StoreKey, paramsKeeper params.Keeper, paramSpace params.Subspace, - supplyKeeper SupplyKeeper, sk StakingKeeper, codespace sdk.CodespaceType, rtr Router, + supplyKeeper types.SupplyKeeper, sk types.StakingKeeper, codespace sdk.CodespaceType, rtr Router, ) Keeper { // ensure governance module account is set diff --git a/x/gov/keeper_test.go b/x/gov/internal/keeper/keeper_test.go similarity index 99% rename from x/gov/keeper_test.go rename to x/gov/internal/keeper/keeper_test.go index 8689bf55d888..795aefb08b4f 100644 --- a/x/gov/keeper_test.go +++ b/x/gov/internal/keeper/keeper_test.go @@ -1,4 +1,4 @@ -package gov +package keeper import ( "strings" diff --git a/x/gov/proposal.go b/x/gov/internal/keeper/proposal.go similarity index 98% rename from x/gov/proposal.go rename to x/gov/internal/keeper/proposal.go index ef9b7e89e281..e639b5af141f 100644 --- a/x/gov/proposal.go +++ b/x/gov/internal/keeper/proposal.go @@ -1,10 +1,10 @@ -package gov +package keeper import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/cosmos/cosmos-sdk/x/gov/internal/types" ) // SubmitProposal create new proposal given a content diff --git a/x/gov/querier.go b/x/gov/internal/keeper/querier.go similarity index 98% rename from x/gov/querier.go rename to x/gov/internal/keeper/querier.go index 03e37c84a13b..6713de8e891c 100644 --- a/x/gov/querier.go +++ b/x/gov/internal/keeper/querier.go @@ -1,4 +1,4 @@ -package gov +package keeper import ( "fmt" @@ -7,9 +7,10 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/cosmos/cosmos-sdk/x/gov/internal/types" ) +// NewQuerier creates a new gov Querier instance func NewQuerier(keeper Keeper) sdk.Querier { return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, sdk.Error) { switch path[0] { diff --git a/x/gov/querier_test.go b/x/gov/internal/keeper/querier_test.go similarity index 99% rename from x/gov/querier_test.go rename to x/gov/internal/keeper/querier_test.go index 86f804b22f55..fb19d26c8c87 100644 --- a/x/gov/querier_test.go +++ b/x/gov/internal/keeper/querier_test.go @@ -1,4 +1,4 @@ -package gov +package keeper import ( "strings" @@ -9,7 +9,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/cosmos/cosmos-sdk/x/gov/internal/types" ) const custom = "custom" diff --git a/x/gov/tally.go b/x/gov/internal/keeper/tally.go similarity index 78% rename from x/gov/tally.go rename to x/gov/internal/keeper/tally.go index 58160b8ab02a..b4ce5dd92eb5 100644 --- a/x/gov/tally.go +++ b/x/gov/internal/keeper/tally.go @@ -1,34 +1,17 @@ -package gov +package keeper import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/cosmos/cosmos-sdk/x/gov/internal/types" "github.com/cosmos/cosmos-sdk/x/staking/exported" ) -// validatorGovInfo used for tallying -type validatorGovInfo struct { - Address sdk.ValAddress // address of the validator operator - BondedTokens sdk.Int // Power of a Validator - DelegatorShares sdk.Dec // Total outstanding delegator shares - DelegatorDeductions sdk.Dec // Delegator deductions from validator's delegators voting independently - Vote VoteOption // Vote of the validator -} - -func newValidatorGovInfo(address sdk.ValAddress, bondedTokens sdk.Int, delegatorShares, - delegatorDeductions sdk.Dec, vote VoteOption) validatorGovInfo { - - return validatorGovInfo{ - Address: address, - BondedTokens: bondedTokens, - DelegatorShares: delegatorShares, - DelegatorDeductions: delegatorDeductions, - Vote: vote, - } -} // TODO: Break into several smaller functions for clarity -func tally(ctx sdk.Context, keeper Keeper, proposal Proposal) (passes bool, burnDeposits bool, tallyResults TallyResult) { + +// Tally iterates over the votes and updates the tally of a proposal based on the voting power of the +// voters +func (keeper Keeper) Tally(ctx sdk.Context, proposal Proposal) (passes bool, burnDeposits bool, tallyResults TallyResult) { results := make(map[VoteOption]sdk.Dec) results[OptionYes] = sdk.ZeroDec() results[OptionAbstain] = sdk.ZeroDec() diff --git a/x/gov/tally_test.go b/x/gov/internal/keeper/tally_test.go similarity index 99% rename from x/gov/tally_test.go rename to x/gov/internal/keeper/tally_test.go index 8cc70301ee4b..9610f010a5fc 100644 --- a/x/gov/tally_test.go +++ b/x/gov/internal/keeper/tally_test.go @@ -1,4 +1,4 @@ -package gov +package keeper import ( "testing" diff --git a/x/gov/vote.go b/x/gov/internal/keeper/vote.go similarity index 97% rename from x/gov/vote.go rename to x/gov/internal/keeper/vote.go index 7ebb352cc705..3df3fa32cc93 100644 --- a/x/gov/vote.go +++ b/x/gov/internal/keeper/vote.go @@ -1,10 +1,10 @@ -package gov +package keeper import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/cosmos/cosmos-sdk/x/gov/internal/types" ) // AddVote Adds a vote on a specific proposal diff --git a/x/gov/types/codec.go b/x/gov/internal/types/codec.go similarity index 100% rename from x/gov/types/codec.go rename to x/gov/internal/types/codec.go diff --git a/x/gov/types/content.go b/x/gov/internal/types/content.go similarity index 100% rename from x/gov/types/content.go rename to x/gov/internal/types/content.go diff --git a/x/gov/types/deposit.go b/x/gov/internal/types/deposit.go similarity index 100% rename from x/gov/types/deposit.go rename to x/gov/internal/types/deposit.go diff --git a/x/gov/types/errors.go b/x/gov/internal/types/errors.go similarity index 98% rename from x/gov/types/errors.go rename to x/gov/internal/types/errors.go index 65b97d908e48..784fde7cd360 100644 --- a/x/gov/types/errors.go +++ b/x/gov/internal/types/errors.go @@ -8,7 +8,7 @@ import ( ) const ( - DefaultCodespace sdk.CodespaceType = "gov" + DefaultCodespace sdk.CodespaceType = ModuleName CodeUnknownProposal sdk.CodeType = 1 CodeInactiveProposal sdk.CodeType = 2 diff --git a/x/gov/types/events.go b/x/gov/internal/types/events.go similarity index 100% rename from x/gov/types/events.go rename to x/gov/internal/types/events.go diff --git a/x/gov/expected_keepers.go b/x/gov/internal/types/expected_keepers.go similarity index 99% rename from x/gov/expected_keepers.go rename to x/gov/internal/types/expected_keepers.go index f53a49527269..bda5ed4fdc4c 100644 --- a/x/gov/expected_keepers.go +++ b/x/gov/internal/types/expected_keepers.go @@ -1,4 +1,4 @@ -package gov +package types import ( sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/gov/internal/types/genesis.go b/x/gov/internal/types/genesis.go new file mode 100644 index 000000000000..6d8bb1c90237 --- /dev/null +++ b/x/gov/internal/types/genesis.go @@ -0,0 +1,90 @@ +package types + +import ( + "bytes" + "fmt" + "time" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +const ( + // Default period for deposits & voting + DefaultPeriod time.Duration = 86400 * 2 * time.Second // 2 days +) + +// GenesisState - all staking state that must be provided at genesis +type GenesisState struct { + StartingProposalID uint64 `json:"starting_proposal_id"` + Deposits Deposits `json:"deposits"` + Votes Votes `json:"votes"` + Proposals []Proposal `json:"proposals"` + DepositParams DepositParams `json:"deposit_params"` + VotingParams VotingParams `json:"voting_params"` + TallyParams TallyParams `json:"tally_params"` +} + +// NewGenesisState creates a new genesis state for the governance module +func NewGenesisState(startingProposalID uint64, dp DepositParams, vp VotingParams, tp TallyParams) GenesisState { + return GenesisState{ + StartingProposalID: startingProposalID, + DepositParams: dp, + VotingParams: vp, + TallyParams: tp, + } +} + +// get raw genesis raw message for testing +func DefaultGenesisState() GenesisState { + minDepositTokens := sdk.TokensFromConsensusPower(10) + return GenesisState{ + StartingProposalID: 1, + DepositParams: DepositParams{ + MinDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, minDepositTokens)), + MaxDepositPeriod: DefaultPeriod, + }, + VotingParams: VotingParams{ + VotingPeriod: DefaultPeriod, + }, + TallyParams: TallyParams{ + Quorum: sdk.NewDecWithPrec(334, 3), + Threshold: sdk.NewDecWithPrec(5, 1), + Veto: sdk.NewDecWithPrec(334, 3), + }, + } +} + +// Checks whether 2 GenesisState structs are equivalent. +func (data GenesisState) Equal(data2 GenesisState) bool { + b1 := types.ModuleCdc.MustMarshalBinaryBare(data) + b2 := types.ModuleCdc.MustMarshalBinaryBare(data2) + return bytes.Equal(b1, b2) +} + +// Returns if a GenesisState is empty or has data in it +func (data GenesisState) IsEmpty() bool { + emptyGenState := GenesisState{} + return data.Equal(emptyGenState) +} + +// ValidateGenesis checks if parameters are within valid ranges +func ValidateGenesis(data GenesisState) error { + threshold := data.TallyParams.Threshold + if threshold.IsNegative() || threshold.GT(sdk.OneDec()) { + return fmt.Errorf("Governance vote threshold should be positive and less or equal to one, is %s", + threshold.String()) + } + + veto := data.TallyParams.Veto + if veto.IsNegative() || veto.GT(sdk.OneDec()) { + return fmt.Errorf("Governance vote veto threshold should be positive and less or equal to one, is %s", + veto.String()) + } + + if !data.DepositParams.MinDeposit.IsValid() { + return fmt.Errorf("Governance deposit amount must be a valid sdk.Coins amount, is %s", + data.DepositParams.MinDeposit.String()) + } + + return nil +} \ No newline at end of file diff --git a/x/gov/internal/types/genesis_test.go b/x/gov/internal/types/genesis_test.go new file mode 100644 index 000000000000..d1dca5011985 --- /dev/null +++ b/x/gov/internal/types/genesis_test.go @@ -0,0 +1,66 @@ +package types + +import ( + "testing" + + "github.com/stretchr/testify/require" + + abci "github.com/tendermint/tendermint/abci/types" +) + +func TestEqualProposalID(t *testing.T) { + state1 := GenesisState{} + state2 := GenesisState{} + require.Equal(t, state1, state2) + + // Proposals + state1.StartingProposalID = 1 + require.NotEqual(t, state1, state2) + require.False(t, state1.Equal(state2)) + + state2.StartingProposalID = 1 + require.Equal(t, state1, state2) + require.True(t, state1.Equal(state2)) +} + +func TestEqualProposals(t *testing.T) { + // Generate mock app and keepers + input := getMockApp(t, 2, GenesisState{}, nil) + SortAddresses(input.addrs) + + header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} + input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) + + ctx := input.mApp.BaseApp.NewContext(false, abci.Header{}) + + // Submit two proposals + proposal := testProposal() + proposal1, err := input.keeper.SubmitProposal(ctx, proposal) + require.NoError(t, err) + proposal2, err := input.keeper.SubmitProposal(ctx, proposal) + require.NoError(t, err) + + // They are similar but their IDs should be different + require.NotEqual(t, proposal1, proposal2) + require.False(t, ProposalEqual(proposal1, proposal2)) + + // Now create two genesis blocks + state1 := GenesisState{Proposals: []Proposal{proposal1}} + state2 := GenesisState{Proposals: []Proposal{proposal2}} + require.NotEqual(t, state1, state2) + require.False(t, state1.Equal(state2)) + + // Now make proposals identical by setting both IDs to 55 + proposal1.ProposalID = 55 + proposal2.ProposalID = 55 + require.Equal(t, proposal1, proposal1) + require.True(t, ProposalEqual(proposal1, proposal2)) + + // Reassign proposals into state + state1.Proposals[0] = proposal1 + state2.Proposals[0] = proposal2 + + // State should be identical now.. + require.Equal(t, state1, state2) + require.True(t, state1.Equal(state2)) +} \ No newline at end of file diff --git a/x/gov/types/keys.go b/x/gov/internal/types/keys.go similarity index 100% rename from x/gov/types/keys.go rename to x/gov/internal/types/keys.go diff --git a/x/gov/types/keys_test.go b/x/gov/internal/types/keys_test.go similarity index 100% rename from x/gov/types/keys_test.go rename to x/gov/internal/types/keys_test.go diff --git a/x/gov/types/msgs.go b/x/gov/internal/types/msgs.go similarity index 100% rename from x/gov/types/msgs.go rename to x/gov/internal/types/msgs.go diff --git a/x/gov/types/msgs_test.go b/x/gov/internal/types/msgs_test.go similarity index 100% rename from x/gov/types/msgs_test.go rename to x/gov/internal/types/msgs_test.go diff --git a/x/gov/types/params.go b/x/gov/internal/types/params.go similarity index 100% rename from x/gov/types/params.go rename to x/gov/internal/types/params.go diff --git a/x/gov/types/proposal.go b/x/gov/internal/types/proposal.go similarity index 86% rename from x/gov/types/proposal.go rename to x/gov/internal/types/proposal.go index ef18eaf15cc7..d72cb24ddc5e 100644 --- a/x/gov/types/proposal.go +++ b/x/gov/internal/types/proposal.go @@ -195,57 +195,6 @@ func (status ProposalStatus) Format(s fmt.State, verb rune) { } } -// Tally Results -type TallyResult struct { - Yes sdk.Int `json:"yes"` - Abstain sdk.Int `json:"abstain"` - No sdk.Int `json:"no"` - NoWithVeto sdk.Int `json:"no_with_veto"` -} - -func NewTallyResult(yes, abstain, no, noWithVeto sdk.Int) TallyResult { - return TallyResult{ - Yes: yes, - Abstain: abstain, - No: no, - NoWithVeto: noWithVeto, - } -} - -func NewTallyResultFromMap(results map[VoteOption]sdk.Dec) TallyResult { - return TallyResult{ - Yes: results[OptionYes].TruncateInt(), - Abstain: results[OptionAbstain].TruncateInt(), - No: results[OptionNo].TruncateInt(), - NoWithVeto: results[OptionNoWithVeto].TruncateInt(), - } -} - -// EmptyTallyResult returns an empty TallyResult. -func EmptyTallyResult() TallyResult { - return TallyResult{ - Yes: sdk.ZeroInt(), - Abstain: sdk.ZeroInt(), - No: sdk.ZeroInt(), - NoWithVeto: sdk.ZeroInt(), - } -} - -// Equals returns if two proposals are equal. -func (tr TallyResult) Equals(comp TallyResult) bool { - return tr.Yes.Equal(comp.Yes) && - tr.Abstain.Equal(comp.Abstain) && - tr.No.Equal(comp.No) && - tr.NoWithVeto.Equal(comp.NoWithVeto) -} - -func (tr TallyResult) String() string { - return fmt.Sprintf(`Tally Result: - Yes: %s - Abstain: %s - No: %s - NoWithVeto: %s`, tr.Yes, tr.Abstain, tr.No, tr.NoWithVeto) -} // Proposal types const ( diff --git a/x/gov/types/proposals_test.go b/x/gov/internal/types/proposals_test.go similarity index 100% rename from x/gov/types/proposals_test.go rename to x/gov/internal/types/proposals_test.go diff --git a/x/gov/types/querier.go b/x/gov/internal/types/querier.go similarity index 100% rename from x/gov/types/querier.go rename to x/gov/internal/types/querier.go diff --git a/x/gov/internal/types/tally.go b/x/gov/internal/types/tally.go new file mode 100644 index 000000000000..168f464376cc --- /dev/null +++ b/x/gov/internal/types/tally.go @@ -0,0 +1,76 @@ + + +// ValidatorGovInfo used for tallying +type ValidatorGovInfo struct { + Address sdk.ValAddress // address of the validator operator + BondedTokens sdk.Int // Power of a Validator + DelegatorShares sdk.Dec // Total outstanding delegator shares + DelegatorDeductions sdk.Dec // Delegator deductions from validator's delegators voting independently + Vote VoteOption // Vote of the validator +} + +func NewValidatorGovInfo(address sdk.ValAddress, bondedTokens sdk.Int, delegatorShares, + delegatorDeductions sdk.Dec, vote VoteOption) ValidatorGovInfo { + + return ValidatorGovInfo{ + Address: address, + BondedTokens: bondedTokens, + DelegatorShares: delegatorShares, + DelegatorDeductions: delegatorDeductions, + Vote: vote, + } +} + +// TallyResult represents the current or final tally of a Proposal +type TallyResult struct { + Yes sdk.Int `json:"yes"` + Abstain sdk.Int `json:"abstain"` + No sdk.Int `json:"no"` + NoWithVeto sdk.Int `json:"no_with_veto"` +} + +// NewTallyResult creates a new TallyResult instance +func NewTallyResult(yes, abstain, no, noWithVeto sdk.Int) TallyResult { + return TallyResult{ + Yes: yes, + Abstain: abstain, + No: no, + NoWithVeto: noWithVeto, + } +} + +// NewTallyResultFromMap creates a new TallyResult from map +func NewTallyResultFromMap(results map[VoteOption]sdk.Dec) TallyResult { + return TallyResult{ + Yes: results[OptionYes].TruncateInt(), + Abstain: results[OptionAbstain].TruncateInt(), + No: results[OptionNo].TruncateInt(), + NoWithVeto: results[OptionNoWithVeto].TruncateInt(), + } +} + +// EmptyTallyResult returns an empty TallyResult. +func EmptyTallyResult() TallyResult { + return TallyResult{ + Yes: sdk.ZeroInt(), + Abstain: sdk.ZeroInt(), + No: sdk.ZeroInt(), + NoWithVeto: sdk.ZeroInt(), + } +} + +// Equals returns if two proposals are equal. +func (tr TallyResult) Equals(comp TallyResult) bool { + return tr.Yes.Equal(comp.Yes) && + tr.Abstain.Equal(comp.Abstain) && + tr.No.Equal(comp.No) && + tr.NoWithVeto.Equal(comp.NoWithVeto) +} + +func (tr TallyResult) String() string { + return fmt.Sprintf(`Tally Result: + Yes: %s + Abstain: %s + No: %s + NoWithVeto: %s`, tr.Yes, tr.Abstain, tr.No, tr.NoWithVeto) +} \ No newline at end of file diff --git a/x/gov/types/vote.go b/x/gov/internal/types/vote.go similarity index 100% rename from x/gov/types/vote.go rename to x/gov/internal/types/vote.go diff --git a/x/gov/simulation/msgs.go b/x/gov/simulation.go similarity index 81% rename from x/gov/simulation/msgs.go rename to x/gov/simulation.go index 8b65fa3d611a..a99c91a84b4a 100644 --- a/x/gov/simulation/msgs.go +++ b/x/gov/simulation.go @@ -8,21 +8,20 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov" "github.com/cosmos/cosmos-sdk/x/simulation" ) // ContentSimulator defines a function type alias for generating random proposal // content. -type ContentSimulator func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) gov.Content +type ContentSimulator func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) Content // SimulateSubmittingVotingAndSlashingForProposal simulates creating a msg Submit Proposal // voting on the proposal, and subsequently slashing the proposal. It is implemented using // future operations. // TODO: Vote more intelligently, so we can actually do some checks regarding votes passing or failing // TODO: Actually check that validator slashings happened -func SimulateSubmittingVotingAndSlashingForProposal(k gov.Keeper, contentSim ContentSimulator) simulation.Operation { - handler := gov.NewHandler(k) +func SimulateSubmittingVotingAndSlashingForProposal(k Keeper, contentSim ContentSimulator) simulation.Operation { + handler := NewHandler(k) // The states are: // column 1: All validators vote @@ -97,7 +96,7 @@ func SimulateSubmittingVotingAndSlashingForProposal(k gov.Keeper, contentSim Con } } -func simulateHandleMsgSubmitProposal(msg gov.MsgSubmitProposal, handler sdk.Handler, ctx sdk.Context) (ok bool) { +func simulateHandleMsgSubmitProposal(msg MsgSubmitProposal, handler sdk.Handler, ctx sdk.Context) (ok bool) { ctx, write := ctx.CacheContext() ok = handler(ctx, msg).IsOK() if ok { @@ -107,15 +106,15 @@ func simulateHandleMsgSubmitProposal(msg gov.MsgSubmitProposal, handler sdk.Hand } // SimulateTextProposalContent returns random text proposal content. -func SimulateTextProposalContent(r *rand.Rand, _ *baseapp.BaseApp, _ sdk.Context, _ []simulation.Account) gov.Content { - return gov.NewTextProposal( +func SimulateTextProposalContent(r *rand.Rand, _ *baseapp.BaseApp, _ sdk.Context, _ []simulation.Account) Content { + return NewTextProposal( simulation.RandStringOfLength(r, 140), simulation.RandStringOfLength(r, 5000), ) } -func simulationCreateMsgSubmitProposal(r *rand.Rand, c gov.Content, s simulation.Account) (msg gov.MsgSubmitProposal, err error) { - msg = gov.NewMsgSubmitProposal(c, randomDeposit(r), s.Address) +func simulationCreateMsgSubmitProposal(r *rand.Rand, c Content, s simulation.Account) (msg MsgSubmitProposal, err error) { + msg = NewMsgSubmitProposal(c, randomDeposit(r), s.Address) if msg.ValidateBasic() != nil { err = fmt.Errorf("expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) } @@ -123,7 +122,7 @@ func simulationCreateMsgSubmitProposal(r *rand.Rand, c gov.Content, s simulation } // SimulateMsgDeposit -func SimulateMsgDeposit(k gov.Keeper) simulation.Operation { +func SimulateMsgDeposit(k Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) ( opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { @@ -133,12 +132,12 @@ func SimulateMsgDeposit(k gov.Keeper) simulation.Operation { return simulation.NoOpMsg(), nil, nil } deposit := randomDeposit(r) - msg := gov.NewMsgDeposit(acc.Address, proposalID, deposit) + msg := NewMsgDeposit(acc.Address, proposalID, deposit) if msg.ValidateBasic() != nil { return simulation.NoOpMsg(), nil, fmt.Errorf("expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) } ctx, write := ctx.CacheContext() - ok = gov.NewHandler(k)(ctx, msg).IsOK() + ok = NewHandler(k)(ctx, msg).IsOK() if ok { write() } @@ -150,12 +149,12 @@ func SimulateMsgDeposit(k gov.Keeper) simulation.Operation { // SimulateMsgVote // nolint: unparam -func SimulateMsgVote(k gov.Keeper) simulation.Operation { +func SimulateMsgVote(k Keeper) simulation.Operation { return operationSimulateMsgVote(k, simulation.Account{}, 0) } // nolint: unparam -func operationSimulateMsgVote(k gov.Keeper, acc simulation.Account, proposalID uint64) simulation.Operation { +func operationSimulateMsgVote(k Keeper, acc simulation.Account, proposalID uint64) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) ( opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { @@ -172,13 +171,13 @@ func operationSimulateMsgVote(k gov.Keeper, acc simulation.Account, proposalID u } option := randomVotingOption(r) - msg := gov.NewMsgVote(acc.Address, proposalID, option) + msg := NewMsgVote(acc.Address, proposalID, option) if msg.ValidateBasic() != nil { return simulation.NoOpMsg(), nil, fmt.Errorf("expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) } ctx, write := ctx.CacheContext() - ok := gov.NewHandler(k)(ctx, msg).IsOK() + ok := NewHandler(k)(ctx, msg).IsOK() if ok { write() } @@ -196,7 +195,7 @@ func randomDeposit(r *rand.Rand) sdk.Coins { } // Pick a random proposal ID -func randomProposalID(r *rand.Rand, k gov.Keeper, ctx sdk.Context) (proposalID uint64, ok bool) { +func randomProposalID(r *rand.Rand, k Keeper, ctx sdk.Context) (proposalID uint64, ok bool) { lastProposalID, _ := k.GetProposalID(ctx) lastProposalID = uint64(math.Max(float64(lastProposalID)-1, 0)) @@ -208,16 +207,16 @@ func randomProposalID(r *rand.Rand, k gov.Keeper, ctx sdk.Context) (proposalID u } // Pick a random voting option -func randomVotingOption(r *rand.Rand) gov.VoteOption { +func randomVotingOption(r *rand.Rand) VoteOption { switch r.Intn(4) { case 0: - return gov.OptionYes + return OptionYes case 1: - return gov.OptionAbstain + return OptionAbstain case 2: - return gov.OptionNo + return OptionNo case 3: - return gov.OptionNoWithVeto + return OptionNoWithVeto } panic("should not happen") } From 026ba68a8395b319893aa5cdff003d8e686ca5c0 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Tue, 2 Jul 2019 17:35:08 +0200 Subject: [PATCH 02/36] updates --- x/distribution/simulation/msgs.go | 3 +- x/gov/alias.go | 128 ++++++++++++++--------- x/gov/client/rest/query.go | 2 +- x/gov/client/rest/tx.go | 2 +- x/gov/internal/keeper/keeper.go | 12 +-- x/gov/internal/types/expected_keepers.go | 6 +- x/gov/internal/types/tally.go | 5 + x/gov/{ => simulation}/simulation.go | 17 +-- x/params/proposal_handler.go | 7 +- x/params/types/keys.go | 2 +- x/params/types/proposal.go | 10 +- 11 files changed, 112 insertions(+), 82 deletions(-) rename x/gov/{ => simulation}/simulation.go (93%) diff --git a/x/distribution/simulation/msgs.go b/x/distribution/simulation/msgs.go index bd787b30fd6e..8232229d3cd4 100644 --- a/x/distribution/simulation/msgs.go +++ b/x/distribution/simulation/msgs.go @@ -9,7 +9,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/distribution" "github.com/cosmos/cosmos-sdk/x/gov" - govsim "github.com/cosmos/cosmos-sdk/x/gov/simulation" "github.com/cosmos/cosmos-sdk/x/simulation" ) @@ -88,7 +87,7 @@ func SimulateMsgWithdrawValidatorCommission(m auth.AccountKeeper, k distribution } // SimulateCommunityPoolSpendProposalContent generates random community-pool-spend proposal content -func SimulateCommunityPoolSpendProposalContent(k distribution.Keeper) govsim.ContentSimulator { +func SimulateCommunityPoolSpendProposalContent(k distribution.Keeper) gov.ContentSimulator { return func(r *rand.Rand, _ *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) gov.Content { recipientAcc := simulation.RandomAcc(r, accs) coins := sdk.Coins{} diff --git a/x/gov/alias.go b/x/gov/alias.go index d4d99f2c44b5..dc8193eb0775 100644 --- a/x/gov/alias.go +++ b/x/gov/alias.go @@ -11,56 +11,77 @@ import ( ) const ( - MaxDescriptionLength = types.MaxDescriptionLength - MaxTitleLength = types.MaxTitleLength - DefaultCodespace = types.DefaultCodespace - CodeUnknownProposal = types.CodeUnknownProposal - CodeInactiveProposal = types.CodeInactiveProposal - CodeAlreadyActiveProposal = types.CodeAlreadyActiveProposal - CodeAlreadyFinishedProposal = types.CodeAlreadyFinishedProposal - CodeAddressNotStaked = types.CodeAddressNotStaked - CodeInvalidContent = types.CodeInvalidContent - CodeInvalidProposalType = types.CodeInvalidProposalType - CodeInvalidVote = types.CodeInvalidVote - CodeInvalidGenesis = types.CodeInvalidGenesis - CodeInvalidProposalStatus = types.CodeInvalidProposalStatus - CodeProposalHandlerNotExists = types.CodeProposalHandlerNotExists - ModuleName = types.ModuleName - StoreKey = types.StoreKey - RouterKey = types.RouterKey - QuerierRoute = types.QuerierRoute - DefaultParamspace = types.DefaultParamspace - TypeMsgDeposit = types.TypeMsgDeposit - TypeMsgVote = types.TypeMsgVote - TypeMsgSubmitProposal = types.TypeMsgSubmitProposal - StatusNil = types.StatusNil - StatusDepositPeriod = types.StatusDepositPeriod - StatusVotingPeriod = types.StatusVotingPeriod - StatusPassed = types.StatusPassed - StatusRejected = types.StatusRejected - 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 - OptionNo = types.OptionNo - OptionNoWithVeto = types.OptionNoWithVeto + MaxDescriptionLength = types.MaxDescriptionLength + MaxTitleLength = types.MaxTitleLength + DefaultCodespace = types.DefaultCodespace + CodeUnknownProposal = types.CodeUnknownProposal + CodeInactiveProposal = types.CodeInactiveProposal + CodeAlreadyActiveProposal = types.CodeAlreadyActiveProposal + CodeAlreadyFinishedProposal = types.CodeAlreadyFinishedProposal + CodeAddressNotStaked = types.CodeAddressNotStaked + CodeInvalidContent = types.CodeInvalidContent + CodeInvalidProposalType = types.CodeInvalidProposalType + CodeInvalidVote = types.CodeInvalidVote + CodeInvalidGenesis = types.CodeInvalidGenesis + CodeInvalidProposalStatus = types.CodeInvalidProposalStatus + CodeProposalHandlerNotExists = types.CodeProposalHandlerNotExists + EventTypeSubmitProposal = types.EventTypeSubmitProposal + EventTypeProposalDeposit = types.EventTypeProposalDeposit + EventTypeProposalVote = types.EventTypeProposalVote + EventTypeInactiveProposal = types.EventTypeInactiveProposal + EventTypeActiveProposal = types.EventTypeActiveProposal + AttributeKeyProposalResult = types.AttributeKeyProposalResult + AttributeKeyAmount = types.AttributeKeyAmount + AttributeKeyOption = types.AttributeKeyOption + AttributeKeyProposalID = types.AttributeKeyProposalID + AttributeKeyVotingPeriodStart = types.AttributeKeyVotingPeriodStart + AttributeValueCategory = types.AttributeValueCategory + AttributeValueProposalDropped = types.AttributeValueProposalDropped + AttributeValueProposalPassed = types.AttributeValueProposalPassed + AttributeValueProposalRejected = types.AttributeValueProposalRejected + AttributeValueProposalFailed = types.AttributeValueProposalFailed + DefaultPeriod = types.DefaultPeriod + ModuleName = types.ModuleName + StoreKey = types.StoreKey + RouterKey = types.RouterKey + QuerierRoute = types.QuerierRoute + DefaultParamspace = types.DefaultParamspace + TypeMsgDeposit = types.TypeMsgDeposit + TypeMsgVote = types.TypeMsgVote + TypeMsgSubmitProposal = types.TypeMsgSubmitProposal + StatusNil = types.StatusNil + StatusDepositPeriod = types.StatusDepositPeriod + StatusVotingPeriod = types.StatusVotingPeriod + StatusPassed = types.StatusPassed + StatusRejected = types.StatusRejected + 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 + OptionNo = types.OptionNo + OptionNoWithVeto = types.OptionNoWithVeto ) var ( // functions aliases + RegisterInvariants = keeper.RegisterInvariants + AllInvariants = keeper.AllInvariants + ModuleAccountInvariant = keeper.ModuleAccountInvariant + NewKeeper = keeper.NewKeeper + NewQuerier = keeper.NewQuerier RegisterCodec = types.RegisterCodec RegisterProposalTypeCodec = types.RegisterProposalTypeCodec ValidateAbstract = types.ValidateAbstract @@ -75,6 +96,9 @@ var ( ErrInvalidVote = types.ErrInvalidVote ErrInvalidGenesis = types.ErrInvalidGenesis ErrNoProposalHandlerExists = types.ErrNoProposalHandlerExists + NewGenesisState = types.NewGenesisState + DefaultGenesisState = types.DefaultGenesisState + ValidateGenesis = types.ValidateGenesis ProposalKey = types.ProposalKey ActiveProposalByTimeKey = types.ActiveProposalByTimeKey ActiveProposalQueueKey = types.ActiveProposalQueueKey @@ -100,9 +124,6 @@ var ( NewProposal = types.NewProposal ProposalStatusFromString = types.ProposalStatusFromString ValidProposalStatus = types.ValidProposalStatus - NewTallyResult = types.NewTallyResult - NewTallyResultFromMap = types.NewTallyResultFromMap - EmptyTallyResult = types.EmptyTallyResult NewTextProposal = types.NewTextProposal NewSoftwareUpgradeProposal = types.NewSoftwareUpgradeProposal RegisterProposalType = types.RegisterProposalType @@ -113,6 +134,10 @@ var ( NewQueryDepositParams = types.NewQueryDepositParams NewQueryVoteParams = types.NewQueryVoteParams NewQueryProposalsParams = types.NewQueryProposalsParams + NewValidatorGovInfo = types.NewValidatorGovInfo + NewTallyResult = types.NewTallyResult + NewTallyResultFromMap = types.NewTallyResultFromMap + EmptyTallyResult = types.EmptyTallyResult NewVote = types.NewVote VoteOptionFromString = types.VoteOptionFromString ValidVoteOption = types.ValidVoteOption @@ -131,10 +156,12 @@ var ( ) type ( + Keeper = keeper.Keeper Content = types.Content Handler = types.Handler Deposit = types.Deposit Deposits = types.Deposits + GenesisState = types.GenesisState MsgSubmitProposal = types.MsgSubmitProposal MsgDeposit = types.MsgDeposit MsgVote = types.MsgVote @@ -146,13 +173,14 @@ type ( Proposals = types.Proposals ProposalQueue = types.ProposalQueue ProposalStatus = types.ProposalStatus - TallyResult = types.TallyResult TextProposal = types.TextProposal SoftwareUpgradeProposal = types.SoftwareUpgradeProposal QueryProposalParams = types.QueryProposalParams QueryDepositParams = types.QueryDepositParams QueryVoteParams = types.QueryVoteParams QueryProposalsParams = types.QueryProposalsParams + ValidatorGovInfo = types.ValidatorGovInfo + TallyResult = types.TallyResult Vote = types.Vote Votes = types.Votes VoteOption = types.VoteOption diff --git a/x/gov/client/rest/query.go b/x/gov/client/rest/query.go index 23f471f027ea..05f78914d113 100644 --- a/x/gov/client/rest/query.go +++ b/x/gov/client/rest/query.go @@ -16,7 +16,7 @@ import ( ) -func registerQueryRoutes() { +func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router) { r.HandleFunc(fmt.Sprintf("/gov/parameters/{%s}", RestParamsType), queryParamsHandlerFn(cliCtx)).Methods("GET") r.HandleFunc("/gov/proposals", queryProposalsWithParameterFn(cliCtx)).Methods("GET") r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}", RestProposalID), queryProposalHandlerFn(cliCtx)).Methods("GET") diff --git a/x/gov/client/rest/tx.go b/x/gov/client/rest/tx.go index 764cb7943fa4..55bd3bef45f0 100644 --- a/x/gov/client/rest/tx.go +++ b/x/gov/client/rest/tx.go @@ -15,7 +15,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/gov/types" ) -func registerTxRoutes(cliCtx, r, phs []ProposalRESTHandler) { +func registerTxRoutes(cliCtx context.CLIContext, r *mux.Router, phs []ProposalRESTHandler) { propSubRtr := r.PathPrefix("/gov/proposals").Subrouter() for _, ph := range phs { propSubRtr.HandleFunc(fmt.Sprintf("/%s", ph.SubRoute), ph.Handler).Methods("POST") diff --git a/x/gov/internal/keeper/keeper.go b/x/gov/internal/keeper/keeper.go index d196892cd8d1..ac56de7ca084 100644 --- a/x/gov/internal/keeper/keeper.go +++ b/x/gov/internal/keeper/keeper.go @@ -7,19 +7,16 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/gov/internal/types" - "github.com/cosmos/cosmos-sdk/x/params" + "github.com/cosmos/cosmos-sdk/x/params/subspace" "github.com/cosmos/cosmos-sdk/x/supply/exported" "github.com/tendermint/tendermint/libs/log" ) -// Governance Keeper +// Keeper defines the governance module Keeper type Keeper struct { - // The reference to the Param Keeper to get and set Global Params - paramsKeeper params.Keeper - // The reference to the Paramstore to get and set gov specific params - paramSpace params.Subspace + paramSpace subspace.Subspace // The SupplyKeeper to reduce the supply of the network supplyKeeper types.SupplyKeeper @@ -46,7 +43,7 @@ type Keeper struct { // - users voting on proposals, with weight proportional to stake in the system // - and tallying the result of the vote. func NewKeeper( - cdc *codec.Codec, key sdk.StoreKey, paramsKeeper params.Keeper, paramSpace params.Subspace, + cdc *codec.Codec, key sdk.StoreKey, paramSpace subspace.Subspace, supplyKeeper types.SupplyKeeper, sk types.StakingKeeper, codespace sdk.CodespaceType, rtr Router, ) Keeper { @@ -62,7 +59,6 @@ func NewKeeper( return Keeper{ storeKey: key, - paramsKeeper: paramsKeeper, paramSpace: paramSpace.WithKeyTable(ParamKeyTable()), supplyKeeper: supplyKeeper, sk: sk, diff --git a/x/gov/internal/types/expected_keepers.go b/x/gov/internal/types/expected_keepers.go index bda5ed4fdc4c..3b0691ab5723 100644 --- a/x/gov/internal/types/expected_keepers.go +++ b/x/gov/internal/types/expected_keepers.go @@ -6,7 +6,7 @@ import ( supplyexported "github.com/cosmos/cosmos-sdk/x/supply/exported" ) -// SupplyKeeper defines the supply Keeper for module accounts +// SupplyKeeper defines the supply Keeper for module accounts (noalias) type SupplyKeeper interface { GetModuleAddress(name string) sdk.AccAddress GetModuleAccount(ctx sdk.Context, name string) supplyexported.ModuleAccountI @@ -19,7 +19,7 @@ type SupplyKeeper interface { BurnCoins(ctx sdk.Context, name string, amt sdk.Coins) sdk.Error } -// StakingKeeper expected staking keeper (Validator and Delegator sets) +// StakingKeeper expected staking keeper (Validator and Delegator sets) (noalias) type StakingKeeper interface { // iterate through bonded validators by operator address, execute func for each validator IterateBondedValidatorsByPower(sdk.Context, @@ -29,4 +29,4 @@ type StakingKeeper interface { IterateDelegations(ctx sdk.Context, delegator sdk.AccAddress, fn func(index int64, delegation stakingexported.DelegationI) (stop bool)) -} +} \ No newline at end of file diff --git a/x/gov/internal/types/tally.go b/x/gov/internal/types/tally.go index 168f464376cc..2232d4693175 100644 --- a/x/gov/internal/types/tally.go +++ b/x/gov/internal/types/tally.go @@ -1,4 +1,8 @@ +package types +import ( + sdk "github.com/cosmos/cosmos-sdk/types" +) // ValidatorGovInfo used for tallying type ValidatorGovInfo struct { @@ -9,6 +13,7 @@ type ValidatorGovInfo struct { Vote VoteOption // Vote of the validator } +// NewValidatorGovInfo creates a ValidatorGovInfo instance func NewValidatorGovInfo(address sdk.ValAddress, bondedTokens sdk.Int, delegatorShares, delegatorDeductions sdk.Dec, vote VoteOption) ValidatorGovInfo { diff --git a/x/gov/simulation.go b/x/gov/simulation/simulation.go similarity index 93% rename from x/gov/simulation.go rename to x/gov/simulation/simulation.go index a99c91a84b4a..eee110cedfac 100644 --- a/x/gov/simulation.go +++ b/x/gov/simulation/simulation.go @@ -9,11 +9,12 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/simulation" + "github.com/cosmos/cosmos-sdk/x/gov" ) // ContentSimulator defines a function type alias for generating random proposal // content. -type ContentSimulator func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) Content +type ContentSimulator func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) gov.Content // SimulateSubmittingVotingAndSlashingForProposal simulates creating a msg Submit Proposal // voting on the proposal, and subsequently slashing the proposal. It is implemented using @@ -96,7 +97,7 @@ func SimulateSubmittingVotingAndSlashingForProposal(k Keeper, contentSim Content } } -func simulateHandleMsgSubmitProposal(msg MsgSubmitProposal, handler sdk.Handler, ctx sdk.Context) (ok bool) { +func simulateHandleMsgSubmitProposal(msg gov.MsgSubmitProposal, handler sdk.Handler, ctx sdk.Context) (ok bool) { ctx, write := ctx.CacheContext() ok = handler(ctx, msg).IsOK() if ok { @@ -113,7 +114,7 @@ func SimulateTextProposalContent(r *rand.Rand, _ *baseapp.BaseApp, _ sdk.Context ) } -func simulationCreateMsgSubmitProposal(r *rand.Rand, c Content, s simulation.Account) (msg MsgSubmitProposal, err error) { +func simulationCreateMsgSubmitProposal(r *rand.Rand, c Content, s simulation.Account) (msg gov.MsgSubmitProposal, err error) { msg = NewMsgSubmitProposal(c, randomDeposit(r), s.Address) if msg.ValidateBasic() != nil { err = fmt.Errorf("expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) @@ -207,16 +208,16 @@ func randomProposalID(r *rand.Rand, k Keeper, ctx sdk.Context) (proposalID uint6 } // Pick a random voting option -func randomVotingOption(r *rand.Rand) VoteOption { +func randomVotingOption(r *rand.Rand) gov.VoteOption { switch r.Intn(4) { case 0: - return OptionYes + return gov.OptionYes case 1: - return OptionAbstain + return gov.OptionAbstain case 2: - return OptionNo + return gov.OptionNo case 3: - return OptionNoWithVeto + return gov.OptionNoWithVeto } panic("should not happen") } diff --git a/x/params/proposal_handler.go b/x/params/proposal_handler.go index a40d8df838dd..31763cf81d48 100644 --- a/x/params/proposal_handler.go +++ b/x/params/proposal_handler.go @@ -4,11 +4,12 @@ import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/cosmos/cosmos-sdk/x/gov" ) -func NewParamChangeProposalHandler(k Keeper) govtypes.Handler { - return func(ctx sdk.Context, content govtypes.Content) sdk.Error { +// NewParamChangeProposalHandler creates a new governance Handler for a ParamChangeProposal +func NewParamChangeProposalHandler(k Keeper) gov.Handler { + return func(ctx sdk.Context, content gov.Content) sdk.Error { switch c := content.(type) { case ParameterChangeProposal: return handleParameterChangeProposal(ctx, k, c) diff --git a/x/params/types/keys.go b/x/params/types/keys.go index e6b1e301cf80..1355a7427b95 100644 --- a/x/params/types/keys.go +++ b/x/params/types/keys.go @@ -1,7 +1,7 @@ package types const ( - // ModuleKey defines the name of the module + // ModuleName defines the name of the module ModuleName = "params" // RouterKey defines the routing key for a ParameterChangeProposal diff --git a/x/params/types/proposal.go b/x/params/types/proposal.go index 9c4ff7eebc83..354b74da174b 100644 --- a/x/params/types/proposal.go +++ b/x/params/types/proposal.go @@ -5,7 +5,7 @@ import ( "strings" sdk "github.com/cosmos/cosmos-sdk/types" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/cosmos/cosmos-sdk/x/gov" ) const ( @@ -17,8 +17,8 @@ const ( var _ govtypes.Content = ParameterChangeProposal{} func init() { - govtypes.RegisterProposalType(ProposalTypeChange) - govtypes.RegisterProposalTypeCodec(ParameterChangeProposal{}, "cosmos-sdk/ParameterChangeProposal") + gov.RegisterProposalType(ProposalTypeChange) + gov.RegisterProposalTypeCodec(ParameterChangeProposal{}, "cosmos-sdk/ParameterChangeProposal") } // ParameterChangeProposal defines a proposal which contains multiple parameter @@ -39,7 +39,7 @@ func (pcp ParameterChangeProposal) GetTitle() string { return pcp.Title } // GetDescription returns the description of a parameter change proposal. func (pcp ParameterChangeProposal) GetDescription() string { return pcp.Description } -// GetDescription returns the routing key of a parameter change proposal. +// ProposalRoute returns the routing key of a parameter change proposal. func (pcp ParameterChangeProposal) ProposalRoute() string { return RouterKey } // ProposalType returns the type of a parameter change proposal. @@ -103,7 +103,7 @@ func (pc ParamChange) String() string { `, pc.Subspace, pc.Key, pc.Subkey, pc.Value) } -// ValidateChange performs basic validation checks over a set of ParamChange. It +// ValidateChanges performs basic validation checks over a set of ParamChange. It // returns an error if any ParamChange is invalid. func ValidateChanges(changes []ParamChange) sdk.Error { if len(changes) == 0 { From 4d1b71a144eabeaf1f4cd3ede78a37ce26f47755 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Tue, 2 Jul 2019 17:43:06 +0200 Subject: [PATCH 03/36] revert sim changes --- x/distribution/simulation/msgs.go | 3 +- x/gov/simulation/{simulation.go => msgs.go} | 32 ++++++++++----------- 2 files changed, 18 insertions(+), 17 deletions(-) rename x/gov/simulation/{simulation.go => msgs.go} (86%) diff --git a/x/distribution/simulation/msgs.go b/x/distribution/simulation/msgs.go index 8232229d3cd4..bd787b30fd6e 100644 --- a/x/distribution/simulation/msgs.go +++ b/x/distribution/simulation/msgs.go @@ -9,6 +9,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/distribution" "github.com/cosmos/cosmos-sdk/x/gov" + govsim "github.com/cosmos/cosmos-sdk/x/gov/simulation" "github.com/cosmos/cosmos-sdk/x/simulation" ) @@ -87,7 +88,7 @@ func SimulateMsgWithdrawValidatorCommission(m auth.AccountKeeper, k distribution } // SimulateCommunityPoolSpendProposalContent generates random community-pool-spend proposal content -func SimulateCommunityPoolSpendProposalContent(k distribution.Keeper) gov.ContentSimulator { +func SimulateCommunityPoolSpendProposalContent(k distribution.Keeper) govsim.ContentSimulator { return func(r *rand.Rand, _ *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) gov.Content { recipientAcc := simulation.RandomAcc(r, accs) coins := sdk.Coins{} diff --git a/x/gov/simulation/simulation.go b/x/gov/simulation/msgs.go similarity index 86% rename from x/gov/simulation/simulation.go rename to x/gov/simulation/msgs.go index eee110cedfac..2d6f74a28b3f 100644 --- a/x/gov/simulation/simulation.go +++ b/x/gov/simulation/msgs.go @@ -8,8 +8,8 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/simulation" "github.com/cosmos/cosmos-sdk/x/gov" + "github.com/cosmos/cosmos-sdk/x/simulation" ) // ContentSimulator defines a function type alias for generating random proposal @@ -21,8 +21,8 @@ type ContentSimulator func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, // future operations. // TODO: Vote more intelligently, so we can actually do some checks regarding votes passing or failing // TODO: Actually check that validator slashings happened -func SimulateSubmittingVotingAndSlashingForProposal(k Keeper, contentSim ContentSimulator) simulation.Operation { - handler := NewHandler(k) +func SimulateSubmittingVotingAndSlashingForProposal(k gov.Keeper, contentSim ContentSimulator) simulation.Operation { + handler := gov.NewHandler(k) // The states are: // column 1: All validators vote @@ -107,15 +107,15 @@ func simulateHandleMsgSubmitProposal(msg gov.MsgSubmitProposal, handler sdk.Hand } // SimulateTextProposalContent returns random text proposal content. -func SimulateTextProposalContent(r *rand.Rand, _ *baseapp.BaseApp, _ sdk.Context, _ []simulation.Account) Content { - return NewTextProposal( +func SimulateTextProposalContent(r *rand.Rand, _ *baseapp.BaseApp, _ sdk.Context, _ []simulation.Account) gov.Content { + return gov.NewTextProposal( simulation.RandStringOfLength(r, 140), simulation.RandStringOfLength(r, 5000), ) } -func simulationCreateMsgSubmitProposal(r *rand.Rand, c Content, s simulation.Account) (msg gov.MsgSubmitProposal, err error) { - msg = NewMsgSubmitProposal(c, randomDeposit(r), s.Address) +func simulationCreateMsgSubmitProposal(r *rand.Rand, c gov.Content, s simulation.Account) (msg gov.MsgSubmitProposal, err error) { + msg = gov.NewMsgSubmitProposal(c, randomDeposit(r), s.Address) if msg.ValidateBasic() != nil { err = fmt.Errorf("expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) } @@ -123,7 +123,7 @@ func simulationCreateMsgSubmitProposal(r *rand.Rand, c Content, s simulation.Acc } // SimulateMsgDeposit -func SimulateMsgDeposit(k Keeper) simulation.Operation { +func SimulateMsgDeposit(k gov.Keeper) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) ( opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { @@ -133,12 +133,12 @@ func SimulateMsgDeposit(k Keeper) simulation.Operation { return simulation.NoOpMsg(), nil, nil } deposit := randomDeposit(r) - msg := NewMsgDeposit(acc.Address, proposalID, deposit) + msg := gov.NewMsgDeposit(acc.Address, proposalID, deposit) if msg.ValidateBasic() != nil { return simulation.NoOpMsg(), nil, fmt.Errorf("expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) } ctx, write := ctx.CacheContext() - ok = NewHandler(k)(ctx, msg).IsOK() + ok = gov.NewHandler(k)(ctx, msg).IsOK() if ok { write() } @@ -150,12 +150,12 @@ func SimulateMsgDeposit(k Keeper) simulation.Operation { // SimulateMsgVote // nolint: unparam -func SimulateMsgVote(k Keeper) simulation.Operation { +func SimulateMsgVote(k gov.Keeper) simulation.Operation { return operationSimulateMsgVote(k, simulation.Account{}, 0) } // nolint: unparam -func operationSimulateMsgVote(k Keeper, acc simulation.Account, proposalID uint64) simulation.Operation { +func operationSimulateMsgVote(k gov.Keeper, acc simulation.Account, proposalID uint64) simulation.Operation { return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simulation.Account) ( opMsg simulation.OperationMsg, fOps []simulation.FutureOperation, err error) { @@ -172,13 +172,13 @@ func operationSimulateMsgVote(k Keeper, acc simulation.Account, proposalID uint6 } option := randomVotingOption(r) - msg := NewMsgVote(acc.Address, proposalID, option) + msg := gov.NewMsgVote(acc.Address, proposalID, option) if msg.ValidateBasic() != nil { return simulation.NoOpMsg(), nil, fmt.Errorf("expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) } ctx, write := ctx.CacheContext() - ok := NewHandler(k)(ctx, msg).IsOK() + ok := gov.NewHandler(k)(ctx, msg).IsOK() if ok { write() } @@ -196,7 +196,7 @@ func randomDeposit(r *rand.Rand) sdk.Coins { } // Pick a random proposal ID -func randomProposalID(r *rand.Rand, k Keeper, ctx sdk.Context) (proposalID uint64, ok bool) { +func randomProposalID(r *rand.Rand, k gov.Keeper, ctx sdk.Context) (proposalID uint64, ok bool) { lastProposalID, _ := k.GetProposalID(ctx) lastProposalID = uint64(math.Max(float64(lastProposalID)-1, 0)) @@ -220,4 +220,4 @@ func randomVotingOption(r *rand.Rand) gov.VoteOption { return gov.OptionNoWithVeto } panic("should not happen") -} +} \ No newline at end of file From fa6706c82ec6d8a50e88f7ae4785b1ef85dd55f4 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Wed, 3 Jul 2019 12:58:21 +0200 Subject: [PATCH 04/36] updates --- x/gov/abci.go | 2 +- x/gov/alias.go | 1 - x/gov/client/cli/query.go | 2 +- x/gov/client/cli/tx.go | 2 +- x/gov/client/rest/query.go | 2 +- x/gov/client/rest/rest.go | 2 +- x/gov/client/rest/tx.go | 2 +- x/gov/client/utils/query.go | 2 +- x/gov/client/utils/utils.go | 2 +- x/gov/genesis.go | 28 +++++++++++++++--- x/gov/genesis_test.go | 42 ++++++++++++++++++++++++++ x/gov/handler.go | 2 +- x/gov/internal/types/genesis.go | 27 ++--------------- x/gov/internal/types/genesis_test.go | 44 ---------------------------- x/gov/internal/types/tally.go | 1 + x/gov/module.go | 6 ++-- x/gov/test_common.go | 2 +- 17 files changed, 82 insertions(+), 87 deletions(-) diff --git a/x/gov/abci.go b/x/gov/abci.go index 730e4d3a4d29..4bd81f43b7ba 100644 --- a/x/gov/abci.go +++ b/x/gov/abci.go @@ -4,7 +4,7 @@ import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/cosmos/cosmos-sdk/x/gov/internal/types" ) // EndBlocker called every block, process inflation, update validator set. diff --git a/x/gov/alias.go b/x/gov/alias.go index dc8193eb0775..22af9de31245 100644 --- a/x/gov/alias.go +++ b/x/gov/alias.go @@ -98,7 +98,6 @@ var ( ErrNoProposalHandlerExists = types.ErrNoProposalHandlerExists NewGenesisState = types.NewGenesisState DefaultGenesisState = types.DefaultGenesisState - ValidateGenesis = types.ValidateGenesis ProposalKey = types.ProposalKey ActiveProposalByTimeKey = types.ActiveProposalByTimeKey ActiveProposalQueueKey = types.ActiveProposalQueueKey diff --git a/x/gov/client/cli/query.go b/x/gov/client/cli/query.go index 28b957e41bbc..0eaa0118c6a2 100644 --- a/x/gov/client/cli/query.go +++ b/x/gov/client/cli/query.go @@ -14,7 +14,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" gcutils "github.com/cosmos/cosmos-sdk/x/gov/client/utils" - "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/cosmos/cosmos-sdk/x/gov/internal/types" ) // GetQueryCmd returns the cli query commands for this module diff --git a/x/gov/client/cli/tx.go b/x/gov/client/cli/tx.go index 137003c51930..b8873123c8b0 100644 --- a/x/gov/client/cli/tx.go +++ b/x/gov/client/cli/tx.go @@ -15,7 +15,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/auth/client/utils" govutils "github.com/cosmos/cosmos-sdk/x/gov/client/utils" - "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/cosmos/cosmos-sdk/x/gov/internal/types" ) // Proposal flags diff --git a/x/gov/client/rest/query.go b/x/gov/client/rest/query.go index 05f78914d113..47c93a08dbd3 100644 --- a/x/gov/client/rest/query.go +++ b/x/gov/client/rest/query.go @@ -12,7 +12,7 @@ import ( "github.com/cosmos/cosmos-sdk/types/rest" "github.com/cosmos/cosmos-sdk/x/auth/client/utils" gcutils "github.com/cosmos/cosmos-sdk/x/gov/client/utils" - "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/cosmos/cosmos-sdk/x/gov/internal/types" ) diff --git a/x/gov/client/rest/rest.go b/x/gov/client/rest/rest.go index 58a054c1a7c5..ff27814f8ca6 100644 --- a/x/gov/client/rest/rest.go +++ b/x/gov/client/rest/rest.go @@ -12,7 +12,7 @@ import ( "github.com/cosmos/cosmos-sdk/types/rest" "github.com/cosmos/cosmos-sdk/x/auth/client/utils" gcutils "github.com/cosmos/cosmos-sdk/x/gov/client/utils" - "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/cosmos/cosmos-sdk/x/gov/internal/types" ) // REST Variable names diff --git a/x/gov/client/rest/tx.go b/x/gov/client/rest/tx.go index 55bd3bef45f0..78ded1c76cfb 100644 --- a/x/gov/client/rest/tx.go +++ b/x/gov/client/rest/tx.go @@ -12,7 +12,7 @@ import ( "github.com/cosmos/cosmos-sdk/types/rest" "github.com/cosmos/cosmos-sdk/x/auth/client/utils" gcutils "github.com/cosmos/cosmos-sdk/x/gov/client/utils" - "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/cosmos/cosmos-sdk/x/gov/internal/types" ) func registerTxRoutes(cliCtx context.CLIContext, r *mux.Router, phs []ProposalRESTHandler) { diff --git a/x/gov/client/utils/query.go b/x/gov/client/utils/query.go index f6d0fa83f0ae..7c742f6bbd24 100644 --- a/x/gov/client/utils/query.go +++ b/x/gov/client/utils/query.go @@ -6,7 +6,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/context" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/client/utils" - "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/cosmos/cosmos-sdk/x/gov/internal/types" ) const ( diff --git a/x/gov/client/utils/utils.go b/x/gov/client/utils/utils.go index e23aa3ca1e85..1d03f5d23ba0 100644 --- a/x/gov/client/utils/utils.go +++ b/x/gov/client/utils/utils.go @@ -1,6 +1,6 @@ package utils -import "github.com/cosmos/cosmos-sdk/x/gov/types" +import "github.com/cosmos/cosmos-sdk/x/gov/internal/types" // NormalizeVoteOption - normalize user specified vote option func NormalizeVoteOption(option string) string { diff --git a/x/gov/genesis.go b/x/gov/genesis.go index a633f45d5f46..ced7fd92ea22 100644 --- a/x/gov/genesis.go +++ b/x/gov/genesis.go @@ -1,16 +1,14 @@ package gov import ( - "bytes" "fmt" - "time" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/cosmos/cosmos-sdk/x/gov/internal/types" ) // InitGenesis - store genesis parameters -func InitGenesis(ctx sdk.Context, k Keeper, supplyKeeper SupplyKeeper, data GenesisState) { +func InitGenesis(ctx sdk.Context, k Keeper, supplyKeeper types.SupplyKeeper, data GenesisState) { k.setProposalID(ctx, data.StartingProposalID) k.setDepositParams(ctx, data.DepositParams) @@ -81,3 +79,25 @@ func ExportGenesis(ctx sdk.Context, k Keeper) GenesisState { TallyParams: tallyParams, } } + +// ValidateGenesis checks if parameters are within valid ranges +func ValidateGenesis(data GenesisState) error { + threshold := data.TallyParams.Threshold + if threshold.IsNegative() || threshold.GT(sdk.OneDec()) { + return fmt.Errorf("Governance vote threshold should be positive and less or equal to one, is %s", + threshold.String()) + } + + veto := data.TallyParams.Veto + if veto.IsNegative() || veto.GT(sdk.OneDec()) { + return fmt.Errorf("Governance vote veto threshold should be positive and less or equal to one, is %s", + veto.String()) + } + + if !data.DepositParams.MinDeposit.IsValid() { + return fmt.Errorf("Governance deposit amount must be a valid sdk.Coins amount, is %s", + data.DepositParams.MinDeposit.String()) + } + + return nil +} diff --git a/x/gov/genesis_test.go b/x/gov/genesis_test.go index 37ce0619155f..7cf18f513a73 100644 --- a/x/gov/genesis_test.go +++ b/x/gov/genesis_test.go @@ -72,3 +72,45 @@ func TestImportExportQueues(t *testing.T) { require.True(t, ok) require.True(t, proposal2.Status == StatusRejected) } + +func TestEqualProposals(t *testing.T) { + // Generate mock app and keepers + input := getMockApp(t, 2, GenesisState{}, nil) + SortAddresses(input.addrs) + + header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} + input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) + + ctx := input.mApp.BaseApp.NewContext(false, abci.Header{}) + + // Submit two proposals + proposal := testProposal() + proposal1, err := input.keeper.SubmitProposal(ctx, proposal) + require.NoError(t, err) + proposal2, err := input.keeper.SubmitProposal(ctx, proposal) + require.NoError(t, err) + + // They are similar but their IDs should be different + require.NotEqual(t, proposal1, proposal2) + require.False(t, ProposalEqual(proposal1, proposal2)) + + // Now create two genesis blocks + state1 := GenesisState{Proposals: []Proposal{proposal1}} + state2 := GenesisState{Proposals: []Proposal{proposal2}} + require.NotEqual(t, state1, state2) + require.False(t, state1.Equal(state2)) + + // Now make proposals identical by setting both IDs to 55 + proposal1.ProposalID = 55 + proposal2.ProposalID = 55 + require.Equal(t, proposal1, proposal1) + require.True(t, ProposalEqual(proposal1, proposal2)) + + // Reassign proposals into state + state1.Proposals[0] = proposal1 + state2.Proposals[0] = proposal2 + + // State should be identical now.. + require.Equal(t, state1, state2) + require.True(t, state1.Equal(state2)) +} diff --git a/x/gov/handler.go b/x/gov/handler.go index 11011baff611..a8ec89cda049 100644 --- a/x/gov/handler.go +++ b/x/gov/handler.go @@ -4,7 +4,7 @@ import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/cosmos/cosmos-sdk/x/gov/internal/types" ) // Handle all "gov" type messages. diff --git a/x/gov/internal/types/genesis.go b/x/gov/internal/types/genesis.go index 6d8bb1c90237..894de753d53b 100644 --- a/x/gov/internal/types/genesis.go +++ b/x/gov/internal/types/genesis.go @@ -2,7 +2,6 @@ package types import ( "bytes" - "fmt" "time" sdk "github.com/cosmos/cosmos-sdk/types" @@ -56,8 +55,8 @@ func DefaultGenesisState() GenesisState { // Checks whether 2 GenesisState structs are equivalent. func (data GenesisState) Equal(data2 GenesisState) bool { - b1 := types.ModuleCdc.MustMarshalBinaryBare(data) - b2 := types.ModuleCdc.MustMarshalBinaryBare(data2) + b1 := ModuleCdc.MustMarshalBinaryBare(data) + b2 := ModuleCdc.MustMarshalBinaryBare(data2) return bytes.Equal(b1, b2) } @@ -66,25 +65,3 @@ func (data GenesisState) IsEmpty() bool { emptyGenState := GenesisState{} return data.Equal(emptyGenState) } - -// ValidateGenesis checks if parameters are within valid ranges -func ValidateGenesis(data GenesisState) error { - threshold := data.TallyParams.Threshold - if threshold.IsNegative() || threshold.GT(sdk.OneDec()) { - return fmt.Errorf("Governance vote threshold should be positive and less or equal to one, is %s", - threshold.String()) - } - - veto := data.TallyParams.Veto - if veto.IsNegative() || veto.GT(sdk.OneDec()) { - return fmt.Errorf("Governance vote veto threshold should be positive and less or equal to one, is %s", - veto.String()) - } - - if !data.DepositParams.MinDeposit.IsValid() { - return fmt.Errorf("Governance deposit amount must be a valid sdk.Coins amount, is %s", - data.DepositParams.MinDeposit.String()) - } - - return nil -} \ No newline at end of file diff --git a/x/gov/internal/types/genesis_test.go b/x/gov/internal/types/genesis_test.go index d1dca5011985..480c3cb5df8b 100644 --- a/x/gov/internal/types/genesis_test.go +++ b/x/gov/internal/types/genesis_test.go @@ -4,8 +4,6 @@ import ( "testing" "github.com/stretchr/testify/require" - - abci "github.com/tendermint/tendermint/abci/types" ) func TestEqualProposalID(t *testing.T) { @@ -21,46 +19,4 @@ func TestEqualProposalID(t *testing.T) { state2.StartingProposalID = 1 require.Equal(t, state1, state2) require.True(t, state1.Equal(state2)) -} - -func TestEqualProposals(t *testing.T) { - // Generate mock app and keepers - input := getMockApp(t, 2, GenesisState{}, nil) - SortAddresses(input.addrs) - - header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} - input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) - - ctx := input.mApp.BaseApp.NewContext(false, abci.Header{}) - - // Submit two proposals - proposal := testProposal() - proposal1, err := input.keeper.SubmitProposal(ctx, proposal) - require.NoError(t, err) - proposal2, err := input.keeper.SubmitProposal(ctx, proposal) - require.NoError(t, err) - - // They are similar but their IDs should be different - require.NotEqual(t, proposal1, proposal2) - require.False(t, ProposalEqual(proposal1, proposal2)) - - // Now create two genesis blocks - state1 := GenesisState{Proposals: []Proposal{proposal1}} - state2 := GenesisState{Proposals: []Proposal{proposal2}} - require.NotEqual(t, state1, state2) - require.False(t, state1.Equal(state2)) - - // Now make proposals identical by setting both IDs to 55 - proposal1.ProposalID = 55 - proposal2.ProposalID = 55 - require.Equal(t, proposal1, proposal1) - require.True(t, ProposalEqual(proposal1, proposal2)) - - // Reassign proposals into state - state1.Proposals[0] = proposal1 - state2.Proposals[0] = proposal2 - - // State should be identical now.. - require.Equal(t, state1, state2) - require.True(t, state1.Equal(state2)) } \ No newline at end of file diff --git a/x/gov/internal/types/tally.go b/x/gov/internal/types/tally.go index 2232d4693175..bb0e817c9042 100644 --- a/x/gov/internal/types/tally.go +++ b/x/gov/internal/types/tally.go @@ -1,6 +1,7 @@ package types import ( + "fmt" sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/gov/module.go b/x/gov/module.go index bd50770dc2d9..682b3d5e03ad 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -15,7 +15,7 @@ import ( "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" + "github.com/cosmos/cosmos-sdk/x/gov/internal/types" ) var ( @@ -93,11 +93,11 @@ func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { type AppModule struct { AppModuleBasic keeper Keeper - supplyKeeper SupplyKeeper + supplyKeeper types.SupplyKeeper } // NewAppModule creates a new AppModule object -func NewAppModule(keeper Keeper, supplyKeeper SupplyKeeper) AppModule { +func NewAppModule(keeper Keeper, supplyKeeper types.SupplyKeeper) AppModule { return AppModule{ AppModuleBasic: AppModuleBasic{}, keeper: keeper, diff --git a/x/gov/test_common.go b/x/gov/test_common.go index d5ec1628bc2b..31cadaa006be 100644 --- a/x/gov/test_common.go +++ b/x/gov/test_common.go @@ -17,7 +17,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/bank" - "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/cosmos/cosmos-sdk/x/gov/internal/types" "github.com/cosmos/cosmos-sdk/x/mock" "github.com/cosmos/cosmos-sdk/x/staking" "github.com/cosmos/cosmos-sdk/x/supply" From 34d9daee6bb67d522327927f29636980dda7b7e5 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Wed, 3 Jul 2019 13:53:26 +0200 Subject: [PATCH 05/36] more updates/fixes --- x/distribution/handler.go | 2 +- x/gov/abci.go | 2 +- x/gov/alias.go | 8 +- x/gov/client/cli/query.go | 2 +- x/gov/client/cli/tx.go | 2 +- x/gov/client/rest/query.go | 3 +- x/gov/client/rest/rest.go | 5 - x/gov/client/rest/tx.go | 2 +- x/gov/client/utils/query.go | 2 +- x/gov/client/utils/utils.go | 2 +- x/gov/genesis.go | 2 +- x/gov/handler.go | 2 +- x/gov/{internal => }/keeper/deposit.go | 28 ++-- x/gov/{internal => }/keeper/invariants.go | 2 +- x/gov/{internal => }/keeper/keeper.go | 42 ++--- x/gov/{internal => }/keeper/keeper_test.go | 17 +- x/gov/{internal => }/keeper/proposal.go | 44 ++--- x/gov/{internal => }/keeper/querier.go | 50 +++--- x/gov/{internal => }/keeper/querier_test.go | 80 ++++----- x/gov/{internal => }/keeper/tally.go | 30 ++-- x/gov/{internal => }/keeper/tally_test.go | 153 +++++++++--------- x/gov/{ => keeper}/test_common.go | 36 ++--- x/gov/{internal => }/keeper/vote.go | 28 ++-- x/gov/module.go | 2 +- x/gov/{internal => }/types/codec.go | 0 x/gov/{internal => }/types/content.go | 0 x/gov/{internal => }/types/deposit.go | 0 x/gov/{internal => }/types/errors.go | 0 x/gov/{internal => }/types/events.go | 0 .../{internal => }/types/expected_keepers.go | 0 x/gov/{internal => }/types/genesis.go | 0 x/gov/{internal => }/types/genesis_test.go | 0 x/gov/{internal => }/types/keys.go | 0 x/gov/{internal => }/types/keys_test.go | 0 x/gov/{internal => }/types/msgs.go | 0 x/gov/{internal => }/types/msgs_test.go | 0 x/gov/{internal => }/types/params.go | 0 x/gov/{internal => }/types/proposal.go | 0 x/gov/{internal => }/types/proposals_test.go | 0 x/gov/{internal => }/types/querier.go | 0 x/gov/{ => types}/router.go | 2 +- x/gov/{internal => }/types/tally.go | 0 x/gov/{internal => }/types/vote.go | 0 x/params/client/cli/tx.go | 4 +- x/params/client/rest/rest.go | 4 +- x/params/proposal_handler.go | 6 +- x/params/simulation/msgs.go | 4 +- x/params/types/proposal.go | 6 +- 48 files changed, 284 insertions(+), 288 deletions(-) rename x/gov/{internal => }/keeper/deposit.go (78%) rename x/gov/{internal => }/keeper/invariants.go (95%) rename x/gov/{internal => }/keeper/keeper.go (86%) rename x/gov/{internal => }/keeper/keeper_test.go (96%) rename x/gov/{internal => }/keeper/proposal.go (75%) rename x/gov/{internal => }/keeper/querier.go (85%) rename x/gov/{internal => }/keeper/querier_test.go (78%) rename x/gov/{internal => }/keeper/tally.go (77%) rename x/gov/{internal => }/keeper/tally_test.go (76%) rename x/gov/{ => keeper}/test_common.go (85%) rename x/gov/{internal => }/keeper/vote.go (71%) rename x/gov/{internal => }/types/codec.go (100%) rename x/gov/{internal => }/types/content.go (100%) rename x/gov/{internal => }/types/deposit.go (100%) rename x/gov/{internal => }/types/errors.go (100%) rename x/gov/{internal => }/types/events.go (100%) rename x/gov/{internal => }/types/expected_keepers.go (100%) rename x/gov/{internal => }/types/genesis.go (100%) rename x/gov/{internal => }/types/genesis_test.go (100%) rename x/gov/{internal => }/types/keys.go (100%) rename x/gov/{internal => }/types/keys_test.go (100%) rename x/gov/{internal => }/types/msgs.go (100%) rename x/gov/{internal => }/types/msgs_test.go (100%) rename x/gov/{internal => }/types/params.go (100%) rename x/gov/{internal => }/types/proposal.go (100%) rename x/gov/{internal => }/types/proposals_test.go (100%) rename x/gov/{internal => }/types/querier.go (100%) rename x/gov/{ => types}/router.go (99%) rename x/gov/{internal => }/types/tally.go (100%) rename x/gov/{internal => }/types/vote.go (100%) diff --git a/x/distribution/handler.go b/x/distribution/handler.go index ca047cec3672..bad5c88f8410 100644 --- a/x/distribution/handler.go +++ b/x/distribution/handler.go @@ -6,7 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/distribution/keeper" "github.com/cosmos/cosmos-sdk/x/distribution/types" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/internal/types" ) func NewHandler(k keeper.Keeper) sdk.Handler { diff --git a/x/gov/abci.go b/x/gov/abci.go index 4bd81f43b7ba..730e4d3a4d29 100644 --- a/x/gov/abci.go +++ b/x/gov/abci.go @@ -4,7 +4,7 @@ import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov/internal/types" + "github.com/cosmos/cosmos-sdk/x/gov/types" ) // EndBlocker called every block, process inflation, update validator set. diff --git a/x/gov/alias.go b/x/gov/alias.go index 22af9de31245..6482b0750b71 100644 --- a/x/gov/alias.go +++ b/x/gov/alias.go @@ -1,13 +1,13 @@ // nolint // autogenerated code using github.com/rigelrozanski/multitool // aliases generated for the following subdirectories: -// ALIASGEN: github.com/cosmos/cosmos-sdk/x/gov/internal/keeper -// ALIASGEN: github.com/cosmos/cosmos-sdk/x/gov/internal/types +// ALIASGEN: github.com/cosmos/cosmos-sdk/x/gov/keeper +// ALIASGEN: github.com/cosmos/cosmos-sdk/x/gov/types package gov import ( - "github.com/cosmos/cosmos-sdk/x/gov/internal/keeper" - "github.com/cosmos/cosmos-sdk/x/gov/internal/types" + "github.com/cosmos/cosmos-sdk/x/gov/keeper" + "github.com/cosmos/cosmos-sdk/x/gov/types" ) const ( diff --git a/x/gov/client/cli/query.go b/x/gov/client/cli/query.go index 0eaa0118c6a2..28b957e41bbc 100644 --- a/x/gov/client/cli/query.go +++ b/x/gov/client/cli/query.go @@ -14,7 +14,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" gcutils "github.com/cosmos/cosmos-sdk/x/gov/client/utils" - "github.com/cosmos/cosmos-sdk/x/gov/internal/types" + "github.com/cosmos/cosmos-sdk/x/gov/types" ) // GetQueryCmd returns the cli query commands for this module diff --git a/x/gov/client/cli/tx.go b/x/gov/client/cli/tx.go index b8873123c8b0..137003c51930 100644 --- a/x/gov/client/cli/tx.go +++ b/x/gov/client/cli/tx.go @@ -15,7 +15,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/auth/client/utils" govutils "github.com/cosmos/cosmos-sdk/x/gov/client/utils" - "github.com/cosmos/cosmos-sdk/x/gov/internal/types" + "github.com/cosmos/cosmos-sdk/x/gov/types" ) // Proposal flags diff --git a/x/gov/client/rest/query.go b/x/gov/client/rest/query.go index 47c93a08dbd3..f02942d5b615 100644 --- a/x/gov/client/rest/query.go +++ b/x/gov/client/rest/query.go @@ -10,9 +10,8 @@ import ( "github.com/cosmos/cosmos-sdk/client/context" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/auth/client/utils" gcutils "github.com/cosmos/cosmos-sdk/x/gov/client/utils" - "github.com/cosmos/cosmos-sdk/x/gov/internal/types" + "github.com/cosmos/cosmos-sdk/x/gov/types" ) diff --git a/x/gov/client/rest/rest.go b/x/gov/client/rest/rest.go index ff27814f8ca6..108faac604e9 100644 --- a/x/gov/client/rest/rest.go +++ b/x/gov/client/rest/rest.go @@ -1,8 +1,6 @@ package rest import ( - "errors" - "fmt" "net/http" "github.com/gorilla/mux" @@ -10,9 +8,6 @@ import ( "github.com/cosmos/cosmos-sdk/client/context" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/auth/client/utils" - gcutils "github.com/cosmos/cosmos-sdk/x/gov/client/utils" - "github.com/cosmos/cosmos-sdk/x/gov/internal/types" ) // REST Variable names diff --git a/x/gov/client/rest/tx.go b/x/gov/client/rest/tx.go index 78ded1c76cfb..55bd3bef45f0 100644 --- a/x/gov/client/rest/tx.go +++ b/x/gov/client/rest/tx.go @@ -12,7 +12,7 @@ import ( "github.com/cosmos/cosmos-sdk/types/rest" "github.com/cosmos/cosmos-sdk/x/auth/client/utils" gcutils "github.com/cosmos/cosmos-sdk/x/gov/client/utils" - "github.com/cosmos/cosmos-sdk/x/gov/internal/types" + "github.com/cosmos/cosmos-sdk/x/gov/types" ) func registerTxRoutes(cliCtx context.CLIContext, r *mux.Router, phs []ProposalRESTHandler) { diff --git a/x/gov/client/utils/query.go b/x/gov/client/utils/query.go index 7c742f6bbd24..f6d0fa83f0ae 100644 --- a/x/gov/client/utils/query.go +++ b/x/gov/client/utils/query.go @@ -6,7 +6,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/context" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/client/utils" - "github.com/cosmos/cosmos-sdk/x/gov/internal/types" + "github.com/cosmos/cosmos-sdk/x/gov/types" ) const ( diff --git a/x/gov/client/utils/utils.go b/x/gov/client/utils/utils.go index 1d03f5d23ba0..e23aa3ca1e85 100644 --- a/x/gov/client/utils/utils.go +++ b/x/gov/client/utils/utils.go @@ -1,6 +1,6 @@ package utils -import "github.com/cosmos/cosmos-sdk/x/gov/internal/types" +import "github.com/cosmos/cosmos-sdk/x/gov/types" // NormalizeVoteOption - normalize user specified vote option func NormalizeVoteOption(option string) string { diff --git a/x/gov/genesis.go b/x/gov/genesis.go index ced7fd92ea22..e1d8571804ae 100644 --- a/x/gov/genesis.go +++ b/x/gov/genesis.go @@ -4,7 +4,7 @@ import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov/internal/types" + "github.com/cosmos/cosmos-sdk/x/gov/types" ) // InitGenesis - store genesis parameters diff --git a/x/gov/handler.go b/x/gov/handler.go index a8ec89cda049..11011baff611 100644 --- a/x/gov/handler.go +++ b/x/gov/handler.go @@ -4,7 +4,7 @@ import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov/internal/types" + "github.com/cosmos/cosmos-sdk/x/gov/types" ) // Handle all "gov" type messages. diff --git a/x/gov/internal/keeper/deposit.go b/x/gov/keeper/deposit.go similarity index 78% rename from x/gov/internal/keeper/deposit.go rename to x/gov/keeper/deposit.go index d327b4dd87d0..ea8244ae8202 100644 --- a/x/gov/internal/keeper/deposit.go +++ b/x/gov/keeper/deposit.go @@ -4,11 +4,11 @@ import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov/internal/types" + "github.com/cosmos/cosmos-sdk/x/gov/types" ) // GetDeposit gets the deposit of a specific depositor on a specific proposal -func (keeper Keeper) GetDeposit(ctx sdk.Context, proposalID uint64, depositorAddr sdk.AccAddress) (deposit Deposit, found bool) { +func (keeper Keeper) GetDeposit(ctx sdk.Context, proposalID uint64, depositorAddr sdk.AccAddress) (deposit types.Deposit, found bool) { store := ctx.KVStore(keeper.storeKey) bz := store.Get(types.DepositKey(proposalID, depositorAddr)) if bz == nil { @@ -19,7 +19,7 @@ func (keeper Keeper) GetDeposit(ctx sdk.Context, proposalID uint64, depositorAdd return deposit, true } -func (keeper Keeper) setDeposit(ctx sdk.Context, proposalID uint64, depositorAddr sdk.AccAddress, deposit Deposit) { +func (keeper Keeper) setDeposit(ctx sdk.Context, proposalID uint64, depositorAddr sdk.AccAddress, deposit types.Deposit) { store := ctx.KVStore(keeper.storeKey) bz := keeper.cdc.MustMarshalBinaryLengthPrefixed(deposit) store.Set(types.DepositKey(proposalID, depositorAddr), bz) @@ -31,12 +31,12 @@ func (keeper Keeper) AddDeposit(ctx sdk.Context, proposalID uint64, depositorAdd // Checks to see if proposal exists proposal, ok := keeper.GetProposal(ctx, proposalID) if !ok { - return ErrUnknownProposal(keeper.codespace, proposalID), false + return types.ErrUnknownProposal(keeper.codespace, proposalID), false } // Check if proposal is still depositable - if (proposal.Status != StatusDepositPeriod) && (proposal.Status != StatusVotingPeriod) { - return ErrAlreadyFinishedProposal(keeper.codespace, proposalID), false + if (proposal.Status != types.StatusDepositPeriod) && (proposal.Status != types.StatusVotingPeriod) { + return types.ErrAlreadyFinishedProposal(keeper.codespace, proposalID), false } // update the governance module's account coins pool @@ -51,7 +51,7 @@ func (keeper Keeper) AddDeposit(ctx sdk.Context, proposalID uint64, depositorAdd // Check if deposit has provided sufficient total funds to transition the proposal into the voting period activatedVotingPeriod := false - if proposal.Status == StatusDepositPeriod && proposal.TotalDeposit.IsAllGTE(keeper.GetDepositParams(ctx).MinDeposit) { + if proposal.Status == types.StatusDepositPeriod && proposal.TotalDeposit.IsAllGTE(keeper.GetDepositParams(ctx).MinDeposit) { keeper.activateVotingPeriod(ctx, proposal) activatedVotingPeriod = true } @@ -61,7 +61,7 @@ func (keeper Keeper) AddDeposit(ctx sdk.Context, proposalID uint64, depositorAdd if found { deposit.Amount = deposit.Amount.Add(depositAmount) } else { - deposit = NewDeposit(proposalID, depositorAddr, depositAmount) + deposit = types.NewDeposit(proposalID, depositorAddr, depositAmount) } ctx.EventManager().EmitEvent( @@ -77,8 +77,8 @@ func (keeper Keeper) AddDeposit(ctx sdk.Context, proposalID uint64, depositorAdd } // GetAllDeposits returns all the deposits from the store -func (keeper Keeper) GetAllDeposits(ctx sdk.Context) (deposits Deposits) { - keeper.IterateAllDeposits(ctx, func(deposit Deposit) bool { +func (keeper Keeper) GetAllDeposits(ctx sdk.Context) (deposits types.Deposits) { + keeper.IterateAllDeposits(ctx, func(deposit types.Deposit) bool { deposits = append(deposits, deposit) return false }) @@ -86,8 +86,8 @@ func (keeper Keeper) GetAllDeposits(ctx sdk.Context) (deposits Deposits) { } // GetDeposits returns all the deposits from a proposal -func (keeper Keeper) GetDeposits(ctx sdk.Context, proposalID uint64) (deposits Deposits) { - keeper.IterateDeposits(ctx, proposalID, func(deposit Deposit) bool { +func (keeper Keeper) GetDeposits(ctx sdk.Context, proposalID uint64) (deposits types.Deposits) { + keeper.IterateDeposits(ctx, proposalID, func(deposit types.Deposit) bool { deposits = append(deposits, deposit) return false }) @@ -110,7 +110,7 @@ func (keeper Keeper) RefundDeposits(ctx sdk.Context, proposalID uint64) { panic(err) } - store.Delete(DepositKey(proposalID, deposit.Depositor)) + store.Delete(types.DepositKey(proposalID, deposit.Depositor)) return false }) } @@ -125,7 +125,7 @@ func (keeper Keeper) DeleteDeposits(ctx sdk.Context, proposalID uint64) { panic(err) } - store.Delete(DepositKey(proposalID, deposit.Depositor)) + store.Delete(types.DepositKey(proposalID, deposit.Depositor)) return false }) } diff --git a/x/gov/internal/keeper/invariants.go b/x/gov/keeper/invariants.go similarity index 95% rename from x/gov/internal/keeper/invariants.go rename to x/gov/keeper/invariants.go index 1fa9cdbad656..73e5d38fe50a 100644 --- a/x/gov/internal/keeper/invariants.go +++ b/x/gov/keeper/invariants.go @@ -4,7 +4,7 @@ import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov/internal/types" + "github.com/cosmos/cosmos-sdk/x/gov/types" ) // RegisterInvariants registers all governance invariants diff --git a/x/gov/internal/keeper/keeper.go b/x/gov/keeper/keeper.go similarity index 86% rename from x/gov/internal/keeper/keeper.go rename to x/gov/keeper/keeper.go index ac56de7ca084..0a223e94089b 100644 --- a/x/gov/internal/keeper/keeper.go +++ b/x/gov/keeper/keeper.go @@ -6,7 +6,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov/internal/types" + "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/cosmos/cosmos-sdk/x/params/subspace" "github.com/cosmos/cosmos-sdk/x/supply/exported" @@ -34,7 +34,7 @@ type Keeper struct { codespace sdk.CodespaceType // Proposal router - router Router + router types.Router } // NewKeeper returns a governance keeper. It handles: @@ -44,7 +44,7 @@ type Keeper struct { // - and tallying the result of the vote. func NewKeeper( cdc *codec.Codec, key sdk.StoreKey, paramSpace subspace.Subspace, - supplyKeeper types.SupplyKeeper, sk types.StakingKeeper, codespace sdk.CodespaceType, rtr Router, + supplyKeeper types.SupplyKeeper, sk types.StakingKeeper, codespace sdk.CodespaceType, rtr types.Router, ) Keeper { // ensure governance module account is set @@ -59,7 +59,7 @@ func NewKeeper( return Keeper{ storeKey: key, - paramSpace: paramSpace.WithKeyTable(ParamKeyTable()), + paramSpace: paramSpace.WithKeyTable(types.ParamKeyTable()), supplyKeeper: supplyKeeper, sk: sk, cdc: cdc, @@ -81,36 +81,36 @@ func (keeper Keeper) GetGovernanceAccount(ctx sdk.Context) exported.ModuleAccoun // Params // Returns the current DepositParams from the global param store -func (keeper Keeper) GetDepositParams(ctx sdk.Context) DepositParams { - var depositParams DepositParams - keeper.paramSpace.Get(ctx, ParamStoreKeyDepositParams, &depositParams) +func (keeper Keeper) GetDepositParams(ctx sdk.Context) types.DepositParams { + var depositParams types.DepositParams + keeper.paramSpace.Get(ctx, types.ParamStoreKeyDepositParams, &depositParams) return depositParams } // Returns the current VotingParams from the global param store -func (keeper Keeper) GetVotingParams(ctx sdk.Context) VotingParams { - var votingParams VotingParams - keeper.paramSpace.Get(ctx, ParamStoreKeyVotingParams, &votingParams) +func (keeper Keeper) GetVotingParams(ctx sdk.Context) types.VotingParams { + var votingParams types.VotingParams + keeper.paramSpace.Get(ctx, types.ParamStoreKeyVotingParams, &votingParams) return votingParams } // Returns the current TallyParam from the global param store -func (keeper Keeper) GetTallyParams(ctx sdk.Context) TallyParams { - var tallyParams TallyParams - keeper.paramSpace.Get(ctx, ParamStoreKeyTallyParams, &tallyParams) +func (keeper Keeper) GetTallyParams(ctx sdk.Context) types.TallyParams { + var tallyParams types.TallyParams + keeper.paramSpace.Get(ctx, types.ParamStoreKeyTallyParams, &tallyParams) return tallyParams } -func (keeper Keeper) setDepositParams(ctx sdk.Context, depositParams DepositParams) { - keeper.paramSpace.Set(ctx, ParamStoreKeyDepositParams, &depositParams) +func (keeper Keeper) setDepositParams(ctx sdk.Context, depositParams types.DepositParams) { + keeper.paramSpace.Set(ctx, types.ParamStoreKeyDepositParams, &depositParams) } -func (keeper Keeper) setVotingParams(ctx sdk.Context, votingParams VotingParams) { - keeper.paramSpace.Set(ctx, ParamStoreKeyVotingParams, &votingParams) +func (keeper Keeper) setVotingParams(ctx sdk.Context, votingParams types.VotingParams) { + keeper.paramSpace.Set(ctx, types.ParamStoreKeyVotingParams, &votingParams) } -func (keeper Keeper) setTallyParams(ctx sdk.Context, tallyParams TallyParams) { - keeper.paramSpace.Set(ctx, ParamStoreKeyTallyParams, &tallyParams) +func (keeper Keeper) setTallyParams(ctx sdk.Context, tallyParams types.TallyParams) { + keeper.paramSpace.Set(ctx, types.ParamStoreKeyTallyParams, &tallyParams) } // ProposalQueues @@ -262,11 +262,11 @@ func (keeper Keeper) IterateVotes(ctx sdk.Context, proposalID uint64, cb func(vo // ActiveProposalQueueIterator returns an sdk.Iterator for all the proposals in the Active Queue that expire by endTime func (keeper Keeper) ActiveProposalQueueIterator(ctx sdk.Context, endTime time.Time) sdk.Iterator { store := ctx.KVStore(keeper.storeKey) - return store.Iterator(ActiveProposalQueuePrefix, sdk.PrefixEndBytes(types.ActiveProposalByTimeKey(endTime))) + return store.Iterator(types.ActiveProposalQueuePrefix, sdk.PrefixEndBytes(types.ActiveProposalByTimeKey(endTime))) } // InactiveProposalQueueIterator returns an sdk.Iterator for all the proposals in the Inactive Queue that expire by endTime func (keeper Keeper) InactiveProposalQueueIterator(ctx sdk.Context, endTime time.Time) sdk.Iterator { store := ctx.KVStore(keeper.storeKey) - return store.Iterator(InactiveProposalQueuePrefix, sdk.PrefixEndBytes(types.InactiveProposalByTimeKey(endTime))) + return store.Iterator(types.InactiveProposalQueuePrefix, sdk.PrefixEndBytes(types.InactiveProposalByTimeKey(endTime))) } diff --git a/x/gov/internal/keeper/keeper_test.go b/x/gov/keeper/keeper_test.go similarity index 96% rename from x/gov/internal/keeper/keeper_test.go rename to x/gov/keeper/keeper_test.go index 795aefb08b4f..0aa3a0014d05 100644 --- a/x/gov/internal/keeper/keeper_test.go +++ b/x/gov/keeper/keeper_test.go @@ -11,6 +11,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/gov/types" ) func TestGetSetProposal(t *testing.T) { @@ -201,28 +202,28 @@ func TestVotes(t *testing.T) { input.keeper.SetProposal(ctx, proposal) // Test first vote - input.keeper.AddVote(ctx, proposalID, input.addrs[0], OptionAbstain) + input.keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionAbstain) vote, found := input.keeper.GetVote(ctx, proposalID, input.addrs[0]) require.True(t, found) require.Equal(t, input.addrs[0], vote.Voter) require.Equal(t, proposalID, vote.ProposalID) - require.Equal(t, OptionAbstain, vote.Option) + require.Equal(t, types.OptionAbstain, vote.Option) // Test change of vote - input.keeper.AddVote(ctx, proposalID, input.addrs[0], OptionYes) + input.keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionYes) vote, found = input.keeper.GetVote(ctx, proposalID, input.addrs[0]) require.True(t, found) require.Equal(t, input.addrs[0], vote.Voter) require.Equal(t, proposalID, vote.ProposalID) - require.Equal(t, OptionYes, vote.Option) + require.Equal(t, types.OptionYes, vote.Option) // Test second vote - input.keeper.AddVote(ctx, proposalID, input.addrs[1], OptionNoWithVeto) + input.keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionNoWithVeto) vote, found = input.keeper.GetVote(ctx, proposalID, input.addrs[1]) require.True(t, found) require.Equal(t, input.addrs[1], vote.Voter) require.Equal(t, proposalID, vote.ProposalID) - require.Equal(t, OptionNoWithVeto, vote.Option) + require.Equal(t, types.OptionNoWithVeto, vote.Option) // Test vote iterator votesIterator := input.keeper.GetVotesIterator(ctx, proposalID) @@ -231,14 +232,14 @@ func TestVotes(t *testing.T) { require.True(t, votesIterator.Valid()) require.Equal(t, input.addrs[0], vote.Voter) require.Equal(t, proposalID, vote.ProposalID) - require.Equal(t, OptionYes, vote.Option) + require.Equal(t, types.OptionYes, vote.Option) votesIterator.Next() require.True(t, votesIterator.Valid()) input.keeper.cdc.MustUnmarshalBinaryLengthPrefixed(votesIterator.Value(), &vote) require.True(t, votesIterator.Valid()) require.Equal(t, input.addrs[1], vote.Voter) require.Equal(t, proposalID, vote.ProposalID) - require.Equal(t, OptionNoWithVeto, vote.Option) + require.Equal(t, types.OptionNoWithVeto, vote.Option) votesIterator.Next() require.False(t, votesIterator.Valid()) votesIterator.Close() diff --git a/x/gov/internal/keeper/proposal.go b/x/gov/keeper/proposal.go similarity index 75% rename from x/gov/internal/keeper/proposal.go rename to x/gov/keeper/proposal.go index e639b5af141f..10a12cb01af4 100644 --- a/x/gov/internal/keeper/proposal.go +++ b/x/gov/keeper/proposal.go @@ -4,13 +4,13 @@ import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov/internal/types" + "github.com/cosmos/cosmos-sdk/x/gov/types" ) // SubmitProposal create new proposal given a content -func (keeper Keeper) SubmitProposal(ctx sdk.Context, content Content) (Proposal, sdk.Error) { +func (keeper Keeper) SubmitProposal(ctx sdk.Context, content types.Content) (types.Proposal, sdk.Error) { if !keeper.router.HasRoute(content.ProposalRoute()) { - return Proposal{}, ErrNoProposalHandlerExists(keeper.codespace, content) + return types.Proposal{}, types.ErrNoProposalHandlerExists(keeper.codespace, content) } // Execute the proposal content in a cache-wrapped context to validate the @@ -19,18 +19,18 @@ func (keeper Keeper) SubmitProposal(ctx sdk.Context, content Content) (Proposal, cacheCtx, _ := ctx.CacheContext() handler := keeper.router.GetRoute(content.ProposalRoute()) if err := handler(cacheCtx, content); err != nil { - return Proposal{}, ErrInvalidProposalContent(keeper.codespace, err.Result().Log) + return types.Proposal{}, types.ErrInvalidProposalContent(keeper.codespace, err.Result().Log) } proposalID, err := keeper.GetProposalID(ctx) if err != nil { - return Proposal{}, err + return types.Proposal{}, err } submitTime := ctx.BlockHeader().Time depositPeriod := keeper.GetDepositParams(ctx).MaxDepositPeriod - proposal := NewProposal(content, proposalID, submitTime, submitTime.Add(depositPeriod)) + proposal := types.NewProposal(content, proposalID, submitTime, submitTime.Add(depositPeriod)) keeper.SetProposal(ctx, proposal) keeper.InsertInactiveProposalQueue(ctx, proposalID, proposal.DepositEndTime) @@ -46,10 +46,10 @@ func (keeper Keeper) SubmitProposal(ctx sdk.Context, content Content) (Proposal, return proposal, nil } -// GetProposal get Proposal from store by ProposalID -func (keeper Keeper) GetProposal(ctx sdk.Context, proposalID uint64) (proposal Proposal, ok bool) { +// GetProposal get types.Proposal from store by ProposalID +func (keeper Keeper) GetProposal(ctx sdk.Context, proposalID uint64) (proposal types.Proposal, ok bool) { store := ctx.KVStore(keeper.storeKey) - bz := store.Get(ProposalKey(proposalID)) + bz := store.Get(types.ProposalKey(proposalID)) if bz == nil { return } @@ -58,10 +58,10 @@ func (keeper Keeper) GetProposal(ctx sdk.Context, proposalID uint64) (proposal P } // SetProposal set a proposal to store -func (keeper Keeper) SetProposal(ctx sdk.Context, proposal Proposal) { +func (keeper Keeper) SetProposal(ctx sdk.Context, proposal types.Proposal) { store := ctx.KVStore(keeper.storeKey) bz := keeper.cdc.MustMarshalBinaryLengthPrefixed(proposal) - store.Set(ProposalKey(proposal.ProposalID), bz) + store.Set(types.ProposalKey(proposal.ProposalID), bz) } // DeleteProposal deletes a proposal from store @@ -73,11 +73,11 @@ func (keeper Keeper) DeleteProposal(ctx sdk.Context, proposalID uint64) { } keeper.RemoveFromInactiveProposalQueue(ctx, proposalID, proposal.DepositEndTime) keeper.RemoveFromActiveProposalQueue(ctx, proposalID, proposal.VotingEndTime) - store.Delete(ProposalKey(proposalID)) + store.Delete(types.ProposalKey(proposalID)) } // GetProposals returns all the proposals from store -func (keeper Keeper) GetProposals(ctx sdk.Context) (proposals Proposals) { +func (keeper Keeper) GetProposals(ctx sdk.Context) (proposals types.Proposals) { keeper.IterateProposals(ctx, func(proposal types.Proposal) bool { proposals = append(proposals, proposal) return false @@ -90,14 +90,14 @@ func (keeper Keeper) GetProposals(ctx sdk.Context) (proposals Proposals) { // depositorAddr will filter proposals by whether or not that address has deposited to them // status will filter proposals by status // numLatest will fetch a specified number of the most recent proposals, or 0 for all proposals -func (keeper Keeper) GetProposalsFiltered(ctx sdk.Context, voterAddr sdk.AccAddress, depositorAddr sdk.AccAddress, status ProposalStatus, numLatest uint64) []Proposal { +func (keeper Keeper) GetProposalsFiltered(ctx sdk.Context, voterAddr sdk.AccAddress, depositorAddr sdk.AccAddress, status types.ProposalStatus, numLatest uint64) []types.Proposal { maxProposalID, err := keeper.GetProposalID(ctx) if err != nil { - return []Proposal{} + return []types.Proposal{} } - matchingProposals := []Proposal{} + matchingProposals := []types.Proposal{} if numLatest == 0 { numLatest = maxProposalID @@ -123,7 +123,7 @@ func (keeper Keeper) GetProposalsFiltered(ctx sdk.Context, voterAddr sdk.AccAddr continue } - if ValidProposalStatus(status) && proposal.Status != status { + if types.ValidProposalStatus(status) && proposal.Status != status { continue } @@ -135,9 +135,9 @@ func (keeper Keeper) GetProposalsFiltered(ctx sdk.Context, voterAddr sdk.AccAddr // GetProposalID gets the highest proposal ID func (keeper Keeper) GetProposalID(ctx sdk.Context) (proposalID uint64, err sdk.Error) { store := ctx.KVStore(keeper.storeKey) - bz := store.Get(ProposalIDKey) + bz := store.Get(types.ProposalIDKey) if bz == nil { - return 0, ErrInvalidGenesis(keeper.codespace, "initial proposal ID hasn't been set") + return 0, types.ErrInvalidGenesis(keeper.codespace, "initial proposal ID hasn't been set") } keeper.cdc.MustUnmarshalBinaryLengthPrefixed(bz, &proposalID) return proposalID, nil @@ -147,14 +147,14 @@ func (keeper Keeper) GetProposalID(ctx sdk.Context) (proposalID uint64, err sdk. func (keeper Keeper) setProposalID(ctx sdk.Context, proposalID uint64) { store := ctx.KVStore(keeper.storeKey) bz := keeper.cdc.MustMarshalBinaryLengthPrefixed(proposalID) - store.Set(ProposalIDKey, bz) + store.Set(types.ProposalIDKey, bz) } -func (keeper Keeper) activateVotingPeriod(ctx sdk.Context, proposal Proposal) { +func (keeper Keeper) activateVotingPeriod(ctx sdk.Context, proposal types.Proposal) { proposal.VotingStartTime = ctx.BlockHeader().Time votingPeriod := keeper.GetVotingParams(ctx).VotingPeriod proposal.VotingEndTime = proposal.VotingStartTime.Add(votingPeriod) - proposal.Status = StatusVotingPeriod + proposal.Status = types.StatusVotingPeriod keeper.SetProposal(ctx, proposal) keeper.RemoveFromInactiveProposalQueue(ctx, proposal.ProposalID, proposal.DepositEndTime) diff --git a/x/gov/internal/keeper/querier.go b/x/gov/keeper/querier.go similarity index 85% rename from x/gov/internal/keeper/querier.go rename to x/gov/keeper/querier.go index 6713de8e891c..4ffcaa04a0a3 100644 --- a/x/gov/internal/keeper/querier.go +++ b/x/gov/keeper/querier.go @@ -7,7 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov/internal/types" + "github.com/cosmos/cosmos-sdk/x/gov/types" ) // NewQuerier creates a new gov Querier instance @@ -16,19 +16,19 @@ func NewQuerier(keeper Keeper) sdk.Querier { switch path[0] { case types.QueryParams: return queryParams(ctx, path[1:], req, keeper) - case QueryProposals: + case types.QueryProposals: return queryProposals(ctx, path[1:], req, keeper) - case QueryProposal: + case types.QueryProposal: return queryProposal(ctx, path[1:], req, keeper) - case QueryDeposits: + case types.QueryDeposits: return queryDeposits(ctx, path[1:], req, keeper) - case QueryDeposit: + case types.QueryDeposit: return queryDeposit(ctx, path[1:], req, keeper) - case QueryVotes: + case types.QueryVotes: return queryVotes(ctx, path[1:], req, keeper) - case QueryVote: + case types.QueryVote: return queryVote(ctx, path[1:], req, keeper) - case QueryTally: + case types.QueryTally: return queryTally(ctx, path[1:], req, keeper) default: return nil, sdk.ErrUnknownRequest("unknown gov query endpoint") @@ -38,19 +38,19 @@ func NewQuerier(keeper Keeper) sdk.Querier { func queryParams(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper) ([]byte, sdk.Error) { switch path[0] { - case ParamDeposit: + case types.ParamDeposit: bz, err := codec.MarshalJSONIndent(keeper.cdc, keeper.GetDepositParams(ctx)) if err != nil { return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could not marshal result to JSON", err.Error())) } return bz, nil - case ParamVoting: + case types.ParamVoting: bz, err := codec.MarshalJSONIndent(keeper.cdc, keeper.GetVotingParams(ctx)) if err != nil { return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could not marshal result to JSON", err.Error())) } return bz, nil - case ParamTallying: + case types.ParamTallying: bz, err := codec.MarshalJSONIndent(keeper.cdc, keeper.GetTallyParams(ctx)) if err != nil { return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could not marshal result to JSON", err.Error())) @@ -63,7 +63,7 @@ func queryParams(ctx sdk.Context, path []string, req abci.RequestQuery, keeper K // nolint: unparam func queryProposal(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper) ([]byte, sdk.Error) { - var params QueryProposalParams + var params types.QueryProposalParams err := keeper.cdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { return nil, sdk.ErrUnknownRequest(sdk.AppendMsgToErr("incorrectly formatted request data", err.Error())) @@ -71,7 +71,7 @@ func queryProposal(ctx sdk.Context, path []string, req abci.RequestQuery, keeper proposal, ok := keeper.GetProposal(ctx, params.ProposalID) if !ok { - return nil, ErrUnknownProposal(DefaultCodespace, params.ProposalID) + return nil, types.ErrUnknownProposal(types.DefaultCodespace, params.ProposalID) } bz, err := codec.MarshalJSONIndent(keeper.cdc, proposal) @@ -83,7 +83,7 @@ func queryProposal(ctx sdk.Context, path []string, req abci.RequestQuery, keeper // nolint: unparam func queryDeposit(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper) ([]byte, sdk.Error) { - var params QueryDepositParams + var params types.QueryDepositParams err := keeper.cdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { return nil, sdk.ErrUnknownRequest(sdk.AppendMsgToErr("incorrectly formatted request data", err.Error())) @@ -99,7 +99,7 @@ func queryDeposit(ctx sdk.Context, path []string, req abci.RequestQuery, keeper // nolint: unparam func queryVote(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper) ([]byte, sdk.Error) { - var params QueryVoteParams + var params types.QueryVoteParams err := keeper.cdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { return nil, sdk.ErrUnknownRequest(sdk.AppendMsgToErr("incorrectly formatted request data", err.Error())) @@ -115,7 +115,7 @@ func queryVote(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Kee // nolint: unparam func queryDeposits(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper) ([]byte, sdk.Error) { - var params QueryProposalParams + var params types.QueryProposalParams err := keeper.cdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { return nil, sdk.ErrUnknownRequest(sdk.AppendMsgToErr("incorrectly formatted request data", err.Error())) @@ -132,7 +132,7 @@ func queryDeposits(ctx sdk.Context, path []string, req abci.RequestQuery, keeper // nolint: unparam func queryTally(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper) ([]byte, sdk.Error) { - var params QueryProposalParams + var params types.QueryProposalParams err := keeper.cdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { return nil, sdk.ErrUnknownRequest(sdk.AppendMsgToErr("incorrectly formatted request data", err.Error())) @@ -142,18 +142,18 @@ func queryTally(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Ke proposal, ok := keeper.GetProposal(ctx, proposalID) if !ok { - return nil, ErrUnknownProposal(DefaultCodespace, proposalID) + return nil, types.ErrUnknownProposal(types.DefaultCodespace, proposalID) } - var tallyResult TallyResult + var tallyResult types.TallyResult - if proposal.Status == StatusDepositPeriod { - tallyResult = EmptyTallyResult() - } else if proposal.Status == StatusPassed || proposal.Status == StatusRejected { + if proposal.Status == types.StatusDepositPeriod { + tallyResult = types.EmptyTallyResult() + } else if proposal.Status == types.StatusPassed || proposal.Status == types.StatusRejected { tallyResult = proposal.FinalTallyResult } else { // proposal is in voting period - _, _, tallyResult = tally(ctx, keeper, proposal) + _, _, tallyResult = keeper.Tally(ctx, proposal) } bz, err := codec.MarshalJSONIndent(keeper.cdc, tallyResult) @@ -165,7 +165,7 @@ func queryTally(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Ke // nolint: unparam func queryVotes(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper) ([]byte, sdk.Error) { - var params QueryProposalParams + var params types.QueryProposalParams err := keeper.cdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { @@ -183,7 +183,7 @@ func queryVotes(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Ke // nolint: unparam func queryProposals(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper) ([]byte, sdk.Error) { - var params QueryProposalsParams + var params types.QueryProposalsParams err := keeper.cdc.UnmarshalJSON(req.Data, ¶ms) if err != nil { return nil, sdk.ErrUnknownRequest(sdk.AppendMsgToErr("incorrectly formatted request data", err.Error())) diff --git a/x/gov/internal/keeper/querier_test.go b/x/gov/keeper/querier_test.go similarity index 78% rename from x/gov/internal/keeper/querier_test.go rename to x/gov/keeper/querier_test.go index fb19d26c8c87..51a4187500c7 100644 --- a/x/gov/internal/keeper/querier_test.go +++ b/x/gov/keeper/querier_test.go @@ -9,77 +9,77 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov/internal/types" + "github.com/cosmos/cosmos-sdk/x/gov/types" ) const custom = "custom" -func getQueriedParams(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier) (DepositParams, VotingParams, TallyParams) { +func getQueriedParams(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier) (types.DepositParams, types.VotingParams, types.TallyParams) { query := abci.RequestQuery{ - Path: strings.Join([]string{custom, QuerierRoute, QueryParams, ParamDeposit}, "/"), + Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryParams, types.ParamDeposit}, "/"), Data: []byte{}, } - bz, err := querier(ctx, []string{QueryParams, ParamDeposit}, query) + bz, err := querier(ctx, []string{types.QueryParams, types.ParamDeposit}, query) require.Nil(t, err) require.NotNil(t, bz) - var depositParams DepositParams + var depositParams types.DepositParams err2 := cdc.UnmarshalJSON(bz, &depositParams) require.Nil(t, err2) query = abci.RequestQuery{ - Path: strings.Join([]string{custom, QuerierRoute, QueryParams, ParamVoting}, "/"), + Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryParams, types.ParamVoting}, "/"), Data: []byte{}, } - bz, err = querier(ctx, []string{QueryParams, ParamVoting}, query) + bz, err = querier(ctx, []string{types.QueryParams, types.ParamVoting}, query) require.Nil(t, err) require.NotNil(t, bz) - var votingParams VotingParams + var votingParams types.VotingParams err2 = cdc.UnmarshalJSON(bz, &votingParams) require.Nil(t, err2) query = abci.RequestQuery{ - Path: strings.Join([]string{custom, QuerierRoute, QueryParams, ParamTallying}, "/"), + Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryParams, types.ParamTallying}, "/"), Data: []byte{}, } - bz, err = querier(ctx, []string{QueryParams, ParamTallying}, query) + bz, err = querier(ctx, []string{types.QueryParams, types.ParamTallying}, query) require.Nil(t, err) require.NotNil(t, bz) - var tallyParams TallyParams + var tallyParams types.TallyParams err2 = cdc.UnmarshalJSON(bz, &tallyParams) require.Nil(t, err2) return depositParams, votingParams, tallyParams } -func getQueriedProposal(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier, proposalID uint64) Proposal { +func getQueriedProposal(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier, proposalID uint64) types.Proposal { query := abci.RequestQuery{ - Path: strings.Join([]string{custom, QuerierRoute, QueryProposal}, "/"), + Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryProposal}, "/"), Data: cdc.MustMarshalJSON(NewQueryProposalParams(proposalID)), } - bz, err := querier(ctx, []string{QueryProposal}, query) + bz, err := querier(ctx, []string{types.QueryProposal}, query) require.Nil(t, err) require.NotNil(t, bz) - var proposal Proposal + var proposal types.Proposal err2 := cdc.UnmarshalJSON(bz, proposal) require.Nil(t, err2) return proposal } -func getQueriedProposals(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier, depositor, voter sdk.AccAddress, status ProposalStatus, limit uint64) []Proposal { +func getQueriedProposals(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier, depositor, voter sdk.AccAddress, status types.ProposalStatus, limit uint64) []types.Proposal { query := abci.RequestQuery{ - Path: strings.Join([]string{custom, QuerierRoute, QueryProposals}, "/"), + Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryProposals}, "/"), Data: cdc.MustMarshalJSON(NewQueryProposalsParams(status, limit, voter, depositor)), } - bz, err := querier(ctx, []string{QueryProposals}, query) + bz, err := querier(ctx, []string{types.QueryProposals}, query) require.Nil(t, err) require.NotNil(t, bz) @@ -89,57 +89,57 @@ func getQueriedProposals(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querie return proposals } -func getQueriedDeposit(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier, proposalID uint64, depositor sdk.AccAddress) Deposit { +func getQueriedDeposit(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier, proposalID uint64, depositor sdk.AccAddress) types.Deposit { query := abci.RequestQuery{ - Path: strings.Join([]string{custom, QuerierRoute, QueryDeposit}, "/"), + Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryDeposit}, "/"), Data: cdc.MustMarshalJSON(NewQueryDepositParams(proposalID, depositor)), } - bz, err := querier(ctx, []string{QueryDeposit}, query) + bz, err := querier(ctx, []string{types.QueryDeposit}, query) require.Nil(t, err) require.NotNil(t, bz) - var deposit Deposit + var deposit types.Deposit err2 := cdc.UnmarshalJSON(bz, &deposit) require.Nil(t, err2) return deposit } -func getQueriedDeposits(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier, proposalID uint64) []Deposit { +func getQueriedDeposits(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier, proposalID uint64) []types.Deposit { query := abci.RequestQuery{ - Path: strings.Join([]string{custom, QuerierRoute, QueryDeposits}, "/"), + Path: strings.Join([]string{custom, types.QuerierRoute, types.types.QueryDeposits}, "/"), Data: cdc.MustMarshalJSON(NewQueryProposalParams(proposalID)), } - bz, err := querier(ctx, []string{QueryDeposits}, query) + bz, err := querier(ctx, []string{types.types.QueryDeposits}, query) require.Nil(t, err) require.NotNil(t, bz) - var deposits []Deposit + var deposits []types.Deposit err2 := cdc.UnmarshalJSON(bz, &deposits) require.Nil(t, err2) return deposits } -func getQueriedVote(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier, proposalID uint64, voter sdk.AccAddress) Vote { +func getQueriedVote(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier, proposalID uint64, voter sdk.AccAddress) types.Vote { query := abci.RequestQuery{ - Path: strings.Join([]string{custom, QuerierRoute, QueryVote}, "/"), + Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryVote}, "/"), Data: cdc.MustMarshalJSON(NewQueryVoteParams(proposalID, voter)), } - bz, err := querier(ctx, []string{QueryVote}, query) + bz, err := querier(ctx, []string{types.QueryVote}, query) require.Nil(t, err) require.NotNil(t, bz) - var vote Vote + var vote types.Vote err2 := cdc.UnmarshalJSON(bz, &vote) require.Nil(t, err2) return vote } -func getQueriedVotes(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier, proposalID uint64) []Vote { +func getQueriedVotes(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier, proposalID uint64) []types.Vote { query := abci.RequestQuery{ - Path: strings.Join([]string{custom, QuerierRoute, QueryVote}, "/"), + Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryVote}, "/"), Data: cdc.MustMarshalJSON(NewQueryProposalParams(proposalID)), } @@ -147,7 +147,7 @@ func getQueriedVotes(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sd require.Nil(t, err) require.NotNil(t, bz) - var votes []Vote + var votes []types.Vote err2 := cdc.UnmarshalJSON(bz, &votes) require.Nil(t, err2) return votes @@ -155,11 +155,11 @@ func getQueriedVotes(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sd func getQueriedTally(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier, proposalID uint64) TallyResult { query := abci.RequestQuery{ - Path: strings.Join([]string{custom, QuerierRoute, QueryTally}, "/"), + Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryTally}, "/"), Data: cdc.MustMarshalJSON(NewQueryProposalParams(proposalID)), } - bz, err := querier(ctx, []string{QueryTally}, query) + bz, err := querier(ctx, []string{types.QueryTally}, query) require.Nil(t, err) require.NotNil(t, bz) @@ -171,7 +171,7 @@ func getQueriedTally(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sd func TestQueryParams(t *testing.T) { cdc := codec.New() - input := getMockApp(t, 1000, GenesisState{}, nil) + input := getMockApp(t, 1000, types.GenesisState{}, nil) querier := NewQuerier(input.keeper) header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} @@ -184,7 +184,7 @@ func TestQueryParams(t *testing.T) { func TestQueries(t *testing.T) { cdc := codec.New() - input := getMockApp(t, 1000, GenesisState{}, nil) + input := getMockApp(t, 1000, types.GenesisState{}, nil) querier := NewQuerier(input.keeper) handler := NewHandler(input.keeper) @@ -238,7 +238,7 @@ func TestQueries(t *testing.T) { deposit = getQueriedDeposit(t, ctx, cdc, querier, proposalID3, input.addrs[1]) require.Equal(t, deposit, deposits[0]) - // Only proposal #1 should be in Deposit Period + // Only proposal #1 should be in types.Deposit Period proposals := getQueriedProposals(t, ctx, cdc, querier, nil, nil, StatusDepositPeriod, 0) require.Len(t, proposals, 1) require.Equal(t, proposalID1, proposals[0].ProposalID) @@ -261,7 +261,7 @@ func TestQueries(t *testing.T) { require.Equal(t, proposalID2, (proposals[0]).ProposalID) require.Equal(t, proposalID3, (proposals[1]).ProposalID) - // Test query votes on Proposal 2 + // Test query votes on types.Proposal 2 votes := getQueriedVotes(t, ctx, cdc, querier, proposalID2) require.Len(t, votes, 1) require.Equal(t, input.addrs[0], votes[0].Voter) @@ -269,7 +269,7 @@ func TestQueries(t *testing.T) { vote := getQueriedVote(t, ctx, cdc, querier, proposalID2, input.addrs[0]) require.Equal(t, vote, votes[0]) - // Test query votes on Proposal 3 + // Test query votes on types.Proposal 3 votes = getQueriedVotes(t, ctx, cdc, querier, proposalID3) require.Len(t, votes, 2) require.True(t, input.addrs[0].String() == votes[0].Voter.String()) diff --git a/x/gov/internal/keeper/tally.go b/x/gov/keeper/tally.go similarity index 77% rename from x/gov/internal/keeper/tally.go rename to x/gov/keeper/tally.go index b4ce5dd92eb5..9f081779e7e9 100644 --- a/x/gov/internal/keeper/tally.go +++ b/x/gov/keeper/tally.go @@ -2,7 +2,7 @@ package keeper import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov/internal/types" + "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/cosmos/cosmos-sdk/x/staking/exported" ) @@ -11,24 +11,24 @@ import ( // Tally iterates over the votes and updates the tally of a proposal based on the voting power of the // voters -func (keeper Keeper) Tally(ctx sdk.Context, proposal Proposal) (passes bool, burnDeposits bool, tallyResults TallyResult) { - results := make(map[VoteOption]sdk.Dec) - results[OptionYes] = sdk.ZeroDec() - results[OptionAbstain] = sdk.ZeroDec() - results[OptionNo] = sdk.ZeroDec() - results[OptionNoWithVeto] = sdk.ZeroDec() +func (keeper Keeper) Tally(ctx sdk.Context, proposal types.Proposal) (passes bool, burnDeposits bool, tallyResults types.TallyResult) { + results := make(map[types.VoteOption]sdk.Dec) + results[types.OptionYes] = sdk.ZeroDec() + results[types.OptionAbstain] = sdk.ZeroDec() + results[types.OptionNo] = sdk.ZeroDec() + results[types.OptionNoWithVeto] = sdk.ZeroDec() totalVotingPower := sdk.ZeroDec() - currValidators := make(map[string]validatorGovInfo) + currValidators := make(map[string]types.ValidatorGovInfo) // fetch all the bonded validators, insert them into currValidators keeper.sk.IterateBondedValidatorsByPower(ctx, func(index int64, validator exported.ValidatorI) (stop bool) { - currValidators[validator.GetOperator().String()] = newValidatorGovInfo( + currValidators[validator.GetOperator().String()] = types.NewValidatorGovInfo( validator.GetOperator(), validator.GetBondedTokens(), validator.GetDelegatorShares(), sdk.ZeroDec(), - OptionEmpty, + types.OptionEmpty, ) return false @@ -67,7 +67,7 @@ func (keeper Keeper) Tally(ctx sdk.Context, proposal Proposal) (passes bool, bur // iterate over the validators again to tally their voting power for _, val := range currValidators { - if val.Vote == OptionEmpty { + if val.Vote == types.OptionEmpty { continue } @@ -80,7 +80,7 @@ func (keeper Keeper) Tally(ctx sdk.Context, proposal Proposal) (passes bool, bur } tallyParams := keeper.GetTallyParams(ctx) - tallyResults = NewTallyResultFromMap(results) + tallyResults = types.NewTallyResultFromMap(results) // TODO: Upgrade the spec to cover all of these cases & remove pseudocode. // If there is no staked coins, the proposal fails @@ -95,17 +95,17 @@ func (keeper Keeper) Tally(ctx sdk.Context, proposal Proposal) (passes bool, bur } // If no one votes (everyone abstains), proposal fails - if totalVotingPower.Sub(results[OptionAbstain]).Equal(sdk.ZeroDec()) { + if totalVotingPower.Sub(results[types.OptionAbstain]).Equal(sdk.ZeroDec()) { return false, false, tallyResults } // If more than 1/3 of voters veto, proposal fails - if results[OptionNoWithVeto].Quo(totalVotingPower).GT(tallyParams.Veto) { + if results[types.OptionNoWithVeto].Quo(totalVotingPower).GT(tallyParams.Veto) { return false, true, tallyResults } // If more than 1/2 of non-abstaining voters vote Yes, proposal passes - if results[OptionYes].Quo(totalVotingPower.Sub(results[OptionAbstain])).GT(tallyParams.Threshold) { + if results[types.OptionYes].Quo(totalVotingPower.Sub(results[types.OptionAbstain])).GT(tallyParams.Threshold) { return true, false, tallyResults } diff --git a/x/gov/internal/keeper/tally_test.go b/x/gov/keeper/tally_test.go similarity index 76% rename from x/gov/internal/keeper/tally_test.go rename to x/gov/keeper/tally_test.go index 9610f010a5fc..400bce4c75bd 100644 --- a/x/gov/internal/keeper/tally_test.go +++ b/x/gov/keeper/tally_test.go @@ -9,6 +9,7 @@ import ( "github.com/tendermint/tendermint/crypto/ed25519" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/cosmos/cosmos-sdk/x/staking" ) @@ -33,16 +34,16 @@ func TestTallyNoOneVotes(t *testing.T) { proposal, err := input.keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID - proposal.Status = StatusVotingPeriod + proposal.Status = types.StatusVotingPeriod input.keeper.SetProposal(ctx, proposal) proposal, ok := input.keeper.GetProposal(ctx, proposalID) require.True(t, ok) - passes, burnDeposits, tallyResults := tally(ctx, input.keeper, proposal) + passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) require.False(t, passes) require.True(t, burnDeposits) - require.True(t, tallyResults.Equals(EmptyTallyResult())) + require.True(t, tallyResults.Equals(types.EmptyTallyResult())) } func TestTallyNoQuorum(t *testing.T) { @@ -66,15 +67,15 @@ func TestTallyNoQuorum(t *testing.T) { proposal, err := input.keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID - proposal.Status = StatusVotingPeriod + proposal.Status = types.StatusVotingPeriod input.keeper.SetProposal(ctx, proposal) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[0], OptionYes) + err = input.keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionYes) require.Nil(t, err) proposal, ok := input.keeper.GetProposal(ctx, proposalID) require.True(t, ok) - passes, burnDeposits, _ := tally(ctx, input.keeper, proposal) + passes, burnDeposits, _ := input.keeper.Tally(ctx, proposal) require.False(t, passes) require.True(t, burnDeposits) } @@ -100,21 +101,21 @@ func TestTallyOnlyValidatorsAllYes(t *testing.T) { proposal, err := input.keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID - proposal.Status = StatusVotingPeriod + proposal.Status = types.StatusVotingPeriod input.keeper.SetProposal(ctx, proposal) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[0], OptionYes) + err = input.keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionYes) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[1], OptionYes) + err = input.keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionYes) require.Nil(t, err) proposal, ok := input.keeper.GetProposal(ctx, proposalID) require.True(t, ok) - passes, burnDeposits, tallyResults := tally(ctx, input.keeper, proposal) + passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) require.True(t, passes) require.False(t, burnDeposits) - require.False(t, tallyResults.Equals(EmptyTallyResult())) + require.False(t, tallyResults.Equals(types.EmptyTallyResult())) } func TestTallyOnlyValidators51No(t *testing.T) { @@ -138,17 +139,17 @@ func TestTallyOnlyValidators51No(t *testing.T) { proposal, err := input.keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID - proposal.Status = StatusVotingPeriod + proposal.Status = types.StatusVotingPeriod input.keeper.SetProposal(ctx, proposal) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[0], OptionYes) + err = input.keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionYes) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[1], OptionNo) + err = input.keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionNo) require.Nil(t, err) proposal, ok := input.keeper.GetProposal(ctx, proposalID) require.True(t, ok) - passes, burnDeposits, _ := tally(ctx, input.keeper, proposal) + passes, burnDeposits, _ := input.keeper.Tally(ctx, proposal) require.False(t, passes) require.False(t, burnDeposits) @@ -175,23 +176,23 @@ func TestTallyOnlyValidators51Yes(t *testing.T) { proposal, err := input.keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID - proposal.Status = StatusVotingPeriod + proposal.Status = types.StatusVotingPeriod input.keeper.SetProposal(ctx, proposal) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[0], OptionYes) + err = input.keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionYes) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[1], OptionYes) + err = input.keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionYes) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[2], OptionNo) + err = input.keeper.AddVote(ctx, proposalID, input.addrs[2], types.OptionNo) require.Nil(t, err) proposal, ok := input.keeper.GetProposal(ctx, proposalID) require.True(t, ok) - passes, burnDeposits, tallyResults := tally(ctx, input.keeper, proposal) + passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) require.True(t, passes) require.False(t, burnDeposits) - require.False(t, tallyResults.Equals(EmptyTallyResult())) + require.False(t, tallyResults.Equals(types.EmptyTallyResult())) } func TestTallyOnlyValidatorsVetoed(t *testing.T) { @@ -215,23 +216,23 @@ func TestTallyOnlyValidatorsVetoed(t *testing.T) { proposal, err := input.keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID - proposal.Status = StatusVotingPeriod + proposal.Status = types.StatusVotingPeriod input.keeper.SetProposal(ctx, proposal) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[0], OptionYes) + err = input.keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionYes) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[1], OptionYes) + err = input.keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionYes) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[2], OptionNoWithVeto) + err = input.keeper.AddVote(ctx, proposalID, input.addrs[2], types.OptionNoWithVeto) require.Nil(t, err) proposal, ok := input.keeper.GetProposal(ctx, proposalID) require.True(t, ok) - passes, burnDeposits, tallyResults := tally(ctx, input.keeper, proposal) + passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) require.False(t, passes) require.True(t, burnDeposits) - require.False(t, tallyResults.Equals(EmptyTallyResult())) + require.False(t, tallyResults.Equals(types.EmptyTallyResult())) } @@ -256,23 +257,23 @@ func TestTallyOnlyValidatorsAbstainPasses(t *testing.T) { proposal, err := input.keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID - proposal.Status = StatusVotingPeriod + proposal.Status = types.StatusVotingPeriod input.keeper.SetProposal(ctx, proposal) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[0], OptionAbstain) + err = input.keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionAbstain) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[1], OptionNo) + err = input.keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionNo) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[2], OptionYes) + err = input.keeper.AddVote(ctx, proposalID, input.addrs[2], types.OptionYes) require.Nil(t, err) proposal, ok := input.keeper.GetProposal(ctx, proposalID) require.True(t, ok) - passes, burnDeposits, tallyResults := tally(ctx, input.keeper, proposal) + passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) require.True(t, passes) require.False(t, burnDeposits) - require.False(t, tallyResults.Equals(EmptyTallyResult())) + require.False(t, tallyResults.Equals(types.EmptyTallyResult())) } func TestTallyOnlyValidatorsAbstainFails(t *testing.T) { @@ -296,23 +297,23 @@ func TestTallyOnlyValidatorsAbstainFails(t *testing.T) { proposal, err := input.keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID - proposal.Status = StatusVotingPeriod + proposal.Status = types.StatusVotingPeriod input.keeper.SetProposal(ctx, proposal) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[0], OptionAbstain) + err = input.keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionAbstain) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[1], OptionYes) + err = input.keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionYes) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[2], OptionNo) + err = input.keeper.AddVote(ctx, proposalID, input.addrs[2], types.OptionNo) require.Nil(t, err) proposal, ok := input.keeper.GetProposal(ctx, proposalID) require.True(t, ok) - passes, burnDeposits, tallyResults := tally(ctx, input.keeper, proposal) + passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) require.False(t, passes) require.False(t, burnDeposits) - require.False(t, tallyResults.Equals(EmptyTallyResult())) + require.False(t, tallyResults.Equals(types.EmptyTallyResult())) } func TestTallyOnlyValidatorsNonVoter(t *testing.T) { @@ -336,21 +337,21 @@ func TestTallyOnlyValidatorsNonVoter(t *testing.T) { proposal, err := input.keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID - proposal.Status = StatusVotingPeriod + proposal.Status = types.StatusVotingPeriod input.keeper.SetProposal(ctx, proposal) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[1], OptionYes) + err = input.keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionYes) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[2], OptionNo) + err = input.keeper.AddVote(ctx, proposalID, input.addrs[2], types.OptionNo) require.Nil(t, err) proposal, ok := input.keeper.GetProposal(ctx, proposalID) require.True(t, ok) - passes, burnDeposits, tallyResults := tally(ctx, input.keeper, proposal) + passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) require.False(t, passes) require.False(t, burnDeposits) - require.False(t, tallyResults.Equals(EmptyTallyResult())) + require.False(t, tallyResults.Equals(types.EmptyTallyResult())) } func TestTallyDelgatorOverride(t *testing.T) { @@ -378,25 +379,25 @@ func TestTallyDelgatorOverride(t *testing.T) { proposal, err := input.keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID - proposal.Status = StatusVotingPeriod + proposal.Status = types.StatusVotingPeriod input.keeper.SetProposal(ctx, proposal) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[0], OptionYes) + err = input.keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionYes) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[1], OptionYes) + err = input.keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionYes) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[2], OptionYes) + err = input.keeper.AddVote(ctx, proposalID, input.addrs[2], types.OptionYes) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[3], OptionNo) + err = input.keeper.AddVote(ctx, proposalID, input.addrs[3], types.OptionNo) require.Nil(t, err) proposal, ok := input.keeper.GetProposal(ctx, proposalID) require.True(t, ok) - passes, burnDeposits, tallyResults := tally(ctx, input.keeper, proposal) + passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) require.False(t, passes) require.False(t, burnDeposits) - require.False(t, tallyResults.Equals(EmptyTallyResult())) + require.False(t, tallyResults.Equals(types.EmptyTallyResult())) } func TestTallyDelgatorInherit(t *testing.T) { @@ -424,23 +425,23 @@ func TestTallyDelgatorInherit(t *testing.T) { proposal, err := input.keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID - proposal.Status = StatusVotingPeriod + proposal.Status = types.StatusVotingPeriod input.keeper.SetProposal(ctx, proposal) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[0], OptionNo) + err = input.keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionNo) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[1], OptionNo) + err = input.keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionNo) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[2], OptionYes) + err = input.keeper.AddVote(ctx, proposalID, input.addrs[2], types.OptionYes) require.Nil(t, err) proposal, ok := input.keeper.GetProposal(ctx, proposalID) require.True(t, ok) - passes, burnDeposits, tallyResults := tally(ctx, input.keeper, proposal) + passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) require.True(t, passes) require.False(t, burnDeposits) - require.False(t, tallyResults.Equals(EmptyTallyResult())) + require.False(t, tallyResults.Equals(types.EmptyTallyResult())) } func TestTallyDelgatorMultipleOverride(t *testing.T) { @@ -470,25 +471,25 @@ func TestTallyDelgatorMultipleOverride(t *testing.T) { proposal, err := input.keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID - proposal.Status = StatusVotingPeriod + proposal.Status = types.StatusVotingPeriod input.keeper.SetProposal(ctx, proposal) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[0], OptionYes) + err = input.keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionYes) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[1], OptionYes) + err = input.keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionYes) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[2], OptionYes) + err = input.keeper.AddVote(ctx, proposalID, input.addrs[2], types.OptionYes) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[3], OptionNo) + err = input.keeper.AddVote(ctx, proposalID, input.addrs[3], types.OptionNo) require.Nil(t, err) proposal, ok := input.keeper.GetProposal(ctx, proposalID) require.True(t, ok) - passes, burnDeposits, tallyResults := tally(ctx, input.keeper, proposal) + passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) require.False(t, passes) require.False(t, burnDeposits) - require.False(t, tallyResults.Equals(EmptyTallyResult())) + require.False(t, tallyResults.Equals(types.EmptyTallyResult())) } func TestTallyDelgatorMultipleInherit(t *testing.T) { @@ -531,23 +532,23 @@ func TestTallyDelgatorMultipleInherit(t *testing.T) { proposal, err := input.keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID - proposal.Status = StatusVotingPeriod + proposal.Status = types.StatusVotingPeriod input.keeper.SetProposal(ctx, proposal) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[0], OptionYes) + err = input.keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionYes) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[1], OptionNo) + err = input.keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionNo) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[2], OptionNo) + err = input.keeper.AddVote(ctx, proposalID, input.addrs[2], types.OptionNo) require.Nil(t, err) proposal, ok := input.keeper.GetProposal(ctx, proposalID) require.True(t, ok) - passes, burnDeposits, tallyResults := tally(ctx, input.keeper, proposal) + passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) require.False(t, passes) require.False(t, burnDeposits) - require.False(t, tallyResults.Equals(EmptyTallyResult())) + require.False(t, tallyResults.Equals(types.EmptyTallyResult())) } func TestTallyJailedValidator(t *testing.T) { @@ -584,21 +585,21 @@ func TestTallyJailedValidator(t *testing.T) { proposal, err := input.keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID - proposal.Status = StatusVotingPeriod + proposal.Status = types.StatusVotingPeriod input.keeper.SetProposal(ctx, proposal) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[0], OptionYes) + err = input.keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionYes) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[1], OptionNo) + err = input.keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionNo) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[2], OptionNo) + err = input.keeper.AddVote(ctx, proposalID, input.addrs[2], types.OptionNo) require.Nil(t, err) proposal, ok := input.keeper.GetProposal(ctx, proposalID) require.True(t, ok) - passes, burnDeposits, tallyResults := tally(ctx, input.keeper, proposal) + passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) require.True(t, passes) require.False(t, burnDeposits) - require.False(t, tallyResults.Equals(EmptyTallyResult())) + require.False(t, tallyResults.Equals(types.EmptyTallyResult())) } diff --git a/x/gov/test_common.go b/x/gov/keeper/test_common.go similarity index 85% rename from x/gov/test_common.go rename to x/gov/keeper/test_common.go index 31cadaa006be..cff4e8afa6c0 100644 --- a/x/gov/test_common.go +++ b/x/gov/keeper/test_common.go @@ -1,5 +1,5 @@ // nolint:deadcode unused -package gov +package keeper import ( "bytes" @@ -17,7 +17,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/bank" - "github.com/cosmos/cosmos-sdk/x/gov/internal/types" + "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/cosmos/cosmos-sdk/x/mock" "github.com/cosmos/cosmos-sdk/x/staking" "github.com/cosmos/cosmos-sdk/x/supply" @@ -33,14 +33,14 @@ var ( type testInput struct { mApp *mock.App keeper Keeper - router Router + router types.Router sk staking.Keeper addrs []sdk.AccAddress pubKeys []crypto.PubKey privKeys []crypto.PrivKey } -func getMockApp(t *testing.T, numGenAccs int, genState GenesisState, genAccs []auth.Account) testInput { +func getMockApp(t *testing.T, numGenAccs int, genState types.GenesisState, genAccs []auth.Account) testInput { mApp := mock.NewApp() staking.RegisterCodec(mApp.Cdc) @@ -49,13 +49,13 @@ func getMockApp(t *testing.T, numGenAccs int, genState GenesisState, genAccs []a keyStaking := sdk.NewKVStoreKey(staking.StoreKey) tKeyStaking := sdk.NewTransientStoreKey(staking.TStoreKey) - keyGov := sdk.NewKVStoreKey(StoreKey) + keyGov := sdk.NewKVStoreKey(types.StoreKey) keySupply := sdk.NewKVStoreKey(supply.StoreKey) pk := mApp.ParamsKeeper - rtr := NewRouter(). - AddRoute(RouterKey, ProposalHandler) + rtr := types.NewRouter(). + AddRoute(types.RouterKey, types.ProposalHandler) bk := bank.NewBaseKeeper(mApp.AccountKeeper, mApp.ParamsKeeper.Subspace(bank.DefaultParamspace), bank.DefaultCodespace) @@ -63,10 +63,10 @@ func getMockApp(t *testing.T, numGenAccs int, genState GenesisState, genAccs []a []string{}, []string{}, []string{types.ModuleName, staking.NotBondedPoolName, staking.BondedPoolName}) sk := staking.NewKeeper(mApp.Cdc, keyStaking, tKeyStaking, supplyKeeper, pk.Subspace(staking.DefaultParamspace), staking.DefaultCodespace) - keeper := NewKeeper(mApp.Cdc, keyGov, pk, pk.Subspace("testgov"), supplyKeeper, sk, DefaultCodespace, rtr) + keeper := NewKeeper(mApp.Cdc, keyGov, pk.Subspace("testgov"), supplyKeeper, sk, types.DefaultCodespace, rtr) - mApp.Router().AddRoute(RouterKey, NewHandler(keeper)) - mApp.QueryRouter().AddRoute(QuerierRoute, NewQuerier(keeper)) + mApp.Router().AddRoute(types.RouterKey, types.NewHandler(keeper)) + mApp.QueryRouter().AddRoute(types.QuerierRoute, NewQuerier(keeper)) mApp.SetEndBlocker(getEndBlocker(keeper)) mApp.SetInitChainer(getInitChainer(mApp, keeper, sk, supplyKeeper, genAccs, genState)) @@ -97,7 +97,7 @@ func getEndBlocker(keeper Keeper) sdk.EndBlocker { } // gov and staking initchainer -func getInitChainer(mapp *mock.App, keeper Keeper, stakingKeeper staking.Keeper, supplyKeeper supply.Keeper, accs []auth.Account, genState GenesisState) sdk.InitChainer { +func getInitChainer(mapp *mock.App, keeper Keeper, stakingKeeper staking.Keeper, supplyKeeper supply.Keeper, accs []auth.Account, genState types.GenesisState) sdk.InitChainer { return func(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain { mapp.InitChainer(ctx, req) @@ -117,7 +117,7 @@ func getInitChainer(mapp *mock.App, keeper Keeper, stakingKeeper staking.Keeper, validators := staking.InitGenesis(ctx, stakingKeeper, mapp.AccountKeeper, supplyKeeper, stakingGenesis) if genState.IsEmpty() { - InitGenesis(ctx, keeper, supplyKeeper, DefaultGenesisState()) + InitGenesis(ctx, keeper, supplyKeeper, types.DefaultGenesisState()) } else { InitGenesis(ctx, keeper, supplyKeeper, genState) } @@ -170,8 +170,8 @@ func SortByteArrays(src [][]byte) [][]byte { return sorted } -func testProposal() Content { - return NewTextProposal("Test", "description") +func testProposal() types.Content { + return types.NewTextProposal("Test", "description") } const contextKeyBadProposal = "contextKeyBadProposal" @@ -179,9 +179,9 @@ const contextKeyBadProposal = "contextKeyBadProposal" // badProposalHandler implements a governance proposal handler that is identical // to the actual handler except this fails if the context doesn't contain a value // for the key contextKeyBadProposal or if the value is false. -func badProposalHandler(ctx sdk.Context, c Content) sdk.Error { +func badProposalHandler(ctx sdk.Context, c types.Content) sdk.Error { switch c.ProposalType() { - case ProposalTypeText, ProposalTypeSoftwareUpgrade: + case types.ProposalTypeText, types.ProposalTypeSoftwareUpgrade: v := ctx.Value(contextKeyBadProposal) if v == nil || !v.(bool) { @@ -196,8 +196,8 @@ func badProposalHandler(ctx sdk.Context, c Content) sdk.Error { } } -// checks if two proposals are equal (note: slow, for tests only) -func ProposalEqual(proposalA Proposal, proposalB Proposal) bool { +// ProposalEqual checks if two proposals are equal (note: slow, for tests only) +func ProposalEqual(proposalA types.Proposal, proposalB types.Proposal) bool { return bytes.Equal(types.ModuleCdc.MustMarshalBinaryBare(proposalA), types.ModuleCdc.MustMarshalBinaryBare(proposalB)) } diff --git a/x/gov/internal/keeper/vote.go b/x/gov/keeper/vote.go similarity index 71% rename from x/gov/internal/keeper/vote.go rename to x/gov/keeper/vote.go index 3df3fa32cc93..c8443f5c0514 100644 --- a/x/gov/internal/keeper/vote.go +++ b/x/gov/keeper/vote.go @@ -4,24 +4,24 @@ import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov/internal/types" + "github.com/cosmos/cosmos-sdk/x/gov/types" ) // AddVote Adds a vote on a specific proposal -func (keeper Keeper) AddVote(ctx sdk.Context, proposalID uint64, voterAddr sdk.AccAddress, option VoteOption) sdk.Error { +func (keeper Keeper) AddVote(ctx sdk.Context, proposalID uint64, voterAddr sdk.AccAddress, option types.VoteOption) sdk.Error { proposal, ok := keeper.GetProposal(ctx, proposalID) if !ok { - return ErrUnknownProposal(keeper.codespace, proposalID) + return types.ErrUnknownProposal(keeper.codespace, proposalID) } - if proposal.Status != StatusVotingPeriod { - return ErrInactiveProposal(keeper.codespace, proposalID) + if proposal.Status != types.StatusVotingPeriod { + return types.ErrInactiveProposal(keeper.codespace, proposalID) } - if !ValidVoteOption(option) { - return ErrInvalidVote(keeper.codespace, option) + if !types.ValidVoteOption(option) { + return types.ErrInvalidVote(keeper.codespace, option) } - vote := NewVote(proposalID, voterAddr, option) + vote := types.NewVote(proposalID, voterAddr, option) keeper.setVote(ctx, proposalID, voterAddr, vote) ctx.EventManager().EmitEvent( @@ -36,8 +36,8 @@ func (keeper Keeper) AddVote(ctx sdk.Context, proposalID uint64, voterAddr sdk.A } // GetAllVotes returns all the votes from the store -func (keeper Keeper) GetAllVotes(ctx sdk.Context) (votes Votes) { - keeper.IterateAllVotes(ctx, func(vote Vote) bool { +func (keeper Keeper) GetAllVotes(ctx sdk.Context) (votes types.Votes) { + keeper.IterateAllVotes(ctx, func(vote types.Vote) bool { votes = append(votes, vote) return false }) @@ -45,8 +45,8 @@ func (keeper Keeper) GetAllVotes(ctx sdk.Context) (votes Votes) { } // GetVotes returns all the votes from a proposal -func (keeper Keeper) GetVotes(ctx sdk.Context, proposalID uint64) (votes Votes) { - keeper.IterateVotes(ctx, proposalID, func(vote Vote) bool { +func (keeper Keeper) GetVotes(ctx sdk.Context, proposalID uint64) (votes types.Votes) { + keeper.IterateVotes(ctx, proposalID, func(vote types.Vote) bool { votes = append(votes, vote) return false }) @@ -54,7 +54,7 @@ func (keeper Keeper) GetVotes(ctx sdk.Context, proposalID uint64) (votes Votes) } // GetVote gets the vote from an address on a specific proposal -func (keeper Keeper) GetVote(ctx sdk.Context, proposalID uint64, voterAddr sdk.AccAddress) (vote Vote, found bool) { +func (keeper Keeper) GetVote(ctx sdk.Context, proposalID uint64, voterAddr sdk.AccAddress) (vote types.Vote, found bool) { store := ctx.KVStore(keeper.storeKey) bz := store.Get(types.VoteKey(proposalID, voterAddr)) if bz == nil { @@ -65,7 +65,7 @@ func (keeper Keeper) GetVote(ctx sdk.Context, proposalID uint64, voterAddr sdk.A return vote, true } -func (keeper Keeper) setVote(ctx sdk.Context, proposalID uint64, voterAddr sdk.AccAddress, vote Vote) { +func (keeper Keeper) setVote(ctx sdk.Context, proposalID uint64, voterAddr sdk.AccAddress, vote types.Vote) { store := ctx.KVStore(keeper.storeKey) bz := keeper.cdc.MustMarshalBinaryLengthPrefixed(vote) store.Set(types.VoteKey(proposalID, voterAddr), bz) diff --git a/x/gov/module.go b/x/gov/module.go index 682b3d5e03ad..9101f53c5b56 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -15,7 +15,7 @@ import ( "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/internal/types" + "github.com/cosmos/cosmos-sdk/x/gov/types" ) var ( diff --git a/x/gov/internal/types/codec.go b/x/gov/types/codec.go similarity index 100% rename from x/gov/internal/types/codec.go rename to x/gov/types/codec.go diff --git a/x/gov/internal/types/content.go b/x/gov/types/content.go similarity index 100% rename from x/gov/internal/types/content.go rename to x/gov/types/content.go diff --git a/x/gov/internal/types/deposit.go b/x/gov/types/deposit.go similarity index 100% rename from x/gov/internal/types/deposit.go rename to x/gov/types/deposit.go diff --git a/x/gov/internal/types/errors.go b/x/gov/types/errors.go similarity index 100% rename from x/gov/internal/types/errors.go rename to x/gov/types/errors.go diff --git a/x/gov/internal/types/events.go b/x/gov/types/events.go similarity index 100% rename from x/gov/internal/types/events.go rename to x/gov/types/events.go diff --git a/x/gov/internal/types/expected_keepers.go b/x/gov/types/expected_keepers.go similarity index 100% rename from x/gov/internal/types/expected_keepers.go rename to x/gov/types/expected_keepers.go diff --git a/x/gov/internal/types/genesis.go b/x/gov/types/genesis.go similarity index 100% rename from x/gov/internal/types/genesis.go rename to x/gov/types/genesis.go diff --git a/x/gov/internal/types/genesis_test.go b/x/gov/types/genesis_test.go similarity index 100% rename from x/gov/internal/types/genesis_test.go rename to x/gov/types/genesis_test.go diff --git a/x/gov/internal/types/keys.go b/x/gov/types/keys.go similarity index 100% rename from x/gov/internal/types/keys.go rename to x/gov/types/keys.go diff --git a/x/gov/internal/types/keys_test.go b/x/gov/types/keys_test.go similarity index 100% rename from x/gov/internal/types/keys_test.go rename to x/gov/types/keys_test.go diff --git a/x/gov/internal/types/msgs.go b/x/gov/types/msgs.go similarity index 100% rename from x/gov/internal/types/msgs.go rename to x/gov/types/msgs.go diff --git a/x/gov/internal/types/msgs_test.go b/x/gov/types/msgs_test.go similarity index 100% rename from x/gov/internal/types/msgs_test.go rename to x/gov/types/msgs_test.go diff --git a/x/gov/internal/types/params.go b/x/gov/types/params.go similarity index 100% rename from x/gov/internal/types/params.go rename to x/gov/types/params.go diff --git a/x/gov/internal/types/proposal.go b/x/gov/types/proposal.go similarity index 100% rename from x/gov/internal/types/proposal.go rename to x/gov/types/proposal.go diff --git a/x/gov/internal/types/proposals_test.go b/x/gov/types/proposals_test.go similarity index 100% rename from x/gov/internal/types/proposals_test.go rename to x/gov/types/proposals_test.go diff --git a/x/gov/internal/types/querier.go b/x/gov/types/querier.go similarity index 100% rename from x/gov/internal/types/querier.go rename to x/gov/types/querier.go diff --git a/x/gov/router.go b/x/gov/types/router.go similarity index 99% rename from x/gov/router.go rename to x/gov/types/router.go index 7c86c6cf3075..5fd4b6479dcb 100644 --- a/x/gov/router.go +++ b/x/gov/types/router.go @@ -1,4 +1,4 @@ -package gov +package types import ( "fmt" diff --git a/x/gov/internal/types/tally.go b/x/gov/types/tally.go similarity index 100% rename from x/gov/internal/types/tally.go rename to x/gov/types/tally.go diff --git a/x/gov/internal/types/vote.go b/x/gov/types/vote.go similarity index 100% rename from x/gov/internal/types/vote.go rename to x/gov/types/vote.go diff --git a/x/params/client/cli/tx.go b/x/params/client/cli/tx.go index 40aeaae83961..79d6bb1257a6 100644 --- a/x/params/client/cli/tx.go +++ b/x/params/client/cli/tx.go @@ -12,7 +12,7 @@ import ( "github.com/cosmos/cosmos-sdk/version" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/auth/client/utils" - "github.com/cosmos/cosmos-sdk/x/gov" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" paramscutils "github.com/cosmos/cosmos-sdk/x/params/client/utils" "github.com/cosmos/cosmos-sdk/x/params/types" ) @@ -75,7 +75,7 @@ Where proposal.json contains: from := cliCtx.GetFromAddress() content := types.NewParameterChangeProposal(proposal.Title, proposal.Description, proposal.Changes.ToParamChanges()) - msg := gov.NewMsgSubmitProposal(content, proposal.Deposit, from) + msg := govtypes.NewMsgSubmitProposal(content, proposal.Deposit, from) if err := msg.ValidateBasic(); err != nil { return err } diff --git a/x/params/client/rest/rest.go b/x/params/client/rest/rest.go index 4d95932b1e26..355296fdb06a 100644 --- a/x/params/client/rest/rest.go +++ b/x/params/client/rest/rest.go @@ -7,7 +7,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" "github.com/cosmos/cosmos-sdk/x/auth/client/utils" - "github.com/cosmos/cosmos-sdk/x/gov" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" govrest "github.com/cosmos/cosmos-sdk/x/gov/client/rest" "github.com/cosmos/cosmos-sdk/x/params" paramscutils "github.com/cosmos/cosmos-sdk/x/params/client/utils" @@ -36,7 +36,7 @@ func postProposalHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { content := params.NewParameterChangeProposal(req.Title, req.Description, req.Changes.ToParamChanges()) - msg := gov.NewMsgSubmitProposal(content, req.Deposit, req.Proposer) + msg := govtypes.NewMsgSubmitProposal(content, req.Deposit, req.Proposer) if err := msg.ValidateBasic(); err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return diff --git a/x/params/proposal_handler.go b/x/params/proposal_handler.go index 31763cf81d48..97efd3e91226 100644 --- a/x/params/proposal_handler.go +++ b/x/params/proposal_handler.go @@ -4,12 +4,12 @@ import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" ) // NewParamChangeProposalHandler creates a new governance Handler for a ParamChangeProposal -func NewParamChangeProposalHandler(k Keeper) gov.Handler { - return func(ctx sdk.Context, content gov.Content) sdk.Error { +func NewParamChangeProposalHandler(k Keeper) govtypes.Handler { + return func(ctx sdk.Context, content govtypes.Content) sdk.Error { switch c := content.(type) { case ParameterChangeProposal: return handleParameterChangeProposal(ctx, k, c) diff --git a/x/params/simulation/msgs.go b/x/params/simulation/msgs.go index df303a8b25fa..db7669ae09ed 100644 --- a/x/params/simulation/msgs.go +++ b/x/params/simulation/msgs.go @@ -8,7 +8,7 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/cosmos/cosmos-sdk/x/params" "github.com/cosmos/cosmos-sdk/x/simulation" ) @@ -158,7 +158,7 @@ var paramChangePool = []simParamChange{ // SimulateParamChangeProposalContent returns random parameter change content. // It will generate a ParameterChangeProposal object with anywhere between 1 and // 3 parameter changes all of which have random, but valid values. -func SimulateParamChangeProposalContent(r *rand.Rand, _ *baseapp.BaseApp, _ sdk.Context, _ []simulation.Account) gov.Content { +func SimulateParamChangeProposalContent(r *rand.Rand, _ *baseapp.BaseApp, _ sdk.Context, _ []simulation.Account) govtypes.Content { numChanges := simulation.RandIntBetween(r, 1, len(paramChangePool)/2) paramChanges := make([]params.ParamChange, numChanges, numChanges) paramChangesKeys := make(map[string]struct{}) diff --git a/x/params/types/proposal.go b/x/params/types/proposal.go index 354b74da174b..a44a4f585f52 100644 --- a/x/params/types/proposal.go +++ b/x/params/types/proposal.go @@ -5,7 +5,7 @@ import ( "strings" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" ) const ( @@ -17,8 +17,8 @@ const ( var _ govtypes.Content = ParameterChangeProposal{} func init() { - gov.RegisterProposalType(ProposalTypeChange) - gov.RegisterProposalTypeCodec(ParameterChangeProposal{}, "cosmos-sdk/ParameterChangeProposal") + govtypes.RegisterProposalType(ProposalTypeChange) + govtypes.RegisterProposalTypeCodec(ParameterChangeProposal{}, "cosmos-sdk/ParameterChangeProposal") } // ParameterChangeProposal defines a proposal which contains multiple parameter From 78dcba6d4aba0f5a536fa0b593b25f765cd4a49d Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Thu, 4 Jul 2019 15:10:37 +0200 Subject: [PATCH 06/36] more updates --- simapp/app.go | 2 +- x/distribution/handler.go | 2 +- x/gov/abci.go | 2 +- x/gov/alias.go | 1 + x/gov/genesis.go | 12 +- x/gov/handler.go | 2 +- x/gov/keeper/deposit.go | 7 +- x/gov/keeper/keeper.go | 20 ++- x/gov/keeper/proposal.go | 6 +- x/gov/keeper/test_common.go | 278 ++++++++++++------------------------ x/gov/keeper/vote.go | 7 +- x/gov/test_common.go | 231 ++++++++++++++++++++++++++++++ 12 files changed, 355 insertions(+), 215 deletions(-) create mode 100644 x/gov/test_common.go diff --git a/simapp/app.go b/simapp/app.go index 89d7c124bd78..bd5a853b1ec0 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -167,7 +167,7 @@ func NewSimApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest bo govRouter.AddRoute(gov.RouterKey, gov.ProposalHandler). AddRoute(params.RouterKey, params.NewParamChangeProposalHandler(app.paramsKeeper)). AddRoute(distr.RouterKey, distr.NewCommunityPoolSpendProposalHandler(app.distrKeeper)) - app.govKeeper = gov.NewKeeper(app.cdc, app.keyGov, app.paramsKeeper, govSubspace, + app.govKeeper = gov.NewKeeper(app.cdc, app.keyGov, govSubspace, app.supplyKeeper, &stakingKeeper, gov.DefaultCodespace, govRouter) // register the staking hooks diff --git a/x/distribution/handler.go b/x/distribution/handler.go index bad5c88f8410..ca047cec3672 100644 --- a/x/distribution/handler.go +++ b/x/distribution/handler.go @@ -6,7 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/distribution/keeper" "github.com/cosmos/cosmos-sdk/x/distribution/types" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/internal/types" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" ) func NewHandler(k keeper.Keeper) sdk.Handler { diff --git a/x/gov/abci.go b/x/gov/abci.go index 730e4d3a4d29..31b1f40c9d2a 100644 --- a/x/gov/abci.go +++ b/x/gov/abci.go @@ -48,7 +48,7 @@ func EndBlocker(ctx sdk.Context, keeper Keeper) { } if passes { - handler := keeper.router.GetRoute(proposal.ProposalRoute()) + handler := keeper.Router().GetRoute(proposal.ProposalRoute()) cacheCtx, writeCache := ctx.CacheContext() // The proposal handler may execute state mutating logic depending diff --git a/x/gov/alias.go b/x/gov/alias.go index 6482b0750b71..5d532692ad2f 100644 --- a/x/gov/alias.go +++ b/x/gov/alias.go @@ -121,6 +121,7 @@ var ( NewVotingParams = types.NewVotingParams NewParams = types.NewParams NewProposal = types.NewProposal + NewRouter = types.NewRouter ProposalStatusFromString = types.ProposalStatusFromString ValidProposalStatus = types.ValidProposalStatus NewTextProposal = types.NewTextProposal diff --git a/x/gov/genesis.go b/x/gov/genesis.go index e1d8571804ae..962b7cd7b8aa 100644 --- a/x/gov/genesis.go +++ b/x/gov/genesis.go @@ -10,10 +10,10 @@ import ( // InitGenesis - store genesis parameters func InitGenesis(ctx sdk.Context, k Keeper, supplyKeeper types.SupplyKeeper, data GenesisState) { - k.setProposalID(ctx, data.StartingProposalID) - k.setDepositParams(ctx, data.DepositParams) - k.setVotingParams(ctx, data.VotingParams) - k.setTallyParams(ctx, data.TallyParams) + k.SetProposalID(ctx, data.StartingProposalID) + k.SetDepositParams(ctx, data.DepositParams) + k.SetVotingParams(ctx, data.VotingParams) + k.SetTallyParams(ctx, data.TallyParams) // check if the deposits pool account exists moduleAcc := k.GetGovernanceAccount(ctx) @@ -23,12 +23,12 @@ func InitGenesis(ctx sdk.Context, k Keeper, supplyKeeper types.SupplyKeeper, dat var totalDeposits sdk.Coins for _, deposit := range data.Deposits { - k.setDeposit(ctx, deposit.ProposalID, deposit.Depositor, deposit) + k.SetDeposit(ctx, deposit) totalDeposits = totalDeposits.Add(deposit.Amount) } for _, vote := range data.Votes { - k.setVote(ctx, vote.ProposalID, vote.Voter, vote) + k.SetVote(ctx, vote) } for _, proposal := range data.Proposals { diff --git a/x/gov/handler.go b/x/gov/handler.go index 11011baff611..197194353f5e 100644 --- a/x/gov/handler.go +++ b/x/gov/handler.go @@ -58,7 +58,7 @@ func handleMsgSubmitProposal(ctx sdk.Context, keeper Keeper, msg MsgSubmitPropos } return sdk.Result{ - Data: keeper.cdc.MustMarshalBinaryLengthPrefixed(proposal.ProposalID), + // Data: keeper.cdc.MustMarshalBinaryLengthPrefixed(proposal.ProposalID), Events: ctx.EventManager().Events(), } } diff --git a/x/gov/keeper/deposit.go b/x/gov/keeper/deposit.go index ea8244ae8202..9db72dc5c378 100644 --- a/x/gov/keeper/deposit.go +++ b/x/gov/keeper/deposit.go @@ -19,10 +19,11 @@ func (keeper Keeper) GetDeposit(ctx sdk.Context, proposalID uint64, depositorAdd return deposit, true } -func (keeper Keeper) setDeposit(ctx sdk.Context, proposalID uint64, depositorAddr sdk.AccAddress, deposit types.Deposit) { +// SetDeposit sets a Deposit to the gov store +func (keeper Keeper) SetDeposit(ctx sdk.Context, deposit types.Deposit) { store := ctx.KVStore(keeper.storeKey) bz := keeper.cdc.MustMarshalBinaryLengthPrefixed(deposit) - store.Set(types.DepositKey(proposalID, depositorAddr), bz) + store.Set(types.DepositKey(deposit.ProposalID, deposit.Depositor), bz) } // AddDeposit adds or updates a deposit of a specific depositor on a specific proposal @@ -72,7 +73,7 @@ func (keeper Keeper) AddDeposit(ctx sdk.Context, proposalID uint64, depositorAdd ), ) - keeper.setDeposit(ctx, proposalID, depositorAddr, deposit) + keeper.SetDeposit(ctx, deposit) return nil, activatedVotingPeriod } diff --git a/x/gov/keeper/keeper.go b/x/gov/keeper/keeper.go index 0a223e94089b..83366cc357de 100644 --- a/x/gov/keeper/keeper.go +++ b/x/gov/keeper/keeper.go @@ -73,6 +73,11 @@ func (keeper Keeper) Logger(ctx sdk.Context) log.Logger { return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) } +// Router returns the gov Keeper Router +func (keeper Keeper) Router() types.Router { + return keeper.router +} + // GetGovernanceAccount returns the governance ModuleAccount func (keeper Keeper) GetGovernanceAccount(ctx sdk.Context) exported.ModuleAccountI { return keeper.supplyKeeper.GetModuleAccount(ctx, types.ModuleName) @@ -80,36 +85,39 @@ func (keeper Keeper) GetGovernanceAccount(ctx sdk.Context) exported.ModuleAccoun // Params -// Returns the current DepositParams from the global param store +// GetDepositParams returns the current DepositParams from the global param store func (keeper Keeper) GetDepositParams(ctx sdk.Context) types.DepositParams { var depositParams types.DepositParams keeper.paramSpace.Get(ctx, types.ParamStoreKeyDepositParams, &depositParams) return depositParams } -// Returns the current VotingParams from the global param store +// GetVotingParams returns the current VotingParams from the global param store func (keeper Keeper) GetVotingParams(ctx sdk.Context) types.VotingParams { var votingParams types.VotingParams keeper.paramSpace.Get(ctx, types.ParamStoreKeyVotingParams, &votingParams) return votingParams } -// Returns the current TallyParam from the global param store +// GetTallyParams returns the current TallyParam from the global param store func (keeper Keeper) GetTallyParams(ctx sdk.Context) types.TallyParams { var tallyParams types.TallyParams keeper.paramSpace.Get(ctx, types.ParamStoreKeyTallyParams, &tallyParams) return tallyParams } -func (keeper Keeper) setDepositParams(ctx sdk.Context, depositParams types.DepositParams) { +// SetDepositParams sets DepositParams to the global param store +func (keeper Keeper) SetDepositParams(ctx sdk.Context, depositParams types.DepositParams) { keeper.paramSpace.Set(ctx, types.ParamStoreKeyDepositParams, &depositParams) } -func (keeper Keeper) setVotingParams(ctx sdk.Context, votingParams types.VotingParams) { +// SetVotingParams sets VotingParams to the global param store +func (keeper Keeper) SetVotingParams(ctx sdk.Context, votingParams types.VotingParams) { keeper.paramSpace.Set(ctx, types.ParamStoreKeyVotingParams, &votingParams) } -func (keeper Keeper) setTallyParams(ctx sdk.Context, tallyParams types.TallyParams) { +// SetTallyParams sets TallyParams to the global param store +func (keeper Keeper) SetTallyParams(ctx sdk.Context, tallyParams types.TallyParams) { keeper.paramSpace.Set(ctx, types.ParamStoreKeyTallyParams, &tallyParams) } diff --git a/x/gov/keeper/proposal.go b/x/gov/keeper/proposal.go index 10a12cb01af4..99af0c46470c 100644 --- a/x/gov/keeper/proposal.go +++ b/x/gov/keeper/proposal.go @@ -34,7 +34,7 @@ func (keeper Keeper) SubmitProposal(ctx sdk.Context, content types.Content) (typ keeper.SetProposal(ctx, proposal) keeper.InsertInactiveProposalQueue(ctx, proposalID, proposal.DepositEndTime) - keeper.setProposalID(ctx, proposalID+1) + keeper.SetProposalID(ctx, proposalID+1) ctx.EventManager().EmitEvent( sdk.NewEvent( @@ -143,8 +143,8 @@ func (keeper Keeper) GetProposalID(ctx sdk.Context) (proposalID uint64, err sdk. return proposalID, nil } -// Set the proposal ID -func (keeper Keeper) setProposalID(ctx sdk.Context, proposalID uint64) { +// SetProposalID sets the new proposal ID to the store +func (keeper Keeper) SetProposalID(ctx sdk.Context, proposalID uint64) { store := ctx.KVStore(keeper.storeKey) bz := keeper.cdc.MustMarshalBinaryLengthPrefixed(proposalID) store.Set(types.ProposalIDKey, bz) diff --git a/x/gov/keeper/test_common.go b/x/gov/keeper/test_common.go index cff4e8afa6c0..d0a351eb1751 100644 --- a/x/gov/keeper/test_common.go +++ b/x/gov/keeper/test_common.go @@ -1,230 +1,128 @@ -// nolint:deadcode unused -package keeper +package keeper // noalias import ( - "bytes" - "fmt" - "log" - "sort" "testing" "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/crypto/ed25519" abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/crypto" + dbm "github.com/tendermint/tendermint/libs/db" + "github.com/tendermint/tendermint/libs/log" + tmtypes "github.com/tendermint/tendermint/types" + "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" "github.com/cosmos/cosmos-sdk/x/bank" + "github.com/cosmos/cosmos-sdk/x/params" "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/cosmos/cosmos-sdk/x/mock" "github.com/cosmos/cosmos-sdk/x/staking" "github.com/cosmos/cosmos-sdk/x/supply" ) +// dummy addresses used for testing +// nolint: unused deadcode var ( - valTokens = sdk.TokensFromConsensusPower(42) - initTokens = sdk.TokensFromConsensusPower(100000) - valCoins = sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, valTokens)) - initCoins = sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, initTokens)) -) - -type testInput struct { - mApp *mock.App - keeper Keeper - router types.Router - sk staking.Keeper - addrs []sdk.AccAddress - pubKeys []crypto.PubKey - privKeys []crypto.PrivKey -} - -func getMockApp(t *testing.T, numGenAccs int, genState types.GenesisState, genAccs []auth.Account) testInput { - mApp := mock.NewApp() - - staking.RegisterCodec(mApp.Cdc) - types.RegisterCodec(mApp.Cdc) - supply.RegisterCodec(mApp.Cdc) - - keyStaking := sdk.NewKVStoreKey(staking.StoreKey) - tKeyStaking := sdk.NewTransientStoreKey(staking.TStoreKey) - keyGov := sdk.NewKVStoreKey(types.StoreKey) - keySupply := sdk.NewKVStoreKey(supply.StoreKey) - - pk := mApp.ParamsKeeper - - rtr := types.NewRouter(). - AddRoute(types.RouterKey, types.ProposalHandler) - - bk := bank.NewBaseKeeper(mApp.AccountKeeper, mApp.ParamsKeeper.Subspace(bank.DefaultParamspace), bank.DefaultCodespace) - - supplyKeeper := supply.NewKeeper(mApp.Cdc, keySupply, mApp.AccountKeeper, bk, supply.DefaultCodespace, - []string{}, []string{}, []string{types.ModuleName, staking.NotBondedPoolName, staking.BondedPoolName}) - sk := staking.NewKeeper(mApp.Cdc, keyStaking, tKeyStaking, supplyKeeper, pk.Subspace(staking.DefaultParamspace), staking.DefaultCodespace) + Addrs = createTestAddrs(500) + PKs = createTestPubKeys(500) - keeper := NewKeeper(mApp.Cdc, keyGov, pk.Subspace("testgov"), supplyKeeper, sk, types.DefaultCodespace, rtr) - - mApp.Router().AddRoute(types.RouterKey, types.NewHandler(keeper)) - mApp.QueryRouter().AddRoute(types.QuerierRoute, NewQuerier(keeper)) - - mApp.SetEndBlocker(getEndBlocker(keeper)) - mApp.SetInitChainer(getInitChainer(mApp, keeper, sk, supplyKeeper, genAccs, genState)) - - require.NoError(t, mApp.CompleteSetup(keyStaking, tKeyStaking, keyGov, keySupply)) - - var ( - addrs []sdk.AccAddress - pubKeys []crypto.PubKey - privKeys []crypto.PrivKey - ) - - if genAccs == nil || len(genAccs) == 0 { - genAccs, addrs, pubKeys, privKeys = mock.CreateGenAccounts(numGenAccs, valCoins) + addrDels = []sdk.AccAddress{ + Addrs[0], + Addrs[1], } - - mock.SetGenesis(mApp, genAccs) - - return testInput{mApp, keeper, rtr, sk, addrs, pubKeys, privKeys} -} - -// gov and staking endblocker -func getEndBlocker(keeper Keeper) sdk.EndBlocker { - return func(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { - EndBlocker(ctx, keeper) - return abci.ResponseEndBlock{} + addrVals = []sdk.ValAddress{ + sdk.ValAddress(Addrs[2]), + sdk.ValAddress(Addrs[3]), + sdk.ValAddress(Addrs[4]), + sdk.ValAddress(Addrs[5]), + sdk.ValAddress(Addrs[6]), } -} -// gov and staking initchainer -func getInitChainer(mapp *mock.App, keeper Keeper, stakingKeeper staking.Keeper, supplyKeeper supply.Keeper, accs []auth.Account, genState types.GenesisState) sdk.InitChainer { - return func(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain { - mapp.InitChainer(ctx, req) - - stakingGenesis := staking.DefaultGenesisState() - - totalSupply := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, initTokens.MulRaw(int64(len(mapp.GenesisAccounts))))) - supplyKeeper.SetSupply(ctx, supply.NewSupply(totalSupply)) - - // set module accounts - govAcc := supply.NewEmptyModuleAccount(types.ModuleName, supply.Burner) - notBondedPool := supply.NewEmptyModuleAccount(staking.NotBondedPoolName, supply.Burner) - bondPool := supply.NewEmptyModuleAccount(staking.BondedPoolName, supply.Burner) - - supplyKeeper.SetModuleAccount(ctx, govAcc) - supplyKeeper.SetModuleAccount(ctx, notBondedPool) - supplyKeeper.SetModuleAccount(ctx, bondPool) - - validators := staking.InitGenesis(ctx, stakingKeeper, mapp.AccountKeeper, supplyKeeper, stakingGenesis) - if genState.IsEmpty() { - InitGenesis(ctx, keeper, supplyKeeper, types.DefaultGenesisState()) - } else { - InitGenesis(ctx, keeper, supplyKeeper, genState) - } - return abci.ResponseInitChain{ - Validators: validators, - } + TestAddrs = []sdk.AccAddress{ + addrDels[0], addrDels[1], addrDels[2], + addrVals[0], addrVals[1], addrVals[2], } -} - -// Sorts Addresses -func SortAddresses(addrs []sdk.AccAddress) { - var byteAddrs [][]byte - for _, addr := range addrs { - byteAddrs = append(byteAddrs, addr.Bytes()) - } - SortByteArrays(byteAddrs) - for i, byteAddr := range byteAddrs { - addrs[i] = byteAddr - } -} - -// implement `Interface` in sort package. -type sortByteArrays [][]byte - -func (b sortByteArrays) Len() int { - return len(b) -} +) -func (b sortByteArrays) Less(i, j int) bool { - // bytes package already implements Comparable for []byte. - switch bytes.Compare(b[i], b[j]) { - case -1: - return true - case 0, 1: - return false - default: - log.Panic("not fail-able with `bytes.Comparable` bounded [-1, 1].") - return false - } +// nolint: deadcode unused +func makeTestCodec() *codec.Codec { + var cdc = codec.New() + auth.RegisterCodec(cdc) + types.RegisterCodec(cdc) + supply.RegisterCodec(cdc) + staking.RegisterCodec(cdc) + sdk.RegisterCodec(cdc) + codec.RegisterCrypto(cdc) + + return cdc } -func (b sortByteArrays) Swap(i, j int) { - b[j], b[i] = b[i], b[j] -} +// nolint: deadcode unused +func createTestInput(t *testing.T, isCheckTx bool, initPower int64) (sdk.Context, auth.AccountKeeper, Keeper, types.SupplyKeeper) { -// Public -func SortByteArrays(src [][]byte) [][]byte { - sorted := sortByteArrays(src) - sort.Sort(sorted) - return sorted -} +// FIXME: update tests -func testProposal() types.Content { - return types.NewTextProposal("Test", "description") -} + initTokens := sdk.TokensFromConsensusPower(initPower) -const contextKeyBadProposal = "contextKeyBadProposal" + keyAcc := sdk.NewKVStoreKey(auth.StoreKey) + keyGov:= sdk.NewKVStoreKey(types.StoreKey) + keySupply := sdk.NewKVStoreKey(supply.StoreKey) + keyParams := sdk.NewKVStoreKey(params.StoreKey) + tkeyParams := sdk.NewTransientStoreKey(params.TStoreKey) + + db := dbm.NewMemDB() + ms := store.NewCommitMultiStore(db) + + ms.MountStoreWithDB(keySupply, sdk.StoreTypeIAVL, db) + ms.MountStoreWithDB(keyGov, sdk.StoreTypeIAVL, db) + ms.MountStoreWithDB(keyAcc, sdk.StoreTypeIAVL, db) + ms.MountStoreWithDB(keyParams, sdk.StoreTypeIAVL, db) + ms.MountStoreWithDB(tkeyParams, sdk.StoreTypeTransient, db) + require.Nil(t, ms.LoadLatestVersion()) + + + ctx := sdk.NewContext(ms, abci.Header{ChainID: "gov-chain"}, isCheckTx, log.NewNopLogger()) + ctx = ctx.WithConsensusParams( + &abci.ConsensusParams{ + Validator: &abci.ValidatorParams{ + PubKeyTypes: []string{tmtypes.ABCIPubKeyTypeEd25519}, + }, + }, + ) + cdc := makeTestCodec() -// badProposalHandler implements a governance proposal handler that is identical -// to the actual handler except this fails if the context doesn't contain a value -// for the key contextKeyBadProposal or if the value is false. -func badProposalHandler(ctx sdk.Context, c types.Content) sdk.Error { - switch c.ProposalType() { - case types.ProposalTypeText, types.ProposalTypeSoftwareUpgrade: - v := ctx.Value(contextKeyBadProposal) + pk := params.NewKeeper(cdc, keyParams, tkeyParams, params.DefaultCodespace) + accountKeeper := auth.NewAccountKeeper(cdc, keyAcc, pk.Subspace(auth.DefaultParamspace), auth.ProtoBaseAccount) + bankKeeper := bank.NewBaseKeeper(accountKeeper, pk.Subspace(bank.DefaultParamspace), bank.DefaultCodespace) + supplyKeeper := supply.NewKeeper(cdc, keySupply, accountKeeper, bankKeeper, supply.DefaultCodespace, + []string{auth.FeeCollectorName}, []string{}, []string{types.ModuleName}) - if v == nil || !v.(bool) { - return sdk.ErrInternal("proposal failed") - } + sk := staking.NewKeeper(cdc, keyStaking, tkeyStaking, supplyKeeper, pk.Subspace(staking.DefaultParamspace), staking.DefaultCodespace) + sk.SetParams(ctx, staking.DefaultParams()) - return nil + rtr := types.NewRouter(). + AddRoute(types.RouterKey, types.ProposalHandler) - default: - errMsg := fmt.Sprintf("unrecognized gov proposal type: %s", c.ProposalType()) - return sdk.ErrUnknownRequest(errMsg) - } -} + keeper := keep.NewKeeper(mApp.Cdc, keyGov, pk.Subspace(types.DefaultParamspace), supplyKeeper, sk, types.DefaultCodespace, rtr) -// ProposalEqual checks if two proposals are equal (note: slow, for tests only) -func ProposalEqual(proposalA types.Proposal, proposalB types.Proposal) bool { - return bytes.Equal(types.ModuleCdc.MustMarshalBinaryBare(proposalA), - types.ModuleCdc.MustMarshalBinaryBare(proposalB)) -} + initCoins := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), initTokens)) + totalSupply := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), initTokens.MulRaw(int64(len(TestAddrs))))) + supplyKeeper.SetSupply(ctx, supply.NewSupply(totalSupply)) -var ( - pubkeys = []crypto.PubKey{ - ed25519.GenPrivKey().PubKey(), - ed25519.GenPrivKey().PubKey(), - ed25519.GenPrivKey().PubKey(), + for _, addr := range TestAddrs { + _, err := bankKeeper.AddCoins(ctx, addr, initCoins) + require.Nil(t, err) } - testDescription = staking.NewDescription("T", "E", "S", "T") - testCommissionRates = staking.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()) -) - -func createValidators(t *testing.T, stakingHandler sdk.Handler, ctx sdk.Context, addrs []sdk.ValAddress, powerAmt []int64) { - require.True(t, len(addrs) <= len(pubkeys), "Not enough pubkeys specified at top of file.") + // create module accounts + feeCollectorAcc := supply.NewEmptyModuleAccount(auth.FeeCollectorName, supply.Basic) + govAcc := supply.NewEmptyModuleAccount(types.ModuleName, supply.Burner) - for i := 0; i < len(addrs); i++ { + keeper.supplyKeeper.SetModuleAccount(ctx, feeCollectorAcc) + keeper.supplyKeeper.SetModuleAccount(ctx, govAcc) - valTokens := sdk.TokensFromConsensusPower(powerAmt[i]) - valCreateMsg := staking.NewMsgCreateValidator( - addrs[i], pubkeys[i], sdk.NewCoin(sdk.DefaultBondDenom, valTokens), - testDescription, testCommissionRates, sdk.OneInt(), - ) - res := stakingHandler(ctx, valCreateMsg) - require.True(t, res.IsOK()) - } + return ctx, accountKeeper, keeper, supplyKeeper } + diff --git a/x/gov/keeper/vote.go b/x/gov/keeper/vote.go index c8443f5c0514..5ca322dbc613 100644 --- a/x/gov/keeper/vote.go +++ b/x/gov/keeper/vote.go @@ -22,7 +22,7 @@ func (keeper Keeper) AddVote(ctx sdk.Context, proposalID uint64, voterAddr sdk.A } vote := types.NewVote(proposalID, voterAddr, option) - keeper.setVote(ctx, proposalID, voterAddr, vote) + keeper.SetVote(ctx, vote) ctx.EventManager().EmitEvent( sdk.NewEvent( @@ -65,10 +65,11 @@ func (keeper Keeper) GetVote(ctx sdk.Context, proposalID uint64, voterAddr sdk.A return vote, true } -func (keeper Keeper) setVote(ctx sdk.Context, proposalID uint64, voterAddr sdk.AccAddress, vote types.Vote) { +// SetVote sets a Vote to the gov store +func (keeper Keeper) SetVote(ctx sdk.Context, vote types.Vote) { store := ctx.KVStore(keeper.storeKey) bz := keeper.cdc.MustMarshalBinaryLengthPrefixed(vote) - store.Set(types.VoteKey(proposalID, voterAddr), bz) + store.Set(types.VoteKey(vote.ProposalID, vote.Voter), bz) } // GetVotesIterator gets all the votes on a specific proposal as an sdk.Iterator diff --git a/x/gov/test_common.go b/x/gov/test_common.go new file mode 100644 index 000000000000..93e9b3597836 --- /dev/null +++ b/x/gov/test_common.go @@ -0,0 +1,231 @@ +// nolint:deadcode unused +package gov + +import ( + "bytes" + "fmt" + "log" + "sort" + "testing" + + "github.com/stretchr/testify/require" + "github.com/tendermint/tendermint/crypto/ed25519" + + abci "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/crypto" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/bank" + "github.com/cosmos/cosmos-sdk/x/gov/types" + keep "github.com/cosmos/cosmos-sdk/x/gov/keeper" + "github.com/cosmos/cosmos-sdk/x/mock" + "github.com/cosmos/cosmos-sdk/x/staking" + "github.com/cosmos/cosmos-sdk/x/supply" +) + +var ( + valTokens = sdk.TokensFromConsensusPower(42) + initTokens = sdk.TokensFromConsensusPower(100000) + valCoins = sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, valTokens)) + initCoins = sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, initTokens)) +) + +type testInput struct { + mApp *mock.App + keeper keep.Keeper + router types.Router + sk staking.Keeper + addrs []sdk.AccAddress + pubKeys []crypto.PubKey + privKeys []crypto.PrivKey +} + +func getMockApp(t *testing.T, numGenAccs int, genState types.GenesisState, genAccs []auth.Account) testInput { + mApp := mock.NewApp() + + staking.RegisterCodec(mApp.Cdc) + types.RegisterCodec(mApp.Cdc) + supply.RegisterCodec(mApp.Cdc) + + keyStaking := sdk.NewKVStoreKey(staking.StoreKey) + tKeyStaking := sdk.NewTransientStoreKey(staking.TStoreKey) + keyGov := sdk.NewKVStoreKey(types.StoreKey) + keySupply := sdk.NewKVStoreKey(supply.StoreKey) + + pk := mApp.ParamsKeeper + + rtr := types.NewRouter(). + AddRoute(types.RouterKey, types.ProposalHandler) + + bk := bank.NewBaseKeeper(mApp.AccountKeeper, mApp.ParamsKeeper.Subspace(bank.DefaultParamspace), bank.DefaultCodespace) + + supplyKeeper := supply.NewKeeper(mApp.Cdc, keySupply, mApp.AccountKeeper, bk, supply.DefaultCodespace, + []string{}, []string{}, []string{types.ModuleName, staking.NotBondedPoolName, staking.BondedPoolName}) + sk := staking.NewKeeper(mApp.Cdc, keyStaking, tKeyStaking, supplyKeeper, pk.Subspace(staking.DefaultParamspace), staking.DefaultCodespace) + + keeper := keep.NewKeeper(mApp.Cdc, keyGov, pk.Subspace("testgov"), supplyKeeper, sk, types.DefaultCodespace, rtr) + + mApp.Router().AddRoute(types.RouterKey, NewHandler(keeper)) + mApp.QueryRouter().AddRoute(types.QuerierRoute, keep.NewQuerier(keeper)) + + mApp.SetEndBlocker(getEndBlocker(keeper)) + mApp.SetInitChainer(getInitChainer(mApp, keeper, sk, supplyKeeper, genAccs, genState)) + + require.NoError(t, mApp.CompleteSetup(keyStaking, tKeyStaking, keyGov, keySupply)) + + var ( + addrs []sdk.AccAddress + pubKeys []crypto.PubKey + privKeys []crypto.PrivKey + ) + + if genAccs == nil || len(genAccs) == 0 { + genAccs, addrs, pubKeys, privKeys = mock.CreateGenAccounts(numGenAccs, valCoins) + } + + mock.SetGenesis(mApp, genAccs) + + return testInput{mApp, keeper, rtr, sk, addrs, pubKeys, privKeys} +} + +// gov and staking endblocker +func getEndBlocker(keeper Keeper) sdk.EndBlocker { + return func(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { + EndBlocker(ctx, keeper) + return abci.ResponseEndBlock{} + } +} + +// gov and staking initchainer +func getInitChainer(mapp *mock.App, keeper Keeper, stakingKeeper staking.Keeper, supplyKeeper supply.Keeper, accs []auth.Account, genState types.GenesisState) sdk.InitChainer { + return func(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain { + mapp.InitChainer(ctx, req) + + stakingGenesis := staking.DefaultGenesisState() + + totalSupply := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, initTokens.MulRaw(int64(len(mapp.GenesisAccounts))))) + supplyKeeper.SetSupply(ctx, supply.NewSupply(totalSupply)) + + // set module accounts + govAcc := supply.NewEmptyModuleAccount(types.ModuleName, supply.Burner) + notBondedPool := supply.NewEmptyModuleAccount(staking.NotBondedPoolName, supply.Burner) + bondPool := supply.NewEmptyModuleAccount(staking.BondedPoolName, supply.Burner) + + supplyKeeper.SetModuleAccount(ctx, govAcc) + supplyKeeper.SetModuleAccount(ctx, notBondedPool) + supplyKeeper.SetModuleAccount(ctx, bondPool) + + validators := staking.InitGenesis(ctx, stakingKeeper, mapp.AccountKeeper, supplyKeeper, stakingGenesis) + if genState.IsEmpty() { + InitGenesis(ctx, keeper, supplyKeeper, types.DefaultGenesisState()) + } else { + InitGenesis(ctx, keeper, supplyKeeper, genState) + } + return abci.ResponseInitChain{ + Validators: validators, + } + } +} + +// Sorts Addresses +func SortAddresses(addrs []sdk.AccAddress) { + var byteAddrs [][]byte + for _, addr := range addrs { + byteAddrs = append(byteAddrs, addr.Bytes()) + } + SortByteArrays(byteAddrs) + for i, byteAddr := range byteAddrs { + addrs[i] = byteAddr + } +} + +// implement `Interface` in sort package. +type sortByteArrays [][]byte + +func (b sortByteArrays) Len() int { + return len(b) +} + +func (b sortByteArrays) Less(i, j int) bool { + // bytes package already implements Comparable for []byte. + switch bytes.Compare(b[i], b[j]) { + case -1: + return true + case 0, 1: + return false + default: + log.Panic("not fail-able with `bytes.Comparable` bounded [-1, 1].") + return false + } +} + +func (b sortByteArrays) Swap(i, j int) { + b[j], b[i] = b[i], b[j] +} + +// Public +func SortByteArrays(src [][]byte) [][]byte { + sorted := sortByteArrays(src) + sort.Sort(sorted) + return sorted +} + +func testProposal() types.Content { + return types.NewTextProposal("Test", "description") +} + +const contextKeyBadProposal = "contextKeyBadProposal" + +// badProposalHandler implements a governance proposal handler that is identical +// to the actual handler except this fails if the context doesn't contain a value +// for the key contextKeyBadProposal or if the value is false. +func badProposalHandler(ctx sdk.Context, c types.Content) sdk.Error { + switch c.ProposalType() { + case types.ProposalTypeText, types.ProposalTypeSoftwareUpgrade: + v := ctx.Value(contextKeyBadProposal) + + if v == nil || !v.(bool) { + return sdk.ErrInternal("proposal failed") + } + + return nil + + default: + errMsg := fmt.Sprintf("unrecognized gov proposal type: %s", c.ProposalType()) + return sdk.ErrUnknownRequest(errMsg) + } +} + +// ProposalEqual checks if two proposals are equal (note: slow, for tests only) +func ProposalEqual(proposalA types.Proposal, proposalB types.Proposal) bool { + return bytes.Equal(types.ModuleCdc.MustMarshalBinaryBare(proposalA), + types.ModuleCdc.MustMarshalBinaryBare(proposalB)) +} + +var ( + pubkeys = []crypto.PubKey{ + ed25519.GenPrivKey().PubKey(), + ed25519.GenPrivKey().PubKey(), + ed25519.GenPrivKey().PubKey(), + } + + testDescription = staking.NewDescription("T", "E", "S", "T") + testCommissionRates = staking.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()) +) + +func createValidators(t *testing.T, stakingHandler sdk.Handler, ctx sdk.Context, addrs []sdk.ValAddress, powerAmt []int64) { + require.True(t, len(addrs) <= len(pubkeys), "Not enough pubkeys specified at top of file.") + + for i := 0; i < len(addrs); i++ { + + valTokens := sdk.TokensFromConsensusPower(powerAmt[i]) + valCreateMsg := staking.NewMsgCreateValidator( + addrs[i], pubkeys[i], sdk.NewCoin(sdk.DefaultBondDenom, valTokens), + testDescription, testCommissionRates, sdk.OneInt(), + ) + + res := stakingHandler(ctx, valCreateMsg) + require.True(t, res.IsOK()) + } +} From 71034f5eac9228ec41748dac98ad93d72867430e Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Fri, 12 Jul 2019 12:43:36 +0200 Subject: [PATCH 07/36] updates --- x/gov/abci_test.go | 7 ++-- x/gov/handler.go | 6 ++- x/gov/keeper/keeper_test.go | 4 +- x/gov/keeper/proposal.go | 6 ++- x/gov/keeper/querier_test.go | 26 ++++++------- x/gov/keeper/tally_test.go | 56 ++++++++++++++-------------- x/gov/keeper/test_common.go | 71 +++++++++++++++++++++++------------- x/gov/test_common.go | 2 +- 8 files changed, 103 insertions(+), 75 deletions(-) diff --git a/x/gov/abci_test.go b/x/gov/abci_test.go index f197ae85a258..18a9a84933c4 100644 --- a/x/gov/abci_test.go +++ b/x/gov/abci_test.go @@ -154,7 +154,7 @@ func TestTickPassedDepositPeriod(t *testing.T) { res := govHandler(ctx, newProposalMsg) require.True(t, res.IsOK()) var proposalID uint64 - input.keeper.cdc.MustUnmarshalBinaryLengthPrefixed(res.Data, &proposalID) + input.mApp.Cdc.MustUnmarshalBinaryLengthPrefixed(res.Data, &proposalID) inactiveQueue = input.keeper.InactiveProposalQueueIterator(ctx, ctx.BlockHeader().Time) require.False(t, inactiveQueue.Valid()) @@ -200,7 +200,7 @@ func TestTickPassedVotingPeriod(t *testing.T) { res := govHandler(ctx, newProposalMsg) require.True(t, res.IsOK()) var proposalID uint64 - input.keeper.cdc.MustUnmarshalBinaryLengthPrefixed(res.Data, &proposalID) + input.mApp.Cdc.MustUnmarshalBinaryLengthPrefixed(res.Data, &proposalID) newHeader := ctx.BlockHeader() newHeader.Time = ctx.BlockHeader().Time.Add(time.Duration(1) * time.Second) @@ -223,7 +223,7 @@ func TestTickPassedVotingPeriod(t *testing.T) { var activeProposalID uint64 - require.NoError(t, input.keeper.cdc.UnmarshalBinaryLengthPrefixed(activeQueue.Value(), &activeProposalID)) + require.NoError(t, input.mApp.Cdc.UnmarshalBinaryLengthPrefixed(activeQueue.Value(), &activeProposalID)) proposal, ok := input.keeper.GetProposal(ctx, activeProposalID) require.True(t, ok) require.Equal(t, StatusVotingPeriod, proposal.Status) @@ -293,6 +293,7 @@ func TestEndBlockerProposalHandlerFailed(t *testing.T) { SortAddresses(input.addrs) // hijack the router to one that will fail in a proposal's handler + // TODO: set router or add route input.keeper.router = NewRouter().AddRoute(RouterKey, badProposalHandler) handler := NewHandler(input.keeper) diff --git a/x/gov/handler.go b/x/gov/handler.go index 197194353f5e..83606c3eb4cc 100644 --- a/x/gov/handler.go +++ b/x/gov/handler.go @@ -1,6 +1,7 @@ package gov import ( + "encoding/binary" "fmt" sdk "github.com/cosmos/cosmos-sdk/types" @@ -57,8 +58,11 @@ func handleMsgSubmitProposal(ctx sdk.Context, keeper Keeper, msg MsgSubmitPropos ) } + proposalIDBz := make([]byte, 8) + binary.LittleEndian.PutUint64(proposalIDBz, proposal.ProposalID) + return sdk.Result{ - // Data: keeper.cdc.MustMarshalBinaryLengthPrefixed(proposal.ProposalID), + Data: proposalIDBz, Events: ctx.EventManager().Events(), } } diff --git a/x/gov/keeper/keeper_test.go b/x/gov/keeper/keeper_test.go index 0aa3a0014d05..dd512f9aabd0 100644 --- a/x/gov/keeper/keeper_test.go +++ b/x/gov/keeper/keeper_test.go @@ -335,7 +335,7 @@ func TestSubmitProposal(t *testing.T) { input.mApp.InitChainer(ctx, abci.RequestInitChain{}) testCases := []struct { - content Content + content types.Content expectedErr sdk.Error }{ {validProposal{}, nil}, @@ -345,7 +345,7 @@ func TestSubmitProposal(t *testing.T) { {invalidProposalDesc1{}, nil}, {invalidProposalDesc2{}, nil}, // error only when invalid route - {invalidProposalRoute{}, ErrNoProposalHandlerExists(DefaultCodespace, invalidProposalRoute{})}, + {invalidProposalRoute{}, types.ErrNoProposalHandlerExists(types.DefaultCodespace, invalidProposalRoute{})}, // Keeper does not call ValidateBasic, msg.ValidateBasic does {invalidProposalValidation{}, nil}, } diff --git a/x/gov/keeper/proposal.go b/x/gov/keeper/proposal.go index 99af0c46470c..34d456eae293 100644 --- a/x/gov/keeper/proposal.go +++ b/x/gov/keeper/proposal.go @@ -1,6 +1,7 @@ package keeper import ( + "encoding/binary" "fmt" sdk "github.com/cosmos/cosmos-sdk/types" @@ -139,14 +140,15 @@ func (keeper Keeper) GetProposalID(ctx sdk.Context) (proposalID uint64, err sdk. if bz == nil { return 0, types.ErrInvalidGenesis(keeper.codespace, "initial proposal ID hasn't been set") } - keeper.cdc.MustUnmarshalBinaryLengthPrefixed(bz, &proposalID) + proposalID = binary.LittleEndian.Uint64(bz) return proposalID, nil } // SetProposalID sets the new proposal ID to the store func (keeper Keeper) SetProposalID(ctx sdk.Context, proposalID uint64) { store := ctx.KVStore(keeper.storeKey) - bz := keeper.cdc.MustMarshalBinaryLengthPrefixed(proposalID) + bz := make([]byte, 8) + binary.LittleEndian.PutUint64(bz, proposalID) store.Set(types.ProposalIDKey, bz) } diff --git a/x/gov/keeper/querier_test.go b/x/gov/keeper/querier_test.go index 51a4187500c7..ddfa69ee0f09 100644 --- a/x/gov/keeper/querier_test.go +++ b/x/gov/keeper/querier_test.go @@ -60,7 +60,7 @@ func getQueriedParams(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier s func getQueriedProposal(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier, proposalID uint64) types.Proposal { query := abci.RequestQuery{ Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryProposal}, "/"), - Data: cdc.MustMarshalJSON(NewQueryProposalParams(proposalID)), + Data: cdc.MustMarshalJSON(types.NewQueryProposalParams(proposalID)), } bz, err := querier(ctx, []string{types.QueryProposal}, query) @@ -76,14 +76,14 @@ func getQueriedProposal(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier func getQueriedProposals(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier, depositor, voter sdk.AccAddress, status types.ProposalStatus, limit uint64) []types.Proposal { query := abci.RequestQuery{ Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryProposals}, "/"), - Data: cdc.MustMarshalJSON(NewQueryProposalsParams(status, limit, voter, depositor)), + Data: cdc.MustMarshalJSON(types.NewQueryProposalsParams(status, limit, voter, depositor)), } bz, err := querier(ctx, []string{types.QueryProposals}, query) require.Nil(t, err) require.NotNil(t, bz) - var proposals Proposals + var proposals types.Proposals err2 := cdc.UnmarshalJSON(bz, &proposals) require.Nil(t, err2) return proposals @@ -92,7 +92,7 @@ func getQueriedProposals(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querie func getQueriedDeposit(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier, proposalID uint64, depositor sdk.AccAddress) types.Deposit { query := abci.RequestQuery{ Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryDeposit}, "/"), - Data: cdc.MustMarshalJSON(NewQueryDepositParams(proposalID, depositor)), + Data: cdc.MustMarshalJSON(types.NewQueryDepositParams(proposalID, depositor)), } bz, err := querier(ctx, []string{types.QueryDeposit}, query) @@ -107,11 +107,11 @@ func getQueriedDeposit(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier func getQueriedDeposits(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier, proposalID uint64) []types.Deposit { query := abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, types.types.QueryDeposits}, "/"), - Data: cdc.MustMarshalJSON(NewQueryProposalParams(proposalID)), + Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryDeposits}, "/"), + Data: cdc.MustMarshalJSON(types.NewQueryProposalParams(proposalID)), } - bz, err := querier(ctx, []string{types.types.QueryDeposits}, query) + bz, err := querier(ctx, []string{types.QueryDeposits}, query) require.Nil(t, err) require.NotNil(t, bz) @@ -124,7 +124,7 @@ func getQueriedDeposits(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier func getQueriedVote(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier, proposalID uint64, voter sdk.AccAddress) types.Vote { query := abci.RequestQuery{ Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryVote}, "/"), - Data: cdc.MustMarshalJSON(NewQueryVoteParams(proposalID, voter)), + Data: cdc.MustMarshalJSON(types.NewQueryVoteParams(proposalID, voter)), } bz, err := querier(ctx, []string{types.QueryVote}, query) @@ -140,10 +140,10 @@ func getQueriedVote(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk func getQueriedVotes(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier, proposalID uint64) []types.Vote { query := abci.RequestQuery{ Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryVote}, "/"), - Data: cdc.MustMarshalJSON(NewQueryProposalParams(proposalID)), + Data: cdc.MustMarshalJSON(types.NewQueryProposalParams(proposalID)), } - bz, err := querier(ctx, []string{QueryVotes}, query) + bz, err := querier(ctx, []string{types.QueryVotes}, query) require.Nil(t, err) require.NotNil(t, bz) @@ -153,17 +153,17 @@ func getQueriedVotes(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sd return votes } -func getQueriedTally(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier, proposalID uint64) TallyResult { +func getQueriedTally(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier, proposalID uint64) types.TallyResult { query := abci.RequestQuery{ Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryTally}, "/"), - Data: cdc.MustMarshalJSON(NewQueryProposalParams(proposalID)), + Data: cdc.MustMarshalJSON(types.NewQueryProposalParams(proposalID)), } bz, err := querier(ctx, []string{types.QueryTally}, query) require.Nil(t, err) require.NotNil(t, bz) - var tally TallyResult + var tally types.TallyResult err2 := cdc.UnmarshalJSON(bz, &tally) require.Nil(t, err2) return tally diff --git a/x/gov/keeper/tally_test.go b/x/gov/keeper/tally_test.go index 400bce4c75bd..ecdacf76b445 100644 --- a/x/gov/keeper/tally_test.go +++ b/x/gov/keeper/tally_test.go @@ -14,7 +14,7 @@ import ( ) func TestTallyNoOneVotes(t *testing.T) { - input := getMockApp(t, 10, GenesisState{}, nil) + input := getMockApp(t, 10, types.GenesisState{}, nil) header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) @@ -39,7 +39,7 @@ func TestTallyNoOneVotes(t *testing.T) { proposal, ok := input.keeper.GetProposal(ctx, proposalID) require.True(t, ok) - passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) + passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) require.False(t, passes) require.True(t, burnDeposits) @@ -47,7 +47,7 @@ func TestTallyNoOneVotes(t *testing.T) { } func TestTallyNoQuorum(t *testing.T) { - input := getMockApp(t, 10, GenesisState{}, nil) + input := getMockApp(t, 10, types.GenesisState{}, nil) header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) @@ -75,13 +75,13 @@ func TestTallyNoQuorum(t *testing.T) { proposal, ok := input.keeper.GetProposal(ctx, proposalID) require.True(t, ok) - passes, burnDeposits, _ := input.keeper.Tally(ctx, proposal) + passes, burnDeposits, _ := input.keeper.Tally(ctx, proposal) require.False(t, passes) require.True(t, burnDeposits) } func TestTallyOnlyValidatorsAllYes(t *testing.T) { - input := getMockApp(t, 10, GenesisState{}, nil) + input := getMockApp(t, 10, types.GenesisState{}, nil) header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) @@ -111,7 +111,7 @@ func TestTallyOnlyValidatorsAllYes(t *testing.T) { proposal, ok := input.keeper.GetProposal(ctx, proposalID) require.True(t, ok) - passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) + passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) require.True(t, passes) require.False(t, burnDeposits) @@ -119,7 +119,7 @@ func TestTallyOnlyValidatorsAllYes(t *testing.T) { } func TestTallyOnlyValidators51No(t *testing.T) { - input := getMockApp(t, 10, GenesisState{}, nil) + input := getMockApp(t, 10, types.GenesisState{}, nil) header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) @@ -149,14 +149,14 @@ func TestTallyOnlyValidators51No(t *testing.T) { proposal, ok := input.keeper.GetProposal(ctx, proposalID) require.True(t, ok) - passes, burnDeposits, _ := input.keeper.Tally(ctx, proposal) + passes, burnDeposits, _ := input.keeper.Tally(ctx, proposal) require.False(t, passes) require.False(t, burnDeposits) } func TestTallyOnlyValidators51Yes(t *testing.T) { - input := getMockApp(t, 10, GenesisState{}, nil) + input := getMockApp(t, 10, types.GenesisState{}, nil) header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) @@ -188,7 +188,7 @@ func TestTallyOnlyValidators51Yes(t *testing.T) { proposal, ok := input.keeper.GetProposal(ctx, proposalID) require.True(t, ok) - passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) + passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) require.True(t, passes) require.False(t, burnDeposits) @@ -196,7 +196,7 @@ func TestTallyOnlyValidators51Yes(t *testing.T) { } func TestTallyOnlyValidatorsVetoed(t *testing.T) { - input := getMockApp(t, 10, GenesisState{}, nil) + input := getMockApp(t, 10, types.GenesisState{}, nil) header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) @@ -228,7 +228,7 @@ func TestTallyOnlyValidatorsVetoed(t *testing.T) { proposal, ok := input.keeper.GetProposal(ctx, proposalID) require.True(t, ok) - passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) + passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) require.False(t, passes) require.True(t, burnDeposits) @@ -237,7 +237,7 @@ func TestTallyOnlyValidatorsVetoed(t *testing.T) { } func TestTallyOnlyValidatorsAbstainPasses(t *testing.T) { - input := getMockApp(t, 10, GenesisState{}, nil) + input := getMockApp(t, 10, types.GenesisState{}, nil) header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) @@ -269,7 +269,7 @@ func TestTallyOnlyValidatorsAbstainPasses(t *testing.T) { proposal, ok := input.keeper.GetProposal(ctx, proposalID) require.True(t, ok) - passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) + passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) require.True(t, passes) require.False(t, burnDeposits) @@ -277,7 +277,7 @@ func TestTallyOnlyValidatorsAbstainPasses(t *testing.T) { } func TestTallyOnlyValidatorsAbstainFails(t *testing.T) { - input := getMockApp(t, 10, GenesisState{}, nil) + input := getMockApp(t, 10, types.GenesisState{}, nil) header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) @@ -309,7 +309,7 @@ func TestTallyOnlyValidatorsAbstainFails(t *testing.T) { proposal, ok := input.keeper.GetProposal(ctx, proposalID) require.True(t, ok) - passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) + passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) require.False(t, passes) require.False(t, burnDeposits) @@ -317,7 +317,7 @@ func TestTallyOnlyValidatorsAbstainFails(t *testing.T) { } func TestTallyOnlyValidatorsNonVoter(t *testing.T) { - input := getMockApp(t, 10, GenesisState{}, nil) + input := getMockApp(t, 10, types.GenesisState{}, nil) header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) @@ -347,7 +347,7 @@ func TestTallyOnlyValidatorsNonVoter(t *testing.T) { proposal, ok := input.keeper.GetProposal(ctx, proposalID) require.True(t, ok) - passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) + passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) require.False(t, passes) require.False(t, burnDeposits) @@ -355,7 +355,7 @@ func TestTallyOnlyValidatorsNonVoter(t *testing.T) { } func TestTallyDelgatorOverride(t *testing.T) { - input := getMockApp(t, 10, GenesisState{}, nil) + input := getMockApp(t, 10, types.GenesisState{}, nil) header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) @@ -393,7 +393,7 @@ func TestTallyDelgatorOverride(t *testing.T) { proposal, ok := input.keeper.GetProposal(ctx, proposalID) require.True(t, ok) - passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) + passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) require.False(t, passes) require.False(t, burnDeposits) @@ -401,7 +401,7 @@ func TestTallyDelgatorOverride(t *testing.T) { } func TestTallyDelgatorInherit(t *testing.T) { - input := getMockApp(t, 10, GenesisState{}, nil) + input := getMockApp(t, 10, types.GenesisState{}, nil) header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) @@ -437,7 +437,7 @@ func TestTallyDelgatorInherit(t *testing.T) { proposal, ok := input.keeper.GetProposal(ctx, proposalID) require.True(t, ok) - passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) + passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) require.True(t, passes) require.False(t, burnDeposits) @@ -445,7 +445,7 @@ func TestTallyDelgatorInherit(t *testing.T) { } func TestTallyDelgatorMultipleOverride(t *testing.T) { - input := getMockApp(t, 10, GenesisState{}, nil) + input := getMockApp(t, 10, types.GenesisState{}, nil) header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) @@ -485,7 +485,7 @@ func TestTallyDelgatorMultipleOverride(t *testing.T) { proposal, ok := input.keeper.GetProposal(ctx, proposalID) require.True(t, ok) - passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) + passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) require.False(t, passes) require.False(t, burnDeposits) @@ -493,7 +493,7 @@ func TestTallyDelgatorMultipleOverride(t *testing.T) { } func TestTallyDelgatorMultipleInherit(t *testing.T) { - input := getMockApp(t, 10, GenesisState{}, nil) + input := getMockApp(t, 10, types.GenesisState{}, nil) header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) @@ -544,7 +544,7 @@ func TestTallyDelgatorMultipleInherit(t *testing.T) { proposal, ok := input.keeper.GetProposal(ctx, proposalID) require.True(t, ok) - passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) + passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) require.False(t, passes) require.False(t, burnDeposits) @@ -552,7 +552,7 @@ func TestTallyDelgatorMultipleInherit(t *testing.T) { } func TestTallyJailedValidator(t *testing.T) { - input := getMockApp(t, 10, GenesisState{}, nil) + input := getMockApp(t, 10, types.GenesisState{}, nil) header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) @@ -597,7 +597,7 @@ func TestTallyJailedValidator(t *testing.T) { proposal, ok := input.keeper.GetProposal(ctx, proposalID) require.True(t, ok) - passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) + passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) require.True(t, passes) require.False(t, burnDeposits) diff --git a/x/gov/keeper/test_common.go b/x/gov/keeper/test_common.go index d0a351eb1751..9909fe858505 100644 --- a/x/gov/keeper/test_common.go +++ b/x/gov/keeper/test_common.go @@ -5,6 +5,9 @@ import ( "github.com/stretchr/testify/require" + "github.com/tendermint/tendermint/crypto" + "github.com/tendermint/tendermint/crypto/ed25519" + abci "github.com/tendermint/tendermint/abci/types" dbm "github.com/tendermint/tendermint/libs/db" "github.com/tendermint/tendermint/libs/log" @@ -15,8 +18,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/bank" - "github.com/cosmos/cosmos-sdk/x/params" "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/cosmos/cosmos-sdk/x/params" "github.com/cosmos/cosmos-sdk/x/staking" "github.com/cosmos/cosmos-sdk/x/supply" ) @@ -24,27 +27,40 @@ import ( // dummy addresses used for testing // nolint: unused deadcode var ( - Addrs = createTestAddrs(500) - PKs = createTestPubKeys(500) - - addrDels = []sdk.AccAddress{ - Addrs[0], - Addrs[1], - } - addrVals = []sdk.ValAddress{ - sdk.ValAddress(Addrs[2]), - sdk.ValAddress(Addrs[3]), - sdk.ValAddress(Addrs[4]), - sdk.ValAddress(Addrs[5]), - sdk.ValAddress(Addrs[6]), - } + delPk1 = ed25519.GenPrivKey().PubKey() + delPk2 = ed25519.GenPrivKey().PubKey() + delPk3 = ed25519.GenPrivKey().PubKey() + delAddr1 = sdk.AccAddress(delPk1.Address()) + delAddr2 = sdk.AccAddress(delPk2.Address()) + delAddr3 = sdk.AccAddress(delPk3.Address()) + + valOpPk1 = ed25519.GenPrivKey().PubKey() + valOpPk2 = ed25519.GenPrivKey().PubKey() + valOpPk3 = ed25519.GenPrivKey().PubKey() + valOpAddr1 = sdk.ValAddress(valOpPk1.Address()) + valOpAddr2 = sdk.ValAddress(valOpPk2.Address()) + valOpAddr3 = sdk.ValAddress(valOpPk3.Address()) + valAccAddr1 = sdk.AccAddress(valOpPk1.Address()) // generate acc addresses for these validator keys too + valAccAddr2 = sdk.AccAddress(valOpPk2.Address()) + valAccAddr3 = sdk.AccAddress(valOpPk3.Address()) TestAddrs = []sdk.AccAddress{ - addrDels[0], addrDels[1], addrDels[2], - addrVals[0], addrVals[1], addrVals[2], + delAddr1, delAddr2, delAddr3, + valAccAddr1, valAccAddr2, valAccAddr3, } + + emptyDelAddr sdk.AccAddress + emptyValAddr sdk.ValAddress + emptyPubkey crypto.PubKey ) +type testInput struct { + keeper Keeper + router types.Router + ak auth.AccountKeeper + sk types.StakingKeeper +} + // nolint: deadcode unused func makeTestCodec() *codec.Codec { var cdc = codec.New() @@ -61,12 +77,14 @@ func makeTestCodec() *codec.Codec { // nolint: deadcode unused func createTestInput(t *testing.T, isCheckTx bool, initPower int64) (sdk.Context, auth.AccountKeeper, Keeper, types.SupplyKeeper) { -// FIXME: update tests + // FIXME: update tests initTokens := sdk.TokensFromConsensusPower(initPower) keyAcc := sdk.NewKVStoreKey(auth.StoreKey) - keyGov:= sdk.NewKVStoreKey(types.StoreKey) + keyGov := sdk.NewKVStoreKey(types.StoreKey) + keyStaking := sdk.NewKVStoreKey(staking.StoreKey) + tkeyStaking := sdk.NewTransientStoreKey(staking.TStoreKey) keySupply := sdk.NewKVStoreKey(supply.StoreKey) keyParams := sdk.NewKVStoreKey(params.StoreKey) tkeyParams := sdk.NewTransientStoreKey(params.TStoreKey) @@ -81,7 +99,6 @@ func createTestInput(t *testing.T, isCheckTx bool, initPower int64) (sdk.Context ms.MountStoreWithDB(tkeyParams, sdk.StoreTypeTransient, db) require.Nil(t, ms.LoadLatestVersion()) - ctx := sdk.NewContext(ms, abci.Header{ChainID: "gov-chain"}, isCheckTx, log.NewNopLogger()) ctx = ctx.WithConsensusParams( &abci.ConsensusParams{ @@ -92,11 +109,17 @@ func createTestInput(t *testing.T, isCheckTx bool, initPower int64) (sdk.Context ) cdc := makeTestCodec() + maccPerms := map[string][]string{ + auth.FeeCollectorName: []string{supply.Basic}, + types.ModuleName: []string{supply.Basic}, + staking.NotBondedPoolName: []string{supply.Burner, supply.Staking}, + staking.BondedPoolName: []string{supply.Burner, supply.Staking}, + } + pk := params.NewKeeper(cdc, keyParams, tkeyParams, params.DefaultCodespace) accountKeeper := auth.NewAccountKeeper(cdc, keyAcc, pk.Subspace(auth.DefaultParamspace), auth.ProtoBaseAccount) bankKeeper := bank.NewBaseKeeper(accountKeeper, pk.Subspace(bank.DefaultParamspace), bank.DefaultCodespace) - supplyKeeper := supply.NewKeeper(cdc, keySupply, accountKeeper, bankKeeper, supply.DefaultCodespace, - []string{auth.FeeCollectorName}, []string{}, []string{types.ModuleName}) + supplyKeeper := supply.NewKeeper(cdc, keySupply, accountKeeper, bankKeeper, supply.DefaultCodespace, maccPerms) sk := staking.NewKeeper(cdc, keyStaking, tkeyStaking, supplyKeeper, pk.Subspace(staking.DefaultParamspace), staking.DefaultCodespace) sk.SetParams(ctx, staking.DefaultParams()) @@ -104,7 +127,7 @@ func createTestInput(t *testing.T, isCheckTx bool, initPower int64) (sdk.Context rtr := types.NewRouter(). AddRoute(types.RouterKey, types.ProposalHandler) - keeper := keep.NewKeeper(mApp.Cdc, keyGov, pk.Subspace(types.DefaultParamspace), supplyKeeper, sk, types.DefaultCodespace, rtr) + keeper := NewKeeper(cdc, keyGov, pk.Subspace(types.DefaultParamspace), supplyKeeper, sk, types.DefaultCodespace, rtr) initCoins := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), initTokens)) totalSupply := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), initTokens.MulRaw(int64(len(TestAddrs))))) @@ -122,7 +145,5 @@ func createTestInput(t *testing.T, isCheckTx bool, initPower int64) (sdk.Context keeper.supplyKeeper.SetModuleAccount(ctx, feeCollectorAcc) keeper.supplyKeeper.SetModuleAccount(ctx, govAcc) - return ctx, accountKeeper, keeper, supplyKeeper } - diff --git a/x/gov/test_common.go b/x/gov/test_common.go index 116d2e8f5512..ad1f72c58986 100644 --- a/x/gov/test_common.go +++ b/x/gov/test_common.go @@ -17,8 +17,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/bank" - "github.com/cosmos/cosmos-sdk/x/gov/types" keep "github.com/cosmos/cosmos-sdk/x/gov/keeper" + "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/cosmos/cosmos-sdk/x/mock" "github.com/cosmos/cosmos-sdk/x/staking" "github.com/cosmos/cosmos-sdk/x/supply" From 593f5a8feca4a734b0f46c5e2694166c700ff6d8 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Fri, 12 Jul 2019 14:48:12 +0200 Subject: [PATCH 08/36] more restructuring --- x/gov/abci_test.go | 7 +- x/gov/genesis_test.go | 9 +- x/gov/handler.go | 2 +- x/gov/keeper/deposit.go | 109 +++++---- x/gov/keeper/deposit_test.go | 108 +++++++++ x/gov/keeper/keeper.go | 118 +--------- x/gov/keeper/keeper_test.go | 344 ++------------------------- x/gov/keeper/params.go | 42 ++++ x/gov/keeper/proposal.go | 16 ++ x/gov/keeper/proposal_test.go | 122 ++++++++++ x/gov/keeper/querier_test.go | 47 ++-- x/gov/keeper/tally_test.go | 422 ++++++++++------------------------ x/gov/keeper/test_common.go | 25 +- x/gov/keeper/vote.go | 31 +++ x/gov/keeper/vote_test.go | 68 ++++++ x/gov/test_common.go | 12 +- x/gov/types/deposit.go | 2 +- x/gov/types/querier.go | 18 +- x/gov/types/router.go | 1 + x/gov/types/tally.go | 3 + 20 files changed, 654 insertions(+), 852 deletions(-) create mode 100644 x/gov/keeper/deposit_test.go create mode 100644 x/gov/keeper/params.go create mode 100644 x/gov/keeper/proposal_test.go create mode 100644 x/gov/keeper/vote_test.go diff --git a/x/gov/abci_test.go b/x/gov/abci_test.go index 18a9a84933c4..56b684624745 100644 --- a/x/gov/abci_test.go +++ b/x/gov/abci_test.go @@ -9,6 +9,7 @@ import ( abci "github.com/tendermint/tendermint/abci/types" sdk "github.com/cosmos/cosmos-sdk/types" + keep "github.com/cosmos/cosmos-sdk/x/gov/keeper" "github.com/cosmos/cosmos-sdk/x/staking" ) @@ -195,7 +196,7 @@ func TestTickPassedVotingPeriod(t *testing.T) { activeQueue.Close() proposalCoins := sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.TokensFromConsensusPower(5))} - newProposalMsg := NewMsgSubmitProposal(testProposal(), proposalCoins, input.addrs[0]) + newProposalMsg := NewMsgSubmitProposal(keep.TestProposal(), proposalCoins, input.addrs[0]) res := govHandler(ctx, newProposalMsg) require.True(t, res.IsOK()) @@ -259,7 +260,7 @@ func TestProposalPassedEndblocker(t *testing.T) { require.NotNil(t, macc) initialModuleAccCoins := macc.GetCoins() - proposal, err := input.keeper.SubmitProposal(ctx, testProposal()) + proposal, err := input.keeper.SubmitProposal(ctx, keep.TestProposal()) require.NoError(t, err) proposalCoins := sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.TokensFromConsensusPower(10))} @@ -311,7 +312,7 @@ func TestEndBlockerProposalHandlerFailed(t *testing.T) { // Create a proposal where the handler will pass for the test proposal // because the value of contextKeyBadProposal is true. ctx = ctx.WithValue(contextKeyBadProposal, true) - proposal, err := input.keeper.SubmitProposal(ctx, testProposal()) + proposal, err := input.keeper.SubmitProposal(ctx, keep.TestProposal()) require.NoError(t, err) proposalCoins := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.TokensFromConsensusPower(10))) diff --git a/x/gov/genesis_test.go b/x/gov/genesis_test.go index 7cf18f513a73..c8c0ef1641ab 100644 --- a/x/gov/genesis_test.go +++ b/x/gov/genesis_test.go @@ -3,6 +3,7 @@ package gov import ( "testing" + keep "github.com/cosmos/cosmos-sdk/x/gov/keeper" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" @@ -19,7 +20,7 @@ func TestImportExportQueues(t *testing.T) { ctx := input.mApp.BaseApp.NewContext(false, abci.Header{}) // Create two proposals, put the second into the voting period - proposal := testProposal() + proposal := keep.TestProposal() proposal1, err := input.keeper.SubmitProposal(ctx, proposal) require.NoError(t, err) proposalID1 := proposal1.ProposalID @@ -84,7 +85,7 @@ func TestEqualProposals(t *testing.T) { ctx := input.mApp.BaseApp.NewContext(false, abci.Header{}) // Submit two proposals - proposal := testProposal() + proposal := keep.TestProposal() proposal1, err := input.keeper.SubmitProposal(ctx, proposal) require.NoError(t, err) proposal2, err := input.keeper.SubmitProposal(ctx, proposal) @@ -92,7 +93,7 @@ func TestEqualProposals(t *testing.T) { // They are similar but their IDs should be different require.NotEqual(t, proposal1, proposal2) - require.False(t, ProposalEqual(proposal1, proposal2)) + require.False(t, keep.ProposalEqual(proposal1, proposal2)) // Now create two genesis blocks state1 := GenesisState{Proposals: []Proposal{proposal1}} @@ -104,7 +105,7 @@ func TestEqualProposals(t *testing.T) { proposal1.ProposalID = 55 proposal2.ProposalID = 55 require.Equal(t, proposal1, proposal1) - require.True(t, ProposalEqual(proposal1, proposal2)) + require.True(t, keep.ProposalEqual(proposal1, proposal2)) // Reassign proposals into state state1.Proposals[0] = proposal1 diff --git a/x/gov/handler.go b/x/gov/handler.go index 83606c3eb4cc..0c3ea7e9dab1 100644 --- a/x/gov/handler.go +++ b/x/gov/handler.go @@ -8,7 +8,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/gov/types" ) -// Handle all "gov" type messages. +// NewHandler creates an sdk.Handler for all the gov type messages func NewHandler(keeper Keeper) sdk.Handler { return func(ctx sdk.Context, msg sdk.Msg) sdk.Result { ctx = ctx.WithEventManager(sdk.NewEventManager()) diff --git a/x/gov/keeper/deposit.go b/x/gov/keeper/deposit.go index 9db72dc5c378..494daccbecd3 100644 --- a/x/gov/keeper/deposit.go +++ b/x/gov/keeper/deposit.go @@ -26,6 +26,76 @@ func (keeper Keeper) SetDeposit(ctx sdk.Context, deposit types.Deposit) { store.Set(types.DepositKey(deposit.ProposalID, deposit.Depositor), bz) } +// GetAllDeposits returns all the deposits from the store +func (keeper Keeper) GetAllDeposits(ctx sdk.Context) (deposits types.Deposits) { + keeper.IterateAllDeposits(ctx, func(deposit types.Deposit) bool { + deposits = append(deposits, deposit) + return false + }) + return +} + +// GetDeposits returns all the deposits from a proposal +func (keeper Keeper) GetDeposits(ctx sdk.Context, proposalID uint64) (deposits types.Deposits) { + keeper.IterateDeposits(ctx, proposalID, func(deposit types.Deposit) bool { + deposits = append(deposits, deposit) + return false + }) + return +} + +// DeleteDeposits deletes all the deposits on a specific proposal without refunding them +func (keeper Keeper) DeleteDeposits(ctx sdk.Context, proposalID uint64) { + store := ctx.KVStore(keeper.storeKey) + + keeper.IterateDeposits(ctx, proposalID, func(deposit types.Deposit) bool { + err := keeper.supplyKeeper.BurnCoins(ctx, types.ModuleName, deposit.Amount) + if err != nil { + panic(err) + } + + store.Delete(types.DepositKey(proposalID, deposit.Depositor)) + return false + }) +} + +// GetDepositsIterator gets all the deposits on a specific proposal as an sdk.Iterator +func (keeper Keeper) GetDepositsIterator(ctx sdk.Context, proposalID uint64) sdk.Iterator { + store := ctx.KVStore(keeper.storeKey) + return sdk.KVStorePrefixIterator(store, types.DepositsKey(proposalID)) +} + +// IterateAllDeposits iterates over the all the stored deposits and performs a callback function +func (keeper Keeper) IterateAllDeposits(ctx sdk.Context, cb func(deposit types.Deposit) (stop bool)) { + store := ctx.KVStore(keeper.storeKey) + iterator := sdk.KVStorePrefixIterator(store, types.DepositsKeyPrefix) + + defer iterator.Close() + for ; iterator.Valid(); iterator.Next() { + var deposit types.Deposit + keeper.cdc.MustUnmarshalBinaryLengthPrefixed(iterator.Value(), &deposit) + + if cb(deposit) { + break + } + } +} + +// IterateDeposits iterates over the all the proposals deposits and performs a callback function +func (keeper Keeper) IterateDeposits(ctx sdk.Context, proposalID uint64, cb func(deposit types.Deposit) (stop bool)) { + iterator := keeper.GetDepositsIterator(ctx, proposalID) + + defer iterator.Close() + for ; iterator.Valid(); iterator.Next() { + var deposit types.Deposit + keeper.cdc.MustUnmarshalBinaryLengthPrefixed(iterator.Value(), &deposit) + + if cb(deposit) { + break + } + } +} + // AddDeposit adds or updates a deposit of a specific depositor on a specific proposal // Activates voting period when appropriate func (keeper Keeper) AddDeposit(ctx sdk.Context, proposalID uint64, depositorAddr sdk.AccAddress, depositAmount sdk.Coins) (sdk.Error, bool) { @@ -77,30 +147,6 @@ func (keeper Keeper) AddDeposit(ctx sdk.Context, proposalID uint64, depositorAdd return nil, activatedVotingPeriod } -// GetAllDeposits returns all the deposits from the store -func (keeper Keeper) GetAllDeposits(ctx sdk.Context) (deposits types.Deposits) { - keeper.IterateAllDeposits(ctx, func(deposit types.Deposit) bool { - deposits = append(deposits, deposit) - return false - }) - return -} - -// GetDeposits returns all the deposits from a proposal -func (keeper Keeper) GetDeposits(ctx sdk.Context, proposalID uint64) (deposits types.Deposits) { - keeper.IterateDeposits(ctx, proposalID, func(deposit types.Deposit) bool { - deposits = append(deposits, deposit) - return false - }) - return -} - -// GetDepositsIterator gets all the deposits on a specific proposal as an sdk.Iterator -func (keeper Keeper) GetDepositsIterator(ctx sdk.Context, proposalID uint64) sdk.Iterator { - store := ctx.KVStore(keeper.storeKey) - return sdk.KVStorePrefixIterator(store, types.DepositsKey(proposalID)) -} - // RefundDeposits refunds and deletes all the deposits on a specific proposal func (keeper Keeper) RefundDeposits(ctx sdk.Context, proposalID uint64) { store := ctx.KVStore(keeper.storeKey) @@ -115,18 +161,3 @@ func (keeper Keeper) RefundDeposits(ctx sdk.Context, proposalID uint64) { return false }) } - -// DeleteDeposits deletes all the deposits on a specific proposal without refunding them -func (keeper Keeper) DeleteDeposits(ctx sdk.Context, proposalID uint64) { - store := ctx.KVStore(keeper.storeKey) - - keeper.IterateDeposits(ctx, proposalID, func(deposit types.Deposit) bool { - err := keeper.supplyKeeper.BurnCoins(ctx, types.ModuleName, deposit.Amount) - if err != nil { - panic(err) - } - - store.Delete(types.DepositKey(proposalID, deposit.Depositor)) - return false - }) -} diff --git a/x/gov/keeper/deposit_test.go b/x/gov/keeper/deposit_test.go new file mode 100644 index 000000000000..11520621bcc5 --- /dev/null +++ b/x/gov/keeper/deposit_test.go @@ -0,0 +1,108 @@ +package keeper + +import ( + "strings" + "testing" + "time" + + "github.com/stretchr/testify/require" + + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/gov/types" +) + +func TestDeposits(t *testing.T) { + ctx, ak, keeper, _ := createTestInput(t, false, 100) + + tp := TestProposal() + proposal, err := keeper.SubmitProposal(ctx, tp) + require.NoError(t, err) + proposalID := proposal.ProposalID + + fourStake := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.TokensFromConsensusPower(4))) + fiveStake := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.TokensFromConsensusPower(5))) + + addr0Initial := ak.GetAccount(ctx, input.addrs[0]).GetCoins() + addr1Initial := ak.GetAccount(ctx, input.addrs[1]).GetCoins() + + expTokens := sdk.TokensFromConsensusPower(42) + require.Equal(t, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, expTokens)), addr0Initial) + require.True(t, proposal.TotalDeposit.IsEqual(sdk.NewCoins())) + + // Check no deposits at beginning + deposit, found := keeper.GetDeposit(ctx, proposalID, input.addrs[1]) + require.False(t, found) + proposal, ok := keeper.GetProposal(ctx, proposalID) + require.True(t, ok) + require.True(t, proposal.VotingStartTime.Equal(time.Time{})) + + // Check first deposit + err, votingStarted := keeper.AddDeposit(ctx, proposalID, input.addrs[0], fourStake) + require.Nil(t, err) + require.False(t, votingStarted) + deposit, found = keeper.GetDeposit(ctx, proposalID, input.addrs[0]) + require.True(t, found) + require.Equal(t, fourStake, deposit.Amount) + require.Equal(t, input.addrs[0], deposit.Depositor) + proposal, ok = keeper.GetProposal(ctx, proposalID) + require.True(t, ok) + require.Equal(t, fourStake, proposal.TotalDeposit) + require.Equal(t, addr0Initial.Sub(fourStake), ak.GetAccount(ctx, input.addrs[0]).GetCoins()) + + // Check a second deposit from same address + err, votingStarted = keeper.AddDeposit(ctx, proposalID, input.addrs[0], fiveStake) + require.Nil(t, err) + require.False(t, votingStarted) + deposit, found = keeper.GetDeposit(ctx, proposalID, input.addrs[0]) + require.True(t, found) + require.Equal(t, fourStake.Add(fiveStake), deposit.Amount) + require.Equal(t, input.addrs[0], deposit.Depositor) + proposal, ok = keeper.GetProposal(ctx, proposalID) + require.True(t, ok) + require.Equal(t, fourStake.Add(fiveStake), proposal.TotalDeposit) + require.Equal(t, addr0Initial.Sub(fourStake).Sub(fiveStake), ak.GetAccount(ctx, input.addrs[0]).GetCoins()) + + // Check third deposit from a new address + err, votingStarted = keeper.AddDeposit(ctx, proposalID, input.addrs[1], fourStake) + require.Nil(t, err) + require.True(t, votingStarted) + deposit, found = keeper.GetDeposit(ctx, proposalID, input.addrs[1]) + require.True(t, found) + require.Equal(t, input.addrs[1], deposit.Depositor) + require.Equal(t, fourStake, deposit.Amount) + proposal, ok = keeper.GetProposal(ctx, proposalID) + require.True(t, ok) + require.Equal(t, fourStake.Add(fiveStake).Add(fourStake), proposal.TotalDeposit) + require.Equal(t, addr1Initial.Sub(fourStake), ak.GetAccount(ctx, input.addrs[1]).GetCoins()) + + // Check that proposal moved to voting period + proposal, ok = keeper.GetProposal(ctx, proposalID) + require.True(t, ok) + require.True(t, proposal.VotingStartTime.Equal(ctx.BlockHeader().Time)) + + // Test deposit iterator + depositsIterator := keeper.GetDepositsIterator(ctx, proposalID) + require.True(t, depositsIterator.Valid()) + keeper.cdc.MustUnmarshalBinaryLengthPrefixed(depositsIterator.Value(), &deposit) + require.Equal(t, input.addrs[0], deposit.Depositor) + require.Equal(t, fourStake.Add(fiveStake), deposit.Amount) + depositsIterator.Next() + keeper.cdc.MustUnmarshalBinaryLengthPrefixed(depositsIterator.Value(), &deposit) + require.Equal(t, input.addrs[1], deposit.Depositor) + require.Equal(t, fourStake, deposit.Amount) + depositsIterator.Next() + require.False(t, depositsIterator.Valid()) + depositsIterator.Close() + + // Test Refund Deposits + deposit, found = keeper.GetDeposit(ctx, proposalID, input.addrs[1]) + require.True(t, found) + require.Equal(t, fourStake, deposit.Amount) + keeper.RefundDeposits(ctx, proposalID) + deposit, found = keeper.GetDeposit(ctx, proposalID, input.addrs[1]) + require.False(t, found) + require.Equal(t, addr0Initial, ak.GetAccount(ctx, input.addrs[0]).GetCoins()) + require.Equal(t, addr1Initial, ak.GetAccount(ctx, input.addrs[1]).GetCoins()) + +} \ No newline at end of file diff --git a/x/gov/keeper/keeper.go b/x/gov/keeper/keeper.go index 83366cc357de..a266ab4f6170 100644 --- a/x/gov/keeper/keeper.go +++ b/x/gov/keeper/keeper.go @@ -73,7 +73,7 @@ func (keeper Keeper) Logger(ctx sdk.Context) log.Logger { return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) } -// Router returns the gov Keeper Router +// Router returns the gov Keeper's Router func (keeper Keeper) Router() types.Router { return keeper.router } @@ -83,44 +83,6 @@ func (keeper Keeper) GetGovernanceAccount(ctx sdk.Context) exported.ModuleAccoun return keeper.supplyKeeper.GetModuleAccount(ctx, types.ModuleName) } -// Params - -// GetDepositParams returns the current DepositParams from the global param store -func (keeper Keeper) GetDepositParams(ctx sdk.Context) types.DepositParams { - var depositParams types.DepositParams - keeper.paramSpace.Get(ctx, types.ParamStoreKeyDepositParams, &depositParams) - return depositParams -} - -// GetVotingParams returns the current VotingParams from the global param store -func (keeper Keeper) GetVotingParams(ctx sdk.Context) types.VotingParams { - var votingParams types.VotingParams - keeper.paramSpace.Get(ctx, types.ParamStoreKeyVotingParams, &votingParams) - return votingParams -} - -// GetTallyParams returns the current TallyParam from the global param store -func (keeper Keeper) GetTallyParams(ctx sdk.Context) types.TallyParams { - var tallyParams types.TallyParams - keeper.paramSpace.Get(ctx, types.ParamStoreKeyTallyParams, &tallyParams) - return tallyParams -} - -// SetDepositParams sets DepositParams to the global param store -func (keeper Keeper) SetDepositParams(ctx sdk.Context, depositParams types.DepositParams) { - keeper.paramSpace.Set(ctx, types.ParamStoreKeyDepositParams, &depositParams) -} - -// SetVotingParams sets VotingParams to the global param store -func (keeper Keeper) SetVotingParams(ctx sdk.Context, votingParams types.VotingParams) { - keeper.paramSpace.Set(ctx, types.ParamStoreKeyVotingParams, &votingParams) -} - -// SetTallyParams sets TallyParams to the global param store -func (keeper Keeper) SetTallyParams(ctx sdk.Context, tallyParams types.TallyParams) { - keeper.paramSpace.Set(ctx, types.ParamStoreKeyTallyParams, &tallyParams) -} - // ProposalQueues // InsertActiveProposalQueue inserts a ProposalID into the active proposal queue at endTime @@ -151,22 +113,6 @@ func (keeper Keeper) RemoveFromInactiveProposalQueue(ctx sdk.Context, proposalID // Iterators -// IterateProposals iterates over the all the proposals and performs a callback function -func (keeper Keeper) IterateProposals(ctx sdk.Context, cb func(proposal types.Proposal) (stop bool)) { - store := ctx.KVStore(keeper.storeKey) - iterator := sdk.KVStorePrefixIterator(store, types.ProposalsKeyPrefix) - - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var proposal types.Proposal - keeper.cdc.MustUnmarshalBinaryLengthPrefixed(iterator.Value(), &proposal) - - if cb(proposal) { - break - } - } -} - // IterateActiveProposalsQueue iterates over the proposals in the active proposal queue // and performs a callback function func (keeper Keeper) IterateActiveProposalsQueue(ctx sdk.Context, endTime time.Time, cb func(proposal types.Proposal) (stop bool)) { @@ -205,68 +151,6 @@ func (keeper Keeper) IterateInactiveProposalsQueue(ctx sdk.Context, endTime time } } -// IterateAllDeposits iterates over the all the stored deposits and performs a callback function -func (keeper Keeper) IterateAllDeposits(ctx sdk.Context, cb func(deposit types.Deposit) (stop bool)) { - store := ctx.KVStore(keeper.storeKey) - iterator := sdk.KVStorePrefixIterator(store, types.DepositsKeyPrefix) - - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var deposit types.Deposit - keeper.cdc.MustUnmarshalBinaryLengthPrefixed(iterator.Value(), &deposit) - - if cb(deposit) { - break - } - } -} - -// IterateDeposits iterates over the all the proposals deposits and performs a callback function -func (keeper Keeper) IterateDeposits(ctx sdk.Context, proposalID uint64, cb func(deposit types.Deposit) (stop bool)) { - iterator := keeper.GetDepositsIterator(ctx, proposalID) - - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var deposit types.Deposit - keeper.cdc.MustUnmarshalBinaryLengthPrefixed(iterator.Value(), &deposit) - - if cb(deposit) { - break - } - } -} - -// IterateAllVotes iterates over the all the stored votes and performs a callback function -func (keeper Keeper) IterateAllVotes(ctx sdk.Context, cb func(vote types.Vote) (stop bool)) { - store := ctx.KVStore(keeper.storeKey) - iterator := sdk.KVStorePrefixIterator(store, types.VotesKeyPrefix) - - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var vote types.Vote - keeper.cdc.MustUnmarshalBinaryLengthPrefixed(iterator.Value(), &vote) - - if cb(vote) { - break - } - } -} - -// IterateVotes iterates over the all the proposals votes and performs a callback function -func (keeper Keeper) IterateVotes(ctx sdk.Context, proposalID uint64, cb func(vote types.Vote) (stop bool)) { - iterator := keeper.GetVotesIterator(ctx, proposalID) - - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var vote types.Vote - keeper.cdc.MustUnmarshalBinaryLengthPrefixed(iterator.Value(), &vote) - - if cb(vote) { - break - } - } -} - // ActiveProposalQueueIterator returns an sdk.Iterator for all the proposals in the Active Queue that expire by endTime func (keeper Keeper) ActiveProposalQueueIterator(ctx sdk.Context, endTime time.Time) sdk.Iterator { store := ctx.KVStore(keeper.storeKey) diff --git a/x/gov/keeper/keeper_test.go b/x/gov/keeper/keeper_test.go index dd512f9aabd0..04d3e8b776be 100644 --- a/x/gov/keeper/keeper_test.go +++ b/x/gov/keeper/keeper_test.go @@ -1,357 +1,49 @@ package keeper import ( - "strings" "testing" - "time" "github.com/stretchr/testify/require" - - abci "github.com/tendermint/tendermint/abci/types" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov/types" ) -func TestGetSetProposal(t *testing.T) { - input := getMockApp(t, 0, GenesisState{}, nil) - - header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} - input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) - - ctx := input.mApp.BaseApp.NewContext(false, abci.Header{}) - - tp := testProposal() - proposal, err := input.keeper.SubmitProposal(ctx, tp) - require.NoError(t, err) - proposalID := proposal.ProposalID - input.keeper.SetProposal(ctx, proposal) - - gotProposal, ok := input.keeper.GetProposal(ctx, proposalID) - require.True(t, ok) - require.True(t, ProposalEqual(proposal, gotProposal)) -} - func TestIncrementProposalNumber(t *testing.T) { - input := getMockApp(t, 0, GenesisState{}, nil) - - header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} - input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) - - ctx := input.mApp.BaseApp.NewContext(false, abci.Header{}) - - tp := testProposal() - input.keeper.SubmitProposal(ctx, tp) - input.keeper.SubmitProposal(ctx, tp) - input.keeper.SubmitProposal(ctx, tp) - input.keeper.SubmitProposal(ctx, tp) - input.keeper.SubmitProposal(ctx, tp) - proposal6, err := input.keeper.SubmitProposal(ctx, tp) + ctx, _, keeper, _ := createTestInput(t, false, 100) + + tp := TestProposal() + keeper.SubmitProposal(ctx, tp) + keeper.SubmitProposal(ctx, tp) + keeper.SubmitProposal(ctx, tp) + keeper.SubmitProposal(ctx, tp) + keeper.SubmitProposal(ctx, tp) + proposal6, err := keeper.SubmitProposal(ctx, tp) require.NoError(t, err) require.Equal(t, uint64(6), proposal6.ProposalID) } -func TestActivateVotingPeriod(t *testing.T) { - input := getMockApp(t, 0, GenesisState{}, nil) - - header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} - input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) - - ctx := input.mApp.BaseApp.NewContext(false, abci.Header{}) - - tp := testProposal() - proposal, err := input.keeper.SubmitProposal(ctx, tp) - require.NoError(t, err) - - require.True(t, proposal.VotingStartTime.Equal(time.Time{})) - - input.keeper.activateVotingPeriod(ctx, proposal) - - require.True(t, proposal.VotingStartTime.Equal(ctx.BlockHeader().Time)) - - proposal, ok := input.keeper.GetProposal(ctx, proposal.ProposalID) - require.True(t, ok) - - activeIterator := input.keeper.ActiveProposalQueueIterator(ctx, proposal.VotingEndTime) - require.True(t, activeIterator.Valid()) - var proposalID uint64 - input.keeper.cdc.UnmarshalBinaryLengthPrefixed(activeIterator.Value(), &proposalID) - require.Equal(t, proposalID, proposal.ProposalID) - activeIterator.Close() -} - -func TestDeposits(t *testing.T) { - input := getMockApp(t, 2, GenesisState{}, nil) - - SortAddresses(input.addrs) - - header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} - input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) - - ctx := input.mApp.BaseApp.NewContext(false, abci.Header{}) - - tp := testProposal() - proposal, err := input.keeper.SubmitProposal(ctx, tp) - require.NoError(t, err) - proposalID := proposal.ProposalID - - fourStake := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.TokensFromConsensusPower(4))) - fiveStake := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.TokensFromConsensusPower(5))) - - addr0Initial := input.mApp.AccountKeeper.GetAccount(ctx, input.addrs[0]).GetCoins() - addr1Initial := input.mApp.AccountKeeper.GetAccount(ctx, input.addrs[1]).GetCoins() - - expTokens := sdk.TokensFromConsensusPower(42) - require.Equal(t, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, expTokens)), addr0Initial) - require.True(t, proposal.TotalDeposit.IsEqual(sdk.NewCoins())) - - // Check no deposits at beginning - deposit, found := input.keeper.GetDeposit(ctx, proposalID, input.addrs[1]) - require.False(t, found) - proposal, ok := input.keeper.GetProposal(ctx, proposalID) - require.True(t, ok) - require.True(t, proposal.VotingStartTime.Equal(time.Time{})) - - // Check first deposit - err, votingStarted := input.keeper.AddDeposit(ctx, proposalID, input.addrs[0], fourStake) - require.Nil(t, err) - require.False(t, votingStarted) - deposit, found = input.keeper.GetDeposit(ctx, proposalID, input.addrs[0]) - require.True(t, found) - require.Equal(t, fourStake, deposit.Amount) - require.Equal(t, input.addrs[0], deposit.Depositor) - proposal, ok = input.keeper.GetProposal(ctx, proposalID) - require.True(t, ok) - require.Equal(t, fourStake, proposal.TotalDeposit) - require.Equal(t, addr0Initial.Sub(fourStake), input.mApp.AccountKeeper.GetAccount(ctx, input.addrs[0]).GetCoins()) - - // Check a second deposit from same address - err, votingStarted = input.keeper.AddDeposit(ctx, proposalID, input.addrs[0], fiveStake) - require.Nil(t, err) - require.False(t, votingStarted) - deposit, found = input.keeper.GetDeposit(ctx, proposalID, input.addrs[0]) - require.True(t, found) - require.Equal(t, fourStake.Add(fiveStake), deposit.Amount) - require.Equal(t, input.addrs[0], deposit.Depositor) - proposal, ok = input.keeper.GetProposal(ctx, proposalID) - require.True(t, ok) - require.Equal(t, fourStake.Add(fiveStake), proposal.TotalDeposit) - require.Equal(t, addr0Initial.Sub(fourStake).Sub(fiveStake), input.mApp.AccountKeeper.GetAccount(ctx, input.addrs[0]).GetCoins()) - - // Check third deposit from a new address - err, votingStarted = input.keeper.AddDeposit(ctx, proposalID, input.addrs[1], fourStake) - require.Nil(t, err) - require.True(t, votingStarted) - deposit, found = input.keeper.GetDeposit(ctx, proposalID, input.addrs[1]) - require.True(t, found) - require.Equal(t, input.addrs[1], deposit.Depositor) - require.Equal(t, fourStake, deposit.Amount) - proposal, ok = input.keeper.GetProposal(ctx, proposalID) - require.True(t, ok) - require.Equal(t, fourStake.Add(fiveStake).Add(fourStake), proposal.TotalDeposit) - require.Equal(t, addr1Initial.Sub(fourStake), input.mApp.AccountKeeper.GetAccount(ctx, input.addrs[1]).GetCoins()) - - // Check that proposal moved to voting period - proposal, ok = input.keeper.GetProposal(ctx, proposalID) - require.True(t, ok) - require.True(t, proposal.VotingStartTime.Equal(ctx.BlockHeader().Time)) - - // Test deposit iterator - depositsIterator := input.keeper.GetDepositsIterator(ctx, proposalID) - require.True(t, depositsIterator.Valid()) - input.keeper.cdc.MustUnmarshalBinaryLengthPrefixed(depositsIterator.Value(), &deposit) - require.Equal(t, input.addrs[0], deposit.Depositor) - require.Equal(t, fourStake.Add(fiveStake), deposit.Amount) - depositsIterator.Next() - input.keeper.cdc.MustUnmarshalBinaryLengthPrefixed(depositsIterator.Value(), &deposit) - require.Equal(t, input.addrs[1], deposit.Depositor) - require.Equal(t, fourStake, deposit.Amount) - depositsIterator.Next() - require.False(t, depositsIterator.Valid()) - depositsIterator.Close() - - // Test Refund Deposits - deposit, found = input.keeper.GetDeposit(ctx, proposalID, input.addrs[1]) - require.True(t, found) - require.Equal(t, fourStake, deposit.Amount) - input.keeper.RefundDeposits(ctx, proposalID) - deposit, found = input.keeper.GetDeposit(ctx, proposalID, input.addrs[1]) - require.False(t, found) - require.Equal(t, addr0Initial, input.mApp.AccountKeeper.GetAccount(ctx, input.addrs[0]).GetCoins()) - require.Equal(t, addr1Initial, input.mApp.AccountKeeper.GetAccount(ctx, input.addrs[1]).GetCoins()) - -} - -func TestVotes(t *testing.T) { - input := getMockApp(t, 2, GenesisState{}, nil) - SortAddresses(input.addrs) - - header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} - input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) - - ctx := input.mApp.BaseApp.NewContext(false, abci.Header{}) - - tp := testProposal() - proposal, err := input.keeper.SubmitProposal(ctx, tp) - require.NoError(t, err) - proposalID := proposal.ProposalID - - proposal.Status = StatusVotingPeriod - input.keeper.SetProposal(ctx, proposal) - - // Test first vote - input.keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionAbstain) - vote, found := input.keeper.GetVote(ctx, proposalID, input.addrs[0]) - require.True(t, found) - require.Equal(t, input.addrs[0], vote.Voter) - require.Equal(t, proposalID, vote.ProposalID) - require.Equal(t, types.OptionAbstain, vote.Option) - - // Test change of vote - input.keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionYes) - vote, found = input.keeper.GetVote(ctx, proposalID, input.addrs[0]) - require.True(t, found) - require.Equal(t, input.addrs[0], vote.Voter) - require.Equal(t, proposalID, vote.ProposalID) - require.Equal(t, types.OptionYes, vote.Option) - - // Test second vote - input.keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionNoWithVeto) - vote, found = input.keeper.GetVote(ctx, proposalID, input.addrs[1]) - require.True(t, found) - require.Equal(t, input.addrs[1], vote.Voter) - require.Equal(t, proposalID, vote.ProposalID) - require.Equal(t, types.OptionNoWithVeto, vote.Option) - - // Test vote iterator - votesIterator := input.keeper.GetVotesIterator(ctx, proposalID) - require.True(t, votesIterator.Valid()) - input.keeper.cdc.MustUnmarshalBinaryLengthPrefixed(votesIterator.Value(), &vote) - require.True(t, votesIterator.Valid()) - require.Equal(t, input.addrs[0], vote.Voter) - require.Equal(t, proposalID, vote.ProposalID) - require.Equal(t, types.OptionYes, vote.Option) - votesIterator.Next() - require.True(t, votesIterator.Valid()) - input.keeper.cdc.MustUnmarshalBinaryLengthPrefixed(votesIterator.Value(), &vote) - require.True(t, votesIterator.Valid()) - require.Equal(t, input.addrs[1], vote.Voter) - require.Equal(t, proposalID, vote.ProposalID) - require.Equal(t, types.OptionNoWithVeto, vote.Option) - votesIterator.Next() - require.False(t, votesIterator.Valid()) - votesIterator.Close() -} - func TestProposalQueues(t *testing.T) { - input := getMockApp(t, 0, GenesisState{}, nil) - - header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} - input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) - - ctx := input.mApp.BaseApp.NewContext(false, abci.Header{}) - input.mApp.InitChainer(ctx, abci.RequestInitChain{}) + ctx, _, keeper, _ := createTestInput(t, false, 100) // create test proposals - tp := testProposal() - proposal, err := input.keeper.SubmitProposal(ctx, tp) + tp := TestProposal() + proposal, err := keeper.SubmitProposal(ctx, tp) require.NoError(t, err) - inactiveIterator := input.keeper.InactiveProposalQueueIterator(ctx, proposal.DepositEndTime) + inactiveIterator := keeper.InactiveProposalQueueIterator(ctx, proposal.DepositEndTime) require.True(t, inactiveIterator.Valid()) var proposalID uint64 - input.keeper.cdc.UnmarshalBinaryLengthPrefixed(inactiveIterator.Value(), &proposalID) + keeper.cdc.UnmarshalBinaryLengthPrefixed(inactiveIterator.Value(), &proposalID) require.Equal(t, proposalID, proposal.ProposalID) inactiveIterator.Close() - input.keeper.activateVotingPeriod(ctx, proposal) + keeper.activateVotingPeriod(ctx, proposal) - proposal, ok := input.keeper.GetProposal(ctx, proposal.ProposalID) + proposal, ok := keeper.GetProposal(ctx, proposal.ProposalID) require.True(t, ok) - activeIterator := input.keeper.ActiveProposalQueueIterator(ctx, proposal.VotingEndTime) + activeIterator := keeper.ActiveProposalQueueIterator(ctx, proposal.VotingEndTime) require.True(t, activeIterator.Valid()) - input.keeper.cdc.UnmarshalBinaryLengthPrefixed(activeIterator.Value(), &proposalID) + keeper.cdc.UnmarshalBinaryLengthPrefixed(activeIterator.Value(), &proposalID) require.Equal(t, proposalID, proposal.ProposalID) activeIterator.Close() } - -type validProposal struct{} - -func (validProposal) GetTitle() string { return "title" } -func (validProposal) GetDescription() string { return "description" } -func (validProposal) ProposalRoute() string { return RouterKey } -func (validProposal) ProposalType() string { return ProposalTypeText } -func (validProposal) String() string { return "" } -func (validProposal) ValidateBasic() sdk.Error { return nil } - -type invalidProposalTitle1 struct{ validProposal } - -func (invalidProposalTitle1) GetTitle() string { return "" } - -type invalidProposalTitle2 struct{ validProposal } - -func (invalidProposalTitle2) GetTitle() string { return strings.Repeat("1234567890", 100) } - -type invalidProposalDesc1 struct{ validProposal } - -func (invalidProposalDesc1) GetDescription() string { return "" } - -type invalidProposalDesc2 struct{ validProposal } - -func (invalidProposalDesc2) GetDescription() string { return strings.Repeat("1234567890", 1000) } - -type invalidProposalRoute struct{ validProposal } - -func (invalidProposalRoute) ProposalRoute() string { return "nonexistingroute" } - -type invalidProposalValidation struct{ validProposal } - -func (invalidProposalValidation) ValidateBasic() sdk.Error { - return sdk.NewError(sdk.CodespaceUndefined, sdk.CodeInternal, "") -} - -func registerTestCodec(cdc *codec.Codec) { - cdc.RegisterConcrete(validProposal{}, "test/validproposal", nil) - cdc.RegisterConcrete(invalidProposalTitle1{}, "test/invalidproposalt1", nil) - cdc.RegisterConcrete(invalidProposalTitle2{}, "test/invalidproposalt2", nil) - cdc.RegisterConcrete(invalidProposalDesc1{}, "test/invalidproposald1", nil) - cdc.RegisterConcrete(invalidProposalDesc2{}, "test/invalidproposald2", nil) - cdc.RegisterConcrete(invalidProposalRoute{}, "test/invalidproposalr", nil) - cdc.RegisterConcrete(invalidProposalValidation{}, "test/invalidproposalv", nil) -} - -func TestSubmitProposal(t *testing.T) { - input := getMockApp(t, 0, GenesisState{}, nil) - - registerTestCodec(input.keeper.cdc) - - header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} - input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) - - ctx := input.mApp.BaseApp.NewContext(false, abci.Header{}) - input.mApp.InitChainer(ctx, abci.RequestInitChain{}) - - testCases := []struct { - content types.Content - expectedErr sdk.Error - }{ - {validProposal{}, nil}, - // Keeper does not check the validity of title and description, no error - {invalidProposalTitle1{}, nil}, - {invalidProposalTitle2{}, nil}, - {invalidProposalDesc1{}, nil}, - {invalidProposalDesc2{}, nil}, - // error only when invalid route - {invalidProposalRoute{}, types.ErrNoProposalHandlerExists(types.DefaultCodespace, invalidProposalRoute{})}, - // Keeper does not call ValidateBasic, msg.ValidateBasic does - {invalidProposalValidation{}, nil}, - } - - for _, tc := range testCases { - _, err := input.keeper.SubmitProposal(ctx, tc.content) - require.Equal(t, tc.expectedErr, err, "unexpected type of error: %s", err) - } -} diff --git a/x/gov/keeper/params.go b/x/gov/keeper/params.go new file mode 100644 index 000000000000..0c6fc4338b9f --- /dev/null +++ b/x/gov/keeper/params.go @@ -0,0 +1,42 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/gov/types" +) + +// GetDepositParams returns the current DepositParams from the global param store +func (keeper Keeper) GetDepositParams(ctx sdk.Context) types.DepositParams { + var depositParams types.DepositParams + keeper.paramSpace.Get(ctx, types.ParamStoreKeyDepositParams, &depositParams) + return depositParams +} + +// GetVotingParams returns the current VotingParams from the global param store +func (keeper Keeper) GetVotingParams(ctx sdk.Context) types.VotingParams { + var votingParams types.VotingParams + keeper.paramSpace.Get(ctx, types.ParamStoreKeyVotingParams, &votingParams) + return votingParams +} + +// GetTallyParams returns the current TallyParam from the global param store +func (keeper Keeper) GetTallyParams(ctx sdk.Context) types.TallyParams { + var tallyParams types.TallyParams + keeper.paramSpace.Get(ctx, types.ParamStoreKeyTallyParams, &tallyParams) + return tallyParams +} + +// SetDepositParams sets DepositParams to the global param store +func (keeper Keeper) SetDepositParams(ctx sdk.Context, depositParams types.DepositParams) { + keeper.paramSpace.Set(ctx, types.ParamStoreKeyDepositParams, &depositParams) +} + +// SetVotingParams sets VotingParams to the global param store +func (keeper Keeper) SetVotingParams(ctx sdk.Context, votingParams types.VotingParams) { + keeper.paramSpace.Set(ctx, types.ParamStoreKeyVotingParams, &votingParams) +} + +// SetTallyParams sets TallyParams to the global param store +func (keeper Keeper) SetTallyParams(ctx sdk.Context, tallyParams types.TallyParams) { + keeper.paramSpace.Set(ctx, types.ParamStoreKeyTallyParams, &tallyParams) +} diff --git a/x/gov/keeper/proposal.go b/x/gov/keeper/proposal.go index 34d456eae293..253dbdfb5ae3 100644 --- a/x/gov/keeper/proposal.go +++ b/x/gov/keeper/proposal.go @@ -77,6 +77,22 @@ func (keeper Keeper) DeleteProposal(ctx sdk.Context, proposalID uint64) { store.Delete(types.ProposalKey(proposalID)) } +// IterateProposals iterates over the all the proposals and performs a callback function +func (keeper Keeper) IterateProposals(ctx sdk.Context, cb func(proposal types.Proposal) (stop bool)) { + store := ctx.KVStore(keeper.storeKey) + iterator := sdk.KVStorePrefixIterator(store, types.ProposalsKeyPrefix) + + defer iterator.Close() + for ; iterator.Valid(); iterator.Next() { + var proposal types.Proposal + keeper.cdc.MustUnmarshalBinaryLengthPrefixed(iterator.Value(), &proposal) + + if cb(proposal) { + break + } + } +} + // GetProposals returns all the proposals from store func (keeper Keeper) GetProposals(ctx sdk.Context) (proposals types.Proposals) { keeper.IterateProposals(ctx, func(proposal types.Proposal) bool { diff --git a/x/gov/keeper/proposal_test.go b/x/gov/keeper/proposal_test.go new file mode 100644 index 000000000000..ed3a247e93db --- /dev/null +++ b/x/gov/keeper/proposal_test.go @@ -0,0 +1,122 @@ +package keeper + +import ( + "strings" + "testing" + "time" + + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/stretchr/testify/require" +) + +func TestGetSetProposal(t *testing.T) { + ctx, _, keeper, _ := createTestInput(t, false, 100) + + tp := TestProposal() + proposal, err := keeper.SubmitProposal(ctx, tp) + require.NoError(t, err) + proposalID := proposal.ProposalID + keeper.SetProposal(ctx, proposal) + + gotProposal, ok := keeper.GetProposal(ctx, proposalID) + require.True(t, ok) + require.True(t, ProposalEqual(proposal, gotProposal)) +} + +func TestActivateVotingPeriod(t *testing.T) { + ctx, _, keeper, _ := createTestInput(t, false, 100) + + tp := TestProposal() + proposal, err := keeper.SubmitProposal(ctx, tp) + require.NoError(t, err) + + require.True(t, proposal.VotingStartTime.Equal(time.Time{})) + + keeper.activateVotingPeriod(ctx, proposal) + + require.True(t, proposal.VotingStartTime.Equal(ctx.BlockHeader().Time)) + + proposal, ok := keeper.GetProposal(ctx, proposal.ProposalID) + require.True(t, ok) + + activeIterator := keeper.ActiveProposalQueueIterator(ctx, proposal.VotingEndTime) + require.True(t, activeIterator.Valid()) + var proposalID uint64 + keeper.cdc.UnmarshalBinaryLengthPrefixed(activeIterator.Value(), &proposalID) + require.Equal(t, proposalID, proposal.ProposalID) + activeIterator.Close() +} + +type validProposal struct{} + +func (validProposal) GetTitle() string { return "title" } +func (validProposal) GetDescription() string { return "description" } +func (validProposal) ProposalRoute() string { return types.RouterKey } +func (validProposal) ProposalType() string { return types.ProposalTypeText } +func (validProposal) String() string { return "" } +func (validProposal) ValidateBasic() sdk.Error { return nil } + +type invalidProposalTitle1 struct{ validProposal } + +func (invalidProposalTitle1) GetTitle() string { return "" } + +type invalidProposalTitle2 struct{ validProposal } + +func (invalidProposalTitle2) GetTitle() string { return strings.Repeat("1234567890", 100) } + +type invalidProposalDesc1 struct{ validProposal } + +func (invalidProposalDesc1) GetDescription() string { return "" } + +type invalidProposalDesc2 struct{ validProposal } + +func (invalidProposalDesc2) GetDescription() string { return strings.Repeat("1234567890", 1000) } + +type invalidProposalRoute struct{ validProposal } + +func (invalidProposalRoute) ProposalRoute() string { return "nonexistingroute" } + +type invalidProposalValidation struct{ validProposal } + +func (invalidProposalValidation) ValidateBasic() sdk.Error { + return sdk.NewError(sdk.CodespaceUndefined, sdk.CodeInternal, "") +} + +func registerTestCodec(cdc *codec.Codec) { + cdc.RegisterConcrete(validProposal{}, "test/validproposal", nil) + cdc.RegisterConcrete(invalidProposalTitle1{}, "test/invalidproposalt1", nil) + cdc.RegisterConcrete(invalidProposalTitle2{}, "test/invalidproposalt2", nil) + cdc.RegisterConcrete(invalidProposalDesc1{}, "test/invalidproposald1", nil) + cdc.RegisterConcrete(invalidProposalDesc2{}, "test/invalidproposald2", nil) + cdc.RegisterConcrete(invalidProposalRoute{}, "test/invalidproposalr", nil) + cdc.RegisterConcrete(invalidProposalValidation{}, "test/invalidproposalv", nil) +} + +func TestSubmitProposal(t *testing.T) { + ctx, _, keeper, _ := createTestInput(t, false, 100) + + registerTestCodec(keeper.cdc) + + testCases := []struct { + content types.Content + expectedErr sdk.Error + }{ + {validProposal{}, nil}, + // Keeper does not check the validity of title and description, no error + {invalidProposalTitle1{}, nil}, + {invalidProposalTitle2{}, nil}, + {invalidProposalDesc1{}, nil}, + {invalidProposalDesc2{}, nil}, + // error only when invalid route + {invalidProposalRoute{}, types.ErrNoProposalHandlerExists(types.DefaultCodespace, invalidProposalRoute{})}, + // Keeper does not call ValidateBasic, msg.ValidateBasic does + {invalidProposalValidation{}, nil}, + } + + for _, tc := range testCases { + _, err := keeper.SubmitProposal(ctx, tc.content) + require.Equal(t, tc.expectedErr, err, "unexpected type of error: %s", err) + } +} diff --git a/x/gov/keeper/querier_test.go b/x/gov/keeper/querier_test.go index ddfa69ee0f09..0d24b2da7816 100644 --- a/x/gov/keeper/querier_test.go +++ b/x/gov/keeper/querier_test.go @@ -25,8 +25,7 @@ func getQueriedParams(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier s require.NotNil(t, bz) var depositParams types.DepositParams - err2 := cdc.UnmarshalJSON(bz, &depositParams) - require.Nil(t, err2) + require.NoError(t, cdc.UnmarshalJSON(bz, &depositParams)) query = abci.RequestQuery{ Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryParams, types.ParamVoting}, "/"), @@ -38,8 +37,7 @@ func getQueriedParams(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier s require.NotNil(t, bz) var votingParams types.VotingParams - err2 = cdc.UnmarshalJSON(bz, &votingParams) - require.Nil(t, err2) + require.NoError(t, cdc.UnmarshalJSON(bz, &votingParams)) query = abci.RequestQuery{ Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryParams, types.ParamTallying}, "/"), @@ -51,8 +49,7 @@ func getQueriedParams(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier s require.NotNil(t, bz) var tallyParams types.TallyParams - err2 = cdc.UnmarshalJSON(bz, &tallyParams) - require.Nil(t, err2) + require.NoError(t, cdc.UnmarshalJSON(bz, &tallyParams)) return depositParams, votingParams, tallyParams } @@ -68,8 +65,8 @@ func getQueriedProposal(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier require.NotNil(t, bz) var proposal types.Proposal - err2 := cdc.UnmarshalJSON(bz, proposal) - require.Nil(t, err2) + require.NoError(t, cdc.UnmarshalJSON(bz, proposal)) + return proposal } @@ -84,8 +81,8 @@ func getQueriedProposals(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querie require.NotNil(t, bz) var proposals types.Proposals - err2 := cdc.UnmarshalJSON(bz, &proposals) - require.Nil(t, err2) + require.NoError(t, cdc.UnmarshalJSON(bz, &proposals)) + return proposals } @@ -100,8 +97,8 @@ func getQueriedDeposit(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier require.NotNil(t, bz) var deposit types.Deposit - err2 := cdc.UnmarshalJSON(bz, &deposit) - require.Nil(t, err2) + require.NoError(t, cdc.UnmarshalJSON(bz, &deposit)) + return deposit } @@ -116,8 +113,8 @@ func getQueriedDeposits(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier require.NotNil(t, bz) var deposits []types.Deposit - err2 := cdc.UnmarshalJSON(bz, &deposits) - require.Nil(t, err2) + require.NoError(t, cdc.UnmarshalJSON(bz, &deposits)) + return deposits } @@ -132,8 +129,8 @@ func getQueriedVote(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk require.NotNil(t, bz) var vote types.Vote - err2 := cdc.UnmarshalJSON(bz, &vote) - require.Nil(t, err2) + require.NoError(t, cdc.UnmarshalJSON(bz, &vote)) + return vote } @@ -148,8 +145,8 @@ func getQueriedVotes(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sd require.NotNil(t, bz) var votes []types.Vote - err2 := cdc.UnmarshalJSON(bz, &votes) - require.Nil(t, err2) + require.NoError(t, cdc.UnmarshalJSON(bz, &votes)) + return votes } @@ -164,8 +161,8 @@ func getQueriedTally(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sd require.NotNil(t, bz) var tally types.TallyResult - err2 := cdc.UnmarshalJSON(bz, &tally) - require.Nil(t, err2) + require.NoError(t, cdc.UnmarshalJSON(bz, &tally)) + return tally } @@ -184,16 +181,10 @@ func TestQueryParams(t *testing.T) { func TestQueries(t *testing.T) { cdc := codec.New() - input := getMockApp(t, 1000, types.GenesisState{}, nil) - querier := NewQuerier(input.keeper) - handler := NewHandler(input.keeper) - types.RegisterCodec(cdc) + // ctx, _, keeper, sk, _ := CreateTestInputDefault(t, false, 100) - header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} - input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) - - ctx := input.mApp.NewContext(false, abci.Header{}) + types.RegisterCodec(cdc) depositParams, _, _ := getQueriedParams(t, ctx, cdc, querier) diff --git a/x/gov/keeper/tally_test.go b/x/gov/keeper/tally_test.go index ecdacf76b445..1cf978671595 100644 --- a/x/gov/keeper/tally_test.go +++ b/x/gov/keeper/tally_test.go @@ -14,32 +14,18 @@ import ( ) func TestTallyNoOneVotes(t *testing.T) { - input := getMockApp(t, 10, types.GenesisState{}, nil) + ctx, _, keeper, _ := createTestInput(t, false, 100) - header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} - input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) - - ctx := input.mApp.BaseApp.NewContext(false, abci.Header{}) - stakingHandler := staking.NewHandler(input.sk) - - valAddrs := make([]sdk.ValAddress, len(input.addrs[:2])) - for i, addr := range input.addrs[:2] { - valAddrs[i] = sdk.ValAddress(addr) - } - - createValidators(t, stakingHandler, ctx, valAddrs, []int64{5, 5}) - staking.EndBlocker(ctx, input.sk) - - tp := testProposal() - proposal, err := input.keeper.SubmitProposal(ctx, tp) + tp := TestProposal() + proposal, err := keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID proposal.Status = types.StatusVotingPeriod - input.keeper.SetProposal(ctx, proposal) + keeper.SetProposal(ctx, proposal) - proposal, ok := input.keeper.GetProposal(ctx, proposalID) + proposal, ok := keeper.GetProposal(ctx, proposalID) require.True(t, ok) - passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) + passes, burnDeposits, tallyResults := keeper.Tally(ctx, proposal) require.False(t, passes) require.True(t, burnDeposits) @@ -47,71 +33,43 @@ func TestTallyNoOneVotes(t *testing.T) { } func TestTallyNoQuorum(t *testing.T) { - input := getMockApp(t, 10, types.GenesisState{}, nil) - - header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} - input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) - - ctx := input.mApp.BaseApp.NewContext(false, abci.Header{}) - stakingHandler := staking.NewHandler(input.sk) + ctx, _, keeper, _ := createTestInput(t, false, 100) - valAddrs := make([]sdk.ValAddress, len(input.addrs[:2])) - for i, addr := range input.addrs[:2] { - valAddrs[i] = sdk.ValAddress(addr) - } - - createValidators(t, stakingHandler, ctx, valAddrs, []int64{2, 5}) - staking.EndBlocker(ctx, input.sk) - - tp := testProposal() - proposal, err := input.keeper.SubmitProposal(ctx, tp) + tp := TestProposal() + proposal, err := keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID proposal.Status = types.StatusVotingPeriod - input.keeper.SetProposal(ctx, proposal) + keeper.SetProposal(ctx, proposal) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionYes) + err = keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionYes) require.Nil(t, err) - proposal, ok := input.keeper.GetProposal(ctx, proposalID) + proposal, ok := keeper.GetProposal(ctx, proposalID) require.True(t, ok) - passes, burnDeposits, _ := input.keeper.Tally(ctx, proposal) + passes, burnDeposits, _ := keeper.Tally(ctx, proposal) require.False(t, passes) require.True(t, burnDeposits) } func TestTallyOnlyValidatorsAllYes(t *testing.T) { - input := getMockApp(t, 10, types.GenesisState{}, nil) - - header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} - input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) + ctx, _, keeper, _ := createTestInput(t, false, 100) - ctx := input.mApp.BaseApp.NewContext(false, abci.Header{}) - stakingHandler := staking.NewHandler(input.sk) - - valAddrs := make([]sdk.ValAddress, len(input.addrs[:2])) - for i, addr := range input.addrs[:2] { - valAddrs[i] = sdk.ValAddress(addr) - } - - createValidators(t, stakingHandler, ctx, valAddrs, []int64{5, 5}) - staking.EndBlocker(ctx, input.sk) - - tp := testProposal() - proposal, err := input.keeper.SubmitProposal(ctx, tp) + tp := TestProposal() + proposal, err := keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID proposal.Status = types.StatusVotingPeriod - input.keeper.SetProposal(ctx, proposal) + keeper.SetProposal(ctx, proposal) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionYes) + err = keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionYes) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionYes) + err = keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionYes) require.Nil(t, err) - proposal, ok := input.keeper.GetProposal(ctx, proposalID) + proposal, ok := keeper.GetProposal(ctx, proposalID) require.True(t, ok) - passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) + passes, burnDeposits, tallyResults := keeper.Tally(ctx, proposal) require.True(t, passes) require.False(t, burnDeposits) @@ -119,76 +77,48 @@ func TestTallyOnlyValidatorsAllYes(t *testing.T) { } func TestTallyOnlyValidators51No(t *testing.T) { - input := getMockApp(t, 10, types.GenesisState{}, nil) - - header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} - input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) + ctx, _, keeper, _ := createTestInput(t, false, 100) - ctx := input.mApp.BaseApp.NewContext(false, abci.Header{}) - stakingHandler := staking.NewHandler(input.sk) - - valAddrs := make([]sdk.ValAddress, len(input.addrs[:2])) - for i, addr := range input.addrs[:2] { - valAddrs[i] = sdk.ValAddress(addr) - } - - createValidators(t, stakingHandler, ctx, valAddrs, []int64{5, 6}) - staking.EndBlocker(ctx, input.sk) - - tp := testProposal() - proposal, err := input.keeper.SubmitProposal(ctx, tp) + tp := TestProposal() + proposal, err := keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID proposal.Status = types.StatusVotingPeriod - input.keeper.SetProposal(ctx, proposal) + keeper.SetProposal(ctx, proposal) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionYes) + err = keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionYes) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionNo) + err = keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionNo) require.Nil(t, err) - proposal, ok := input.keeper.GetProposal(ctx, proposalID) + proposal, ok := keeper.GetProposal(ctx, proposalID) require.True(t, ok) - passes, burnDeposits, _ := input.keeper.Tally(ctx, proposal) + passes, burnDeposits, _ := keeper.Tally(ctx, proposal) require.False(t, passes) require.False(t, burnDeposits) } func TestTallyOnlyValidators51Yes(t *testing.T) { - input := getMockApp(t, 10, types.GenesisState{}, nil) - - header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} - input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) - - ctx := input.mApp.BaseApp.NewContext(false, abci.Header{}) - stakingHandler := staking.NewHandler(input.sk) - - valAddrs := make([]sdk.ValAddress, len(input.addrs[:3])) - for i, addr := range input.addrs[:3] { - valAddrs[i] = sdk.ValAddress(addr) - } - - createValidators(t, stakingHandler, ctx, valAddrs, []int64{6, 6, 7}) - staking.EndBlocker(ctx, input.sk) + ctx, _, keeper, _ := createTestInput(t, false, 100) - tp := testProposal() - proposal, err := input.keeper.SubmitProposal(ctx, tp) + tp := TestProposal() + proposal, err := keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID proposal.Status = types.StatusVotingPeriod - input.keeper.SetProposal(ctx, proposal) + keeper.SetProposal(ctx, proposal) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionYes) + err = keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionYes) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionYes) + err = keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionYes) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[2], types.OptionNo) + err = keeper.AddVote(ctx, proposalID, input.addrs[2], types.OptionNo) require.Nil(t, err) - proposal, ok := input.keeper.GetProposal(ctx, proposalID) + proposal, ok := keeper.GetProposal(ctx, proposalID) require.True(t, ok) - passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) + passes, burnDeposits, tallyResults := keeper.Tally(ctx, proposal) require.True(t, passes) require.False(t, burnDeposits) @@ -196,39 +126,25 @@ func TestTallyOnlyValidators51Yes(t *testing.T) { } func TestTallyOnlyValidatorsVetoed(t *testing.T) { - input := getMockApp(t, 10, types.GenesisState{}, nil) + ctx, _, keeper, _ := createTestInput(t, false, 100) - header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} - input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) - - ctx := input.mApp.BaseApp.NewContext(false, abci.Header{}) - stakingHandler := staking.NewHandler(input.sk) - - valAddrs := make([]sdk.ValAddress, len(input.addrs[:3])) - for i, addr := range input.addrs[:3] { - valAddrs[i] = sdk.ValAddress(addr) - } - - createValidators(t, stakingHandler, ctx, valAddrs, []int64{6, 6, 7}) - staking.EndBlocker(ctx, input.sk) - - tp := testProposal() - proposal, err := input.keeper.SubmitProposal(ctx, tp) + tp := TestProposal() + proposal, err := keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID proposal.Status = types.StatusVotingPeriod - input.keeper.SetProposal(ctx, proposal) + keeper.SetProposal(ctx, proposal) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionYes) + err = keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionYes) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionYes) + err = keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionYes) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[2], types.OptionNoWithVeto) + err = keeper.AddVote(ctx, proposalID, input.addrs[2], types.OptionNoWithVeto) require.Nil(t, err) - proposal, ok := input.keeper.GetProposal(ctx, proposalID) + proposal, ok := keeper.GetProposal(ctx, proposalID) require.True(t, ok) - passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) + passes, burnDeposits, tallyResults := keeper.Tally(ctx, proposal) require.False(t, passes) require.True(t, burnDeposits) @@ -237,39 +153,25 @@ func TestTallyOnlyValidatorsVetoed(t *testing.T) { } func TestTallyOnlyValidatorsAbstainPasses(t *testing.T) { - input := getMockApp(t, 10, types.GenesisState{}, nil) + ctx, _, keeper, _ := createTestInput(t, false, 100) - header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} - input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) - - ctx := input.mApp.BaseApp.NewContext(false, abci.Header{}) - stakingHandler := staking.NewHandler(input.sk) - - valAddrs := make([]sdk.ValAddress, len(input.addrs[:3])) - for i, addr := range input.addrs[:3] { - valAddrs[i] = sdk.ValAddress(addr) - } - - createValidators(t, stakingHandler, ctx, valAddrs, []int64{6, 6, 7}) - staking.EndBlocker(ctx, input.sk) - - tp := testProposal() - proposal, err := input.keeper.SubmitProposal(ctx, tp) + tp := TestProposal() + proposal, err := keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID proposal.Status = types.StatusVotingPeriod - input.keeper.SetProposal(ctx, proposal) + keeper.SetProposal(ctx, proposal) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionAbstain) + err = keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionAbstain) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionNo) + err = keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionNo) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[2], types.OptionYes) + err = keeper.AddVote(ctx, proposalID, input.addrs[2], types.OptionYes) require.Nil(t, err) - proposal, ok := input.keeper.GetProposal(ctx, proposalID) + proposal, ok := keeper.GetProposal(ctx, proposalID) require.True(t, ok) - passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) + passes, burnDeposits, tallyResults := keeper.Tally(ctx, proposal) require.True(t, passes) require.False(t, burnDeposits) @@ -277,39 +179,25 @@ func TestTallyOnlyValidatorsAbstainPasses(t *testing.T) { } func TestTallyOnlyValidatorsAbstainFails(t *testing.T) { - input := getMockApp(t, 10, types.GenesisState{}, nil) + ctx, _, keeper, _ := createTestInput(t, false, 100) - header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} - input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) - - ctx := input.mApp.BaseApp.NewContext(false, abci.Header{}) - stakingHandler := staking.NewHandler(input.sk) - - valAddrs := make([]sdk.ValAddress, len(input.addrs[:3])) - for i, addr := range input.addrs[:3] { - valAddrs[i] = sdk.ValAddress(addr) - } - - createValidators(t, stakingHandler, ctx, valAddrs, []int64{6, 6, 7}) - staking.EndBlocker(ctx, input.sk) - - tp := testProposal() - proposal, err := input.keeper.SubmitProposal(ctx, tp) + tp := TestProposal() + proposal, err := keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID proposal.Status = types.StatusVotingPeriod - input.keeper.SetProposal(ctx, proposal) + keeper.SetProposal(ctx, proposal) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionAbstain) + err = keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionAbstain) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionYes) + err = keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionYes) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[2], types.OptionNo) + err = keeper.AddVote(ctx, proposalID, input.addrs[2], types.OptionNo) require.Nil(t, err) - proposal, ok := input.keeper.GetProposal(ctx, proposalID) + proposal, ok := keeper.GetProposal(ctx, proposalID) require.True(t, ok) - passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) + passes, burnDeposits, tallyResults := keeper.Tally(ctx, proposal) require.False(t, passes) require.False(t, burnDeposits) @@ -317,37 +205,23 @@ func TestTallyOnlyValidatorsAbstainFails(t *testing.T) { } func TestTallyOnlyValidatorsNonVoter(t *testing.T) { - input := getMockApp(t, 10, types.GenesisState{}, nil) + ctx, _, keeper, _ := createTestInput(t, false, 100) - header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} - input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) - - ctx := input.mApp.BaseApp.NewContext(false, abci.Header{}) - stakingHandler := staking.NewHandler(input.sk) - - valAddrs := make([]sdk.ValAddress, len(input.addrs[:3])) - for i, addr := range input.addrs[:3] { - valAddrs[i] = sdk.ValAddress(addr) - } - - createValidators(t, stakingHandler, ctx, valAddrs, []int64{6, 6, 7}) - staking.EndBlocker(ctx, input.sk) - - tp := testProposal() - proposal, err := input.keeper.SubmitProposal(ctx, tp) + tp := TestProposal() + proposal, err := keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID proposal.Status = types.StatusVotingPeriod - input.keeper.SetProposal(ctx, proposal) + keeper.SetProposal(ctx, proposal) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionYes) + err = keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionYes) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[2], types.OptionNo) + err = keeper.AddVote(ctx, proposalID, input.addrs[2], types.OptionNo) require.Nil(t, err) - proposal, ok := input.keeper.GetProposal(ctx, proposalID) + proposal, ok := keeper.GetProposal(ctx, proposalID) require.True(t, ok) - passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) + passes, burnDeposits, tallyResults := keeper.Tally(ctx, proposal) require.False(t, passes) require.False(t, burnDeposits) @@ -355,45 +229,31 @@ func TestTallyOnlyValidatorsNonVoter(t *testing.T) { } func TestTallyDelgatorOverride(t *testing.T) { - input := getMockApp(t, 10, types.GenesisState{}, nil) - - header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} - input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) - - ctx := input.mApp.BaseApp.NewContext(false, abci.Header{}) - stakingHandler := staking.NewHandler(input.sk) - - valAddrs := make([]sdk.ValAddress, len(input.addrs[:3])) - for i, addr := range input.addrs[:3] { - valAddrs[i] = sdk.ValAddress(addr) - } - - createValidators(t, stakingHandler, ctx, valAddrs, []int64{5, 6, 7}) - staking.EndBlocker(ctx, input.sk) + ctx, _, keeper, _ := createTestInput(t, false, 100) delTokens := sdk.TokensFromConsensusPower(30) delegator1Msg := staking.NewMsgDelegate(input.addrs[3], sdk.ValAddress(input.addrs[2]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) stakingHandler(ctx, delegator1Msg) - tp := testProposal() - proposal, err := input.keeper.SubmitProposal(ctx, tp) + tp := TestProposal() + proposal, err := keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID proposal.Status = types.StatusVotingPeriod - input.keeper.SetProposal(ctx, proposal) + keeper.SetProposal(ctx, proposal) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionYes) + err = keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionYes) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionYes) + err = keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionYes) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[2], types.OptionYes) + err = keeper.AddVote(ctx, proposalID, input.addrs[2], types.OptionYes) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[3], types.OptionNo) + err = keeper.AddVote(ctx, proposalID, input.addrs[3], types.OptionNo) require.Nil(t, err) - proposal, ok := input.keeper.GetProposal(ctx, proposalID) + proposal, ok := keeper.GetProposal(ctx, proposalID) require.True(t, ok) - passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) + passes, burnDeposits, tallyResults := keeper.Tally(ctx, proposal) require.False(t, passes) require.False(t, burnDeposits) @@ -401,43 +261,29 @@ func TestTallyDelgatorOverride(t *testing.T) { } func TestTallyDelgatorInherit(t *testing.T) { - input := getMockApp(t, 10, types.GenesisState{}, nil) - - header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} - input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) - - ctx := input.mApp.BaseApp.NewContext(false, abci.Header{}) - stakingHandler := staking.NewHandler(input.sk) - - valAddrs := make([]sdk.ValAddress, len(input.addrs[:3])) - for i, addr := range input.addrs[:3] { - valAddrs[i] = sdk.ValAddress(addr) - } - - createValidators(t, stakingHandler, ctx, valAddrs, []int64{5, 6, 7}) - staking.EndBlocker(ctx, input.sk) + ctx, _, keeper, _ := createTestInput(t, false, 100) delTokens := sdk.TokensFromConsensusPower(30) delegator1Msg := staking.NewMsgDelegate(input.addrs[3], sdk.ValAddress(input.addrs[2]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) stakingHandler(ctx, delegator1Msg) - tp := testProposal() - proposal, err := input.keeper.SubmitProposal(ctx, tp) + tp := TestProposal() + proposal, err := keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID proposal.Status = types.StatusVotingPeriod - input.keeper.SetProposal(ctx, proposal) + keeper.SetProposal(ctx, proposal) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionNo) + err = keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionNo) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionNo) + err = keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionNo) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[2], types.OptionYes) + err = keeper.AddVote(ctx, proposalID, input.addrs[2], types.OptionYes) require.Nil(t, err) - proposal, ok := input.keeper.GetProposal(ctx, proposalID) + proposal, ok := keeper.GetProposal(ctx, proposalID) require.True(t, ok) - passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) + passes, burnDeposits, tallyResults := keeper.Tally(ctx, proposal) require.True(t, passes) require.False(t, burnDeposits) @@ -445,21 +291,7 @@ func TestTallyDelgatorInherit(t *testing.T) { } func TestTallyDelgatorMultipleOverride(t *testing.T) { - input := getMockApp(t, 10, types.GenesisState{}, nil) - - header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} - input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) - - ctx := input.mApp.BaseApp.NewContext(false, abci.Header{}) - stakingHandler := staking.NewHandler(input.sk) - - valAddrs := make([]sdk.ValAddress, len(input.addrs[:3])) - for i, addr := range input.addrs[:3] { - valAddrs[i] = sdk.ValAddress(addr) - } - - createValidators(t, stakingHandler, ctx, valAddrs, []int64{5, 6, 7}) - staking.EndBlocker(ctx, input.sk) + ctx, _, keeper, _ := createTestInput(t, false, 100) delTokens := sdk.TokensFromConsensusPower(10) delegator1Msg := staking.NewMsgDelegate(input.addrs[3], sdk.ValAddress(input.addrs[2]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) @@ -467,25 +299,25 @@ func TestTallyDelgatorMultipleOverride(t *testing.T) { delegator1Msg2 := staking.NewMsgDelegate(input.addrs[3], sdk.ValAddress(input.addrs[1]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) stakingHandler(ctx, delegator1Msg2) - tp := testProposal() - proposal, err := input.keeper.SubmitProposal(ctx, tp) + tp := TestProposal() + proposal, err := keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID proposal.Status = types.StatusVotingPeriod - input.keeper.SetProposal(ctx, proposal) + keeper.SetProposal(ctx, proposal) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionYes) + err = keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionYes) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionYes) + err = keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionYes) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[2], types.OptionYes) + err = keeper.AddVote(ctx, proposalID, input.addrs[2], types.OptionYes) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[3], types.OptionNo) + err = keeper.AddVote(ctx, proposalID, input.addrs[3], types.OptionNo) require.Nil(t, err) - proposal, ok := input.keeper.GetProposal(ctx, proposalID) + proposal, ok := keeper.GetProposal(ctx, proposalID) require.True(t, ok) - passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) + passes, burnDeposits, tallyResults := keeper.Tally(ctx, proposal) require.False(t, passes) require.False(t, burnDeposits) @@ -493,7 +325,7 @@ func TestTallyDelgatorMultipleOverride(t *testing.T) { } func TestTallyDelgatorMultipleInherit(t *testing.T) { - input := getMockApp(t, 10, types.GenesisState{}, nil) + ctx, _, keeper, _ := createTestInput(t, false, 100) header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) @@ -528,23 +360,23 @@ func TestTallyDelgatorMultipleInherit(t *testing.T) { staking.EndBlocker(ctx, input.sk) - tp := testProposal() - proposal, err := input.keeper.SubmitProposal(ctx, tp) + tp := TestProposal() + proposal, err := keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID proposal.Status = types.StatusVotingPeriod - input.keeper.SetProposal(ctx, proposal) + keeper.SetProposal(ctx, proposal) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionYes) + err = keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionYes) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionNo) + err = keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionNo) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[2], types.OptionNo) + err = keeper.AddVote(ctx, proposalID, input.addrs[2], types.OptionNo) require.Nil(t, err) - proposal, ok := input.keeper.GetProposal(ctx, proposalID) + proposal, ok := keeper.GetProposal(ctx, proposalID) require.True(t, ok) - passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) + passes, burnDeposits, tallyResults := keeper.Tally(ctx, proposal) require.False(t, passes) require.False(t, burnDeposits) @@ -552,21 +384,7 @@ func TestTallyDelgatorMultipleInherit(t *testing.T) { } func TestTallyJailedValidator(t *testing.T) { - input := getMockApp(t, 10, types.GenesisState{}, nil) - - header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} - input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) - - ctx := input.mApp.BaseApp.NewContext(false, abci.Header{}) - stakingHandler := staking.NewHandler(input.sk) - - valAddrs := make([]sdk.ValAddress, len(input.addrs[:3])) - for i, addr := range input.addrs[:3] { - valAddrs[i] = sdk.ValAddress(addr) - } - - createValidators(t, stakingHandler, ctx, valAddrs, []int64{25, 6, 7}) - staking.EndBlocker(ctx, input.sk) + ctx, _, keeper, _ := createTestInput(t, false, 100) delTokens := sdk.TokensFromConsensusPower(10) delegator1Msg := staking.NewMsgDelegate(input.addrs[3], sdk.ValAddress(input.addrs[2]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) @@ -581,23 +399,23 @@ func TestTallyJailedValidator(t *testing.T) { staking.EndBlocker(ctx, input.sk) - tp := testProposal() - proposal, err := input.keeper.SubmitProposal(ctx, tp) + tp := TestProposal() + proposal, err := keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID proposal.Status = types.StatusVotingPeriod - input.keeper.SetProposal(ctx, proposal) + keeper.SetProposal(ctx, proposal) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionYes) + err = keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionYes) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionNo) + err = keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionNo) require.Nil(t, err) - err = input.keeper.AddVote(ctx, proposalID, input.addrs[2], types.OptionNo) + err = keeper.AddVote(ctx, proposalID, input.addrs[2], types.OptionNo) require.Nil(t, err) - proposal, ok := input.keeper.GetProposal(ctx, proposalID) + proposal, ok := keeper.GetProposal(ctx, proposalID) require.True(t, ok) - passes, burnDeposits, tallyResults := input.keeper.Tally(ctx, proposal) + passes, burnDeposits, tallyResults := keeper.Tally(ctx, proposal) require.True(t, passes) require.False(t, burnDeposits) diff --git a/x/gov/keeper/test_common.go b/x/gov/keeper/test_common.go index 9909fe858505..20737dbd11bc 100644 --- a/x/gov/keeper/test_common.go +++ b/x/gov/keeper/test_common.go @@ -1,6 +1,9 @@ +// nolint +// DONTCOVER package keeper // noalias import ( + "bytes" "testing" "github.com/stretchr/testify/require" @@ -25,7 +28,6 @@ import ( ) // dummy addresses used for testing -// nolint: unused deadcode var ( delPk1 = ed25519.GenPrivKey().PubKey() delPk2 = ed25519.GenPrivKey().PubKey() @@ -54,14 +56,6 @@ var ( emptyPubkey crypto.PubKey ) -type testInput struct { - keeper Keeper - router types.Router - ak auth.AccountKeeper - sk types.StakingKeeper -} - -// nolint: deadcode unused func makeTestCodec() *codec.Codec { var cdc = codec.New() auth.RegisterCodec(cdc) @@ -74,11 +68,8 @@ func makeTestCodec() *codec.Codec { return cdc } -// nolint: deadcode unused func createTestInput(t *testing.T, isCheckTx bool, initPower int64) (sdk.Context, auth.AccountKeeper, Keeper, types.SupplyKeeper) { - // FIXME: update tests - initTokens := sdk.TokensFromConsensusPower(initPower) keyAcc := sdk.NewKVStoreKey(auth.StoreKey) @@ -147,3 +138,13 @@ func createTestInput(t *testing.T, isCheckTx bool, initPower int64) (sdk.Context return ctx, accountKeeper, keeper, supplyKeeper } + +func TestProposal() types.Content { + return types.NewTextProposal("Test", "description") +} + +// ProposalEqual checks if two proposals are equal (note: slow, for tests only) +func ProposalEqual(proposalA types.Proposal, proposalB types.Proposal) bool { + return bytes.Equal(types.ModuleCdc.MustMarshalBinaryBare(proposalA), + types.ModuleCdc.MustMarshalBinaryBare(proposalB)) +} diff --git a/x/gov/keeper/vote.go b/x/gov/keeper/vote.go index 5ca322dbc613..cee3e3d65cf0 100644 --- a/x/gov/keeper/vote.go +++ b/x/gov/keeper/vote.go @@ -78,6 +78,37 @@ func (keeper Keeper) GetVotesIterator(ctx sdk.Context, proposalID uint64) sdk.It return sdk.KVStorePrefixIterator(store, types.VotesKey(proposalID)) } +// IterateAllVotes iterates over the all the stored votes and performs a callback function +func (keeper Keeper) IterateAllVotes(ctx sdk.Context, cb func(vote types.Vote) (stop bool)) { + store := ctx.KVStore(keeper.storeKey) + iterator := sdk.KVStorePrefixIterator(store, types.VotesKeyPrefix) + + defer iterator.Close() + for ; iterator.Valid(); iterator.Next() { + var vote types.Vote + keeper.cdc.MustUnmarshalBinaryLengthPrefixed(iterator.Value(), &vote) + + if cb(vote) { + break + } + } +} + +// IterateVotes iterates over the all the proposals votes and performs a callback function +func (keeper Keeper) IterateVotes(ctx sdk.Context, proposalID uint64, cb func(vote types.Vote) (stop bool)) { + iterator := keeper.GetVotesIterator(ctx, proposalID) + + defer iterator.Close() + for ; iterator.Valid(); iterator.Next() { + var vote types.Vote + keeper.cdc.MustUnmarshalBinaryLengthPrefixed(iterator.Value(), &vote) + + if cb(vote) { + break + } + } +} + func (keeper Keeper) deleteVote(ctx sdk.Context, proposalID uint64, voterAddr sdk.AccAddress) { store := ctx.KVStore(keeper.storeKey) store.Delete(types.VoteKey(proposalID, voterAddr)) diff --git a/x/gov/keeper/vote_test.go b/x/gov/keeper/vote_test.go new file mode 100644 index 000000000000..b0058a000438 --- /dev/null +++ b/x/gov/keeper/vote_test.go @@ -0,0 +1,68 @@ +package keeper + +import ( + "strings" + "testing" + "time" + + "github.com/stretchr/testify/require" + + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/gov/types" +) + +func TestVotes(t *testing.T) { + ctx, _, keeper, _ := createTestInput(t, false, 100) + + tp := TestProposal() + proposal, err := keeper.SubmitProposal(ctx, tp) + require.NoError(t, err) + proposalID := proposal.ProposalID + + proposal.Status = types.StatusVotingPeriod + keeper.SetProposal(ctx, proposal) + + // Test first vote + keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionAbstain) + vote, found := keeper.GetVote(ctx, proposalID, input.addrs[0]) + require.True(t, found) + require.Equal(t, input.addrs[0], vote.Voter) + require.Equal(t, proposalID, vote.ProposalID) + require.Equal(t, types.OptionAbstain, vote.Option) + + // Test change of vote + keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionYes) + vote, found = keeper.GetVote(ctx, proposalID, input.addrs[0]) + require.True(t, found) + require.Equal(t, input.addrs[0], vote.Voter) + require.Equal(t, proposalID, vote.ProposalID) + require.Equal(t, types.OptionYes, vote.Option) + + // Test second vote + keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionNoWithVeto) + vote, found = keeper.GetVote(ctx, proposalID, input.addrs[1]) + require.True(t, found) + require.Equal(t, input.addrs[1], vote.Voter) + require.Equal(t, proposalID, vote.ProposalID) + require.Equal(t, types.OptionNoWithVeto, vote.Option) + + // Test vote iterator + votesIterator := keeper.GetVotesIterator(ctx, proposalID) + require.True(t, votesIterator.Valid()) + keeper.cdc.MustUnmarshalBinaryLengthPrefixed(votesIterator.Value(), &vote) + require.True(t, votesIterator.Valid()) + require.Equal(t, input.addrs[0], vote.Voter) + require.Equal(t, proposalID, vote.ProposalID) + require.Equal(t, types.OptionYes, vote.Option) + votesIterator.Next() + require.True(t, votesIterator.Valid()) + keeper.cdc.MustUnmarshalBinaryLengthPrefixed(votesIterator.Value(), &vote) + require.True(t, votesIterator.Valid()) + require.Equal(t, input.addrs[1], vote.Voter) + require.Equal(t, proposalID, vote.ProposalID) + require.Equal(t, types.OptionNoWithVeto, vote.Option) + votesIterator.Next() + require.False(t, votesIterator.Valid()) + votesIterator.Close() +} \ No newline at end of file diff --git a/x/gov/test_common.go b/x/gov/test_common.go index ad1f72c58986..1c959e4bac21 100644 --- a/x/gov/test_common.go +++ b/x/gov/test_common.go @@ -1,4 +1,5 @@ // nolint:deadcode unused +// DONTCOVER package gov import ( @@ -168,17 +169,12 @@ func (b sortByteArrays) Swap(i, j int) { b[j], b[i] = b[i], b[j] } -// Public func SortByteArrays(src [][]byte) [][]byte { sorted := sortByteArrays(src) sort.Sort(sorted) return sorted } -func testProposal() types.Content { - return types.NewTextProposal("Test", "description") -} - const contextKeyBadProposal = "contextKeyBadProposal" // badProposalHandler implements a governance proposal handler that is identical @@ -201,12 +197,6 @@ func badProposalHandler(ctx sdk.Context, c types.Content) sdk.Error { } } -// ProposalEqual checks if two proposals are equal (note: slow, for tests only) -func ProposalEqual(proposalA types.Proposal, proposalB types.Proposal) bool { - return bytes.Equal(types.ModuleCdc.MustMarshalBinaryBare(proposalA), - types.ModuleCdc.MustMarshalBinaryBare(proposalB)) -} - var ( pubkeys = []crypto.PubKey{ ed25519.GenPrivKey().PubKey(), diff --git a/x/gov/types/deposit.go b/x/gov/types/deposit.go index 2ec06e8e8ee7..4d9ff9304179 100644 --- a/x/gov/types/deposit.go +++ b/x/gov/types/deposit.go @@ -6,7 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -// Deposit +// Deposit defines an amount deposited by an account address to an active proposal type Deposit struct { ProposalID uint64 `json:"proposal_id" yaml:"proposal_id"` // proposalID of the proposal Depositor sdk.AccAddress `json:"depositor" yaml:"depositor"` // Address of the depositor diff --git a/x/gov/types/querier.go b/x/gov/types/querier.go index cfe0abc4d328..2b14592eebaf 100644 --- a/x/gov/types/querier.go +++ b/x/gov/types/querier.go @@ -4,6 +4,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) +// DONTCOVER + // query endpoints supported by the governance Querier const ( QueryParams = "params" @@ -20,7 +22,7 @@ const ( ParamTallying = "tallying" ) -// Params for queries: +// QueryProposalParams Params for queries: // - 'custom/gov/proposal' // - 'custom/gov/deposits' // - 'custom/gov/tally' @@ -29,20 +31,20 @@ type QueryProposalParams struct { ProposalID uint64 } -// creates a new instance of QueryProposalParams +// NewQueryProposalParams creates a new instance of QueryProposalParams func NewQueryProposalParams(proposalID uint64) QueryProposalParams { return QueryProposalParams{ ProposalID: proposalID, } } -// Params for query 'custom/gov/deposit' +// QueryDepositParams params for query 'custom/gov/deposit' type QueryDepositParams struct { ProposalID uint64 Depositor sdk.AccAddress } -// creates a new instance of QueryDepositParams +// NewQueryDepositParams creates a new instance of QueryDepositParams func NewQueryDepositParams(proposalID uint64, depositor sdk.AccAddress) QueryDepositParams { return QueryDepositParams{ ProposalID: proposalID, @@ -50,13 +52,13 @@ func NewQueryDepositParams(proposalID uint64, depositor sdk.AccAddress) QueryDep } } -// Params for query 'custom/gov/vote' +// QueryVoteParams Params for query 'custom/gov/vote' type QueryVoteParams struct { ProposalID uint64 Voter sdk.AccAddress } -// creates a new instance of QueryVoteParams +// NewQueryVoteParams creates a new instance of QueryVoteParams func NewQueryVoteParams(proposalID uint64, voter sdk.AccAddress) QueryVoteParams { return QueryVoteParams{ ProposalID: proposalID, @@ -64,7 +66,7 @@ func NewQueryVoteParams(proposalID uint64, voter sdk.AccAddress) QueryVoteParams } } -// Params for query 'custom/gov/proposals' +// QueryProposalsParams Params for query 'custom/gov/proposals' type QueryProposalsParams struct { Voter sdk.AccAddress Depositor sdk.AccAddress @@ -72,7 +74,7 @@ type QueryProposalsParams struct { Limit uint64 } -// creates a new instance of QueryProposalsParams +// NewQueryProposalsParams creates a new instance of QueryProposalsParams func NewQueryProposalsParams(status ProposalStatus, limit uint64, voter, depositor sdk.AccAddress) QueryProposalsParams { return QueryProposalsParams{ Voter: voter, diff --git a/x/gov/types/router.go b/x/gov/types/router.go index 5fd4b6479dcb..3901d8869e9a 100644 --- a/x/gov/types/router.go +++ b/x/gov/types/router.go @@ -26,6 +26,7 @@ type router struct { sealed bool } +// NewRouter creates a new Router interface instance func NewRouter() Router { return &router{ routes: make(map[string]Handler), diff --git a/x/gov/types/tally.go b/x/gov/types/tally.go index e99a0b58126f..c50e773e7e96 100644 --- a/x/gov/types/tally.go +++ b/x/gov/types/tally.go @@ -28,6 +28,7 @@ func NewValidatorGovInfo(address sdk.ValAddress, bondedTokens sdk.Int, delegator } } +// TallyResult defines a standard tally for a proposal type TallyResult struct { Yes sdk.Int `json:"yes" yaml:"yes"` Abstain sdk.Int `json:"abstain" yaml:"abstain"` @@ -35,6 +36,7 @@ type TallyResult struct { NoWithVeto sdk.Int `json:"no_with_veto" yaml:"no_with_veto"` } +// NewTallyResult creates a new TallyResult instance func NewTallyResult(yes, abstain, no, noWithVeto sdk.Int) TallyResult { return TallyResult{ Yes: yes, @@ -44,6 +46,7 @@ func NewTallyResult(yes, abstain, no, noWithVeto sdk.Int) TallyResult { } } +// NewTallyResultFromMap creates a new TallyResult instance from a Option -> Dec map func NewTallyResultFromMap(results map[VoteOption]sdk.Dec) TallyResult { return TallyResult{ Yes: results[OptionYes].TruncateInt(), From d9ed433b22d67dcfeac8f670dcd956614a086c3f Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Mon, 15 Jul 2019 13:25:09 +0200 Subject: [PATCH 09/36] cleanup --- x/gov/keeper/deposit_test.go | 47 ++++----- x/gov/keeper/keeper.go | 5 +- x/gov/keeper/querier_test.go | 177 +++++++++++++++----------------- x/gov/keeper/tally_test.go | 102 +++++++++--------- x/gov/keeper/vote_test.go | 26 ++--- x/gov/types/expected_keepers.go | 8 ++ 6 files changed, 176 insertions(+), 189 deletions(-) diff --git a/x/gov/keeper/deposit_test.go b/x/gov/keeper/deposit_test.go index 11520621bcc5..dd0a213dc576 100644 --- a/x/gov/keeper/deposit_test.go +++ b/x/gov/keeper/deposit_test.go @@ -1,15 +1,12 @@ package keeper import ( - "strings" - "testing" "time" + "testing" "github.com/stretchr/testify/require" - "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov/types" ) func TestDeposits(t *testing.T) { @@ -23,58 +20,58 @@ func TestDeposits(t *testing.T) { fourStake := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.TokensFromConsensusPower(4))) fiveStake := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.TokensFromConsensusPower(5))) - addr0Initial := ak.GetAccount(ctx, input.addrs[0]).GetCoins() - addr1Initial := ak.GetAccount(ctx, input.addrs[1]).GetCoins() + addr0Initial := ak.GetAccount(ctx, TestAddrs[0]).GetCoins() + addr1Initial := ak.GetAccount(ctx, TestAddrs[1]).GetCoins() expTokens := sdk.TokensFromConsensusPower(42) require.Equal(t, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, expTokens)), addr0Initial) require.True(t, proposal.TotalDeposit.IsEqual(sdk.NewCoins())) // Check no deposits at beginning - deposit, found := keeper.GetDeposit(ctx, proposalID, input.addrs[1]) + deposit, found := keeper.GetDeposit(ctx, proposalID, TestAddrs[1]) require.False(t, found) proposal, ok := keeper.GetProposal(ctx, proposalID) require.True(t, ok) require.True(t, proposal.VotingStartTime.Equal(time.Time{})) // Check first deposit - err, votingStarted := keeper.AddDeposit(ctx, proposalID, input.addrs[0], fourStake) + err, votingStarted := keeper.AddDeposit(ctx, proposalID, TestAddrs[0], fourStake) require.Nil(t, err) require.False(t, votingStarted) - deposit, found = keeper.GetDeposit(ctx, proposalID, input.addrs[0]) + deposit, found = keeper.GetDeposit(ctx, proposalID, TestAddrs[0]) require.True(t, found) require.Equal(t, fourStake, deposit.Amount) - require.Equal(t, input.addrs[0], deposit.Depositor) + require.Equal(t, TestAddrs[0], deposit.Depositor) proposal, ok = keeper.GetProposal(ctx, proposalID) require.True(t, ok) require.Equal(t, fourStake, proposal.TotalDeposit) - require.Equal(t, addr0Initial.Sub(fourStake), ak.GetAccount(ctx, input.addrs[0]).GetCoins()) + require.Equal(t, addr0Initial.Sub(fourStake), ak.GetAccount(ctx, TestAddrs[0]).GetCoins()) // Check a second deposit from same address - err, votingStarted = keeper.AddDeposit(ctx, proposalID, input.addrs[0], fiveStake) + err, votingStarted = keeper.AddDeposit(ctx, proposalID, TestAddrs[0], fiveStake) require.Nil(t, err) require.False(t, votingStarted) - deposit, found = keeper.GetDeposit(ctx, proposalID, input.addrs[0]) + deposit, found = keeper.GetDeposit(ctx, proposalID, TestAddrs[0]) require.True(t, found) require.Equal(t, fourStake.Add(fiveStake), deposit.Amount) - require.Equal(t, input.addrs[0], deposit.Depositor) + require.Equal(t, TestAddrs[0], deposit.Depositor) proposal, ok = keeper.GetProposal(ctx, proposalID) require.True(t, ok) require.Equal(t, fourStake.Add(fiveStake), proposal.TotalDeposit) - require.Equal(t, addr0Initial.Sub(fourStake).Sub(fiveStake), ak.GetAccount(ctx, input.addrs[0]).GetCoins()) + require.Equal(t, addr0Initial.Sub(fourStake).Sub(fiveStake), ak.GetAccount(ctx, TestAddrs[0]).GetCoins()) // Check third deposit from a new address - err, votingStarted = keeper.AddDeposit(ctx, proposalID, input.addrs[1], fourStake) + err, votingStarted = keeper.AddDeposit(ctx, proposalID, TestAddrs[1], fourStake) require.Nil(t, err) require.True(t, votingStarted) - deposit, found = keeper.GetDeposit(ctx, proposalID, input.addrs[1]) + deposit, found = keeper.GetDeposit(ctx, proposalID, TestAddrs[1]) require.True(t, found) - require.Equal(t, input.addrs[1], deposit.Depositor) + require.Equal(t, TestAddrs[1], deposit.Depositor) require.Equal(t, fourStake, deposit.Amount) proposal, ok = keeper.GetProposal(ctx, proposalID) require.True(t, ok) require.Equal(t, fourStake.Add(fiveStake).Add(fourStake), proposal.TotalDeposit) - require.Equal(t, addr1Initial.Sub(fourStake), ak.GetAccount(ctx, input.addrs[1]).GetCoins()) + require.Equal(t, addr1Initial.Sub(fourStake), ak.GetAccount(ctx, TestAddrs[1]).GetCoins()) // Check that proposal moved to voting period proposal, ok = keeper.GetProposal(ctx, proposalID) @@ -85,24 +82,24 @@ func TestDeposits(t *testing.T) { depositsIterator := keeper.GetDepositsIterator(ctx, proposalID) require.True(t, depositsIterator.Valid()) keeper.cdc.MustUnmarshalBinaryLengthPrefixed(depositsIterator.Value(), &deposit) - require.Equal(t, input.addrs[0], deposit.Depositor) + require.Equal(t, TestAddrs[0], deposit.Depositor) require.Equal(t, fourStake.Add(fiveStake), deposit.Amount) depositsIterator.Next() keeper.cdc.MustUnmarshalBinaryLengthPrefixed(depositsIterator.Value(), &deposit) - require.Equal(t, input.addrs[1], deposit.Depositor) + require.Equal(t, TestAddrs[1], deposit.Depositor) require.Equal(t, fourStake, deposit.Amount) depositsIterator.Next() require.False(t, depositsIterator.Valid()) depositsIterator.Close() // Test Refund Deposits - deposit, found = keeper.GetDeposit(ctx, proposalID, input.addrs[1]) + deposit, found = keeper.GetDeposit(ctx, proposalID, TestAddrs[1]) require.True(t, found) require.Equal(t, fourStake, deposit.Amount) keeper.RefundDeposits(ctx, proposalID) - deposit, found = keeper.GetDeposit(ctx, proposalID, input.addrs[1]) + deposit, found = keeper.GetDeposit(ctx, proposalID, TestAddrs[1]) require.False(t, found) - require.Equal(t, addr0Initial, ak.GetAccount(ctx, input.addrs[0]).GetCoins()) - require.Equal(t, addr1Initial, ak.GetAccount(ctx, input.addrs[1]).GetCoins()) + require.Equal(t, addr0Initial, ak.GetAccount(ctx, TestAddrs[0]).GetCoins()) + require.Equal(t, addr1Initial, ak.GetAccount(ctx, TestAddrs[1]).GetCoins()) } \ No newline at end of file diff --git a/x/gov/keeper/keeper.go b/x/gov/keeper/keeper.go index a266ab4f6170..e797f5fe3b29 100644 --- a/x/gov/keeper/keeper.go +++ b/x/gov/keeper/keeper.go @@ -7,7 +7,6 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/cosmos/cosmos-sdk/x/params/subspace" "github.com/cosmos/cosmos-sdk/x/supply/exported" "github.com/tendermint/tendermint/libs/log" @@ -16,7 +15,7 @@ import ( // Keeper defines the governance module Keeper type Keeper struct { // The reference to the Paramstore to get and set gov specific params - paramSpace subspace.Subspace + paramSpace types.ParamSubspace // The SupplyKeeper to reduce the supply of the network supplyKeeper types.SupplyKeeper @@ -43,7 +42,7 @@ type Keeper struct { // - users voting on proposals, with weight proportional to stake in the system // - and tallying the result of the vote. func NewKeeper( - cdc *codec.Codec, key sdk.StoreKey, paramSpace subspace.Subspace, + cdc *codec.Codec, key sdk.StoreKey, paramSpace types.ParamSubspace, supplyKeeper types.SupplyKeeper, sk types.StakingKeeper, codespace sdk.CodespaceType, rtr types.Router, ) Keeper { diff --git a/x/gov/keeper/querier_test.go b/x/gov/keeper/querier_test.go index 0d24b2da7816..bbd1aa2c6f33 100644 --- a/x/gov/keeper/querier_test.go +++ b/x/gov/keeper/querier_test.go @@ -21,7 +21,7 @@ func getQueriedParams(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier s } bz, err := querier(ctx, []string{types.QueryParams, types.ParamDeposit}, query) - require.Nil(t, err) + require.NoError(t, err) require.NotNil(t, bz) var depositParams types.DepositParams @@ -33,7 +33,7 @@ func getQueriedParams(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier s } bz, err = querier(ctx, []string{types.QueryParams, types.ParamVoting}, query) - require.Nil(t, err) + require.NoError(t, err) require.NotNil(t, bz) var votingParams types.VotingParams @@ -45,7 +45,7 @@ func getQueriedParams(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier s } bz, err = querier(ctx, []string{types.QueryParams, types.ParamTallying}, query) - require.Nil(t, err) + require.NoError(t, err) require.NotNil(t, bz) var tallyParams types.TallyParams @@ -61,7 +61,7 @@ func getQueriedProposal(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier } bz, err := querier(ctx, []string{types.QueryProposal}, query) - require.Nil(t, err) + require.NoError(t, err) require.NotNil(t, bz) var proposal types.Proposal @@ -77,7 +77,7 @@ func getQueriedProposals(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querie } bz, err := querier(ctx, []string{types.QueryProposals}, query) - require.Nil(t, err) + require.NoError(t, err) require.NotNil(t, bz) var proposals types.Proposals @@ -93,7 +93,7 @@ func getQueriedDeposit(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier } bz, err := querier(ctx, []string{types.QueryDeposit}, query) - require.Nil(t, err) + require.NoError(t, err) require.NotNil(t, bz) var deposit types.Deposit @@ -109,7 +109,7 @@ func getQueriedDeposits(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier } bz, err := querier(ctx, []string{types.QueryDeposits}, query) - require.Nil(t, err) + require.NoError(t, err) require.NotNil(t, bz) var deposits []types.Deposit @@ -125,7 +125,7 @@ func getQueriedVote(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk } bz, err := querier(ctx, []string{types.QueryVote}, query) - require.Nil(t, err) + require.NoError(t, err) require.NotNil(t, bz) var vote types.Vote @@ -141,7 +141,7 @@ func getQueriedVotes(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sd } bz, err := querier(ctx, []string{types.QueryVotes}, query) - require.Nil(t, err) + require.NoError(t, err) require.NotNil(t, bz) var votes []types.Vote @@ -157,7 +157,7 @@ func getQueriedTally(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sd } bz, err := querier(ctx, []string{types.QueryTally}, query) - require.Nil(t, err) + require.NoError(t, err) require.NotNil(t, bz) var tally types.TallyResult @@ -166,128 +166,121 @@ func getQueriedTally(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sd return tally } -func TestQueryParams(t *testing.T) { - cdc := codec.New() - input := getMockApp(t, 1000, types.GenesisState{}, nil) - querier := NewQuerier(input.keeper) - - header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} - input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) - - ctx := input.mApp.NewContext(false, abci.Header{}) - - getQueriedParams(t, ctx, cdc, querier) -} - func TestQueries(t *testing.T) { - cdc := codec.New() - types.RegisterCodec(cdc) - // ctx, _, keeper, sk, _ := CreateTestInputDefault(t, false, 100) + ctx, _, keeper, _ := createTestInput(t, false, 1000) + querier := NewQuerier(keeper) - types.RegisterCodec(cdc) + tp := TestProposal() - depositParams, _, _ := getQueriedParams(t, ctx, cdc, querier) + depositParams, _, _ := getQueriedParams(t, ctx, keeper.cdc, querier) - // input.addrs[0] proposes (and deposits) proposals #1 and #2 - res := handler(ctx, NewMsgSubmitProposal(testProposal(), sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 1)}, input.addrs[0])) - var proposalID1 uint64 - require.True(t, res.IsOK()) - cdc.MustUnmarshalBinaryLengthPrefixed(res.Data, &proposalID1) + // TestAddrs[0] proposes (and deposits) proposals #1 and #2 + proposal1, err := keeper.SubmitProposal(ctx, tp) + deposit1 := types.NewDeposit(proposal1.ProposalID, TestAddrs[0], sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, 1))) + keeper.SetDeposit(ctx, deposit1) - res = handler(ctx, NewMsgSubmitProposal(testProposal(), sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 10000000)}, input.addrs[0])) - var proposalID2 uint64 - require.True(t, res.IsOK()) - cdc.MustUnmarshalBinaryLengthPrefixed(res.Data, &proposalID2) + proposal2, err := keeper.SubmitProposal(ctx, tp) + deposit2 := types.NewDeposit(proposal2.ProposalID, TestAddrs[0], sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, 10000000))) + keeper.SetDeposit(ctx, deposit2) - // input.addrs[1] proposes (and deposits) proposals #3 - res = handler(ctx, NewMsgSubmitProposal(testProposal(), sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 1)}, input.addrs[1])) - var proposalID3 uint64 - require.True(t, res.IsOK()) - cdc.MustUnmarshalBinaryLengthPrefixed(res.Data, &proposalID3) + // TestAddrs[1] proposes (and deposits) on proposal #3 + proposal3, err := keeper.SubmitProposal(ctx, tp) + deposit3 := types.NewDeposit(proposal3.ProposalID, TestAddrs[1], sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, 1))) + keeper.SetDeposit(ctx, deposit3) - // input.addrs[1] deposits on proposals #2 & #3 - res = handler(ctx, NewMsgDeposit(input.addrs[1], proposalID2, depositParams.MinDeposit)) - res = handler(ctx, NewMsgDeposit(input.addrs[1], proposalID3, depositParams.MinDeposit)) + // TestAddrs[1] deposits on proposals #2 & #3 + deposit4 := types.NewDeposit(proposal2.ProposalID, TestAddrs[1], depositParams.MinDeposit) + deposit5 := types.NewDeposit(proposal3.ProposalID, TestAddrs[1], depositParams.MinDeposit) + keeper.SetDeposit(ctx, deposit4) + keeper.SetDeposit(ctx, deposit5) // check deposits on proposal1 match individual deposits - deposits := getQueriedDeposits(t, ctx, cdc, querier, proposalID1) + deposits := getQueriedDeposits(t, ctx, keeper.cdc, querier, proposal1.ProposalID) require.Len(t, deposits, 1) - deposit := getQueriedDeposit(t, ctx, cdc, querier, proposalID1, input.addrs[0]) - require.Equal(t, deposit, deposits[0]) + require.Equal(t, deposit1, deposits[0]) + + deposit := getQueriedDeposit(t, ctx, keeper.cdc, querier, proposal1.ProposalID, TestAddrs[0]) + require.Equal(t, deposit1, deposit) // check deposits on proposal2 match individual deposits - deposits = getQueriedDeposits(t, ctx, cdc, querier, proposalID2) + deposits = getQueriedDeposits(t, ctx, keeper.cdc, querier, proposal2.ProposalID) require.Len(t, deposits, 2) - deposit = getQueriedDeposit(t, ctx, cdc, querier, proposalID2, input.addrs[0]) - require.True(t, deposit.Equals(deposits[0])) - deposit = getQueriedDeposit(t, ctx, cdc, querier, proposalID2, input.addrs[1]) - require.True(t, deposit.Equals(deposits[1])) + require.Equal(t, deposit2, deposits[0]) + require.Equal(t, deposit4, deposits[1]) + + deposit = getQueriedDeposit(t, ctx, keeper.cdc, querier, proposal2.ProposalID, TestAddrs[0]) + require.Equal(t, deposit2, deposits[0]) + deposit = getQueriedDeposit(t, ctx, keeper.cdc, querier, proposal2.ProposalID, TestAddrs[1]) + require.Equal(t, deposit4, deposits[1]) // check deposits on proposal3 match individual deposits - deposits = getQueriedDeposits(t, ctx, cdc, querier, proposalID3) + deposits = getQueriedDeposits(t, ctx, keeper.cdc, querier, proposal3.ProposalID) require.Len(t, deposits, 1) - deposit = getQueriedDeposit(t, ctx, cdc, querier, proposalID3, input.addrs[1]) - require.Equal(t, deposit, deposits[0]) + require.Equal(t, deposit5, deposits[0]) + + deposit = getQueriedDeposit(t, ctx, keeper.cdc, querier, proposal3.ProposalID, TestAddrs[1]) + require.Equal(t, deposi5, deposit) // Only proposal #1 should be in types.Deposit Period - proposals := getQueriedProposals(t, ctx, cdc, querier, nil, nil, StatusDepositPeriod, 0) + proposals := getQueriedProposals(t, ctx, keeper.cdc, querier, nil, nil, types.StatusDepositPeriod, 0) require.Len(t, proposals, 1) - require.Equal(t, proposalID1, proposals[0].ProposalID) + require.Equal(t, proposal1, proposals[0]) // Only proposals #2 and #3 should be in Voting Period - proposals = getQueriedProposals(t, ctx, cdc, querier, nil, nil, StatusVotingPeriod, 0) + proposals = getQueriedProposals(t, ctx, keeper.cdc, querier, nil, nil, types.StatusVotingPeriod, 0) require.Len(t, proposals, 2) - require.Equal(t, proposalID2, proposals[0].ProposalID) - require.Equal(t, proposalID3, proposals[1].ProposalID) + require.Equal(t, proposal2, proposals[0]) + require.Equal(t, proposal3, proposals[1]) // Addrs[0] votes on proposals #2 & #3 - require.True(t, handler(ctx, NewMsgVote(input.addrs[0], proposalID2, OptionYes)).IsOK()) - require.True(t, handler(ctx, NewMsgVote(input.addrs[0], proposalID3, OptionYes)).IsOK()) + vote1 := types.NewVote(proposal2.ProposalID, TestAddrs[0], types.OptionYes) + vote2 := types.NewVote(proposal3.ProposalID, TestAddrs[0], types.OptionYes) + keeper.SetVote(ctx, vote1) + keeper.SetVote(ctx, vote2) // Addrs[1] votes on proposal #3 - handler(ctx, NewMsgVote(input.addrs[1], proposalID3, OptionYes)) + vote3 := types.NewVote(proposal3.ProposalID, TestAddrs[1], types.OptionYes) + keeper.SetVote(ctx, vote3) - // Test query voted by input.addrs[0] - proposals = getQueriedProposals(t, ctx, cdc, querier, nil, input.addrs[0], StatusNil, 0) - require.Equal(t, proposalID2, (proposals[0]).ProposalID) - require.Equal(t, proposalID3, (proposals[1]).ProposalID) + // Test query voted by TestAddrs[0] + proposals = getQueriedProposals(t, ctx, keeper.cdc, querier, nil, TestAddrs[0], types.StatusNil, 0) + require.Equal(t, proposal2, proposals[0]) + require.Equal(t, proposal3, proposals[1]) // Test query votes on types.Proposal 2 - votes := getQueriedVotes(t, ctx, cdc, querier, proposalID2) + votes := getQueriedVotes(t, ctx, keeper.cdc, querier, proposal2.ProposalID) require.Len(t, votes, 1) - require.Equal(t, input.addrs[0], votes[0].Voter) + require.Equal(t, vote1, votes[0]) - vote := getQueriedVote(t, ctx, cdc, querier, proposalID2, input.addrs[0]) - require.Equal(t, vote, votes[0]) + vote := getQueriedVote(t, ctx, keeper.cdc, querier, proposal2.ProposalID, TestAddrs[0]) + require.Equal(t, vote1, vote) // Test query votes on types.Proposal 3 - votes = getQueriedVotes(t, ctx, cdc, querier, proposalID3) + votes = getQueriedVotes(t, ctx, keeper.cdc, querier, proposal3.ProposalID) require.Len(t, votes, 2) - require.True(t, input.addrs[0].String() == votes[0].Voter.String()) - require.True(t, input.addrs[1].String() == votes[1].Voter.String()) - - // Test proposals queries with filters + require.Equal(t, vote2, votes[0]) + require.Equal(t, vote3, votes[1]) // Test query all proposals - proposals = getQueriedProposals(t, ctx, cdc, querier, nil, nil, StatusNil, 0) - require.Equal(t, proposalID1, (proposals[0]).ProposalID) - require.Equal(t, proposalID2, (proposals[1]).ProposalID) - require.Equal(t, proposalID3, (proposals[2]).ProposalID) + proposals = getQueriedProposals(t, ctx, keeper.cdc, querier, nil, nil, types.StatusNil, 0) + require.Equal(t, proposal1, proposals[0]) + require.Equal(t, proposal2, proposals[1]) + require.Equal(t, proposal3, proposals[2]) - // Test query voted by input.addrs[1] - proposals = getQueriedProposals(t, ctx, cdc, querier, nil, input.addrs[1], StatusNil, 0) - require.Equal(t, proposalID3, (proposals[0]).ProposalID) + // Test query voted by TestAddrs[1] + proposals = getQueriedProposals(t, ctx, keeper.cdc, querier, nil, TestAddrs[1], types.StatusNil, 0) + require.Equal(t, proposal3.ProposalID, proposals[0].ProposalID) - // Test query deposited by input.addrs[0] - proposals = getQueriedProposals(t, ctx, cdc, querier, input.addrs[0], nil, StatusNil, 0) - require.Equal(t, proposalID1, (proposals[0]).ProposalID) + // Test query deposited by TestAddrs[0] + proposals = getQueriedProposals(t, ctx, keeper.cdc, querier, TestAddrs[0], nil, types.StatusNil, 0) + require.Equal(t, proposal1.ProposalID, proposals[0].ProposalID) // Test query deposited by addr2 - proposals = getQueriedProposals(t, ctx, cdc, querier, input.addrs[1], nil, StatusNil, 0) - require.Equal(t, proposalID2, (proposals[0]).ProposalID) - require.Equal(t, proposalID3, (proposals[1]).ProposalID) + proposals = getQueriedProposals(t, ctx, keeper.cdc, querier, TestAddrs[1], nil, types.StatusNil, 0) + require.Equal(t, proposal2.ProposalID, proposals[0].ProposalID) + require.Equal(t, proposal3.ProposalID, proposals[1].ProposalID) // Test query voted AND deposited by addr1 - proposals = getQueriedProposals(t, ctx, cdc, querier, input.addrs[0], input.addrs[0], StatusNil, 0) - require.Equal(t, proposalID2, (proposals[0]).ProposalID) + proposals = getQueriedProposals(t, ctx, keeper.cdc, querier, TestAddrs[0], TestAddrs[0], types.StatusNil, 0) + require.Equal(t, proposal2.ProposalID, proposals[0].ProposalID) } diff --git a/x/gov/keeper/tally_test.go b/x/gov/keeper/tally_test.go index 1cf978671595..bc73dbe7878e 100644 --- a/x/gov/keeper/tally_test.go +++ b/x/gov/keeper/tally_test.go @@ -5,7 +5,6 @@ import ( "github.com/stretchr/testify/require" - abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/crypto/ed25519" sdk "github.com/cosmos/cosmos-sdk/types" @@ -42,7 +41,7 @@ func TestTallyNoQuorum(t *testing.T) { proposal.Status = types.StatusVotingPeriod keeper.SetProposal(ctx, proposal) - err = keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionYes) + err = keeper.AddVote(ctx, proposalID, TestAddrs[0], types.OptionYes) require.Nil(t, err) proposal, ok := keeper.GetProposal(ctx, proposalID) @@ -62,9 +61,9 @@ func TestTallyOnlyValidatorsAllYes(t *testing.T) { proposal.Status = types.StatusVotingPeriod keeper.SetProposal(ctx, proposal) - err = keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionYes) + err = keeper.AddVote(ctx, proposalID, TestAddrs[0], types.OptionYes) require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionYes) + err = keeper.AddVote(ctx, proposalID, TestAddrs[1], types.OptionYes) require.Nil(t, err) proposal, ok := keeper.GetProposal(ctx, proposalID) @@ -86,9 +85,9 @@ func TestTallyOnlyValidators51No(t *testing.T) { proposal.Status = types.StatusVotingPeriod keeper.SetProposal(ctx, proposal) - err = keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionYes) + err = keeper.AddVote(ctx, proposalID, TestAddrs[0], types.OptionYes) require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionNo) + err = keeper.AddVote(ctx, proposalID, TestAddrs[1], types.OptionNo) require.Nil(t, err) proposal, ok := keeper.GetProposal(ctx, proposalID) @@ -109,11 +108,11 @@ func TestTallyOnlyValidators51Yes(t *testing.T) { proposal.Status = types.StatusVotingPeriod keeper.SetProposal(ctx, proposal) - err = keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionYes) + err = keeper.AddVote(ctx, proposalID, TestAddrs[0], types.OptionYes) require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionYes) + err = keeper.AddVote(ctx, proposalID, TestAddrs[1], types.OptionYes) require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, input.addrs[2], types.OptionNo) + err = keeper.AddVote(ctx, proposalID, TestAddrs[2], types.OptionNo) require.Nil(t, err) proposal, ok := keeper.GetProposal(ctx, proposalID) @@ -135,11 +134,11 @@ func TestTallyOnlyValidatorsVetoed(t *testing.T) { proposal.Status = types.StatusVotingPeriod keeper.SetProposal(ctx, proposal) - err = keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionYes) + err = keeper.AddVote(ctx, proposalID, TestAddrs[0], types.OptionYes) require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionYes) + err = keeper.AddVote(ctx, proposalID, TestAddrs[1], types.OptionYes) require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, input.addrs[2], types.OptionNoWithVeto) + err = keeper.AddVote(ctx, proposalID, TestAddrs[2], types.OptionNoWithVeto) require.Nil(t, err) proposal, ok := keeper.GetProposal(ctx, proposalID) @@ -162,11 +161,11 @@ func TestTallyOnlyValidatorsAbstainPasses(t *testing.T) { proposal.Status = types.StatusVotingPeriod keeper.SetProposal(ctx, proposal) - err = keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionAbstain) + err = keeper.AddVote(ctx, proposalID, TestAddrs[0], types.OptionAbstain) require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionNo) + err = keeper.AddVote(ctx, proposalID, TestAddrs[1], types.OptionNo) require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, input.addrs[2], types.OptionYes) + err = keeper.AddVote(ctx, proposalID, TestAddrs[2], types.OptionYes) require.Nil(t, err) proposal, ok := keeper.GetProposal(ctx, proposalID) @@ -188,11 +187,11 @@ func TestTallyOnlyValidatorsAbstainFails(t *testing.T) { proposal.Status = types.StatusVotingPeriod keeper.SetProposal(ctx, proposal) - err = keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionAbstain) + err = keeper.AddVote(ctx, proposalID, TestAddrs[0], types.OptionAbstain) require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionYes) + err = keeper.AddVote(ctx, proposalID, TestAddrs[1], types.OptionYes) require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, input.addrs[2], types.OptionNo) + err = keeper.AddVote(ctx, proposalID, TestAddrs[2], types.OptionNo) require.Nil(t, err) proposal, ok := keeper.GetProposal(ctx, proposalID) @@ -214,9 +213,9 @@ func TestTallyOnlyValidatorsNonVoter(t *testing.T) { proposal.Status = types.StatusVotingPeriod keeper.SetProposal(ctx, proposal) - err = keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionYes) + err = keeper.AddVote(ctx, proposalID, TestAddrs[1], types.OptionYes) require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, input.addrs[2], types.OptionNo) + err = keeper.AddVote(ctx, proposalID, TestAddrs[2], types.OptionNo) require.Nil(t, err) proposal, ok := keeper.GetProposal(ctx, proposalID) @@ -232,7 +231,7 @@ func TestTallyDelgatorOverride(t *testing.T) { ctx, _, keeper, _ := createTestInput(t, false, 100) delTokens := sdk.TokensFromConsensusPower(30) - delegator1Msg := staking.NewMsgDelegate(input.addrs[3], sdk.ValAddress(input.addrs[2]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) + delegator1Msg := staking.NewMsgDelegate(TestAddrs[3], sdk.ValAddress(TestAddrs[2]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) stakingHandler(ctx, delegator1Msg) tp := TestProposal() @@ -242,13 +241,13 @@ func TestTallyDelgatorOverride(t *testing.T) { proposal.Status = types.StatusVotingPeriod keeper.SetProposal(ctx, proposal) - err = keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionYes) + err = keeper.AddVote(ctx, proposalID, TestAddrs[0], types.OptionYes) require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionYes) + err = keeper.AddVote(ctx, proposalID, TestAddrs[1], types.OptionYes) require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, input.addrs[2], types.OptionYes) + err = keeper.AddVote(ctx, proposalID, TestAddrs[2], types.OptionYes) require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, input.addrs[3], types.OptionNo) + err = keeper.AddVote(ctx, proposalID, TestAddrs[3], types.OptionNo) require.Nil(t, err) proposal, ok := keeper.GetProposal(ctx, proposalID) @@ -264,7 +263,7 @@ func TestTallyDelgatorInherit(t *testing.T) { ctx, _, keeper, _ := createTestInput(t, false, 100) delTokens := sdk.TokensFromConsensusPower(30) - delegator1Msg := staking.NewMsgDelegate(input.addrs[3], sdk.ValAddress(input.addrs[2]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) + delegator1Msg := staking.NewMsgDelegate(TestAddrs[3], sdk.ValAddress(TestAddrs[2]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) stakingHandler(ctx, delegator1Msg) tp := TestProposal() @@ -274,11 +273,11 @@ func TestTallyDelgatorInherit(t *testing.T) { proposal.Status = types.StatusVotingPeriod keeper.SetProposal(ctx, proposal) - err = keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionNo) + err = keeper.AddVote(ctx, proposalID, TestAddrs[0], types.OptionNo) require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionNo) + err = keeper.AddVote(ctx, proposalID, TestAddrs[1], types.OptionNo) require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, input.addrs[2], types.OptionYes) + err = keeper.AddVote(ctx, proposalID, TestAddrs[2], types.OptionYes) require.Nil(t, err) proposal, ok := keeper.GetProposal(ctx, proposalID) @@ -294,9 +293,9 @@ func TestTallyDelgatorMultipleOverride(t *testing.T) { ctx, _, keeper, _ := createTestInput(t, false, 100) delTokens := sdk.TokensFromConsensusPower(10) - delegator1Msg := staking.NewMsgDelegate(input.addrs[3], sdk.ValAddress(input.addrs[2]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) + delegator1Msg := staking.NewMsgDelegate(TestAddrs[3], sdk.ValAddress(TestAddrs[2]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) stakingHandler(ctx, delegator1Msg) - delegator1Msg2 := staking.NewMsgDelegate(input.addrs[3], sdk.ValAddress(input.addrs[1]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) + delegator1Msg2 := staking.NewMsgDelegate(TestAddrs[3], sdk.ValAddress(TestAddrs[1]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) stakingHandler(ctx, delegator1Msg2) tp := TestProposal() @@ -306,13 +305,13 @@ func TestTallyDelgatorMultipleOverride(t *testing.T) { proposal.Status = types.StatusVotingPeriod keeper.SetProposal(ctx, proposal) - err = keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionYes) + err = keeper.AddVote(ctx, proposalID, TestAddrs[0], types.OptionYes) require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionYes) + err = keeper.AddVote(ctx, proposalID, TestAddrs[1], types.OptionYes) require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, input.addrs[2], types.OptionYes) + err = keeper.AddVote(ctx, proposalID, TestAddrs[2], types.OptionYes) require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, input.addrs[3], types.OptionNo) + err = keeper.AddVote(ctx, proposalID, TestAddrs[3], types.OptionNo) require.Nil(t, err) proposal, ok := keeper.GetProposal(ctx, proposalID) @@ -326,36 +325,31 @@ func TestTallyDelgatorMultipleOverride(t *testing.T) { func TestTallyDelgatorMultipleInherit(t *testing.T) { ctx, _, keeper, _ := createTestInput(t, false, 100) - - header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} - input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) - - ctx := input.mApp.BaseApp.NewContext(false, abci.Header{}) stakingHandler := staking.NewHandler(input.sk) valTokens1 := sdk.TokensFromConsensusPower(25) val1CreateMsg := staking.NewMsgCreateValidator( - sdk.ValAddress(input.addrs[0]), ed25519.GenPrivKey().PubKey(), sdk.NewCoin(sdk.DefaultBondDenom, valTokens1), testDescription, testCommissionRates, sdk.OneInt(), + sdk.ValAddress(TestAddrs[0]), ed25519.GenPrivKey().PubKey(), sdk.NewCoin(sdk.DefaultBondDenom, valTokens1), testDescription, testCommissionRates, sdk.OneInt(), ) stakingHandler(ctx, val1CreateMsg) valTokens2 := sdk.TokensFromConsensusPower(6) val2CreateMsg := staking.NewMsgCreateValidator( - sdk.ValAddress(input.addrs[1]), ed25519.GenPrivKey().PubKey(), sdk.NewCoin(sdk.DefaultBondDenom, valTokens2), testDescription, testCommissionRates, sdk.OneInt(), + sdk.ValAddress(TestAddrs[1]), ed25519.GenPrivKey().PubKey(), sdk.NewCoin(sdk.DefaultBondDenom, valTokens2), testDescription, testCommissionRates, sdk.OneInt(), ) stakingHandler(ctx, val2CreateMsg) valTokens3 := sdk.TokensFromConsensusPower(7) val3CreateMsg := staking.NewMsgCreateValidator( - sdk.ValAddress(input.addrs[2]), ed25519.GenPrivKey().PubKey(), sdk.NewCoin(sdk.DefaultBondDenom, valTokens3), testDescription, testCommissionRates, sdk.OneInt(), + sdk.ValAddress(TestAddrs[2]), ed25519.GenPrivKey().PubKey(), sdk.NewCoin(sdk.DefaultBondDenom, valTokens3), testDescription, testCommissionRates, sdk.OneInt(), ) stakingHandler(ctx, val3CreateMsg) delTokens := sdk.TokensFromConsensusPower(10) - delegator1Msg := staking.NewMsgDelegate(input.addrs[3], sdk.ValAddress(input.addrs[2]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) + delegator1Msg := staking.NewMsgDelegate(TestAddrs[3], sdk.ValAddress(TestAddrs[2]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) stakingHandler(ctx, delegator1Msg) - delegator1Msg2 := staking.NewMsgDelegate(input.addrs[3], sdk.ValAddress(input.addrs[1]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) + delegator1Msg2 := staking.NewMsgDelegate(TestAddrs[3], sdk.ValAddress(TestAddrs[1]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) stakingHandler(ctx, delegator1Msg2) staking.EndBlocker(ctx, input.sk) @@ -367,11 +361,11 @@ func TestTallyDelgatorMultipleInherit(t *testing.T) { proposal.Status = types.StatusVotingPeriod keeper.SetProposal(ctx, proposal) - err = keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionYes) + err = keeper.AddVote(ctx, proposalID, TestAddrs[0], types.OptionYes) require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionNo) + err = keeper.AddVote(ctx, proposalID, TestAddrs[1], types.OptionNo) require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, input.addrs[2], types.OptionNo) + err = keeper.AddVote(ctx, proposalID, TestAddrs[2], types.OptionNo) require.Nil(t, err) proposal, ok := keeper.GetProposal(ctx, proposalID) @@ -387,13 +381,13 @@ func TestTallyJailedValidator(t *testing.T) { ctx, _, keeper, _ := createTestInput(t, false, 100) delTokens := sdk.TokensFromConsensusPower(10) - delegator1Msg := staking.NewMsgDelegate(input.addrs[3], sdk.ValAddress(input.addrs[2]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) + delegator1Msg := staking.NewMsgDelegate(TestAddrs[3], sdk.ValAddress(TestAddrs[2]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) stakingHandler(ctx, delegator1Msg) - delegator1Msg2 := staking.NewMsgDelegate(input.addrs[3], sdk.ValAddress(input.addrs[1]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) + delegator1Msg2 := staking.NewMsgDelegate(TestAddrs[3], sdk.ValAddress(TestAddrs[1]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) stakingHandler(ctx, delegator1Msg2) - val2, found := input.sk.GetValidator(ctx, sdk.ValAddress(input.addrs[1])) + val2, found := input.sk.GetValidator(ctx, sdk.ValAddress(TestAddrs[1])) require.True(t, found) input.sk.Jail(ctx, sdk.ConsAddress(val2.ConsPubKey.Address())) @@ -406,11 +400,11 @@ func TestTallyJailedValidator(t *testing.T) { proposal.Status = types.StatusVotingPeriod keeper.SetProposal(ctx, proposal) - err = keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionYes) + err = keeper.AddVote(ctx, proposalID, TestAddrs[0], types.OptionYes) require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionNo) + err = keeper.AddVote(ctx, proposalID, TestAddrs[1], types.OptionNo) require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, input.addrs[2], types.OptionNo) + err = keeper.AddVote(ctx, proposalID, TestAddrs[2], types.OptionNo) require.Nil(t, err) proposal, ok := keeper.GetProposal(ctx, proposalID) diff --git a/x/gov/keeper/vote_test.go b/x/gov/keeper/vote_test.go index b0058a000438..0f4421f0c828 100644 --- a/x/gov/keeper/vote_test.go +++ b/x/gov/keeper/vote_test.go @@ -1,14 +1,10 @@ package keeper import ( - "strings" "testing" - "time" "github.com/stretchr/testify/require" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/gov/types" ) @@ -24,26 +20,26 @@ func TestVotes(t *testing.T) { keeper.SetProposal(ctx, proposal) // Test first vote - keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionAbstain) - vote, found := keeper.GetVote(ctx, proposalID, input.addrs[0]) + keeper.AddVote(ctx, proposalID, TestAddrs[0], types.OptionAbstain) + vote, found := keeper.GetVote(ctx, proposalID, TestAddrs[0]) require.True(t, found) - require.Equal(t, input.addrs[0], vote.Voter) + require.Equal(t, TestAddrs[0], vote.Voter) require.Equal(t, proposalID, vote.ProposalID) require.Equal(t, types.OptionAbstain, vote.Option) // Test change of vote - keeper.AddVote(ctx, proposalID, input.addrs[0], types.OptionYes) - vote, found = keeper.GetVote(ctx, proposalID, input.addrs[0]) + keeper.AddVote(ctx, proposalID, TestAddrs[0], types.OptionYes) + vote, found = keeper.GetVote(ctx, proposalID, TestAddrs[0]) require.True(t, found) - require.Equal(t, input.addrs[0], vote.Voter) + require.Equal(t, TestAddrs[0], vote.Voter) require.Equal(t, proposalID, vote.ProposalID) require.Equal(t, types.OptionYes, vote.Option) // Test second vote - keeper.AddVote(ctx, proposalID, input.addrs[1], types.OptionNoWithVeto) - vote, found = keeper.GetVote(ctx, proposalID, input.addrs[1]) + keeper.AddVote(ctx, proposalID, TestAddrs[1], types.OptionNoWithVeto) + vote, found = keeper.GetVote(ctx, proposalID, TestAddrs[1]) require.True(t, found) - require.Equal(t, input.addrs[1], vote.Voter) + require.Equal(t, TestAddrs[1], vote.Voter) require.Equal(t, proposalID, vote.ProposalID) require.Equal(t, types.OptionNoWithVeto, vote.Option) @@ -52,14 +48,14 @@ func TestVotes(t *testing.T) { require.True(t, votesIterator.Valid()) keeper.cdc.MustUnmarshalBinaryLengthPrefixed(votesIterator.Value(), &vote) require.True(t, votesIterator.Valid()) - require.Equal(t, input.addrs[0], vote.Voter) + require.Equal(t, TestAddrs[0], vote.Voter) require.Equal(t, proposalID, vote.ProposalID) require.Equal(t, types.OptionYes, vote.Option) votesIterator.Next() require.True(t, votesIterator.Valid()) keeper.cdc.MustUnmarshalBinaryLengthPrefixed(votesIterator.Value(), &vote) require.True(t, votesIterator.Valid()) - require.Equal(t, input.addrs[1], vote.Voter) + require.Equal(t, TestAddrs[1], vote.Voter) require.Equal(t, proposalID, vote.ProposalID) require.Equal(t, types.OptionNoWithVeto, vote.Option) votesIterator.Next() diff --git a/x/gov/types/expected_keepers.go b/x/gov/types/expected_keepers.go index 3b0691ab5723..7fd90ca620ee 100644 --- a/x/gov/types/expected_keepers.go +++ b/x/gov/types/expected_keepers.go @@ -2,10 +2,18 @@ package types import ( sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/params/subspace" stakingexported "github.com/cosmos/cosmos-sdk/x/staking/exported" supplyexported "github.com/cosmos/cosmos-sdk/x/supply/exported" ) +// ParamSubspace defines the expected Subspace interface for parameters +type ParamSubspace interface { + WithKeyTable(table subspace.KeyTable) subspace.Subspace + Get(ctx sdk.Context, key []byte, ptr interface{}) + Set(ctx sdk.Context, key []byte, param interface{}) +} + // SupplyKeeper defines the supply Keeper for module accounts (noalias) type SupplyKeeper interface { GetModuleAddress(name string) sdk.AccAddress From e277bf8ee936885bc8b538f0e1fb7b85cd472472 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Mon, 15 Jul 2019 15:54:35 +0200 Subject: [PATCH 10/36] more cleanup --- x/gov/abci_test.go | 10 ++--- x/gov/genesis_test.go | 4 +- x/gov/keeper/deposit_test.go | 4 +- x/gov/keeper/keeper_test.go | 8 ++-- x/gov/keeper/proposal_test.go | 10 ++--- x/gov/keeper/querier_test.go | 9 +++-- x/gov/keeper/tally_test.go | 76 ++++++++++++++++++----------------- x/gov/keeper/test_common.go | 21 ++++++++-- x/gov/keeper/vote_test.go | 4 +- x/gov/test_common.go | 5 +-- x/gov/types/genesis.go | 39 +++++------------- x/gov/types/params.go | 50 ++++++++++++++++++++--- x/gov/types/proposal.go | 20 +++++---- 13 files changed, 152 insertions(+), 108 deletions(-) diff --git a/x/gov/abci_test.go b/x/gov/abci_test.go index 56b684624745..e27dd9dd32f8 100644 --- a/x/gov/abci_test.go +++ b/x/gov/abci_test.go @@ -196,7 +196,7 @@ func TestTickPassedVotingPeriod(t *testing.T) { activeQueue.Close() proposalCoins := sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.TokensFromConsensusPower(5))} - newProposalMsg := NewMsgSubmitProposal(keep.TestProposal(), proposalCoins, input.addrs[0]) + newProposalMsg := NewMsgSubmitProposal(keep.TestProposal, proposalCoins, input.addrs[0]) res := govHandler(ctx, newProposalMsg) require.True(t, res.IsOK()) @@ -245,7 +245,7 @@ func TestProposalPassedEndblocker(t *testing.T) { SortAddresses(input.addrs) handler := NewHandler(input.keeper) - stakingHandler := staking.NewHandler(input.sk) + stakingHandler := keep.StakingHandler(input.sk) header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) @@ -260,7 +260,7 @@ func TestProposalPassedEndblocker(t *testing.T) { require.NotNil(t, macc) initialModuleAccCoins := macc.GetCoins() - proposal, err := input.keeper.SubmitProposal(ctx, keep.TestProposal()) + proposal, err := input.keeper.SubmitProposal(ctx, keep.TestProposal) require.NoError(t, err) proposalCoins := sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.TokensFromConsensusPower(10))} @@ -298,7 +298,7 @@ func TestEndBlockerProposalHandlerFailed(t *testing.T) { input.keeper.router = NewRouter().AddRoute(RouterKey, badProposalHandler) handler := NewHandler(input.keeper) - stakingHandler := staking.NewHandler(input.sk) + stakingHandler := keep.StakingHandler(input.sk) header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) @@ -312,7 +312,7 @@ func TestEndBlockerProposalHandlerFailed(t *testing.T) { // Create a proposal where the handler will pass for the test proposal // because the value of contextKeyBadProposal is true. ctx = ctx.WithValue(contextKeyBadProposal, true) - proposal, err := input.keeper.SubmitProposal(ctx, keep.TestProposal()) + proposal, err := input.keeper.SubmitProposal(ctx, keep.TestProposal) require.NoError(t, err) proposalCoins := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.TokensFromConsensusPower(10))) diff --git a/x/gov/genesis_test.go b/x/gov/genesis_test.go index c8c0ef1641ab..19999bcd9ff8 100644 --- a/x/gov/genesis_test.go +++ b/x/gov/genesis_test.go @@ -20,7 +20,7 @@ func TestImportExportQueues(t *testing.T) { ctx := input.mApp.BaseApp.NewContext(false, abci.Header{}) // Create two proposals, put the second into the voting period - proposal := keep.TestProposal() + proposal := keep.TestProposal proposal1, err := input.keeper.SubmitProposal(ctx, proposal) require.NoError(t, err) proposalID1 := proposal1.ProposalID @@ -85,7 +85,7 @@ func TestEqualProposals(t *testing.T) { ctx := input.mApp.BaseApp.NewContext(false, abci.Header{}) // Submit two proposals - proposal := keep.TestProposal() + proposal := keep.TestProposal proposal1, err := input.keeper.SubmitProposal(ctx, proposal) require.NoError(t, err) proposal2, err := input.keeper.SubmitProposal(ctx, proposal) diff --git a/x/gov/keeper/deposit_test.go b/x/gov/keeper/deposit_test.go index dd0a213dc576..ee8932ba62d2 100644 --- a/x/gov/keeper/deposit_test.go +++ b/x/gov/keeper/deposit_test.go @@ -10,9 +10,9 @@ import ( ) func TestDeposits(t *testing.T) { - ctx, ak, keeper, _ := createTestInput(t, false, 100) + ctx, ak, keeper, _, _ := createTestInput(t, false, 100) - tp := TestProposal() + tp := TestProposal proposal, err := keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID diff --git a/x/gov/keeper/keeper_test.go b/x/gov/keeper/keeper_test.go index 04d3e8b776be..a99f43c12e4a 100644 --- a/x/gov/keeper/keeper_test.go +++ b/x/gov/keeper/keeper_test.go @@ -7,9 +7,9 @@ import ( ) func TestIncrementProposalNumber(t *testing.T) { - ctx, _, keeper, _ := createTestInput(t, false, 100) + ctx, _, keeper, _, _ := createTestInput(t, false, 100) - tp := TestProposal() + tp := TestProposal keeper.SubmitProposal(ctx, tp) keeper.SubmitProposal(ctx, tp) keeper.SubmitProposal(ctx, tp) @@ -22,10 +22,10 @@ func TestIncrementProposalNumber(t *testing.T) { } func TestProposalQueues(t *testing.T) { - ctx, _, keeper, _ := createTestInput(t, false, 100) + ctx, _, keeper, _, _ := createTestInput(t, false, 100) // create test proposals - tp := TestProposal() + tp := TestProposal proposal, err := keeper.SubmitProposal(ctx, tp) require.NoError(t, err) diff --git a/x/gov/keeper/proposal_test.go b/x/gov/keeper/proposal_test.go index ed3a247e93db..26beba86eab8 100644 --- a/x/gov/keeper/proposal_test.go +++ b/x/gov/keeper/proposal_test.go @@ -12,9 +12,9 @@ import ( ) func TestGetSetProposal(t *testing.T) { - ctx, _, keeper, _ := createTestInput(t, false, 100) + ctx, _, keeper, _, _ := createTestInput(t, false, 100) - tp := TestProposal() + tp := TestProposal proposal, err := keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID @@ -26,9 +26,9 @@ func TestGetSetProposal(t *testing.T) { } func TestActivateVotingPeriod(t *testing.T) { - ctx, _, keeper, _ := createTestInput(t, false, 100) + ctx, _, keeper, _, _ := createTestInput(t, false, 100) - tp := TestProposal() + tp := TestProposal proposal, err := keeper.SubmitProposal(ctx, tp) require.NoError(t, err) @@ -95,7 +95,7 @@ func registerTestCodec(cdc *codec.Codec) { } func TestSubmitProposal(t *testing.T) { - ctx, _, keeper, _ := createTestInput(t, false, 100) + ctx, _, keeper, _, _ := createTestInput(t, false, 100) registerTestCodec(keeper.cdc) diff --git a/x/gov/keeper/querier_test.go b/x/gov/keeper/querier_test.go index bbd1aa2c6f33..43f8d6020281 100644 --- a/x/gov/keeper/querier_test.go +++ b/x/gov/keeper/querier_test.go @@ -167,24 +167,27 @@ func getQueriedTally(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sd } func TestQueries(t *testing.T) { - ctx, _, keeper, _ := createTestInput(t, false, 1000) + ctx, _, keeper, _, _ := createTestInput(t, false, 1000) querier := NewQuerier(keeper) - tp := TestProposal() + tp := TestProposal depositParams, _, _ := getQueriedParams(t, ctx, keeper.cdc, querier) // TestAddrs[0] proposes (and deposits) proposals #1 and #2 proposal1, err := keeper.SubmitProposal(ctx, tp) + require.NoError(t, err) deposit1 := types.NewDeposit(proposal1.ProposalID, TestAddrs[0], sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, 1))) keeper.SetDeposit(ctx, deposit1) proposal2, err := keeper.SubmitProposal(ctx, tp) + require.NoError(t, err) deposit2 := types.NewDeposit(proposal2.ProposalID, TestAddrs[0], sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, 10000000))) keeper.SetDeposit(ctx, deposit2) // TestAddrs[1] proposes (and deposits) on proposal #3 proposal3, err := keeper.SubmitProposal(ctx, tp) + require.NoError(t, err) deposit3 := types.NewDeposit(proposal3.ProposalID, TestAddrs[1], sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, 1))) keeper.SetDeposit(ctx, deposit3) @@ -219,7 +222,7 @@ func TestQueries(t *testing.T) { require.Equal(t, deposit5, deposits[0]) deposit = getQueriedDeposit(t, ctx, keeper.cdc, querier, proposal3.ProposalID, TestAddrs[1]) - require.Equal(t, deposi5, deposit) + require.Equal(t, deposit5, deposit) // Only proposal #1 should be in types.Deposit Period proposals := getQueriedProposals(t, ctx, keeper.cdc, querier, nil, nil, types.StatusDepositPeriod, 0) diff --git a/x/gov/keeper/tally_test.go b/x/gov/keeper/tally_test.go index bc73dbe7878e..4543c6efc730 100644 --- a/x/gov/keeper/tally_test.go +++ b/x/gov/keeper/tally_test.go @@ -13,9 +13,9 @@ import ( ) func TestTallyNoOneVotes(t *testing.T) { - ctx, _, keeper, _ := createTestInput(t, false, 100) + ctx, _, keeper, _, _ := createTestInput(t, false, 100) - tp := TestProposal() + tp := TestProposal proposal, err := keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID @@ -32,9 +32,9 @@ func TestTallyNoOneVotes(t *testing.T) { } func TestTallyNoQuorum(t *testing.T) { - ctx, _, keeper, _ := createTestInput(t, false, 100) + ctx, _, keeper, _, _ := createTestInput(t, false, 100) - tp := TestProposal() + tp := TestProposal proposal, err := keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID @@ -52,9 +52,9 @@ func TestTallyNoQuorum(t *testing.T) { } func TestTallyOnlyValidatorsAllYes(t *testing.T) { - ctx, _, keeper, _ := createTestInput(t, false, 100) + ctx, _, keeper, _, _ := createTestInput(t, false, 100) - tp := TestProposal() + tp := TestProposal proposal, err := keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID @@ -76,9 +76,9 @@ func TestTallyOnlyValidatorsAllYes(t *testing.T) { } func TestTallyOnlyValidators51No(t *testing.T) { - ctx, _, keeper, _ := createTestInput(t, false, 100) + ctx, _, keeper, _, _ := createTestInput(t, false, 100) - tp := TestProposal() + tp := TestProposal proposal, err := keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID @@ -99,9 +99,9 @@ func TestTallyOnlyValidators51No(t *testing.T) { } func TestTallyOnlyValidators51Yes(t *testing.T) { - ctx, _, keeper, _ := createTestInput(t, false, 100) + ctx, _, keeper, _, _ := createTestInput(t, false, 100) - tp := TestProposal() + tp := TestProposal proposal, err := keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID @@ -125,9 +125,9 @@ func TestTallyOnlyValidators51Yes(t *testing.T) { } func TestTallyOnlyValidatorsVetoed(t *testing.T) { - ctx, _, keeper, _ := createTestInput(t, false, 100) + ctx, _, keeper, _, _ := createTestInput(t, false, 100) - tp := TestProposal() + tp := TestProposal proposal, err := keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID @@ -152,9 +152,9 @@ func TestTallyOnlyValidatorsVetoed(t *testing.T) { } func TestTallyOnlyValidatorsAbstainPasses(t *testing.T) { - ctx, _, keeper, _ := createTestInput(t, false, 100) + ctx, _, keeper, _, _ := createTestInput(t, false, 100) - tp := TestProposal() + tp := TestProposal proposal, err := keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID @@ -178,9 +178,9 @@ func TestTallyOnlyValidatorsAbstainPasses(t *testing.T) { } func TestTallyOnlyValidatorsAbstainFails(t *testing.T) { - ctx, _, keeper, _ := createTestInput(t, false, 100) + ctx, _, keeper, _, _ := createTestInput(t, false, 100) - tp := TestProposal() + tp := TestProposal proposal, err := keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID @@ -204,9 +204,9 @@ func TestTallyOnlyValidatorsAbstainFails(t *testing.T) { } func TestTallyOnlyValidatorsNonVoter(t *testing.T) { - ctx, _, keeper, _ := createTestInput(t, false, 100) + ctx, _, keeper, _, _ := createTestInput(t, false, 100) - tp := TestProposal() + tp := TestProposal proposal, err := keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID @@ -228,13 +228,14 @@ func TestTallyOnlyValidatorsNonVoter(t *testing.T) { } func TestTallyDelgatorOverride(t *testing.T) { - ctx, _, keeper, _ := createTestInput(t, false, 100) + ctx, _, keeper, sk, _ := createTestInput(t, false, 100) + stakingHandler := StakingHandler(sk) delTokens := sdk.TokensFromConsensusPower(30) delegator1Msg := staking.NewMsgDelegate(TestAddrs[3], sdk.ValAddress(TestAddrs[2]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) stakingHandler(ctx, delegator1Msg) - tp := TestProposal() + tp := TestProposal proposal, err := keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID @@ -260,13 +261,14 @@ func TestTallyDelgatorOverride(t *testing.T) { } func TestTallyDelgatorInherit(t *testing.T) { - ctx, _, keeper, _ := createTestInput(t, false, 100) + ctx, _, keeper, sk, _ := createTestInput(t, false, 100) + stakingHandler := StakingHandler(sk) delTokens := sdk.TokensFromConsensusPower(30) delegator1Msg := staking.NewMsgDelegate(TestAddrs[3], sdk.ValAddress(TestAddrs[2]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) stakingHandler(ctx, delegator1Msg) - tp := TestProposal() + tp := TestProposal proposal, err := keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID @@ -290,7 +292,8 @@ func TestTallyDelgatorInherit(t *testing.T) { } func TestTallyDelgatorMultipleOverride(t *testing.T) { - ctx, _, keeper, _ := createTestInput(t, false, 100) + ctx, _, keeper, sk, _ := createTestInput(t, false, 100) + stakingHandler := StakingHandler(sk) delTokens := sdk.TokensFromConsensusPower(10) delegator1Msg := staking.NewMsgDelegate(TestAddrs[3], sdk.ValAddress(TestAddrs[2]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) @@ -298,7 +301,7 @@ func TestTallyDelgatorMultipleOverride(t *testing.T) { delegator1Msg2 := staking.NewMsgDelegate(TestAddrs[3], sdk.ValAddress(TestAddrs[1]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) stakingHandler(ctx, delegator1Msg2) - tp := TestProposal() + tp := TestProposal proposal, err := keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID @@ -324,24 +327,24 @@ func TestTallyDelgatorMultipleOverride(t *testing.T) { } func TestTallyDelgatorMultipleInherit(t *testing.T) { - ctx, _, keeper, _ := createTestInput(t, false, 100) - stakingHandler := staking.NewHandler(input.sk) + ctx, _, keeper, sk, _ := createTestInput(t, false, 100) + stakingHandler := StakingHandler(sk) valTokens1 := sdk.TokensFromConsensusPower(25) val1CreateMsg := staking.NewMsgCreateValidator( - sdk.ValAddress(TestAddrs[0]), ed25519.GenPrivKey().PubKey(), sdk.NewCoin(sdk.DefaultBondDenom, valTokens1), testDescription, testCommissionRates, sdk.OneInt(), + sdk.ValAddress(TestAddrs[0]), ed25519.GenPrivKey().PubKey(), sdk.NewCoin(sdk.DefaultBondDenom, valTokens1), TestDescription, TestCommissionRates, sdk.OneInt(), ) stakingHandler(ctx, val1CreateMsg) valTokens2 := sdk.TokensFromConsensusPower(6) val2CreateMsg := staking.NewMsgCreateValidator( - sdk.ValAddress(TestAddrs[1]), ed25519.GenPrivKey().PubKey(), sdk.NewCoin(sdk.DefaultBondDenom, valTokens2), testDescription, testCommissionRates, sdk.OneInt(), + sdk.ValAddress(TestAddrs[1]), ed25519.GenPrivKey().PubKey(), sdk.NewCoin(sdk.DefaultBondDenom, valTokens2), TestDescription, TestCommissionRates, sdk.OneInt(), ) stakingHandler(ctx, val2CreateMsg) valTokens3 := sdk.TokensFromConsensusPower(7) val3CreateMsg := staking.NewMsgCreateValidator( - sdk.ValAddress(TestAddrs[2]), ed25519.GenPrivKey().PubKey(), sdk.NewCoin(sdk.DefaultBondDenom, valTokens3), testDescription, testCommissionRates, sdk.OneInt(), + sdk.ValAddress(TestAddrs[2]), ed25519.GenPrivKey().PubKey(), sdk.NewCoin(sdk.DefaultBondDenom, valTokens3), TestDescription, TestCommissionRates, sdk.OneInt(), ) stakingHandler(ctx, val3CreateMsg) @@ -352,9 +355,9 @@ func TestTallyDelgatorMultipleInherit(t *testing.T) { delegator1Msg2 := staking.NewMsgDelegate(TestAddrs[3], sdk.ValAddress(TestAddrs[1]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) stakingHandler(ctx, delegator1Msg2) - staking.EndBlocker(ctx, input.sk) + staking.EndBlocker(ctx, sk) - tp := TestProposal() + tp := TestProposal proposal, err := keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID @@ -378,7 +381,8 @@ func TestTallyDelgatorMultipleInherit(t *testing.T) { } func TestTallyJailedValidator(t *testing.T) { - ctx, _, keeper, _ := createTestInput(t, false, 100) + ctx, _, keeper, sk, _ := createTestInput(t, false, 100) + stakingHandler := StakingHandler(sk) delTokens := sdk.TokensFromConsensusPower(10) delegator1Msg := staking.NewMsgDelegate(TestAddrs[3], sdk.ValAddress(TestAddrs[2]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) @@ -387,13 +391,13 @@ func TestTallyJailedValidator(t *testing.T) { delegator1Msg2 := staking.NewMsgDelegate(TestAddrs[3], sdk.ValAddress(TestAddrs[1]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) stakingHandler(ctx, delegator1Msg2) - val2, found := input.sk.GetValidator(ctx, sdk.ValAddress(TestAddrs[1])) + val2, found := sk.GetValidator(ctx, sdk.ValAddress(TestAddrs[1])) require.True(t, found) - input.sk.Jail(ctx, sdk.ConsAddress(val2.ConsPubKey.Address())) + sk.Jail(ctx, sdk.ConsAddress(val2.ConsPubKey.Address())) - staking.EndBlocker(ctx, input.sk) + staking.EndBlocker(ctx, sk) - tp := TestProposal() + tp := TestProposal proposal, err := keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID diff --git a/x/gov/keeper/test_common.go b/x/gov/keeper/test_common.go index 20737dbd11bc..e4e1fd9606c2 100644 --- a/x/gov/keeper/test_common.go +++ b/x/gov/keeper/test_common.go @@ -56,6 +56,13 @@ var ( emptyPubkey crypto.PubKey ) +// TODO: remove dependency with staking +var ( + TestProposal = types.NewTextProposal("Test", "description") + TestDescription = staking.NewDescription("T", "E", "S", "T") + TestCommissionRates = staking.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()) +) + func makeTestCodec() *codec.Codec { var cdc = codec.New() auth.RegisterCodec(cdc) @@ -68,7 +75,7 @@ func makeTestCodec() *codec.Codec { return cdc } -func createTestInput(t *testing.T, isCheckTx bool, initPower int64) (sdk.Context, auth.AccountKeeper, Keeper, types.SupplyKeeper) { +func createTestInput(t *testing.T, isCheckTx bool, initPower int64) (sdk.Context, auth.AccountKeeper, Keeper, staking.Keeper, types.SupplyKeeper) { initTokens := sdk.TokensFromConsensusPower(initPower) @@ -120,6 +127,11 @@ func createTestInput(t *testing.T, isCheckTx bool, initPower int64) (sdk.Context keeper := NewKeeper(cdc, keyGov, pk.Subspace(types.DefaultParamspace), supplyKeeper, sk, types.DefaultCodespace, rtr) + keeper.SetProposalID(ctx, types.DefaultStartingProposalID) + keeper.SetDepositParams(ctx, types.DefaultDepositParams()) + keeper.SetVotingParams(ctx, types.DefaultVotingParams()) + keeper.SetTallyParams(ctx, types.DefaultTallyParams()) + initCoins := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), initTokens)) totalSupply := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), initTokens.MulRaw(int64(len(TestAddrs))))) supplyKeeper.SetSupply(ctx, supply.NewSupply(totalSupply)) @@ -136,11 +148,12 @@ func createTestInput(t *testing.T, isCheckTx bool, initPower int64) (sdk.Context keeper.supplyKeeper.SetModuleAccount(ctx, feeCollectorAcc) keeper.supplyKeeper.SetModuleAccount(ctx, govAcc) - return ctx, accountKeeper, keeper, supplyKeeper + return ctx, accountKeeper, keeper, sk, supplyKeeper } -func TestProposal() types.Content { - return types.NewTextProposal("Test", "description") +// TODO: remove dependency with staking +func StakingHandler(sk staking.Keeper) sdk.Handler{ + return staking.NewHandler(sk) } // ProposalEqual checks if two proposals are equal (note: slow, for tests only) diff --git a/x/gov/keeper/vote_test.go b/x/gov/keeper/vote_test.go index 0f4421f0c828..954424ba9d2d 100644 --- a/x/gov/keeper/vote_test.go +++ b/x/gov/keeper/vote_test.go @@ -9,9 +9,9 @@ import ( ) func TestVotes(t *testing.T) { - ctx, _, keeper, _ := createTestInput(t, false, 100) + ctx, _, keeper, _, _ := createTestInput(t, false, 100) - tp := TestProposal() + tp := TestProposal proposal, err := keeper.SubmitProposal(ctx, tp) require.NoError(t, err) proposalID := proposal.ProposalID diff --git a/x/gov/test_common.go b/x/gov/test_common.go index 1c959e4bac21..4cbe7436d8b9 100644 --- a/x/gov/test_common.go +++ b/x/gov/test_common.go @@ -203,9 +203,6 @@ var ( ed25519.GenPrivKey().PubKey(), ed25519.GenPrivKey().PubKey(), } - - testDescription = staking.NewDescription("T", "E", "S", "T") - testCommissionRates = staking.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()) ) func createValidators(t *testing.T, stakingHandler sdk.Handler, ctx sdk.Context, addrs []sdk.ValAddress, powerAmt []int64) { @@ -216,7 +213,7 @@ func createValidators(t *testing.T, stakingHandler sdk.Handler, ctx sdk.Context, valTokens := sdk.TokensFromConsensusPower(powerAmt[i]) valCreateMsg := staking.NewMsgCreateValidator( addrs[i], pubkeys[i], sdk.NewCoin(sdk.DefaultBondDenom, valTokens), - testDescription, testCommissionRates, sdk.OneInt(), + keep.TestDescription, keep.TestCommissionRates, sdk.OneInt(), ) res := stakingHandler(ctx, valCreateMsg) diff --git a/x/gov/types/genesis.go b/x/gov/types/genesis.go index 796fe06aa9d9..5623422e2fd2 100644 --- a/x/gov/types/genesis.go +++ b/x/gov/types/genesis.go @@ -2,14 +2,6 @@ package types import ( "bytes" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -const ( - // Default period for deposits & voting - DefaultPeriod time.Duration = 86400 * 2 * time.Second // 2 days ) // GenesisState - all staking state that must be provided at genesis @@ -33,35 +25,24 @@ func NewGenesisState(startingProposalID uint64, dp DepositParams, vp VotingParam } } -// get raw genesis raw message for testing +// DefaultGenesisState defines the default governance genesis state func DefaultGenesisState() GenesisState { - minDepositTokens := sdk.TokensFromConsensusPower(10) - return GenesisState{ - StartingProposalID: 1, - DepositParams: DepositParams{ - MinDeposit: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, minDepositTokens)), - MaxDepositPeriod: DefaultPeriod, - }, - VotingParams: VotingParams{ - VotingPeriod: DefaultPeriod, - }, - TallyParams: TallyParams{ - Quorum: sdk.NewDecWithPrec(334, 3), - Threshold: sdk.NewDecWithPrec(5, 1), - Veto: sdk.NewDecWithPrec(334, 3), - }, - } + return NewGenesisState( + DefaultStartingProposalID, + DefaultDepositParams(), + DefaultVotingParams(), + DefaultTallyParams(), + ) } -// Checks whether 2 GenesisState structs are equivalent. +// Equal checks whether two gov GenesisState structs are equivalent func (data GenesisState) Equal(data2 GenesisState) bool { b1 := ModuleCdc.MustMarshalBinaryBare(data) b2 := ModuleCdc.MustMarshalBinaryBare(data2) return bytes.Equal(b1, b2) } -// Returns if a GenesisState is empty or has data in it +// IsEmpty returns true if a GenesisState is empty func (data GenesisState) IsEmpty() bool { - emptyGenState := GenesisState{} - return data.Equal(emptyGenState) + return data.Equal(GenesisState{}) } diff --git a/x/gov/types/params.go b/x/gov/types/params.go index 9ae33e75a0ff..06edca367c2d 100644 --- a/x/gov/types/params.go +++ b/x/gov/types/params.go @@ -8,6 +8,19 @@ import ( params "github.com/cosmos/cosmos-sdk/x/params/subspace" ) + // Default period for deposits & voting +const ( + DefaultPeriod time.Duration = 86400 * 2 * time.Second // 2 days +) + +// Default governance params +var ( + DefaultMinDepositTokens = sdk.TokensFromConsensusPower(10) + DefaultQuorum = sdk.NewDecWithPrec(334, 3) + DefaultThreshold = sdk.NewDecWithPrec(5, 1) + DefaultVeto = sdk.NewDecWithPrec(334, 3) +) + // Parameter store key var ( ParamStoreKeyDepositParams = []byte("depositparams") @@ -15,7 +28,7 @@ var ( ParamStoreKeyTallyParams = []byte("tallyparams") ) -// Key declaration for parameters +// ParamKeyTable - Key declaration for parameters func ParamKeyTable() params.KeyTable { return params.NewKeyTable( ParamStoreKeyDepositParams, DepositParams{}, @@ -24,7 +37,7 @@ func ParamKeyTable() params.KeyTable { ) } -// Param around deposits for governance +// DepositParams defines the params around deposits for governance type DepositParams struct { MinDeposit sdk.Coins `json:"min_deposit,omitempty" yaml:"min_deposit,omitempty"` // Minimum deposit for a proposal to enter voting period. MaxDepositPeriod time.Duration `json:"max_deposit_period,omitempty" yaml:"max_deposit_period,omitempty"` // Maximum period for Atom holders to deposit on a proposal. Initial value: 2 months @@ -38,18 +51,27 @@ func NewDepositParams(minDeposit sdk.Coins, maxDepositPeriod time.Duration) Depo } } +// DefaultDepositParams default parameters for deposits +func DefaultDepositParams() DepositParams { + return NewDepositParams( + sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, DefaultMinDepositTokens)), + DefaultPeriod, + ) +} + +// String implements stringer insterface func (dp DepositParams) String() string { return fmt.Sprintf(`Deposit Params: Min Deposit: %s Max Deposit Period: %s`, dp.MinDeposit, dp.MaxDepositPeriod) } -// Checks equality of DepositParams +// Equal checks equality of DepositParams func (dp DepositParams) Equal(dp2 DepositParams) bool { return dp.MinDeposit.IsEqual(dp2.MinDeposit) && dp.MaxDepositPeriod == dp2.MaxDepositPeriod } -// Param around Tallying votes in governance +// TallyParams defines the params around Tallying votes in governance type TallyParams struct { Quorum sdk.Dec `json:"quorum,omitempty" yaml:"quorum,omitempty"` // Minimum percentage of total stake needed to vote for a result to be considered valid Threshold sdk.Dec `json:"threshold,omitempty" yaml:"threshold,omitempty"` // Minimum proportion of Yes votes for proposal to pass. Initial value: 0.5 @@ -65,6 +87,12 @@ func NewTallyParams(quorum, threshold, veto sdk.Dec) TallyParams { } } +// DefaultTallyParams default parameters for tallying +func DefaultTallyParams() TallyParams { + return NewTallyParams(DefaultQuorum, DefaultThreshold, DefaultVeto) +} + +// String implements stringer insterface func (tp TallyParams) String() string { return fmt.Sprintf(`Tally Params: Quorum: %s @@ -73,7 +101,7 @@ func (tp TallyParams) String() string { tp.Quorum, tp.Threshold, tp.Veto) } -// Param around Voting in governance +// VotingParams defines the params around Voting in governance type VotingParams struct { VotingPeriod time.Duration `json:"voting_period,omitempty" yaml:"voting_period,omitempty"` // Length of the voting period. } @@ -85,6 +113,12 @@ func NewVotingParams(votingPeriod time.Duration) VotingParams { } } +// DefaultVotingParams default parameters for voting +func DefaultVotingParams() VotingParams { + return NewVotingParams(DefaultPeriod) +} + +// String implements stringer insterface func (vp VotingParams) String() string { return fmt.Sprintf(`Voting Params: Voting Period: %s`, vp.VotingPeriod) @@ -102,6 +136,7 @@ func (gp Params) String() string { gp.TallyParams.String() + "\n" + gp.DepositParams.String() } +// NewParams creates a new gov Params instance func NewParams(vp VotingParams, tp TallyParams, dp DepositParams) Params { return Params{ VotingParams: vp, @@ -109,3 +144,8 @@ func NewParams(vp VotingParams, tp TallyParams, dp DepositParams) Params { TallyParams: tp, } } + +// DefaultParams default governance params +func DefaultParams() Params { + return NewParams(DefaultVotingParams(), DefaultTallyParams(), DefaultDepositParams()) +} diff --git a/x/gov/types/proposal.go b/x/gov/types/proposal.go index 15e0b498ec38..f72616db14ff 100644 --- a/x/gov/types/proposal.go +++ b/x/gov/types/proposal.go @@ -9,6 +9,9 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) +// DefaultStartingProposalID is 1 +const DefaultStartingProposalID uint64 = 1 + // Proposal defines a struct used by the governance module to allow for voting // on network changes. type Proposal struct { @@ -26,6 +29,7 @@ type Proposal struct { VotingEndTime time.Time `json:"voting_end_time" yaml:"voting_end_time"` // Time that the VotingPeriod for this proposal will end and votes will be tallied } +// NewProposal creates a new Proposal instance func NewProposal(content Content, id uint64, submitTime, depositEndTime time.Time) Proposal { return Proposal{ Content: content, @@ -38,7 +42,7 @@ func NewProposal(content Content, id uint64, submitTime, depositEndTime time.Tim } } -// nolint +// String implements stringer interface func (p Proposal) String() string { return fmt.Sprintf(`Proposal %d: Title: %s @@ -71,7 +75,7 @@ func (p Proposals) String() string { } type ( - // ProposalQueue + // ProposalQueue defines a queue for proposal ids ProposalQueue []uint64 // ProposalStatus is a type alias that represents a proposal status as a byte @@ -88,7 +92,7 @@ const ( StatusFailed ProposalStatus = 0x05 ) -// ProposalStatusToString turns a string into a ProposalStatus +// ProposalStatusFromString turns a string into a ProposalStatus func ProposalStatusFromString(str string) (ProposalStatus, error) { switch str { case "DepositPeriod": @@ -138,12 +142,12 @@ func (status *ProposalStatus) Unmarshal(data []byte) error { return nil } -// Marshals to JSON using string +// MarshalJSON Marshals to JSON using string representation of the status func (status ProposalStatus) MarshalJSON() ([]byte, error) { return json.Marshal(status.String()) } -// Unmarshals from JSON assuming Bech32 encoding +// UnmarshalJSON Unmarshals from JSON assuming Bech32 encoding func (status *ProposalStatus) UnmarshalJSON(data []byte) error { var s string err := json.Unmarshal(data, &s) @@ -207,11 +211,12 @@ type TextProposal struct { Description string `json:"description" yaml:"description"` } +// NewTextProposal creates a text proposal Content func NewTextProposal(title, description string) Content { return TextProposal{title, description} } -// Implements Proposal Interface +// Implements Content Interface var _ Content = TextProposal{} // nolint @@ -236,11 +241,12 @@ type SoftwareUpgradeProposal struct { Description string `json:"description" yaml:"description"` } +// NewTextProposal creates a software upgrade proposal Content func NewSoftwareUpgradeProposal(title, description string) Content { return SoftwareUpgradeProposal{title, description} } -// Implements Proposal Interface +// Implements Content Interface var _ Content = SoftwareUpgradeProposal{} // nolint From fdbaffc29056085eede777dd1cf98720301949b8 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Mon, 15 Jul 2019 17:15:01 +0200 Subject: [PATCH 11/36] fix more tests --- x/gov/keeper/deposit_test.go | 19 +++------------ x/gov/keeper/querier_test.go | 45 ++++++++++++++++++++++++++++-------- 2 files changed, 38 insertions(+), 26 deletions(-) diff --git a/x/gov/keeper/deposit_test.go b/x/gov/keeper/deposit_test.go index ee8932ba62d2..2bb284b4b565 100644 --- a/x/gov/keeper/deposit_test.go +++ b/x/gov/keeper/deposit_test.go @@ -23,8 +23,6 @@ func TestDeposits(t *testing.T) { addr0Initial := ak.GetAccount(ctx, TestAddrs[0]).GetCoins() addr1Initial := ak.GetAccount(ctx, TestAddrs[1]).GetCoins() - expTokens := sdk.TokensFromConsensusPower(42) - require.Equal(t, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, expTokens)), addr0Initial) require.True(t, proposal.TotalDeposit.IsEqual(sdk.NewCoins())) // Check no deposits at beginning @@ -78,20 +76,6 @@ func TestDeposits(t *testing.T) { require.True(t, ok) require.True(t, proposal.VotingStartTime.Equal(ctx.BlockHeader().Time)) - // Test deposit iterator - depositsIterator := keeper.GetDepositsIterator(ctx, proposalID) - require.True(t, depositsIterator.Valid()) - keeper.cdc.MustUnmarshalBinaryLengthPrefixed(depositsIterator.Value(), &deposit) - require.Equal(t, TestAddrs[0], deposit.Depositor) - require.Equal(t, fourStake.Add(fiveStake), deposit.Amount) - depositsIterator.Next() - keeper.cdc.MustUnmarshalBinaryLengthPrefixed(depositsIterator.Value(), &deposit) - require.Equal(t, TestAddrs[1], deposit.Depositor) - require.Equal(t, fourStake, deposit.Amount) - depositsIterator.Next() - require.False(t, depositsIterator.Valid()) - depositsIterator.Close() - // Test Refund Deposits deposit, found = keeper.GetDeposit(ctx, proposalID, TestAddrs[1]) require.True(t, found) @@ -101,5 +85,8 @@ func TestDeposits(t *testing.T) { require.False(t, found) require.Equal(t, addr0Initial, ak.GetAccount(ctx, TestAddrs[0]).GetCoins()) require.Equal(t, addr1Initial, ak.GetAccount(ctx, TestAddrs[1]).GetCoins()) +} +func TestDepositIterators(t *testing.T) { + // TODO: } \ No newline at end of file diff --git a/x/gov/keeper/querier_test.go b/x/gov/keeper/querier_test.go index 43f8d6020281..b1b162cbec8c 100644 --- a/x/gov/keeper/querier_test.go +++ b/x/gov/keeper/querier_test.go @@ -170,6 +170,9 @@ func TestQueries(t *testing.T) { ctx, _, keeper, _, _ := createTestInput(t, false, 1000) querier := NewQuerier(keeper) + oneCoins := sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, 1)) + consCoins := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.TokensFromConsensusPower(10))) + tp := TestProposal depositParams, _, _ := getQueriedParams(t, ctx, keeper.cdc, querier) @@ -177,25 +180,47 @@ func TestQueries(t *testing.T) { // TestAddrs[0] proposes (and deposits) proposals #1 and #2 proposal1, err := keeper.SubmitProposal(ctx, tp) require.NoError(t, err) - deposit1 := types.NewDeposit(proposal1.ProposalID, TestAddrs[0], sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, 1))) - keeper.SetDeposit(ctx, deposit1) + deposit1 := types.NewDeposit(proposal1.ProposalID, TestAddrs[0], oneCoins) + err, _ = keeper.AddDeposit(ctx, deposit1.ProposalID, deposit1.Depositor, deposit1.Amount) + require.NoError(t, err) + + proposal1.TotalDeposit = proposal1.TotalDeposit.Add(deposit1.Amount) proposal2, err := keeper.SubmitProposal(ctx, tp) require.NoError(t, err) - deposit2 := types.NewDeposit(proposal2.ProposalID, TestAddrs[0], sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, 10000000))) - keeper.SetDeposit(ctx, deposit2) + deposit2 := types.NewDeposit(proposal2.ProposalID, TestAddrs[0], consCoins) + err, _ = keeper.AddDeposit(ctx, deposit2.ProposalID, deposit2.Depositor, deposit2.Amount) + require.NoError(t, err) + + proposal2.TotalDeposit = proposal2.TotalDeposit.Add(deposit2.Amount) // TestAddrs[1] proposes (and deposits) on proposal #3 proposal3, err := keeper.SubmitProposal(ctx, tp) require.NoError(t, err) - deposit3 := types.NewDeposit(proposal3.ProposalID, TestAddrs[1], sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, 1))) - keeper.SetDeposit(ctx, deposit3) + deposit3 := types.NewDeposit(proposal3.ProposalID, TestAddrs[1], oneCoins) + err, _ = keeper.AddDeposit(ctx, deposit3.ProposalID, deposit3.Depositor, deposit3.Amount) + require.NoError(t, err) + + proposal3.TotalDeposit = proposal3.TotalDeposit.Add(deposit3.Amount) // TestAddrs[1] deposits on proposals #2 & #3 deposit4 := types.NewDeposit(proposal2.ProposalID, TestAddrs[1], depositParams.MinDeposit) + err, _ = keeper.AddDeposit(ctx, deposit4.ProposalID, deposit4.Depositor, deposit4.Amount) + require.NoError(t, err) + + proposal2.TotalDeposit = proposal2.TotalDeposit.Add(deposit4.Amount) + proposal2.Status = types.StatusVotingPeriod + proposal2.VotingEndTime = proposal2.VotingEndTime.Add(types.DefaultPeriod) + deposit5 := types.NewDeposit(proposal3.ProposalID, TestAddrs[1], depositParams.MinDeposit) - keeper.SetDeposit(ctx, deposit4) - keeper.SetDeposit(ctx, deposit5) + err, _ = keeper.AddDeposit(ctx, deposit5.ProposalID, deposit5.Depositor, deposit5.Amount) + require.NoError(t, err) + + proposal3.TotalDeposit = proposal3.TotalDeposit.Add(deposit5.Amount) + proposal3.Status = types.StatusVotingPeriod + proposal3.VotingEndTime = proposal3.VotingEndTime.Add(types.DefaultPeriod) + // total deposit of TestAddrs[1] on proposal #3 is worth the proposal deposit + individual deposit + deposit5.Amount = deposit5.Amount.Add(deposit3.Amount) // check deposits on proposal1 match individual deposits deposits := getQueriedDeposits(t, ctx, keeper.cdc, querier, proposal1.ProposalID) @@ -208,9 +233,9 @@ func TestQueries(t *testing.T) { // check deposits on proposal2 match individual deposits deposits = getQueriedDeposits(t, ctx, keeper.cdc, querier, proposal2.ProposalID) require.Len(t, deposits, 2) - require.Equal(t, deposit2, deposits[0]) require.Equal(t, deposit4, deposits[1]) - + require.Equal(t, deposit2, deposits[0]) + deposit = getQueriedDeposit(t, ctx, keeper.cdc, querier, proposal2.ProposalID, TestAddrs[0]) require.Equal(t, deposit2, deposits[0]) deposit = getQueriedDeposit(t, ctx, keeper.cdc, querier, proposal2.ProposalID, TestAddrs[1]) From f4ef7b0e14836ab03a777db5e60668ad9f2cf666 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Mon, 15 Jul 2019 18:00:28 +0200 Subject: [PATCH 12/36] set router on tests --- x/gov/abci_test.go | 24 ++++++++++-------------- x/gov/genesis_test.go | 6 +++--- x/gov/keeper/querier_test.go | 3 ++- x/gov/test_common.go | 5 +++-- 4 files changed, 18 insertions(+), 20 deletions(-) diff --git a/x/gov/abci_test.go b/x/gov/abci_test.go index e27dd9dd32f8..93f13d895374 100644 --- a/x/gov/abci_test.go +++ b/x/gov/abci_test.go @@ -1,6 +1,7 @@ package gov import ( + "encoding/binary" "testing" "time" @@ -14,7 +15,7 @@ import ( ) func TestTickExpiredDepositPeriod(t *testing.T) { - input := getMockApp(t, 10, GenesisState{}, nil) + input := getMockApp(t, 10, GenesisState{}, nil, ProposalHandler) header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) @@ -63,7 +64,7 @@ func TestTickExpiredDepositPeriod(t *testing.T) { } func TestTickMultipleExpiredDepositPeriod(t *testing.T) { - input := getMockApp(t, 10, GenesisState{}, nil) + input := getMockApp(t, 10, GenesisState{}, nil, ProposalHandler) header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) @@ -131,7 +132,7 @@ func TestTickMultipleExpiredDepositPeriod(t *testing.T) { } func TestTickPassedDepositPeriod(t *testing.T) { - input := getMockApp(t, 10, GenesisState{}, nil) + input := getMockApp(t, 10, GenesisState{}, nil, ProposalHandler) header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) @@ -154,8 +155,7 @@ func TestTickPassedDepositPeriod(t *testing.T) { res := govHandler(ctx, newProposalMsg) require.True(t, res.IsOK()) - var proposalID uint64 - input.mApp.Cdc.MustUnmarshalBinaryLengthPrefixed(res.Data, &proposalID) + proposalID := binary.LittleEndian.Uint64(res.Data) inactiveQueue = input.keeper.InactiveProposalQueueIterator(ctx, ctx.BlockHeader().Time) require.False(t, inactiveQueue.Valid()) @@ -179,7 +179,7 @@ func TestTickPassedDepositPeriod(t *testing.T) { } func TestTickPassedVotingPeriod(t *testing.T) { - input := getMockApp(t, 10, GenesisState{}, nil) + input := getMockApp(t, 10, GenesisState{}, nil, ProposalHandler) SortAddresses(input.addrs) header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} @@ -200,8 +200,7 @@ func TestTickPassedVotingPeriod(t *testing.T) { res := govHandler(ctx, newProposalMsg) require.True(t, res.IsOK()) - var proposalID uint64 - input.mApp.Cdc.MustUnmarshalBinaryLengthPrefixed(res.Data, &proposalID) + proposalID := binary.LittleEndian.Uint64(res.Data) newHeader := ctx.BlockHeader() newHeader.Time = ctx.BlockHeader().Time.Add(time.Duration(1) * time.Second) @@ -241,7 +240,7 @@ func TestTickPassedVotingPeriod(t *testing.T) { } func TestProposalPassedEndblocker(t *testing.T) { - input := getMockApp(t, 1, GenesisState{}, nil) + input := getMockApp(t, 1, GenesisState{}, nil, ProposalHandler) SortAddresses(input.addrs) handler := NewHandler(input.keeper) @@ -290,12 +289,9 @@ func TestProposalPassedEndblocker(t *testing.T) { } func TestEndBlockerProposalHandlerFailed(t *testing.T) { - input := getMockApp(t, 1, GenesisState{}, nil) - SortAddresses(input.addrs) - // hijack the router to one that will fail in a proposal's handler - // TODO: set router or add route - input.keeper.router = NewRouter().AddRoute(RouterKey, badProposalHandler) + input := getMockApp(t, 1, GenesisState{}, nil, badProposalHandler) + SortAddresses(input.addrs) handler := NewHandler(input.keeper) stakingHandler := keep.StakingHandler(input.sk) diff --git a/x/gov/genesis_test.go b/x/gov/genesis_test.go index 19999bcd9ff8..1beb0baecaa6 100644 --- a/x/gov/genesis_test.go +++ b/x/gov/genesis_test.go @@ -11,7 +11,7 @@ import ( func TestImportExportQueues(t *testing.T) { // Generate mock app and keepers - input := getMockApp(t, 2, GenesisState{}, nil) + input := getMockApp(t, 2, GenesisState{}, nil, ProposalHandler) SortAddresses(input.addrs) header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} @@ -44,7 +44,7 @@ func TestImportExportQueues(t *testing.T) { // Export the state and import it into a new Mock App genState := ExportGenesis(ctx, input.keeper) - input2 := getMockApp(t, 2, genState, genAccs) + input2 := getMockApp(t, 2, genState, genAccs, ProposalHandler) header = abci.Header{Height: input.mApp.LastBlockHeight() + 1} input2.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) @@ -76,7 +76,7 @@ func TestImportExportQueues(t *testing.T) { func TestEqualProposals(t *testing.T) { // Generate mock app and keepers - input := getMockApp(t, 2, GenesisState{}, nil) + input := getMockApp(t, 2, GenesisState{}, nil, ProposalHandler) SortAddresses(input.addrs) header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} diff --git a/x/gov/keeper/querier_test.go b/x/gov/keeper/querier_test.go index b1b162cbec8c..d7d5d079d172 100644 --- a/x/gov/keeper/querier_test.go +++ b/x/gov/keeper/querier_test.go @@ -233,8 +233,9 @@ func TestQueries(t *testing.T) { // check deposits on proposal2 match individual deposits deposits = getQueriedDeposits(t, ctx, keeper.cdc, querier, proposal2.ProposalID) require.Len(t, deposits, 2) - require.Equal(t, deposit4, deposits[1]) + // FIXME: non determinism on the order of the deposits require.Equal(t, deposit2, deposits[0]) + require.Equal(t, deposit4, deposits[1]) deposit = getQueriedDeposit(t, ctx, keeper.cdc, querier, proposal2.ProposalID, TestAddrs[0]) require.Equal(t, deposit2, deposits[0]) diff --git a/x/gov/test_common.go b/x/gov/test_common.go index 4cbe7436d8b9..e64c38e67300 100644 --- a/x/gov/test_common.go +++ b/x/gov/test_common.go @@ -42,7 +42,8 @@ type testInput struct { privKeys []crypto.PrivKey } -func getMockApp(t *testing.T, numGenAccs int, genState types.GenesisState, genAccs []auth.Account) testInput { +func getMockApp(t *testing.T, numGenAccs int, genState types.GenesisState, genAccs []auth.Account, + handler func (ctx sdk.Context, c types.Content) sdk.Error) testInput { mApp := mock.NewApp() staking.RegisterCodec(mApp.Cdc) @@ -57,7 +58,7 @@ func getMockApp(t *testing.T, numGenAccs int, genState types.GenesisState, genAc pk := mApp.ParamsKeeper rtr := types.NewRouter(). - AddRoute(types.RouterKey, types.ProposalHandler) + AddRoute(types.RouterKey, handler) bk := bank.NewBaseKeeper(mApp.AccountKeeper, mApp.ParamsKeeper.Subspace(bank.DefaultParamspace), bank.DefaultCodespace) From dc4f663efdf09924ef3a7db4a0d810365765125b Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Tue, 16 Jul 2019 12:19:18 +0200 Subject: [PATCH 13/36] add key --- x/gov/keeper/deposit_test.go | 20 +++++++++++++++----- x/gov/keeper/invariants.go | 1 + x/gov/keeper/querier_test.go | 4 ++-- x/gov/keeper/tally.go | 3 +-- x/gov/keeper/test_common.go | 8 +++++--- 5 files changed, 24 insertions(+), 12 deletions(-) diff --git a/x/gov/keeper/deposit_test.go b/x/gov/keeper/deposit_test.go index 2bb284b4b565..f15407d18c08 100644 --- a/x/gov/keeper/deposit_test.go +++ b/x/gov/keeper/deposit_test.go @@ -1,8 +1,8 @@ package keeper import ( - "time" "testing" + "time" "github.com/stretchr/testify/require" @@ -76,6 +76,20 @@ func TestDeposits(t *testing.T) { require.True(t, ok) require.True(t, proposal.VotingStartTime.Equal(ctx.BlockHeader().Time)) + // Test deposit iterator + depositsIterator := keeper.GetDepositsIterator(ctx, proposalID) + require.True(t, depositsIterator.Valid()) + keeper.cdc.MustUnmarshalBinaryLengthPrefixed(depositsIterator.Value(), &deposit) + require.Equal(t, TestAddrs[0], deposit.Depositor) + require.Equal(t, fourStake.Add(fiveStake), deposit.Amount) + depositsIterator.Next() + keeper.cdc.MustUnmarshalBinaryLengthPrefixed(depositsIterator.Value(), &deposit) + require.Equal(t, TestAddrs[1], deposit.Depositor) + require.Equal(t, fourStake, deposit.Amount) + depositsIterator.Next() + require.False(t, depositsIterator.Valid()) + depositsIterator.Close() + // Test Refund Deposits deposit, found = keeper.GetDeposit(ctx, proposalID, TestAddrs[1]) require.True(t, found) @@ -86,7 +100,3 @@ func TestDeposits(t *testing.T) { require.Equal(t, addr0Initial, ak.GetAccount(ctx, TestAddrs[0]).GetCoins()) require.Equal(t, addr1Initial, ak.GetAccount(ctx, TestAddrs[1]).GetCoins()) } - -func TestDepositIterators(t *testing.T) { - // TODO: -} \ No newline at end of file diff --git a/x/gov/keeper/invariants.go b/x/gov/keeper/invariants.go index 61fbeb6cbf1b..9878dfec7e05 100644 --- a/x/gov/keeper/invariants.go +++ b/x/gov/keeper/invariants.go @@ -1,3 +1,4 @@ +// DONTCOVER package keeper import ( diff --git a/x/gov/keeper/querier_test.go b/x/gov/keeper/querier_test.go index d7d5d079d172..4f5dbad0cc0b 100644 --- a/x/gov/keeper/querier_test.go +++ b/x/gov/keeper/querier_test.go @@ -236,7 +236,7 @@ func TestQueries(t *testing.T) { // FIXME: non determinism on the order of the deposits require.Equal(t, deposit2, deposits[0]) require.Equal(t, deposit4, deposits[1]) - + deposit = getQueriedDeposit(t, ctx, keeper.cdc, querier, proposal2.ProposalID, TestAddrs[0]) require.Equal(t, deposit2, deposits[0]) deposit = getQueriedDeposit(t, ctx, keeper.cdc, querier, proposal2.ProposalID, TestAddrs[1]) @@ -265,7 +265,7 @@ func TestQueries(t *testing.T) { vote1 := types.NewVote(proposal2.ProposalID, TestAddrs[0], types.OptionYes) vote2 := types.NewVote(proposal3.ProposalID, TestAddrs[0], types.OptionYes) keeper.SetVote(ctx, vote1) - keeper.SetVote(ctx, vote2) + keeper.SetVote(ctx, vote2) // Addrs[1] votes on proposal #3 vote3 := types.NewVote(proposal3.ProposalID, TestAddrs[1], types.OptionYes) diff --git a/x/gov/keeper/tally.go b/x/gov/keeper/tally.go index 9f081779e7e9..1bd9082031a6 100644 --- a/x/gov/keeper/tally.go +++ b/x/gov/keeper/tally.go @@ -6,10 +6,9 @@ import ( "github.com/cosmos/cosmos-sdk/x/staking/exported" ) - // TODO: Break into several smaller functions for clarity -// Tally iterates over the votes and updates the tally of a proposal based on the voting power of the +// Tally iterates over the votes and updates the tally of a proposal based on the voting power of the // voters func (keeper Keeper) Tally(ctx sdk.Context, proposal types.Proposal) (passes bool, burnDeposits bool, tallyResults types.TallyResult) { results := make(map[types.VoteOption]sdk.Dec) diff --git a/x/gov/keeper/test_common.go b/x/gov/keeper/test_common.go index e4e1fd9606c2..c5a0b09c6cab 100644 --- a/x/gov/keeper/test_common.go +++ b/x/gov/keeper/test_common.go @@ -58,7 +58,7 @@ var ( // TODO: remove dependency with staking var ( - TestProposal = types.NewTextProposal("Test", "description") + TestProposal = types.NewTextProposal("Test", "description") TestDescription = staking.NewDescription("T", "E", "S", "T") TestCommissionRates = staking.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()) ) @@ -90,9 +90,11 @@ func createTestInput(t *testing.T, isCheckTx bool, initPower int64) (sdk.Context db := dbm.NewMemDB() ms := store.NewCommitMultiStore(db) + ms.MountStoreWithDB(keyAcc, sdk.StoreTypeIAVL, db) ms.MountStoreWithDB(keySupply, sdk.StoreTypeIAVL, db) ms.MountStoreWithDB(keyGov, sdk.StoreTypeIAVL, db) - ms.MountStoreWithDB(keyAcc, sdk.StoreTypeIAVL, db) + ms.MountStoreWithDB(keyStaking, sdk.StoreTypeIAVL, db) + ms.MountStoreWithDB(tkeyStaking, sdk.StoreTypeTransient, db) ms.MountStoreWithDB(keyParams, sdk.StoreTypeIAVL, db) ms.MountStoreWithDB(tkeyParams, sdk.StoreTypeTransient, db) require.Nil(t, ms.LoadLatestVersion()) @@ -152,7 +154,7 @@ func createTestInput(t *testing.T, isCheckTx bool, initPower int64) (sdk.Context } // TODO: remove dependency with staking -func StakingHandler(sk staking.Keeper) sdk.Handler{ +func StakingHandler(sk staking.Keeper) sdk.Handler { return staking.NewHandler(sk) } From ddfe980cad979ba4474cb966805801059fa36dcd Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Thu, 18 Jul 2019 15:07:46 +0200 Subject: [PATCH 14/36] cleanup --- x/gov/alias.go | 112 ++++++++++++++++++----------------------- x/gov/genesis.go | 22 -------- x/gov/module.go | 42 ++++++++-------- x/gov/test_common.go | 11 ++-- x/gov/types/genesis.go | 26 ++++++++++ 5 files changed, 103 insertions(+), 110 deletions(-) diff --git a/x/gov/alias.go b/x/gov/alias.go index 5d532692ad2f..bf21c3b3c2fa 100644 --- a/x/gov/alias.go +++ b/x/gov/alias.go @@ -11,68 +11,53 @@ import ( ) const ( - MaxDescriptionLength = types.MaxDescriptionLength - MaxTitleLength = types.MaxTitleLength - DefaultCodespace = types.DefaultCodespace - CodeUnknownProposal = types.CodeUnknownProposal - CodeInactiveProposal = types.CodeInactiveProposal - CodeAlreadyActiveProposal = types.CodeAlreadyActiveProposal - CodeAlreadyFinishedProposal = types.CodeAlreadyFinishedProposal - CodeAddressNotStaked = types.CodeAddressNotStaked - CodeInvalidContent = types.CodeInvalidContent - CodeInvalidProposalType = types.CodeInvalidProposalType - CodeInvalidVote = types.CodeInvalidVote - CodeInvalidGenesis = types.CodeInvalidGenesis - CodeInvalidProposalStatus = types.CodeInvalidProposalStatus - CodeProposalHandlerNotExists = types.CodeProposalHandlerNotExists - EventTypeSubmitProposal = types.EventTypeSubmitProposal - EventTypeProposalDeposit = types.EventTypeProposalDeposit - EventTypeProposalVote = types.EventTypeProposalVote - EventTypeInactiveProposal = types.EventTypeInactiveProposal - EventTypeActiveProposal = types.EventTypeActiveProposal - AttributeKeyProposalResult = types.AttributeKeyProposalResult - AttributeKeyAmount = types.AttributeKeyAmount - AttributeKeyOption = types.AttributeKeyOption - AttributeKeyProposalID = types.AttributeKeyProposalID - AttributeKeyVotingPeriodStart = types.AttributeKeyVotingPeriodStart - AttributeValueCategory = types.AttributeValueCategory - AttributeValueProposalDropped = types.AttributeValueProposalDropped - AttributeValueProposalPassed = types.AttributeValueProposalPassed - AttributeValueProposalRejected = types.AttributeValueProposalRejected - AttributeValueProposalFailed = types.AttributeValueProposalFailed - DefaultPeriod = types.DefaultPeriod - ModuleName = types.ModuleName - StoreKey = types.StoreKey - RouterKey = types.RouterKey - QuerierRoute = types.QuerierRoute - DefaultParamspace = types.DefaultParamspace - TypeMsgDeposit = types.TypeMsgDeposit - TypeMsgVote = types.TypeMsgVote - TypeMsgSubmitProposal = types.TypeMsgSubmitProposal - StatusNil = types.StatusNil - StatusDepositPeriod = types.StatusDepositPeriod - StatusVotingPeriod = types.StatusVotingPeriod - StatusPassed = types.StatusPassed - StatusRejected = types.StatusRejected - 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 - OptionNo = types.OptionNo - OptionNoWithVeto = types.OptionNoWithVeto + MaxDescriptionLength = types.MaxDescriptionLength + MaxTitleLength = types.MaxTitleLength + DefaultCodespace = types.DefaultCodespace + CodeUnknownProposal = types.CodeUnknownProposal + CodeInactiveProposal = types.CodeInactiveProposal + CodeAlreadyActiveProposal = types.CodeAlreadyActiveProposal + CodeAlreadyFinishedProposal = types.CodeAlreadyFinishedProposal + CodeAddressNotStaked = types.CodeAddressNotStaked + CodeInvalidContent = types.CodeInvalidContent + CodeInvalidProposalType = types.CodeInvalidProposalType + CodeInvalidVote = types.CodeInvalidVote + CodeInvalidGenesis = types.CodeInvalidGenesis + CodeInvalidProposalStatus = types.CodeInvalidProposalStatus + CodeProposalHandlerNotExists = types.CodeProposalHandlerNotExists + DefaultPeriod = types.DefaultPeriod + ModuleName = types.ModuleName + StoreKey = types.StoreKey + RouterKey = types.RouterKey + QuerierRoute = types.QuerierRoute + DefaultParamspace = types.DefaultParamspace + TypeMsgDeposit = types.TypeMsgDeposit + TypeMsgVote = types.TypeMsgVote + TypeMsgSubmitProposal = types.TypeMsgSubmitProposal + StatusNil = types.StatusNil + StatusDepositPeriod = types.StatusDepositPeriod + StatusVotingPeriod = types.StatusVotingPeriod + StatusPassed = types.StatusPassed + StatusRejected = types.StatusRejected + 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 + OptionNo = types.OptionNo + OptionNoWithVeto = types.OptionNoWithVeto ) var ( @@ -98,6 +83,7 @@ var ( ErrNoProposalHandlerExists = types.ErrNoProposalHandlerExists NewGenesisState = types.NewGenesisState DefaultGenesisState = types.DefaultGenesisState + ValidateGenesis = types.ValidateGenesis ProposalKey = types.ProposalKey ActiveProposalByTimeKey = types.ActiveProposalByTimeKey ActiveProposalQueueKey = types.ActiveProposalQueueKey @@ -121,7 +107,7 @@ var ( NewVotingParams = types.NewVotingParams NewParams = types.NewParams NewProposal = types.NewProposal - NewRouter = types.NewRouter + NewRouter = types.NewRouter ProposalStatusFromString = types.ProposalStatusFromString ValidProposalStatus = types.ValidProposalStatus NewTextProposal = types.NewTextProposal diff --git a/x/gov/genesis.go b/x/gov/genesis.go index 962b7cd7b8aa..7283e325882e 100644 --- a/x/gov/genesis.go +++ b/x/gov/genesis.go @@ -79,25 +79,3 @@ func ExportGenesis(ctx sdk.Context, k Keeper) GenesisState { TallyParams: tallyParams, } } - -// ValidateGenesis checks if parameters are within valid ranges -func ValidateGenesis(data GenesisState) error { - threshold := data.TallyParams.Threshold - if threshold.IsNegative() || threshold.GT(sdk.OneDec()) { - return fmt.Errorf("Governance vote threshold should be positive and less or equal to one, is %s", - threshold.String()) - } - - veto := data.TallyParams.Veto - if veto.IsNegative() || veto.GT(sdk.OneDec()) { - return fmt.Errorf("Governance vote veto threshold should be positive and less or equal to one, is %s", - veto.String()) - } - - if !data.DepositParams.MinDeposit.IsValid() { - return fmt.Errorf("Governance deposit amount must be a valid sdk.Coins amount, is %s", - data.DepositParams.MinDeposit.String()) - } - - return nil -} diff --git a/x/gov/module.go b/x/gov/module.go index 9101f53c5b56..a0d68ce6de81 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -1,3 +1,4 @@ +// DONTCOVER package gov import ( @@ -23,7 +24,7 @@ var ( _ module.AppModuleBasic = AppModuleBasic{} ) -// app module basics object +// AppModuleBasic - app module basics object type AppModuleBasic struct { proposalHandlers []client.ProposalHandler // proposal handlers which live in governance cli and rest } @@ -37,32 +38,32 @@ func NewAppModuleBasic(proposalHandlers ...client.ProposalHandler) AppModuleBasi var _ module.AppModuleBasic = AppModuleBasic{} -// module name +// Name - module name func (AppModuleBasic) Name() string { return types.ModuleName } -// register module codec +// RegisterCodec -register module codec func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) { RegisterCodec(cdc) } -// default genesis state +// DefaultGenesis - default genesis state func (AppModuleBasic) DefaultGenesis() json.RawMessage { return types.ModuleCdc.MustMarshalJSON(DefaultGenesisState()) } -// module validate genesis +// ValidateGenesis - module validate genesis func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { var data GenesisState err := types.ModuleCdc.UnmarshalJSON(bz, &data) if err != nil { return err } - return ValidateGenesis(data) + return types.ValidateGenesis(data) } -// register rest routes +// RegisterRESTRoutes - register rest routes func (a AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router) { var proposalRESTHandlers []rest.ProposalRESTHandler for _, proposalHandler := range a.proposalHandlers { @@ -72,7 +73,7 @@ func (a AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Rout rest.RegisterRoutes(ctx, rtr, proposalRESTHandlers) } -// get the root tx command of this module +// GetTxCmd gets the root tx command of this module func (a AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command { var proposalCLIHandlers []*cobra.Command @@ -83,13 +84,14 @@ func (a AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command { return cli.GetTxCmd(StoreKey, cdc, proposalCLIHandlers) } -// get the root query command of this module +// GetQueryCmd gets the root query command of this module func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { return cli.GetQueryCmd(StoreKey, cdc) } //___________________________ -// app module + +// AppModule - app module ob type AppModule struct { AppModuleBasic keeper Keeper @@ -105,37 +107,37 @@ func NewAppModule(keeper Keeper, supplyKeeper types.SupplyKeeper) AppModule { } } -// module name +// Name - module name func (AppModule) Name() string { return types.ModuleName } -// register invariants +// RegisterInvariants registers module invariants func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) { RegisterInvariants(ir, am.keeper) } -// module message route name +// Route - module message route name func (AppModule) Route() string { return RouterKey } -// module handler +// NewHandler - module handler func (am AppModule) NewHandler() sdk.Handler { return NewHandler(am.keeper) } -// module querier route name +// QuerierRoute - module querier route name func (AppModule) QuerierRoute() string { return QuerierRoute } -// module querier +// NewQuerierHandler - module querier func (am AppModule) NewQuerierHandler() sdk.Querier { return NewQuerier(am.keeper) } -// module init-genesis +// InitGenesis - module init-genesis func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate { var genesisState GenesisState types.ModuleCdc.MustUnmarshalJSON(data, &genesisState) @@ -143,16 +145,16 @@ func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.Va return []abci.ValidatorUpdate{} } -// module export genesis +// ExportGenesis - module export genesis func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { gs := ExportGenesis(ctx, am.keeper) return types.ModuleCdc.MustMarshalJSON(gs) } -// module begin-block +// BeginBlock - module begin-block func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} -// module end-block +// EndBlock - module end-block func (am AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { EndBlocker(ctx, am.keeper) return []abci.ValidatorUpdate{} diff --git a/x/gov/test_common.go b/x/gov/test_common.go index e64c38e67300..4bbc1179de97 100644 --- a/x/gov/test_common.go +++ b/x/gov/test_common.go @@ -1,4 +1,4 @@ -// nolint:deadcode unused +// nolint // DONTCOVER package gov @@ -43,7 +43,7 @@ type testInput struct { } func getMockApp(t *testing.T, numGenAccs int, genState types.GenesisState, genAccs []auth.Account, - handler func (ctx sdk.Context, c types.Content) sdk.Error) testInput { + handler func(ctx sdk.Context, c types.Content) sdk.Error) testInput { mApp := mock.NewApp() staking.RegisterCodec(mApp.Cdc) @@ -134,7 +134,7 @@ func getInitChainer(mapp *mock.App, keeper Keeper, stakingKeeper staking.Keeper, } } -// Sorts Addresses +// SortAddresses - Sorts Addresses func SortAddresses(addrs []sdk.AccAddress) { var byteAddrs [][]byte for _, addr := range addrs { @@ -170,6 +170,7 @@ func (b sortByteArrays) Swap(i, j int) { b[j], b[i] = b[i], b[j] } +// SortByteArrays - func SortByteArrays(src [][]byte) [][]byte { sorted := sortByteArrays(src) sort.Sort(sorted) @@ -193,8 +194,8 @@ func badProposalHandler(ctx sdk.Context, c types.Content) sdk.Error { return nil default: - errMsg := fmt.Sprintf("unrecognized gov proposal type: %s", c.ProposalType()) - return sdk.ErrUnknownRequest(errMsg) + msg := fmt.Sprintf("unrecognized gov proposal type: %s", c.ProposalType()) + return sdk.ErrUnknownRequest(msg) } } diff --git a/x/gov/types/genesis.go b/x/gov/types/genesis.go index 5623422e2fd2..30b0eacac89c 100644 --- a/x/gov/types/genesis.go +++ b/x/gov/types/genesis.go @@ -1,7 +1,10 @@ package types import ( + "fmt" "bytes" + + sdk "github.com/cosmos/cosmos-sdk/types" ) // GenesisState - all staking state that must be provided at genesis @@ -46,3 +49,26 @@ func (data GenesisState) Equal(data2 GenesisState) bool { func (data GenesisState) IsEmpty() bool { return data.Equal(GenesisState{}) } + +// ValidateGenesis checks if parameters are within valid ranges +func ValidateGenesis(data GenesisState) error { + threshold := data.TallyParams.Threshold + if threshold.IsNegative() || threshold.GT(sdk.OneDec()) { + return fmt.Errorf("Governance vote threshold should be positive and less or equal to one, is %s", + threshold.String()) + } + + veto := data.TallyParams.Veto + if veto.IsNegative() || veto.GT(sdk.OneDec()) { + return fmt.Errorf("Governance vote veto threshold should be positive and less or equal to one, is %s", + veto.String()) + } + + if !data.DepositParams.MinDeposit.IsValid() { + return fmt.Errorf("Governance deposit amount must be a valid sdk.Coins amount, is %s", + data.DepositParams.MinDeposit.String()) + } + + return nil +} + From 187faa035e3361fcdb6fdbcc8ef727190c1bb7a1 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Mon, 22 Jul 2019 16:07:52 +0200 Subject: [PATCH 15/36] replace staking handler for keeper funcs --- x/gov/keeper/tally_test.go | 115 ++++++++++++++++++------------------ x/gov/keeper/test_common.go | 20 +++++++ 2 files changed, 78 insertions(+), 57 deletions(-) diff --git a/x/gov/keeper/tally_test.go b/x/gov/keeper/tally_test.go index 4543c6efc730..c19380c128fb 100644 --- a/x/gov/keeper/tally_test.go +++ b/x/gov/keeper/tally_test.go @@ -5,15 +5,13 @@ import ( "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/crypto/ed25519" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/cosmos/cosmos-sdk/x/staking" ) func TestTallyNoOneVotes(t *testing.T) { - ctx, _, keeper, _, _ := createTestInput(t, false, 100) + ctx, _, keeper, sk, _ := createTestInput(t, false, 100) + createValidators(ctx, sk, []int64{5, 5, 5}) tp := TestProposal proposal, err := keeper.SubmitProposal(ctx, tp) @@ -32,7 +30,8 @@ func TestTallyNoOneVotes(t *testing.T) { } func TestTallyNoQuorum(t *testing.T) { - ctx, _, keeper, _, _ := createTestInput(t, false, 100) + ctx, _, keeper, sk, _ := createTestInput(t, false, 100) + createValidators(ctx, sk, []int64{2, 5, 0}) tp := TestProposal proposal, err := keeper.SubmitProposal(ctx, tp) @@ -52,7 +51,8 @@ func TestTallyNoQuorum(t *testing.T) { } func TestTallyOnlyValidatorsAllYes(t *testing.T) { - ctx, _, keeper, _, _ := createTestInput(t, false, 100) + ctx, _, keeper, sk, _ := createTestInput(t, false, 100) + createValidators(ctx, sk, []int64{5, 5, 0}) tp := TestProposal proposal, err := keeper.SubmitProposal(ctx, tp) @@ -76,7 +76,8 @@ func TestTallyOnlyValidatorsAllYes(t *testing.T) { } func TestTallyOnlyValidators51No(t *testing.T) { - ctx, _, keeper, _, _ := createTestInput(t, false, 100) + ctx, _, keeper, sk, _ := createTestInput(t, false, 100) + createValidators(ctx, sk, []int64{5, 6, 0}) tp := TestProposal proposal, err := keeper.SubmitProposal(ctx, tp) @@ -99,7 +100,8 @@ func TestTallyOnlyValidators51No(t *testing.T) { } func TestTallyOnlyValidators51Yes(t *testing.T) { - ctx, _, keeper, _, _ := createTestInput(t, false, 100) + ctx, _, keeper, sk, _ := createTestInput(t, false, 100) + createValidators(ctx, sk, []int64{5, 6, 0}) tp := TestProposal proposal, err := keeper.SubmitProposal(ctx, tp) @@ -125,7 +127,8 @@ func TestTallyOnlyValidators51Yes(t *testing.T) { } func TestTallyOnlyValidatorsVetoed(t *testing.T) { - ctx, _, keeper, _, _ := createTestInput(t, false, 100) + ctx, _, keeper, sk, _ := createTestInput(t, false, 100) + createValidators(ctx, sk, []int64{6, 6, 7}) tp := TestProposal proposal, err := keeper.SubmitProposal(ctx, tp) @@ -152,7 +155,8 @@ func TestTallyOnlyValidatorsVetoed(t *testing.T) { } func TestTallyOnlyValidatorsAbstainPasses(t *testing.T) { - ctx, _, keeper, _, _ := createTestInput(t, false, 100) + ctx, _, keeper, sk, _ := createTestInput(t, false, 100) + createValidators(ctx, sk, []int64{6, 6, 7}) tp := TestProposal proposal, err := keeper.SubmitProposal(ctx, tp) @@ -178,7 +182,8 @@ func TestTallyOnlyValidatorsAbstainPasses(t *testing.T) { } func TestTallyOnlyValidatorsAbstainFails(t *testing.T) { - ctx, _, keeper, _, _ := createTestInput(t, false, 100) + ctx, _, keeper, sk, _ := createTestInput(t, false, 100) + createValidators(ctx, sk, []int64{6, 6, 7}) tp := TestProposal proposal, err := keeper.SubmitProposal(ctx, tp) @@ -204,7 +209,8 @@ func TestTallyOnlyValidatorsAbstainFails(t *testing.T) { } func TestTallyOnlyValidatorsNonVoter(t *testing.T) { - ctx, _, keeper, _, _ := createTestInput(t, false, 100) + ctx, _, keeper, sk, _ := createTestInput(t, false, 100) + createValidators(ctx, sk, []int64{5, 6, 7}) tp := TestProposal proposal, err := keeper.SubmitProposal(ctx, tp) @@ -229,11 +235,14 @@ func TestTallyOnlyValidatorsNonVoter(t *testing.T) { func TestTallyDelgatorOverride(t *testing.T) { ctx, _, keeper, sk, _ := createTestInput(t, false, 100) - stakingHandler := StakingHandler(sk) + createValidators(ctx, sk, []int64{5, 6, 7}) delTokens := sdk.TokensFromConsensusPower(30) - delegator1Msg := staking.NewMsgDelegate(TestAddrs[3], sdk.ValAddress(TestAddrs[2]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) - stakingHandler(ctx, delegator1Msg) + val1, found := sk.GetValidator(ctx, valOpAddr1) + require.True(t, found) + + _, err := sk.Delegate(ctx, TestAddrs[0], delTokens, sdk.Unbonded, val1, true) + require.NoError(t, err) tp := TestProposal proposal, err := keeper.SubmitProposal(ctx, tp) @@ -262,11 +271,14 @@ func TestTallyDelgatorOverride(t *testing.T) { func TestTallyDelgatorInherit(t *testing.T) { ctx, _, keeper, sk, _ := createTestInput(t, false, 100) - stakingHandler := StakingHandler(sk) + createValidators(ctx, sk, []int64{5, 6, 7}) delTokens := sdk.TokensFromConsensusPower(30) - delegator1Msg := staking.NewMsgDelegate(TestAddrs[3], sdk.ValAddress(TestAddrs[2]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) - stakingHandler(ctx, delegator1Msg) + val1, found := sk.GetValidator(ctx, valOpAddr1) + require.True(t, found) + + _, err := sk.Delegate(ctx, TestAddrs[0], delTokens, sdk.Unbonded, val1, true) + require.NoError(t, err) tp := TestProposal proposal, err := keeper.SubmitProposal(ctx, tp) @@ -293,13 +305,18 @@ func TestTallyDelgatorInherit(t *testing.T) { func TestTallyDelgatorMultipleOverride(t *testing.T) { ctx, _, keeper, sk, _ := createTestInput(t, false, 100) - stakingHandler := StakingHandler(sk) + createValidators(ctx, sk, []int64{5, 6, 7}) delTokens := sdk.TokensFromConsensusPower(10) - delegator1Msg := staking.NewMsgDelegate(TestAddrs[3], sdk.ValAddress(TestAddrs[2]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) - stakingHandler(ctx, delegator1Msg) - delegator1Msg2 := staking.NewMsgDelegate(TestAddrs[3], sdk.ValAddress(TestAddrs[1]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) - stakingHandler(ctx, delegator1Msg2) + val1, found := sk.GetValidator(ctx, valOpAddr1) + require.True(t, found) + val2, found := sk.GetValidator(ctx, valOpAddr2) + require.True(t, found) + + _, err := sk.Delegate(ctx, TestAddrs[0], delTokens, sdk.Unbonded, val1, true) + require.NoError(t, err) + _, err = sk.Delegate(ctx, TestAddrs[0], delTokens, sdk.Unbonded, val2, true) + require.NoError(t, err) tp := TestProposal proposal, err := keeper.SubmitProposal(ctx, tp) @@ -328,34 +345,18 @@ func TestTallyDelgatorMultipleOverride(t *testing.T) { func TestTallyDelgatorMultipleInherit(t *testing.T) { ctx, _, keeper, sk, _ := createTestInput(t, false, 100) - stakingHandler := StakingHandler(sk) - - valTokens1 := sdk.TokensFromConsensusPower(25) - val1CreateMsg := staking.NewMsgCreateValidator( - sdk.ValAddress(TestAddrs[0]), ed25519.GenPrivKey().PubKey(), sdk.NewCoin(sdk.DefaultBondDenom, valTokens1), TestDescription, TestCommissionRates, sdk.OneInt(), - ) - stakingHandler(ctx, val1CreateMsg) - - valTokens2 := sdk.TokensFromConsensusPower(6) - val2CreateMsg := staking.NewMsgCreateValidator( - sdk.ValAddress(TestAddrs[1]), ed25519.GenPrivKey().PubKey(), sdk.NewCoin(sdk.DefaultBondDenom, valTokens2), TestDescription, TestCommissionRates, sdk.OneInt(), - ) - stakingHandler(ctx, val2CreateMsg) - - valTokens3 := sdk.TokensFromConsensusPower(7) - val3CreateMsg := staking.NewMsgCreateValidator( - sdk.ValAddress(TestAddrs[2]), ed25519.GenPrivKey().PubKey(), sdk.NewCoin(sdk.DefaultBondDenom, valTokens3), TestDescription, TestCommissionRates, sdk.OneInt(), - ) - stakingHandler(ctx, val3CreateMsg) + createValidators(ctx, sk, []int64{25, 6, 7}) delTokens := sdk.TokensFromConsensusPower(10) - delegator1Msg := staking.NewMsgDelegate(TestAddrs[3], sdk.ValAddress(TestAddrs[2]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) - stakingHandler(ctx, delegator1Msg) - - delegator1Msg2 := staking.NewMsgDelegate(TestAddrs[3], sdk.ValAddress(TestAddrs[1]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) - stakingHandler(ctx, delegator1Msg2) + val1, found := sk.GetValidator(ctx, valOpAddr1) + require.True(t, found) + val2, found := sk.GetValidator(ctx, valOpAddr2) + require.True(t, found) - staking.EndBlocker(ctx, sk) + _, err := sk.Delegate(ctx, TestAddrs[0], delTokens, sdk.Unbonded, val1, true) + require.NoError(t, err) + _, err = sk.Delegate(ctx, TestAddrs[0], delTokens, sdk.Unbonded, val2, true) + require.NoError(t, err) tp := TestProposal proposal, err := keeper.SubmitProposal(ctx, tp) @@ -382,21 +383,21 @@ func TestTallyDelgatorMultipleInherit(t *testing.T) { func TestTallyJailedValidator(t *testing.T) { ctx, _, keeper, sk, _ := createTestInput(t, false, 100) - stakingHandler := StakingHandler(sk) + createValidators(ctx, sk, []int64{25, 6, 7}) delTokens := sdk.TokensFromConsensusPower(10) - delegator1Msg := staking.NewMsgDelegate(TestAddrs[3], sdk.ValAddress(TestAddrs[2]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) - stakingHandler(ctx, delegator1Msg) + val1, found := sk.GetValidator(ctx, valOpAddr1) + require.True(t, found) + val2, found := sk.GetValidator(ctx, valOpAddr2) + require.True(t, found) - delegator1Msg2 := staking.NewMsgDelegate(TestAddrs[3], sdk.ValAddress(TestAddrs[1]), sdk.NewCoin(sdk.DefaultBondDenom, delTokens)) - stakingHandler(ctx, delegator1Msg2) + _, err := sk.Delegate(ctx, TestAddrs[0], delTokens, sdk.Unbonded, val1, true) + require.NoError(t, err) + _, err = sk.Delegate(ctx, TestAddrs[0], delTokens, sdk.Unbonded, val2, true) + require.NoError(t, err) - val2, found := sk.GetValidator(ctx, sdk.ValAddress(TestAddrs[1])) - require.True(t, found) sk.Jail(ctx, sdk.ConsAddress(val2.ConsPubKey.Address())) - staking.EndBlocker(ctx, sk) - tp := TestProposal proposal, err := keeper.SubmitProposal(ctx, tp) require.NoError(t, err) diff --git a/x/gov/keeper/test_common.go b/x/gov/keeper/test_common.go index c5a0b09c6cab..f5544f2d2b7a 100644 --- a/x/gov/keeper/test_common.go +++ b/x/gov/keeper/test_common.go @@ -163,3 +163,23 @@ func ProposalEqual(proposalA types.Proposal, proposalB types.Proposal) bool { return bytes.Equal(types.ModuleCdc.MustMarshalBinaryBare(proposalA), types.ModuleCdc.MustMarshalBinaryBare(proposalB)) } + +func createValidators(ctx sdk.Context, sk staking.Keeper, powers []int64) { + val1 := staking.NewValidator(valOpAddr1, valOpPk1, staking.Description{}) + val2 := staking.NewValidator(valOpAddr2, valOpPk2, staking.Description{}) + val3 := staking.NewValidator(valOpAddr3, valOpPk3, staking.Description{}) + + sk.SetValidator(ctx, val1) + sk.SetValidator(ctx, val2) + sk.SetValidator(ctx, val3) + sk.SetValidatorByConsAddr(ctx, val1) + sk.SetValidatorByConsAddr(ctx, val2) + sk.SetValidatorByConsAddr(ctx, val3) + sk.SetNewValidatorByPowerIndex(ctx, val1) + sk.SetNewValidatorByPowerIndex(ctx, val2) + sk.SetNewValidatorByPowerIndex(ctx, val3) + + _, _ = sk.Delegate(ctx, valAccAddr1, sdk.TokensFromConsensusPower(powers[0]), sdk.Unbonded, val1, true) + _, _ = sk.Delegate(ctx, valAccAddr2, sdk.TokensFromConsensusPower(powers[1]), sdk.Unbonded, val2, true) + _, _ = sk.Delegate(ctx, valAccAddr3, sdk.TokensFromConsensusPower(powers[2]), sdk.Unbonded, val3, true) +} From f76dd7bc9ebeb8d851cb40c1e4f8c64fdd1bcd6f Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Mon, 22 Jul 2019 17:44:46 +0200 Subject: [PATCH 16/36] fix tally tests --- x/gov/abci_test.go | 4 +- x/gov/keeper/tally_test.go | 138 +++++++++++++++--------------------- x/gov/keeper/test_common.go | 23 +++--- x/gov/test_common.go | 5 ++ 4 files changed, 76 insertions(+), 94 deletions(-) diff --git a/x/gov/abci_test.go b/x/gov/abci_test.go index 93f13d895374..ed84a9ec3708 100644 --- a/x/gov/abci_test.go +++ b/x/gov/abci_test.go @@ -244,7 +244,7 @@ func TestProposalPassedEndblocker(t *testing.T) { SortAddresses(input.addrs) handler := NewHandler(input.keeper) - stakingHandler := keep.StakingHandler(input.sk) + stakingHandler := stakingHandler(input.sk) header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) @@ -294,7 +294,7 @@ func TestEndBlockerProposalHandlerFailed(t *testing.T) { SortAddresses(input.addrs) handler := NewHandler(input.keeper) - stakingHandler := keep.StakingHandler(input.sk) + stakingHandler := stakingHandler(input.sk) header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) diff --git a/x/gov/keeper/tally_test.go b/x/gov/keeper/tally_test.go index c19380c128fb..dcf370289565 100644 --- a/x/gov/keeper/tally_test.go +++ b/x/gov/keeper/tally_test.go @@ -7,6 +7,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/cosmos/cosmos-sdk/x/staking" ) func TestTallyNoOneVotes(t *testing.T) { @@ -52,7 +53,7 @@ func TestTallyNoQuorum(t *testing.T) { func TestTallyOnlyValidatorsAllYes(t *testing.T) { ctx, _, keeper, sk, _ := createTestInput(t, false, 100) - createValidators(ctx, sk, []int64{5, 5, 0}) + createValidators(ctx, sk, []int64{5, 5, 5}) tp := TestProposal proposal, err := keeper.SubmitProposal(ctx, tp) @@ -61,10 +62,9 @@ func TestTallyOnlyValidatorsAllYes(t *testing.T) { proposal.Status = types.StatusVotingPeriod keeper.SetProposal(ctx, proposal) - err = keeper.AddVote(ctx, proposalID, TestAddrs[0], types.OptionYes) - require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, TestAddrs[1], types.OptionYes) - require.Nil(t, err) + require.NoError(t, keeper.AddVote(ctx, proposalID, valAccAddr1, types.OptionYes)) + require.NoError(t, keeper.AddVote(ctx, proposalID, valAccAddr2, types.OptionYes)) + require.NoError(t, keeper.AddVote(ctx, proposalID, valAccAddr3, types.OptionYes)) proposal, ok := keeper.GetProposal(ctx, proposalID) require.True(t, ok) @@ -86,10 +86,8 @@ func TestTallyOnlyValidators51No(t *testing.T) { proposal.Status = types.StatusVotingPeriod keeper.SetProposal(ctx, proposal) - err = keeper.AddVote(ctx, proposalID, TestAddrs[0], types.OptionYes) - require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, TestAddrs[1], types.OptionNo) - require.Nil(t, err) + require.NoError(t, keeper.AddVote(ctx, proposalID, valAccAddr1, types.OptionYes)) + require.NoError(t, keeper.AddVote(ctx, proposalID, valAccAddr2, types.OptionNo)) proposal, ok := keeper.GetProposal(ctx, proposalID) require.True(t, ok) @@ -110,12 +108,8 @@ func TestTallyOnlyValidators51Yes(t *testing.T) { proposal.Status = types.StatusVotingPeriod keeper.SetProposal(ctx, proposal) - err = keeper.AddVote(ctx, proposalID, TestAddrs[0], types.OptionYes) - require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, TestAddrs[1], types.OptionYes) - require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, TestAddrs[2], types.OptionNo) - require.Nil(t, err) + require.NoError(t, keeper.AddVote(ctx, proposalID, valAccAddr1, types.OptionNo)) + require.NoError(t, keeper.AddVote(ctx, proposalID, valAccAddr2, types.OptionYes)) proposal, ok := keeper.GetProposal(ctx, proposalID) require.True(t, ok) @@ -137,12 +131,9 @@ func TestTallyOnlyValidatorsVetoed(t *testing.T) { proposal.Status = types.StatusVotingPeriod keeper.SetProposal(ctx, proposal) - err = keeper.AddVote(ctx, proposalID, TestAddrs[0], types.OptionYes) - require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, TestAddrs[1], types.OptionYes) - require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, TestAddrs[2], types.OptionNoWithVeto) - require.Nil(t, err) + require.NoError(t, keeper.AddVote(ctx, proposalID, valAccAddr1, types.OptionYes)) + require.NoError(t, keeper.AddVote(ctx, proposalID, valAccAddr2, types.OptionYes)) + require.NoError(t, keeper.AddVote(ctx, proposalID, valAccAddr3, types.OptionNoWithVeto)) proposal, ok := keeper.GetProposal(ctx, proposalID) require.True(t, ok) @@ -165,12 +156,9 @@ func TestTallyOnlyValidatorsAbstainPasses(t *testing.T) { proposal.Status = types.StatusVotingPeriod keeper.SetProposal(ctx, proposal) - err = keeper.AddVote(ctx, proposalID, TestAddrs[0], types.OptionAbstain) - require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, TestAddrs[1], types.OptionNo) - require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, TestAddrs[2], types.OptionYes) - require.Nil(t, err) + require.NoError(t, keeper.AddVote(ctx, proposalID, valAccAddr1, types.OptionAbstain)) + require.NoError(t, keeper.AddVote(ctx, proposalID, valAccAddr2, types.OptionNo)) + require.NoError(t, keeper.AddVote(ctx, proposalID, valAccAddr3, types.OptionYes)) proposal, ok := keeper.GetProposal(ctx, proposalID) require.True(t, ok) @@ -192,12 +180,9 @@ func TestTallyOnlyValidatorsAbstainFails(t *testing.T) { proposal.Status = types.StatusVotingPeriod keeper.SetProposal(ctx, proposal) - err = keeper.AddVote(ctx, proposalID, TestAddrs[0], types.OptionAbstain) - require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, TestAddrs[1], types.OptionYes) - require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, TestAddrs[2], types.OptionNo) - require.Nil(t, err) + require.NoError(t, keeper.AddVote(ctx, proposalID, valAccAddr1, types.OptionAbstain)) + require.NoError(t, keeper.AddVote(ctx, proposalID, valAccAddr2, types.OptionYes)) + require.NoError(t, keeper.AddVote(ctx, proposalID, valAccAddr3, types.OptionNo)) proposal, ok := keeper.GetProposal(ctx, proposalID) require.True(t, ok) @@ -219,10 +204,8 @@ func TestTallyOnlyValidatorsNonVoter(t *testing.T) { proposal.Status = types.StatusVotingPeriod keeper.SetProposal(ctx, proposal) - err = keeper.AddVote(ctx, proposalID, TestAddrs[1], types.OptionYes) - require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, TestAddrs[2], types.OptionNo) - require.Nil(t, err) + require.NoError(t, keeper.AddVote(ctx, proposalID, valAccAddr1, types.OptionYes)) + require.NoError(t, keeper.AddVote(ctx, proposalID, valAccAddr2, types.OptionNo)) proposal, ok := keeper.GetProposal(ctx, proposalID) require.True(t, ok) @@ -244,6 +227,8 @@ func TestTallyDelgatorOverride(t *testing.T) { _, err := sk.Delegate(ctx, TestAddrs[0], delTokens, sdk.Unbonded, val1, true) require.NoError(t, err) + _ = staking.EndBlocker(ctx, sk) + tp := TestProposal proposal, err := keeper.SubmitProposal(ctx, tp) require.NoError(t, err) @@ -251,14 +236,10 @@ func TestTallyDelgatorOverride(t *testing.T) { proposal.Status = types.StatusVotingPeriod keeper.SetProposal(ctx, proposal) - err = keeper.AddVote(ctx, proposalID, TestAddrs[0], types.OptionYes) - require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, TestAddrs[1], types.OptionYes) - require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, TestAddrs[2], types.OptionYes) - require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, TestAddrs[3], types.OptionNo) - require.Nil(t, err) + require.NoError(t, keeper.AddVote(ctx, proposalID, valAccAddr1, types.OptionYes)) + require.NoError(t, keeper.AddVote(ctx, proposalID, valAccAddr2, types.OptionYes)) + require.NoError(t, keeper.AddVote(ctx, proposalID, valAccAddr3, types.OptionYes)) + require.NoError(t, keeper.AddVote(ctx, proposalID, TestAddrs[0], types.OptionNo)) proposal, ok := keeper.GetProposal(ctx, proposalID) require.True(t, ok) @@ -274,12 +255,14 @@ func TestTallyDelgatorInherit(t *testing.T) { createValidators(ctx, sk, []int64{5, 6, 7}) delTokens := sdk.TokensFromConsensusPower(30) - val1, found := sk.GetValidator(ctx, valOpAddr1) + val3, found := sk.GetValidator(ctx, valOpAddr3) require.True(t, found) - _, err := sk.Delegate(ctx, TestAddrs[0], delTokens, sdk.Unbonded, val1, true) + _, err := sk.Delegate(ctx, TestAddrs[0], delTokens, sdk.Unbonded, val3, true) require.NoError(t, err) + _ = staking.EndBlocker(ctx, sk) + tp := TestProposal proposal, err := keeper.SubmitProposal(ctx, tp) require.NoError(t, err) @@ -287,12 +270,9 @@ func TestTallyDelgatorInherit(t *testing.T) { proposal.Status = types.StatusVotingPeriod keeper.SetProposal(ctx, proposal) - err = keeper.AddVote(ctx, proposalID, TestAddrs[0], types.OptionNo) - require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, TestAddrs[1], types.OptionNo) - require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, TestAddrs[2], types.OptionYes) - require.Nil(t, err) + require.NoError(t, keeper.AddVote(ctx, proposalID, valAccAddr1, types.OptionNo)) + require.NoError(t, keeper.AddVote(ctx, proposalID, valAccAddr2, types.OptionNo)) + require.NoError(t, keeper.AddVote(ctx, proposalID, valAccAddr3, types.OptionYes)) proposal, ok := keeper.GetProposal(ctx, proposalID) require.True(t, ok) @@ -318,6 +298,8 @@ func TestTallyDelgatorMultipleOverride(t *testing.T) { _, err = sk.Delegate(ctx, TestAddrs[0], delTokens, sdk.Unbonded, val2, true) require.NoError(t, err) + _ = staking.EndBlocker(ctx, sk) + tp := TestProposal proposal, err := keeper.SubmitProposal(ctx, tp) require.NoError(t, err) @@ -325,14 +307,10 @@ func TestTallyDelgatorMultipleOverride(t *testing.T) { proposal.Status = types.StatusVotingPeriod keeper.SetProposal(ctx, proposal) - err = keeper.AddVote(ctx, proposalID, TestAddrs[0], types.OptionYes) - require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, TestAddrs[1], types.OptionYes) - require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, TestAddrs[2], types.OptionYes) - require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, TestAddrs[3], types.OptionNo) - require.Nil(t, err) + require.NoError(t, keeper.AddVote(ctx, proposalID, valAccAddr1, types.OptionYes)) + require.NoError(t, keeper.AddVote(ctx, proposalID, valAccAddr2, types.OptionYes)) + require.NoError(t, keeper.AddVote(ctx, proposalID, valAccAddr3, types.OptionYes)) + require.NoError(t, keeper.AddVote(ctx, proposalID, TestAddrs[0], types.OptionNo)) proposal, ok := keeper.GetProposal(ctx, proposalID) require.True(t, ok) @@ -348,16 +326,18 @@ func TestTallyDelgatorMultipleInherit(t *testing.T) { createValidators(ctx, sk, []int64{25, 6, 7}) delTokens := sdk.TokensFromConsensusPower(10) - val1, found := sk.GetValidator(ctx, valOpAddr1) - require.True(t, found) val2, found := sk.GetValidator(ctx, valOpAddr2) require.True(t, found) + val3, found := sk.GetValidator(ctx, valOpAddr3) + require.True(t, found) - _, err := sk.Delegate(ctx, TestAddrs[0], delTokens, sdk.Unbonded, val1, true) + _, err := sk.Delegate(ctx, TestAddrs[0], delTokens, sdk.Unbonded, val2, true) require.NoError(t, err) - _, err = sk.Delegate(ctx, TestAddrs[0], delTokens, sdk.Unbonded, val2, true) + _, err = sk.Delegate(ctx, TestAddrs[0], delTokens, sdk.Unbonded, val3, true) require.NoError(t, err) + _ = staking.EndBlocker(ctx, sk) + tp := TestProposal proposal, err := keeper.SubmitProposal(ctx, tp) require.NoError(t, err) @@ -365,12 +345,9 @@ func TestTallyDelgatorMultipleInherit(t *testing.T) { proposal.Status = types.StatusVotingPeriod keeper.SetProposal(ctx, proposal) - err = keeper.AddVote(ctx, proposalID, TestAddrs[0], types.OptionYes) - require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, TestAddrs[1], types.OptionNo) - require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, TestAddrs[2], types.OptionNo) - require.Nil(t, err) + require.NoError(t, keeper.AddVote(ctx, proposalID, valAccAddr1, types.OptionYes)) + require.NoError(t, keeper.AddVote(ctx, proposalID, valAccAddr2, types.OptionNo)) + require.NoError(t, keeper.AddVote(ctx, proposalID, valAccAddr3, types.OptionNo)) proposal, ok := keeper.GetProposal(ctx, proposalID) require.True(t, ok) @@ -386,16 +363,18 @@ func TestTallyJailedValidator(t *testing.T) { createValidators(ctx, sk, []int64{25, 6, 7}) delTokens := sdk.TokensFromConsensusPower(10) - val1, found := sk.GetValidator(ctx, valOpAddr1) - require.True(t, found) val2, found := sk.GetValidator(ctx, valOpAddr2) require.True(t, found) + val3, found := sk.GetValidator(ctx, valOpAddr3) + require.True(t, found) - _, err := sk.Delegate(ctx, TestAddrs[0], delTokens, sdk.Unbonded, val1, true) + _, err := sk.Delegate(ctx, TestAddrs[0], delTokens, sdk.Unbonded, val2, true) require.NoError(t, err) - _, err = sk.Delegate(ctx, TestAddrs[0], delTokens, sdk.Unbonded, val2, true) + _, err = sk.Delegate(ctx, TestAddrs[0], delTokens, sdk.Unbonded, val3, true) require.NoError(t, err) + _ = staking.EndBlocker(ctx, sk) + sk.Jail(ctx, sdk.ConsAddress(val2.ConsPubKey.Address())) tp := TestProposal @@ -405,12 +384,9 @@ func TestTallyJailedValidator(t *testing.T) { proposal.Status = types.StatusVotingPeriod keeper.SetProposal(ctx, proposal) - err = keeper.AddVote(ctx, proposalID, TestAddrs[0], types.OptionYes) - require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, TestAddrs[1], types.OptionNo) - require.Nil(t, err) - err = keeper.AddVote(ctx, proposalID, TestAddrs[2], types.OptionNo) - require.Nil(t, err) + require.NoError(t, keeper.AddVote(ctx, proposalID, valAccAddr1, types.OptionYes)) + require.NoError(t, keeper.AddVote(ctx, proposalID, valAccAddr2, types.OptionNo)) + require.NoError(t, keeper.AddVote(ctx, proposalID, valAccAddr3, types.OptionNo)) proposal, ok := keeper.GetProposal(ctx, proposalID) require.True(t, ok) diff --git a/x/gov/keeper/test_common.go b/x/gov/keeper/test_common.go index f5544f2d2b7a..34af463882e9 100644 --- a/x/gov/keeper/test_common.go +++ b/x/gov/keeper/test_common.go @@ -42,7 +42,7 @@ var ( valOpAddr1 = sdk.ValAddress(valOpPk1.Address()) valOpAddr2 = sdk.ValAddress(valOpPk2.Address()) valOpAddr3 = sdk.ValAddress(valOpPk3.Address()) - valAccAddr1 = sdk.AccAddress(valOpPk1.Address()) // generate acc addresses for these validator keys too + valAccAddr1 = sdk.AccAddress(valOpPk1.Address()) valAccAddr2 = sdk.AccAddress(valOpPk2.Address()) valAccAddr3 = sdk.AccAddress(valOpPk3.Address()) @@ -110,10 +110,10 @@ func createTestInput(t *testing.T, isCheckTx bool, initPower int64) (sdk.Context cdc := makeTestCodec() maccPerms := map[string][]string{ - auth.FeeCollectorName: []string{supply.Basic}, - types.ModuleName: []string{supply.Basic}, - staking.NotBondedPoolName: []string{supply.Burner, supply.Staking}, - staking.BondedPoolName: []string{supply.Burner, supply.Staking}, + auth.FeeCollectorName: nil, + types.ModuleName: nil, + staking.NotBondedPoolName: {supply.Burner, supply.Staking}, + staking.BondedPoolName: {supply.Burner, supply.Staking}, } pk := params.NewKeeper(cdc, keyParams, tkeyParams, params.DefaultCodespace) @@ -144,20 +144,19 @@ func createTestInput(t *testing.T, isCheckTx bool, initPower int64) (sdk.Context } // create module accounts - feeCollectorAcc := supply.NewEmptyModuleAccount(auth.FeeCollectorName, supply.Basic) + feeCollectorAcc := supply.NewEmptyModuleAccount(auth.FeeCollectorName) govAcc := supply.NewEmptyModuleAccount(types.ModuleName, supply.Burner) + notBondedPool := supply.NewEmptyModuleAccount(staking.NotBondedPoolName, supply.Burner, supply.Staking) + bondPool := supply.NewEmptyModuleAccount(staking.BondedPoolName, supply.Burner, supply.Staking) keeper.supplyKeeper.SetModuleAccount(ctx, feeCollectorAcc) keeper.supplyKeeper.SetModuleAccount(ctx, govAcc) + keeper.supplyKeeper.SetModuleAccount(ctx, bondPool) + keeper.supplyKeeper.SetModuleAccount(ctx, notBondedPool) return ctx, accountKeeper, keeper, sk, supplyKeeper } -// TODO: remove dependency with staking -func StakingHandler(sk staking.Keeper) sdk.Handler { - return staking.NewHandler(sk) -} - // ProposalEqual checks if two proposals are equal (note: slow, for tests only) func ProposalEqual(proposalA types.Proposal, proposalB types.Proposal) bool { return bytes.Equal(types.ModuleCdc.MustMarshalBinaryBare(proposalA), @@ -182,4 +181,6 @@ func createValidators(ctx sdk.Context, sk staking.Keeper, powers []int64) { _, _ = sk.Delegate(ctx, valAccAddr1, sdk.TokensFromConsensusPower(powers[0]), sdk.Unbonded, val1, true) _, _ = sk.Delegate(ctx, valAccAddr2, sdk.TokensFromConsensusPower(powers[1]), sdk.Unbonded, val2, true) _, _ = sk.Delegate(ctx, valAccAddr3, sdk.TokensFromConsensusPower(powers[2]), sdk.Unbonded, val3, true) + + _ = staking.EndBlocker(ctx, sk) } diff --git a/x/gov/test_common.go b/x/gov/test_common.go index 4bbc1179de97..f0779b41f349 100644 --- a/x/gov/test_common.go +++ b/x/gov/test_common.go @@ -134,6 +134,11 @@ func getInitChainer(mapp *mock.App, keeper Keeper, stakingKeeper staking.Keeper, } } +// TODO: remove dependency with staking +func stakingHandler(sk staking.Keeper) sdk.Handler { + return staking.NewHandler(sk) +} + // SortAddresses - Sorts Addresses func SortAddresses(addrs []sdk.AccAddress) { var byteAddrs [][]byte From 3f6b2376a3daa8f8adadbf8cf1f506feeba9c750 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Mon, 22 Jul 2019 18:06:21 +0200 Subject: [PATCH 17/36] update iterator tests --- x/gov/keeper/deposit_test.go | 19 +++++++------------ x/gov/keeper/vote_test.go | 28 ++++++++++------------------ 2 files changed, 17 insertions(+), 30 deletions(-) diff --git a/x/gov/keeper/deposit_test.go b/x/gov/keeper/deposit_test.go index f15407d18c08..0f95273e7246 100644 --- a/x/gov/keeper/deposit_test.go +++ b/x/gov/keeper/deposit_test.go @@ -77,18 +77,13 @@ func TestDeposits(t *testing.T) { require.True(t, proposal.VotingStartTime.Equal(ctx.BlockHeader().Time)) // Test deposit iterator - depositsIterator := keeper.GetDepositsIterator(ctx, proposalID) - require.True(t, depositsIterator.Valid()) - keeper.cdc.MustUnmarshalBinaryLengthPrefixed(depositsIterator.Value(), &deposit) - require.Equal(t, TestAddrs[0], deposit.Depositor) - require.Equal(t, fourStake.Add(fiveStake), deposit.Amount) - depositsIterator.Next() - keeper.cdc.MustUnmarshalBinaryLengthPrefixed(depositsIterator.Value(), &deposit) - require.Equal(t, TestAddrs[1], deposit.Depositor) - require.Equal(t, fourStake, deposit.Amount) - depositsIterator.Next() - require.False(t, depositsIterator.Valid()) - depositsIterator.Close() + // FIXME: non determinism on the order of the deposits + deposits := keeper.GetAllDeposits(ctx) + require.Len(t, deposits, 2) + require.Equal(t, TestAddrs[0], deposits[0].Depositor) + require.Equal(t, fourStake.Add(fiveStake), deposits[0].Amount) + require.Equal(t, TestAddrs[1], deposits[1].Depositor) + require.Equal(t, fourStake, deposits[1].Amount) // Test Refund Deposits deposit, found = keeper.GetDeposit(ctx, proposalID, TestAddrs[1]) diff --git a/x/gov/keeper/vote_test.go b/x/gov/keeper/vote_test.go index 954424ba9d2d..cfebe20d0c2d 100644 --- a/x/gov/keeper/vote_test.go +++ b/x/gov/keeper/vote_test.go @@ -44,21 +44,13 @@ func TestVotes(t *testing.T) { require.Equal(t, types.OptionNoWithVeto, vote.Option) // Test vote iterator - votesIterator := keeper.GetVotesIterator(ctx, proposalID) - require.True(t, votesIterator.Valid()) - keeper.cdc.MustUnmarshalBinaryLengthPrefixed(votesIterator.Value(), &vote) - require.True(t, votesIterator.Valid()) - require.Equal(t, TestAddrs[0], vote.Voter) - require.Equal(t, proposalID, vote.ProposalID) - require.Equal(t, types.OptionYes, vote.Option) - votesIterator.Next() - require.True(t, votesIterator.Valid()) - keeper.cdc.MustUnmarshalBinaryLengthPrefixed(votesIterator.Value(), &vote) - require.True(t, votesIterator.Valid()) - require.Equal(t, TestAddrs[1], vote.Voter) - require.Equal(t, proposalID, vote.ProposalID) - require.Equal(t, types.OptionNoWithVeto, vote.Option) - votesIterator.Next() - require.False(t, votesIterator.Valid()) - votesIterator.Close() -} \ No newline at end of file + // FIXME: non determinism on the order of the votes + votes := keeper.GetAllVotes(ctx) + require.Len(t, votes, 2) + require.Equal(t, TestAddrs[0], votes[0].Voter) + require.Equal(t, proposalID, votes[0].ProposalID) + require.Equal(t, types.OptionYes, votes[0].Option) + require.Equal(t, TestAddrs[1], votes[1].Voter) + require.Equal(t, proposalID, votes[1].ProposalID) + require.Equal(t, types.OptionNoWithVeto, votes[1].Option) +} From 038f4e26e6be3a8656a0a9b75f02b3b87f0c227e Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Mon, 22 Jul 2019 18:32:50 +0200 Subject: [PATCH 18/36] minor changes --- x/gov/abci_test.go | 4 ++-- x/gov/keeper/proposal.go | 2 +- x/gov/keeper/vote.go | 2 +- x/gov/test_common.go | 5 ----- x/gov/types/expected_keepers.go | 4 ++-- 5 files changed, 6 insertions(+), 11 deletions(-) diff --git a/x/gov/abci_test.go b/x/gov/abci_test.go index ed84a9ec3708..515effe77d37 100644 --- a/x/gov/abci_test.go +++ b/x/gov/abci_test.go @@ -244,7 +244,7 @@ func TestProposalPassedEndblocker(t *testing.T) { SortAddresses(input.addrs) handler := NewHandler(input.keeper) - stakingHandler := stakingHandler(input.sk) + stakingHandler := staking.NewHandler(input.sk) header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) @@ -294,7 +294,7 @@ func TestEndBlockerProposalHandlerFailed(t *testing.T) { SortAddresses(input.addrs) handler := NewHandler(input.keeper) - stakingHandler := stakingHandler(input.sk) + stakingHandler := staking.NewHandler(input.sk) header := abci.Header{Height: input.mApp.LastBlockHeight() + 1} input.mApp.BeginBlock(abci.RequestBeginBlock{Header: header}) diff --git a/x/gov/keeper/proposal.go b/x/gov/keeper/proposal.go index 253dbdfb5ae3..ddc18c8600eb 100644 --- a/x/gov/keeper/proposal.go +++ b/x/gov/keeper/proposal.go @@ -47,7 +47,7 @@ func (keeper Keeper) SubmitProposal(ctx sdk.Context, content types.Content) (typ return proposal, nil } -// GetProposal get types.Proposal from store by ProposalID +// GetProposal get proposal from store by ProposalID func (keeper Keeper) GetProposal(ctx sdk.Context, proposalID uint64) (proposal types.Proposal, ok bool) { store := ctx.KVStore(keeper.storeKey) bz := store.Get(types.ProposalKey(proposalID)) diff --git a/x/gov/keeper/vote.go b/x/gov/keeper/vote.go index cee3e3d65cf0..69cf5c5858a0 100644 --- a/x/gov/keeper/vote.go +++ b/x/gov/keeper/vote.go @@ -7,7 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/gov/types" ) -// AddVote Adds a vote on a specific proposal +// AddVote adds a vote on a specific proposal func (keeper Keeper) AddVote(ctx sdk.Context, proposalID uint64, voterAddr sdk.AccAddress, option types.VoteOption) sdk.Error { proposal, ok := keeper.GetProposal(ctx, proposalID) if !ok { diff --git a/x/gov/test_common.go b/x/gov/test_common.go index f0779b41f349..4bbc1179de97 100644 --- a/x/gov/test_common.go +++ b/x/gov/test_common.go @@ -134,11 +134,6 @@ func getInitChainer(mapp *mock.App, keeper Keeper, stakingKeeper staking.Keeper, } } -// TODO: remove dependency with staking -func stakingHandler(sk staking.Keeper) sdk.Handler { - return staking.NewHandler(sk) -} - // SortAddresses - Sorts Addresses func SortAddresses(addrs []sdk.AccAddress) { var byteAddrs [][]byte diff --git a/x/gov/types/expected_keepers.go b/x/gov/types/expected_keepers.go index 7fd90ca620ee..be4bf6a2ef6c 100644 --- a/x/gov/types/expected_keepers.go +++ b/x/gov/types/expected_keepers.go @@ -7,7 +7,7 @@ import ( supplyexported "github.com/cosmos/cosmos-sdk/x/supply/exported" ) -// ParamSubspace defines the expected Subspace interface for parameters +// ParamSubspace defines the expected Subspace interface for parameters (noalias) type ParamSubspace interface { WithKeyTable(table subspace.KeyTable) subspace.Subspace Get(ctx sdk.Context, key []byte, ptr interface{}) @@ -37,4 +37,4 @@ type StakingKeeper interface { IterateDelegations(ctx sdk.Context, delegator sdk.AccAddress, fn func(index int64, delegation stakingexported.DelegationI) (stop bool)) -} \ No newline at end of file +} From 6fbb1200b758b5e7c7e80c52279920526fd58ebf Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Tue, 23 Jul 2019 10:21:36 +0200 Subject: [PATCH 19/36] delete iterator getter --- x/gov/keeper/deposit.go | 9 ++------- x/gov/keeper/deposit_test.go | 7 ++++--- x/gov/keeper/vote.go | 9 ++------- x/gov/keeper/vote_test.go | 14 +++++++++++--- 4 files changed, 19 insertions(+), 20 deletions(-) diff --git a/x/gov/keeper/deposit.go b/x/gov/keeper/deposit.go index 494daccbecd3..774208afe817 100644 --- a/x/gov/keeper/deposit.go +++ b/x/gov/keeper/deposit.go @@ -59,12 +59,6 @@ func (keeper Keeper) DeleteDeposits(ctx sdk.Context, proposalID uint64) { }) } -// GetDepositsIterator gets all the deposits on a specific proposal as an sdk.Iterator -func (keeper Keeper) GetDepositsIterator(ctx sdk.Context, proposalID uint64) sdk.Iterator { - store := ctx.KVStore(keeper.storeKey) - return sdk.KVStorePrefixIterator(store, types.DepositsKey(proposalID)) -} - // IterateAllDeposits iterates over the all the stored deposits and performs a callback function func (keeper Keeper) IterateAllDeposits(ctx sdk.Context, cb func(deposit types.Deposit) (stop bool)) { store := ctx.KVStore(keeper.storeKey) @@ -83,7 +77,8 @@ func (keeper Keeper) IterateAllDeposits(ctx sdk.Context, cb func(deposit types.D // IterateDeposits iterates over the all the proposals deposits and performs a callback function func (keeper Keeper) IterateDeposits(ctx sdk.Context, proposalID uint64, cb func(deposit types.Deposit) (stop bool)) { - iterator := keeper.GetDepositsIterator(ctx, proposalID) + store := ctx.KVStore(keeper.storeKey) + iterator := sdk.KVStorePrefixIterator(store, types.DepositsKey(proposalID)) defer iterator.Close() for ; iterator.Valid(); iterator.Next() { diff --git a/x/gov/keeper/deposit_test.go b/x/gov/keeper/deposit_test.go index 0f95273e7246..081d7d44a561 100644 --- a/x/gov/keeper/deposit_test.go +++ b/x/gov/keeper/deposit_test.go @@ -34,7 +34,7 @@ func TestDeposits(t *testing.T) { // Check first deposit err, votingStarted := keeper.AddDeposit(ctx, proposalID, TestAddrs[0], fourStake) - require.Nil(t, err) + require.NoError(t, err) require.False(t, votingStarted) deposit, found = keeper.GetDeposit(ctx, proposalID, TestAddrs[0]) require.True(t, found) @@ -47,7 +47,7 @@ func TestDeposits(t *testing.T) { // Check a second deposit from same address err, votingStarted = keeper.AddDeposit(ctx, proposalID, TestAddrs[0], fiveStake) - require.Nil(t, err) + require.NoError(t, err) require.False(t, votingStarted) deposit, found = keeper.GetDeposit(ctx, proposalID, TestAddrs[0]) require.True(t, found) @@ -60,7 +60,7 @@ func TestDeposits(t *testing.T) { // Check third deposit from a new address err, votingStarted = keeper.AddDeposit(ctx, proposalID, TestAddrs[1], fourStake) - require.Nil(t, err) + require.NoError(t, err) require.True(t, votingStarted) deposit, found = keeper.GetDeposit(ctx, proposalID, TestAddrs[1]) require.True(t, found) @@ -80,6 +80,7 @@ func TestDeposits(t *testing.T) { // FIXME: non determinism on the order of the deposits deposits := keeper.GetAllDeposits(ctx) require.Len(t, deposits, 2) + require.Equal(t, deposits, keeper.GetDeposits(ctx, proposalID)) require.Equal(t, TestAddrs[0], deposits[0].Depositor) require.Equal(t, fourStake.Add(fiveStake), deposits[0].Amount) require.Equal(t, TestAddrs[1], deposits[1].Depositor) diff --git a/x/gov/keeper/vote.go b/x/gov/keeper/vote.go index 69cf5c5858a0..b491b4690c4b 100644 --- a/x/gov/keeper/vote.go +++ b/x/gov/keeper/vote.go @@ -72,12 +72,6 @@ func (keeper Keeper) SetVote(ctx sdk.Context, vote types.Vote) { store.Set(types.VoteKey(vote.ProposalID, vote.Voter), bz) } -// GetVotesIterator gets all the votes on a specific proposal as an sdk.Iterator -func (keeper Keeper) GetVotesIterator(ctx sdk.Context, proposalID uint64) sdk.Iterator { - store := ctx.KVStore(keeper.storeKey) - return sdk.KVStorePrefixIterator(store, types.VotesKey(proposalID)) -} - // IterateAllVotes iterates over the all the stored votes and performs a callback function func (keeper Keeper) IterateAllVotes(ctx sdk.Context, cb func(vote types.Vote) (stop bool)) { store := ctx.KVStore(keeper.storeKey) @@ -96,7 +90,8 @@ func (keeper Keeper) IterateAllVotes(ctx sdk.Context, cb func(vote types.Vote) ( // IterateVotes iterates over the all the proposals votes and performs a callback function func (keeper Keeper) IterateVotes(ctx sdk.Context, proposalID uint64, cb func(vote types.Vote) (stop bool)) { - iterator := keeper.GetVotesIterator(ctx, proposalID) + store := ctx.KVStore(keeper.storeKey) + iterator := sdk.KVStorePrefixIterator(store, types.VotesKey(proposalID)) defer iterator.Close() for ; iterator.Valid(); iterator.Next() { diff --git a/x/gov/keeper/vote_test.go b/x/gov/keeper/vote_test.go index cfebe20d0c2d..b4aa14254ffa 100644 --- a/x/gov/keeper/vote_test.go +++ b/x/gov/keeper/vote_test.go @@ -16,11 +16,18 @@ func TestVotes(t *testing.T) { require.NoError(t, err) proposalID := proposal.ProposalID + var invalidOption types.VoteOption + invalidOption = 0x10 + + require.Error(t, keeper.AddVote(ctx, proposalID, TestAddrs[0], types.OptionYes)) + require.Error(t, keeper.AddVote(ctx, 10, TestAddrs[0], types.OptionYes)) + require.Error(t, keeper.AddVote(ctx, 10, TestAddrs[0], invalidOption)) + proposal.Status = types.StatusVotingPeriod keeper.SetProposal(ctx, proposal) // Test first vote - keeper.AddVote(ctx, proposalID, TestAddrs[0], types.OptionAbstain) + require.NoError(t, keeper.AddVote(ctx, proposalID, TestAddrs[0], types.OptionAbstain)) vote, found := keeper.GetVote(ctx, proposalID, TestAddrs[0]) require.True(t, found) require.Equal(t, TestAddrs[0], vote.Voter) @@ -28,7 +35,7 @@ func TestVotes(t *testing.T) { require.Equal(t, types.OptionAbstain, vote.Option) // Test change of vote - keeper.AddVote(ctx, proposalID, TestAddrs[0], types.OptionYes) + require.NoError(t, keeper.AddVote(ctx, proposalID, TestAddrs[0], types.OptionYes)) vote, found = keeper.GetVote(ctx, proposalID, TestAddrs[0]) require.True(t, found) require.Equal(t, TestAddrs[0], vote.Voter) @@ -36,7 +43,7 @@ func TestVotes(t *testing.T) { require.Equal(t, types.OptionYes, vote.Option) // Test second vote - keeper.AddVote(ctx, proposalID, TestAddrs[1], types.OptionNoWithVeto) + require.NoError(t, keeper.AddVote(ctx, proposalID, TestAddrs[1], types.OptionNoWithVeto)) vote, found = keeper.GetVote(ctx, proposalID, TestAddrs[1]) require.True(t, found) require.Equal(t, TestAddrs[1], vote.Voter) @@ -47,6 +54,7 @@ func TestVotes(t *testing.T) { // FIXME: non determinism on the order of the votes votes := keeper.GetAllVotes(ctx) require.Len(t, votes, 2) + require.Equal(t, votes, keeper.GetVotes(ctx, proposalID)) require.Equal(t, TestAddrs[0], votes[0].Voter) require.Equal(t, proposalID, votes[0].ProposalID) require.Equal(t, types.OptionYes, votes[0].Option) From 8bebc28548ab040bc94a0a7740a5f8b2bccdaaef Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Tue, 23 Jul 2019 12:48:10 -0400 Subject: [PATCH 20/36] remove empty deposits iterator check in tests --- go.mod | 1 - x/gov/abci_test.go | 4 +--- x/gov/module.go | 3 ++- 3 files changed, 3 insertions(+), 5 deletions(-) diff --git a/go.mod b/go.mod index f20d9f8e5b81..6809ae310151 100644 --- a/go.mod +++ b/go.mod @@ -9,7 +9,6 @@ require ( github.com/fortytw2/leaktest v1.3.0 // indirect github.com/gogo/protobuf v1.2.1 github.com/golang/mock v1.3.1-0.20190508161146-9fa652df1129 - github.com/golang/protobuf v1.3.0 github.com/gorilla/mux v1.7.0 github.com/gorilla/websocket v1.4.0 // indirect github.com/mattn/go-isatty v0.0.6 diff --git a/x/gov/abci_test.go b/x/gov/abci_test.go index 515effe77d37..44244d3107bf 100644 --- a/x/gov/abci_test.go +++ b/x/gov/abci_test.go @@ -227,9 +227,7 @@ func TestTickPassedVotingPeriod(t *testing.T) { proposal, ok := input.keeper.GetProposal(ctx, activeProposalID) require.True(t, ok) require.Equal(t, StatusVotingPeriod, proposal.Status) - depositsIterator := input.keeper.GetDepositsIterator(ctx, proposalID) - require.True(t, depositsIterator.Valid()) - depositsIterator.Close() + activeQueue.Close() EndBlocker(ctx, input.keeper) diff --git a/x/gov/module.go b/x/gov/module.go index a0d68ce6de81..d0aeacf3511c 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -1,6 +1,7 @@ -// DONTCOVER package gov +// DONTCOVER + import ( "encoding/json" From 88f30e66ecc79e6a599fb8df47eafc50247073b5 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Wed, 24 Jul 2019 11:31:47 +0200 Subject: [PATCH 21/36] minor changes --- x/gov/simulation/msgs.go | 2 +- x/gov/types/genesis.go | 5 ++--- x/gov/types/params.go | 10 +++++----- x/gov/types/tally.go | 19 +++++++------------ 4 files changed, 15 insertions(+), 21 deletions(-) diff --git a/x/gov/simulation/msgs.go b/x/gov/simulation/msgs.go index 2d6f74a28b3f..8b65fa3d611a 100644 --- a/x/gov/simulation/msgs.go +++ b/x/gov/simulation/msgs.go @@ -220,4 +220,4 @@ func randomVotingOption(r *rand.Rand) gov.VoteOption { return gov.OptionNoWithVeto } panic("should not happen") -} \ No newline at end of file +} diff --git a/x/gov/types/genesis.go b/x/gov/types/genesis.go index 30b0eacac89c..165606bc4750 100644 --- a/x/gov/types/genesis.go +++ b/x/gov/types/genesis.go @@ -1,8 +1,8 @@ package types import ( - "fmt" "bytes" + "fmt" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -12,7 +12,7 @@ type GenesisState struct { StartingProposalID uint64 `json:"starting_proposal_id" yaml:"starting_proposal_id"` Deposits Deposits `json:"deposits" yaml:"deposits"` Votes Votes `json:"votes" yaml:"votes"` - Proposals []Proposal `json:"proposals" yaml:"proposals"` + Proposals Proposals `json:"proposals" yaml:"proposals"` DepositParams DepositParams `json:"deposit_params" yaml:"deposit_params"` VotingParams VotingParams `json:"voting_params" yaml:"voting_params"` TallyParams TallyParams `json:"tally_params" yaml:"tally_params"` @@ -71,4 +71,3 @@ func ValidateGenesis(data GenesisState) error { return nil } - diff --git a/x/gov/types/params.go b/x/gov/types/params.go index 06edca367c2d..e4ad5ef2ff5e 100644 --- a/x/gov/types/params.go +++ b/x/gov/types/params.go @@ -8,17 +8,17 @@ import ( params "github.com/cosmos/cosmos-sdk/x/params/subspace" ) - // Default period for deposits & voting +// Default period for deposits & voting const ( - DefaultPeriod time.Duration = 86400 * 2 * time.Second // 2 days + DefaultPeriod time.Duration = time.Hour * 24 * 2 // 2 days ) // Default governance params var ( DefaultMinDepositTokens = sdk.TokensFromConsensusPower(10) - DefaultQuorum = sdk.NewDecWithPrec(334, 3) - DefaultThreshold = sdk.NewDecWithPrec(5, 1) - DefaultVeto = sdk.NewDecWithPrec(334, 3) + DefaultQuorum = sdk.NewDecWithPrec(334, 3) + DefaultThreshold = sdk.NewDecWithPrec(5, 1) + DefaultVeto = sdk.NewDecWithPrec(334, 3) ) // Parameter store key diff --git a/x/gov/types/tally.go b/x/gov/types/tally.go index c50e773e7e96..35b44894482f 100644 --- a/x/gov/types/tally.go +++ b/x/gov/types/tally.go @@ -48,22 +48,17 @@ func NewTallyResult(yes, abstain, no, noWithVeto sdk.Int) TallyResult { // NewTallyResultFromMap creates a new TallyResult instance from a Option -> Dec map func NewTallyResultFromMap(results map[VoteOption]sdk.Dec) TallyResult { - return TallyResult{ - Yes: results[OptionYes].TruncateInt(), - Abstain: results[OptionAbstain].TruncateInt(), - No: results[OptionNo].TruncateInt(), - NoWithVeto: results[OptionNoWithVeto].TruncateInt(), - } + return NewTallyResult( + results[OptionYes].TruncateInt(), + results[OptionAbstain].TruncateInt(), + results[OptionNo].TruncateInt(), + results[OptionNoWithVeto].TruncateInt(), + ) } // EmptyTallyResult returns an empty TallyResult. func EmptyTallyResult() TallyResult { - return TallyResult{ - Yes: sdk.ZeroInt(), - Abstain: sdk.ZeroInt(), - No: sdk.ZeroInt(), - NoWithVeto: sdk.ZeroInt(), - } + return NewTallyResult(sdk.ZeroInt(), sdk.ZeroInt(), sdk.ZeroInt(), sdk.ZeroInt()) } // Equals returns if two proposals are equal. From 807fdb3c20fdaa1686941bf5b207d70fc1cec5ad Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Wed, 24 Jul 2019 18:11:29 -0400 Subject: [PATCH 22/36] fix nondeterminism in iteration within tests --- x/gov/keeper/deposit_test.go | 2 +- x/gov/keeper/invariants.go | 3 ++- x/gov/keeper/querier_test.go | 2 +- x/gov/keeper/test_common.go | 27 ++++++++++++++++++++------- x/gov/keeper/vote_test.go | 2 +- 5 files changed, 25 insertions(+), 11 deletions(-) diff --git a/x/gov/keeper/deposit_test.go b/x/gov/keeper/deposit_test.go index 081d7d44a561..c6c229893119 100644 --- a/x/gov/keeper/deposit_test.go +++ b/x/gov/keeper/deposit_test.go @@ -77,7 +77,7 @@ func TestDeposits(t *testing.T) { require.True(t, proposal.VotingStartTime.Equal(ctx.BlockHeader().Time)) // Test deposit iterator - // FIXME: non determinism on the order of the deposits + // NOTE order of deposits is determined by the addresses deposits := keeper.GetAllDeposits(ctx) require.Len(t, deposits, 2) require.Equal(t, deposits, keeper.GetDeposits(ctx, proposalID)) diff --git a/x/gov/keeper/invariants.go b/x/gov/keeper/invariants.go index 61b6b6af3291..1c8e75a596f5 100644 --- a/x/gov/keeper/invariants.go +++ b/x/gov/keeper/invariants.go @@ -1,6 +1,7 @@ -// DONTCOVER package keeper +// DONTCOVER + import ( "fmt" diff --git a/x/gov/keeper/querier_test.go b/x/gov/keeper/querier_test.go index 4f5dbad0cc0b..818b95e3a8e9 100644 --- a/x/gov/keeper/querier_test.go +++ b/x/gov/keeper/querier_test.go @@ -233,7 +233,7 @@ func TestQueries(t *testing.T) { // check deposits on proposal2 match individual deposits deposits = getQueriedDeposits(t, ctx, keeper.cdc, querier, proposal2.ProposalID) require.Len(t, deposits, 2) - // FIXME: non determinism on the order of the deposits + // NOTE order of deposits is determined by the addresses require.Equal(t, deposit2, deposits[0]) require.Equal(t, deposit4, deposits[1]) diff --git a/x/gov/keeper/test_common.go b/x/gov/keeper/test_common.go index 34af463882e9..72e7d33f57ba 100644 --- a/x/gov/keeper/test_common.go +++ b/x/gov/keeper/test_common.go @@ -1,9 +1,11 @@ // nolint -// DONTCOVER package keeper // noalias +// DONTCOVER + import ( "bytes" + "encoding/hex" "testing" "github.com/stretchr/testify/require" @@ -29,16 +31,16 @@ import ( // dummy addresses used for testing var ( - delPk1 = ed25519.GenPrivKey().PubKey() - delPk2 = ed25519.GenPrivKey().PubKey() - delPk3 = ed25519.GenPrivKey().PubKey() + delPk1 = newPubKey("0B485CFC0EECC619440448436F8FC9DF40566F2369E72400281454CB552AFB51") + delPk2 = newPubKey("0B485CFC0EECC619440448436F8FC9DF40566F2369E72400281454CB552AFB50") + delPk3 = newPubKey("0B485CFC0EECC619440448436F8FC9DF40566F2369E72400281454CB552AFB52") delAddr1 = sdk.AccAddress(delPk1.Address()) delAddr2 = sdk.AccAddress(delPk2.Address()) delAddr3 = sdk.AccAddress(delPk3.Address()) - valOpPk1 = ed25519.GenPrivKey().PubKey() - valOpPk2 = ed25519.GenPrivKey().PubKey() - valOpPk3 = ed25519.GenPrivKey().PubKey() + valOpPk1 = newPubKey("0B485CFC0EECC619440448436F8FC9DF40566F2369E72400281454CB552AFB53") + valOpPk2 = newPubKey("0B485CFC0EECC619440448436F8FC9DF40566F2369E72400281454CB552AFB54") + valOpPk3 = newPubKey("0B485CFC0EECC619440448436F8FC9DF40566F2369E72400281454CB552AFB55") valOpAddr1 = sdk.ValAddress(valOpPk1.Address()) valOpAddr2 = sdk.ValAddress(valOpPk2.Address()) valOpAddr3 = sdk.ValAddress(valOpPk3.Address()) @@ -63,6 +65,17 @@ var ( TestCommissionRates = staking.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()) ) +// TODO move to common testing framework +func newPubKey(pk string) (res crypto.PubKey) { + pkBytes, err := hex.DecodeString(pk) + if err != nil { + panic(err) + } + var pkEd ed25519.PubKeyEd25519 + copy(pkEd[:], pkBytes[:]) + return pkEd +} + func makeTestCodec() *codec.Codec { var cdc = codec.New() auth.RegisterCodec(cdc) diff --git a/x/gov/keeper/vote_test.go b/x/gov/keeper/vote_test.go index b4aa14254ffa..f69b5a427b59 100644 --- a/x/gov/keeper/vote_test.go +++ b/x/gov/keeper/vote_test.go @@ -51,7 +51,7 @@ func TestVotes(t *testing.T) { require.Equal(t, types.OptionNoWithVeto, vote.Option) // Test vote iterator - // FIXME: non determinism on the order of the votes + // NOTE order of deposits is determined by the addresses votes := keeper.GetAllVotes(ctx) require.Len(t, votes, 2) require.Equal(t, votes, keeper.GetVotes(ctx, proposalID)) From f42ab0c92dc767f4abd23025ab3b4aa7572c16ed Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Thu, 25 Jul 2019 12:44:51 +0200 Subject: [PATCH 23/36] cleanup --- x/gov/alias.go | 2 -- x/gov/keeper/deposit.go | 2 +- x/gov/keeper/vote.go | 1 + x/gov/types/errors.go | 19 ++++++++------- x/gov/types/msgs.go | 51 +++++++++++++++++++++++++---------------- x/gov/types/proposal.go | 35 ++++++++++++++++++++++------ 6 files changed, 72 insertions(+), 38 deletions(-) diff --git a/x/gov/alias.go b/x/gov/alias.go index bf21c3b3c2fa..a502351c1843 100644 --- a/x/gov/alias.go +++ b/x/gov/alias.go @@ -74,8 +74,6 @@ var ( ErrUnknownProposal = types.ErrUnknownProposal ErrInactiveProposal = types.ErrInactiveProposal ErrAlreadyActiveProposal = types.ErrAlreadyActiveProposal - ErrAlreadyFinishedProposal = types.ErrAlreadyFinishedProposal - ErrAddressNotStaked = types.ErrAddressNotStaked ErrInvalidProposalContent = types.ErrInvalidProposalContent ErrInvalidProposalType = types.ErrInvalidProposalType ErrInvalidVote = types.ErrInvalidVote diff --git a/x/gov/keeper/deposit.go b/x/gov/keeper/deposit.go index 774208afe817..f673b2099a8d 100644 --- a/x/gov/keeper/deposit.go +++ b/x/gov/keeper/deposit.go @@ -102,7 +102,7 @@ func (keeper Keeper) AddDeposit(ctx sdk.Context, proposalID uint64, depositorAdd // Check if proposal is still depositable if (proposal.Status != types.StatusDepositPeriod) && (proposal.Status != types.StatusVotingPeriod) { - return types.ErrAlreadyFinishedProposal(keeper.codespace, proposalID), false + return types.ErrInactiveProposal(keeper.codespace, proposalID), false } // update the governance module's account coins pool diff --git a/x/gov/keeper/vote.go b/x/gov/keeper/vote.go index b491b4690c4b..49ea2f704c89 100644 --- a/x/gov/keeper/vote.go +++ b/x/gov/keeper/vote.go @@ -104,6 +104,7 @@ func (keeper Keeper) IterateVotes(ctx sdk.Context, proposalID uint64, cb func(vo } } +// deleteVote deletes a vote from a given proposalID and voter from the store func (keeper Keeper) deleteVote(ctx sdk.Context, proposalID uint64, voterAddr sdk.AccAddress) { store := ctx.KVStore(keeper.storeKey) store.Delete(types.VoteKey(proposalID, voterAddr)) diff --git a/x/gov/types/errors.go b/x/gov/types/errors.go index 784fde7cd360..7c07ce1cd5fc 100644 --- a/x/gov/types/errors.go +++ b/x/gov/types/errors.go @@ -1,12 +1,15 @@ //nolint package types +// DONTCOVER + import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" ) +// Codes for governance errors const ( DefaultCodespace sdk.CodespaceType = ModuleName @@ -23,42 +26,42 @@ const ( CodeProposalHandlerNotExists sdk.CodeType = 11 ) +// ErrUnknownProposal error for unknown proposals func ErrUnknownProposal(codespace sdk.CodespaceType, proposalID uint64) sdk.Error { return sdk.NewError(codespace, CodeUnknownProposal, fmt.Sprintf("unknown proposal with id %d", proposalID)) } +// ErrInactiveProposal error for inactive (i.e finalized) proposals func ErrInactiveProposal(codespace sdk.CodespaceType, proposalID uint64) sdk.Error { return sdk.NewError(codespace, CodeInactiveProposal, fmt.Sprintf("inactive proposal with id %d", proposalID)) } +// ErrAlreadyActiveProposal error for proposals that are already active func ErrAlreadyActiveProposal(codespace sdk.CodespaceType, proposalID uint64) sdk.Error { return sdk.NewError(codespace, CodeAlreadyActiveProposal, fmt.Sprintf("proposal %d has been already active", proposalID)) } -func ErrAlreadyFinishedProposal(codespace sdk.CodespaceType, proposalID uint64) sdk.Error { - return sdk.NewError(codespace, CodeAlreadyFinishedProposal, fmt.Sprintf("proposal %d has already passed its voting period", proposalID)) -} - -func ErrAddressNotStaked(codespace sdk.CodespaceType, address sdk.AccAddress) sdk.Error { - return sdk.NewError(codespace, CodeAddressNotStaked, fmt.Sprintf("address %s is not staked and is thus ineligible to vote", address)) -} - +// ErrInvalidProposalContent error for invalid proposal title or description func ErrInvalidProposalContent(cs sdk.CodespaceType, msg string) sdk.Error { return sdk.NewError(cs, CodeInvalidContent, fmt.Sprintf("invalid proposal content: %s", msg)) } +// ErrInvalidProposalType error for non registered proposal types func ErrInvalidProposalType(codespace sdk.CodespaceType, proposalType string) sdk.Error { return sdk.NewError(codespace, CodeInvalidProposalType, fmt.Sprintf("proposal type '%s' is not valid", proposalType)) } +// ErrInvalidVote error for an invalid vote option func ErrInvalidVote(codespace sdk.CodespaceType, voteOption VoteOption) sdk.Error { return sdk.NewError(codespace, CodeInvalidVote, fmt.Sprintf("'%v' is not a valid voting option", voteOption.String())) } +// ErrInvalidGenesis error for an invalid governance GenesisState func ErrInvalidGenesis(codespace sdk.CodespaceType, msg string) sdk.Error { return sdk.NewError(codespace, CodeInvalidVote, msg) } +// ErrNoProposalHandlerExists error when proposal handler is not defined func ErrNoProposalHandlerExists(codespace sdk.CodespaceType, content interface{}) sdk.Error { return sdk.NewError(codespace, CodeProposalHandlerNotExists, fmt.Sprintf("'%T' does not have a corresponding handler", content)) } diff --git a/x/gov/types/msgs.go b/x/gov/types/msgs.go index 57fc2e0ce69f..aead430073ed 100644 --- a/x/gov/types/msgs.go +++ b/x/gov/types/msgs.go @@ -15,22 +15,26 @@ const ( var _, _, _ sdk.Msg = MsgSubmitProposal{}, MsgDeposit{}, MsgVote{} -// MsgSubmitProposal +// MsgSubmitProposal defines a message to create a governance proposal with a +// given content and initial deposit type MsgSubmitProposal struct { Content Content `json:"content" yaml:"content"` InitialDeposit sdk.Coins `json:"initial_deposit" yaml:"initial_deposit"` // Initial deposit paid by sender. Must be strictly positive Proposer sdk.AccAddress `json:"proposer" yaml:"proposer"` // Address of the proposer } +// NewMsgSubmitProposal creates a new MsgSubmitProposal instance func NewMsgSubmitProposal(content Content, initialDeposit sdk.Coins, proposer sdk.AccAddress) MsgSubmitProposal { return MsgSubmitProposal{content, initialDeposit, proposer} } -//nolint +// Route implements Msg func (msg MsgSubmitProposal) Route() string { return RouterKey } -func (msg MsgSubmitProposal) Type() string { return TypeMsgSubmitProposal } -// Implements Msg. +// Type implements Msg +func (msg MsgSubmitProposal) Type() string { return TypeMsgSubmitProposal } + +// ValidateBasic implements Msg func (msg MsgSubmitProposal) ValidateBasic() sdk.Error { if msg.Content == nil { return ErrInvalidProposalContent(DefaultCodespace, "missing content") @@ -57,6 +61,7 @@ func (msg MsgSubmitProposal) ValidateBasic() sdk.Error { return msg.Content.ValidateBasic() } +// String implements the Stringer interface func (msg MsgSubmitProposal) String() string { return fmt.Sprintf(`Submit Proposal Message: Content: %s @@ -64,34 +69,36 @@ func (msg MsgSubmitProposal) String() string { `, msg.Content.String(), msg.InitialDeposit) } -// Implements Msg. +// GetSignBytes implements Msg func (msg MsgSubmitProposal) GetSignBytes() []byte { bz := ModuleCdc.MustMarshalJSON(msg) return sdk.MustSortJSON(bz) } -// Implements Msg. +// GetSigners implements Msg func (msg MsgSubmitProposal) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.Proposer} } -// MsgDeposit +// MsgDeposit defines a message to submit a deposit to an existing proposal type MsgDeposit struct { ProposalID uint64 `json:"proposal_id" yaml:"proposal_id"` // ID of the proposal Depositor sdk.AccAddress `json:"depositor" yaml:"depositor"` // Address of the depositor Amount sdk.Coins `json:"amount" yaml:"amount"` // Coins to add to the proposal's deposit } +// NewMsgDeposit creates a new MsgDeposit instance func NewMsgDeposit(depositor sdk.AccAddress, proposalID uint64, amount sdk.Coins) MsgDeposit { return MsgDeposit{proposalID, depositor, amount} } -// Implements Msg. -// nolint +// Route implements Msg func (msg MsgDeposit) Route() string { return RouterKey } -func (msg MsgDeposit) Type() string { return TypeMsgDeposit } -// Implements Msg. +// Type implements Msg +func (msg MsgDeposit) Type() string { return TypeMsgDeposit } + +// ValidateBasic implements Msg func (msg MsgDeposit) ValidateBasic() sdk.Error { if msg.Depositor.Empty() { return sdk.ErrInvalidAddress(msg.Depositor.String()) @@ -106,6 +113,7 @@ func (msg MsgDeposit) ValidateBasic() sdk.Error { return nil } +// String implements the Stringer interface func (msg MsgDeposit) String() string { return fmt.Sprintf(`Deposit Message: Depositer: %s @@ -114,34 +122,36 @@ func (msg MsgDeposit) String() string { `, msg.Depositor, msg.ProposalID, msg.Amount) } -// Implements Msg. +// GetSignBytes implements Msg func (msg MsgDeposit) GetSignBytes() []byte { bz := ModuleCdc.MustMarshalJSON(msg) return sdk.MustSortJSON(bz) } -// Implements Msg. +// GetSigners implements Msg func (msg MsgDeposit) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.Depositor} } -// MsgVote +// MsgVote defines a message to cast a vote type MsgVote struct { ProposalID uint64 `json:"proposal_id" yaml:"proposal_id"` // ID of the proposal Voter sdk.AccAddress `json:"voter" yaml:"voter"` // address of the voter Option VoteOption `json:"option" yaml:"option"` // option from OptionSet chosen by the voter } +// NewMsgVote creates a message to cast a vote on an active proposal func NewMsgVote(voter sdk.AccAddress, proposalID uint64, option VoteOption) MsgVote { return MsgVote{proposalID, voter, option} } -// Implements Msg. -// nolint +// Route implements Msg func (msg MsgVote) Route() string { return RouterKey } -func (msg MsgVote) Type() string { return TypeMsgVote } -// Implements Msg. +// Type implements Msg +func (msg MsgVote) Type() string { return TypeMsgVote } + +// ValidateBasic implements Msg func (msg MsgVote) ValidateBasic() sdk.Error { if msg.Voter.Empty() { return sdk.ErrInvalidAddress(msg.Voter.String()) @@ -153,6 +163,7 @@ func (msg MsgVote) ValidateBasic() sdk.Error { return nil } +// String implements the Stringer interface func (msg MsgVote) String() string { return fmt.Sprintf(`Vote Message: Proposal ID: %d @@ -160,13 +171,13 @@ func (msg MsgVote) String() string { `, msg.ProposalID, msg.Option) } -// Implements Msg. +// GetSignBytes implements Msg func (msg MsgVote) GetSignBytes() []byte { bz := ModuleCdc.MustMarshalJSON(msg) return sdk.MustSortJSON(bz) } -// Implements Msg. +// GetSigners implements Msg func (msg MsgVote) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.Voter} } diff --git a/x/gov/types/proposal.go b/x/gov/types/proposal.go index f72616db14ff..314a120f10da 100644 --- a/x/gov/types/proposal.go +++ b/x/gov/types/proposal.go @@ -63,7 +63,7 @@ func (p Proposal) String() string { // Proposals is an array of proposal type Proposals []Proposal -// nolint +// String implements stringer interface func (p Proposals) String() string { out := "ID - (Status) [Type] Title\n" for _, prop := range p { @@ -82,7 +82,7 @@ type ( ProposalStatus byte ) -//nolint +// Valid Proposal statuses const ( StatusNil ProposalStatus = 0x00 StatusDepositPeriod ProposalStatus = 0x01 @@ -205,7 +205,8 @@ const ( ProposalTypeSoftwareUpgrade string = "SoftwareUpgrade" ) -// Text Proposal +// TextProposal defines a standard text proposal whose changes need to be +// manually updated in case of approval type TextProposal struct { Title string `json:"title" yaml:"title"` Description string `json:"description" yaml:"description"` @@ -219,13 +220,22 @@ func NewTextProposal(title, description string) Content { // Implements Content Interface var _ Content = TextProposal{} -// nolint +// GetTitle returns the proposal title func (tp TextProposal) GetTitle() string { return tp.Title } + +// GetDescription returns the proposal description func (tp TextProposal) GetDescription() string { return tp.Description } + +// ProposalRoute returns the proposal router key func (tp TextProposal) ProposalRoute() string { return RouterKey } + +// ProposalType is "Text" func (tp TextProposal) ProposalType() string { return ProposalTypeText } + +// ValidateBasic validates the content's title and description of the proposal func (tp TextProposal) ValidateBasic() sdk.Error { return ValidateAbstract(DefaultCodespace, tp) } +// String implements Stringer interface func (tp TextProposal) String() string { return fmt.Sprintf(`Text Proposal: Title: %s @@ -233,7 +243,9 @@ func (tp TextProposal) String() string { `, tp.Title, tp.Description) } -// Software Upgrade Proposals +// SoftwareUpgradeProposal defines a proposal for upgrading the network nodes +// without the need of manually halting at a given height +// // TODO: We have to add fields for SUP specific arguments e.g. commit hash, // upgrade date, etc. type SoftwareUpgradeProposal struct { @@ -241,7 +253,7 @@ type SoftwareUpgradeProposal struct { Description string `json:"description" yaml:"description"` } -// NewTextProposal creates a software upgrade proposal Content +// NewSoftwareUpgradeProposal creates a software upgrade proposal Content func NewSoftwareUpgradeProposal(title, description string) Content { return SoftwareUpgradeProposal{title, description} } @@ -249,15 +261,24 @@ func NewSoftwareUpgradeProposal(title, description string) Content { // Implements Content Interface var _ Content = SoftwareUpgradeProposal{} -// nolint +// GetTitle returns the proposal title func (sup SoftwareUpgradeProposal) GetTitle() string { return sup.Title } + +// GetDescription returns the proposal description func (sup SoftwareUpgradeProposal) GetDescription() string { return sup.Description } + +// ProposalRoute returns the proposal router key func (sup SoftwareUpgradeProposal) ProposalRoute() string { return RouterKey } + +// ProposalType is "SoftwareUpgrade" func (sup SoftwareUpgradeProposal) ProposalType() string { return ProposalTypeSoftwareUpgrade } + +// ValidateBasic validates the content's title and description of the proposal func (sup SoftwareUpgradeProposal) ValidateBasic() sdk.Error { return ValidateAbstract(DefaultCodespace, sup) } +// String implements Stringer interface func (sup SoftwareUpgradeProposal) String() string { return fmt.Sprintf(`Software Upgrade Proposal: Title: %s From 30144910a345976693487f4e319719f4425bfceb Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Thu, 25 Jul 2019 12:47:01 +0200 Subject: [PATCH 24/36] clog --- .pending/improvements/modules/_4665-update-gov | 1 + 1 file changed, 1 insertion(+) create mode 100644 .pending/improvements/modules/_4665-update-gov diff --git a/.pending/improvements/modules/_4665-update-gov b/.pending/improvements/modules/_4665-update-gov new file mode 100644 index 000000000000..01b7e094ef03 --- /dev/null +++ b/.pending/improvements/modules/_4665-update-gov @@ -0,0 +1 @@ +#4665 update `x/gov` to match module spec \ No newline at end of file From a912bf37fb58abfe7c8b4d094ed76cc7907243f3 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Tue, 6 Aug 2019 23:10:08 +0200 Subject: [PATCH 25/36] GetAddress() --- x/distribution/keeper/test_common.go | 8 ++++---- x/gov/test_common.go | 6 +++--- x/mint/internal/keeper/common_test.go | 8 ++++---- x/slashing/app_test.go | 6 +++--- x/slashing/internal/keeper/test_common.go | 6 +++--- x/staking/app_test.go | 6 +++--- x/staking/keeper/test_common.go | 6 +++--- 7 files changed, 23 insertions(+), 23 deletions(-) diff --git a/x/distribution/keeper/test_common.go b/x/distribution/keeper/test_common.go index 06215cf7e43b..b679360d6bd9 100644 --- a/x/distribution/keeper/test_common.go +++ b/x/distribution/keeper/test_common.go @@ -121,10 +121,10 @@ func CreateTestInputAdvanced(t *testing.T, isCheckTx bool, initPower int64, bondPool := supply.NewEmptyModuleAccount(staking.BondedPoolName, supply.Burner, supply.Staking) blacklistedAddrs := make(map[string]bool) - blacklistedAddrs[feeCollectorAcc.String()] = true - blacklistedAddrs[notBondedPool.String()] = true - blacklistedAddrs[bondPool.String()] = true - blacklistedAddrs[distrAcc.String()] = true + blacklistedAddrs[feeCollectorAcc.GetAddress().String()] = true + blacklistedAddrs[notBondedPool.GetAddress().String()] = true + blacklistedAddrs[bondPool.GetAddress().String()] = true + blacklistedAddrs[distrAcc.GetAddress().String()] = true cdc := MakeTestCodec() pk := params.NewKeeper(cdc, keyParams, tkeyParams, params.DefaultCodespace) diff --git a/x/gov/test_common.go b/x/gov/test_common.go index 276b156d2bbb..ddde4025e155 100644 --- a/x/gov/test_common.go +++ b/x/gov/test_common.go @@ -61,9 +61,9 @@ func getMockApp(t *testing.T, numGenAccs int, genState types.GenesisState, genAc bondPool := supply.NewEmptyModuleAccount(staking.BondedPoolName, supply.Burner, supply.Staking) blacklistedAddrs := make(map[string]bool) - blacklistedAddrs[govAcc.String()] = true - blacklistedAddrs[notBondedPool.String()] = true - blacklistedAddrs[bondPool.String()] = true + blacklistedAddrs[govAcc.GetAddress().String()] = true + blacklistedAddrs[notBondedPool.GetAddress().String()] = true + blacklistedAddrs[bondPool.GetAddress().String()] = true pk := mApp.ParamsKeeper diff --git a/x/mint/internal/keeper/common_test.go b/x/mint/internal/keeper/common_test.go index 77b7985d339c..57862d6bfc4c 100644 --- a/x/mint/internal/keeper/common_test.go +++ b/x/mint/internal/keeper/common_test.go @@ -60,10 +60,10 @@ func newTestInput(t *testing.T) testInput { minterAcc := supply.NewEmptyModuleAccount(types.ModuleName, supply.Minter) blacklistedAddrs := make(map[string]bool) - blacklistedAddrs[feeCollectorAcc.String()] = true - blacklistedAddrs[notBondedPool.String()] = true - blacklistedAddrs[bondPool.String()] = true - blacklistedAddrs[minterAcc.String()] = true + blacklistedAddrs[feeCollectorAcc.GetAddress().String()] = true + blacklistedAddrs[notBondedPool.GetAddress().String()] = true + blacklistedAddrs[bondPool.GetAddress().String()] = true + blacklistedAddrs[minterAcc.GetAddress().String()] = true paramsKeeper := params.NewKeeper(types.ModuleCdc, keyParams, tkeyParams, params.DefaultCodespace) accountKeeper := auth.NewAccountKeeper(types.ModuleCdc, keyAcc, paramsKeeper.Subspace(auth.DefaultParamspace), auth.ProtoBaseAccount) diff --git a/x/slashing/app_test.go b/x/slashing/app_test.go index a1ce02fef0cd..2d3373f67667 100644 --- a/x/slashing/app_test.go +++ b/x/slashing/app_test.go @@ -43,9 +43,9 @@ func getMockApp(t *testing.T) (*mock.App, staking.Keeper, Keeper) { bondPool := supply.NewEmptyModuleAccount(types.BondedPoolName, supply.Burner, supply.Staking) blacklistedAddrs := make(map[string]bool) - blacklistedAddrs[feeCollector.String()] = true - blacklistedAddrs[notBondedPool.String()] = true - blacklistedAddrs[bondPool.String()] = true + blacklistedAddrs[feeCollector.GetAddress().String()] = true + blacklistedAddrs[notBondedPool.GetAddress().String()] = true + blacklistedAddrs[bondPool.GetAddress().String()] = true bankKeeper := bank.NewBaseKeeper(mapp.AccountKeeper, mapp.ParamsKeeper.Subspace(bank.DefaultParamspace), bank.DefaultCodespace, blacklistedAddrs) maccPerms := map[string][]string{ diff --git a/x/slashing/internal/keeper/test_common.go b/x/slashing/internal/keeper/test_common.go index 6d3251d6cc94..384b24eb7827 100644 --- a/x/slashing/internal/keeper/test_common.go +++ b/x/slashing/internal/keeper/test_common.go @@ -86,9 +86,9 @@ func CreateTestInput(t *testing.T, defaults types.Params) (sdk.Context, bank.Kee bondPool := supply.NewEmptyModuleAccount(staking.BondedPoolName, supply.Burner, supply.Staking) blacklistedAddrs := make(map[string]bool) - blacklistedAddrs[feeCollectorAcc.String()] = true - blacklistedAddrs[notBondedPool.String()] = true - blacklistedAddrs[bondPool.String()] = true + blacklistedAddrs[feeCollectorAcc.GetAddress().String()] = true + blacklistedAddrs[notBondedPool.GetAddress().String()] = true + blacklistedAddrs[bondPool.GetAddress().String()] = true paramsKeeper := params.NewKeeper(cdc, keyParams, tkeyParams, params.DefaultCodespace) accountKeeper := auth.NewAccountKeeper(cdc, keyAcc, paramsKeeper.Subspace(auth.DefaultParamspace), auth.ProtoBaseAccount) diff --git a/x/staking/app_test.go b/x/staking/app_test.go index 1f148de06bdc..8385f88f1eae 100644 --- a/x/staking/app_test.go +++ b/x/staking/app_test.go @@ -31,9 +31,9 @@ func getMockApp(t *testing.T) (*mock.App, Keeper) { bondPool := supply.NewEmptyModuleAccount(types.BondedPoolName, supply.Burner, supply.Staking) blacklistedAddrs := make(map[string]bool) - blacklistedAddrs[feeCollector.String()] = true - blacklistedAddrs[notBondedPool.String()] = true - blacklistedAddrs[bondPool.String()] = true + blacklistedAddrs[feeCollector.GetAddress().String()] = true + blacklistedAddrs[notBondedPool.GetAddress().String()] = true + blacklistedAddrs[bondPool.GetAddress().String()] = true bankKeeper := bank.NewBaseKeeper(mApp.AccountKeeper, mApp.ParamsKeeper.Subspace(bank.DefaultParamspace), bank.DefaultCodespace, blacklistedAddrs) maccPerms := map[string][]string{ diff --git a/x/staking/keeper/test_common.go b/x/staking/keeper/test_common.go index 86c9b83f20e1..cc178408ca0c 100644 --- a/x/staking/keeper/test_common.go +++ b/x/staking/keeper/test_common.go @@ -112,9 +112,9 @@ func CreateTestInput(t *testing.T, isCheckTx bool, initPower int64) (sdk.Context bondPool := supply.NewEmptyModuleAccount(types.BondedPoolName, supply.Burner, supply.Staking) blacklistedAddrs := make(map[string]bool) - blacklistedAddrs[feeCollectorAcc.String()] = true - blacklistedAddrs[notBondedPool.String()] = true - blacklistedAddrs[bondPool.String()] = true + blacklistedAddrs[feeCollectorAcc.GetAddress().String()] = true + blacklistedAddrs[notBondedPool.GetAddress().String()] = true + blacklistedAddrs[bondPool.GetAddress().String()] = true pk := params.NewKeeper(cdc, keyParams, tkeyParams, params.DefaultCodespace) From b99ace7899895ae6b0f11fae2a2596cb0b4107ce Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Tue, 6 Aug 2019 23:10:17 +0200 Subject: [PATCH 26/36] gov keeper fixes --- x/gov/keeper/test_common.go | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/x/gov/keeper/test_common.go b/x/gov/keeper/test_common.go index 72e7d33f57ba..d84a85188f50 100644 --- a/x/gov/keeper/test_common.go +++ b/x/gov/keeper/test_common.go @@ -14,7 +14,7 @@ import ( "github.com/tendermint/tendermint/crypto/ed25519" abci "github.com/tendermint/tendermint/abci/types" - dbm "github.com/tendermint/tendermint/libs/db" + dbm "github.com/tendermint/tm-db" "github.com/tendermint/tendermint/libs/log" tmtypes "github.com/tendermint/tendermint/types" @@ -129,10 +129,22 @@ func createTestInput(t *testing.T, isCheckTx bool, initPower int64) (sdk.Context staking.BondedPoolName: {supply.Burner, supply.Staking}, } + // create module accounts + feeCollectorAcc := supply.NewEmptyModuleAccount(auth.FeeCollectorName) + govAcc := supply.NewEmptyModuleAccount(types.ModuleName, supply.Burner) + notBondedPool := supply.NewEmptyModuleAccount(staking.NotBondedPoolName, supply.Burner, supply.Staking) + bondPool := supply.NewEmptyModuleAccount(staking.BondedPoolName, supply.Burner, supply.Staking) + + blacklistedAddrs := make(map[string]bool) + blacklistedAddrs[feeCollectorAcc.GetAddress().String()] = true + blacklistedAddrs[govAcc.GetAddress().String()] = true + blacklistedAddrs[notBondedPool.GetAddress().String()] = true + blacklistedAddrs[bondPool.GetAddress().String()] = true + pk := params.NewKeeper(cdc, keyParams, tkeyParams, params.DefaultCodespace) accountKeeper := auth.NewAccountKeeper(cdc, keyAcc, pk.Subspace(auth.DefaultParamspace), auth.ProtoBaseAccount) - bankKeeper := bank.NewBaseKeeper(accountKeeper, pk.Subspace(bank.DefaultParamspace), bank.DefaultCodespace) - supplyKeeper := supply.NewKeeper(cdc, keySupply, accountKeeper, bankKeeper, supply.DefaultCodespace, maccPerms) + bankKeeper := bank.NewBaseKeeper(accountKeeper, pk.Subspace(bank.DefaultParamspace), bank.DefaultCodespace, blacklistedAddrs) + supplyKeeper := supply.NewKeeper(cdc, keySupply, accountKeeper, bankKeeper, maccPerms) sk := staking.NewKeeper(cdc, keyStaking, tkeyStaking, supplyKeeper, pk.Subspace(staking.DefaultParamspace), staking.DefaultCodespace) sk.SetParams(ctx, staking.DefaultParams()) @@ -156,12 +168,6 @@ func createTestInput(t *testing.T, isCheckTx bool, initPower int64) (sdk.Context require.Nil(t, err) } - // create module accounts - feeCollectorAcc := supply.NewEmptyModuleAccount(auth.FeeCollectorName) - govAcc := supply.NewEmptyModuleAccount(types.ModuleName, supply.Burner) - notBondedPool := supply.NewEmptyModuleAccount(staking.NotBondedPoolName, supply.Burner, supply.Staking) - bondPool := supply.NewEmptyModuleAccount(staking.BondedPoolName, supply.Burner, supply.Staking) - keeper.supplyKeeper.SetModuleAccount(ctx, feeCollectorAcc) keeper.supplyKeeper.SetModuleAccount(ctx, govAcc) keeper.supplyKeeper.SetModuleAccount(ctx, bondPool) From 420ed5bf4eae97b3a2dfeab946517de027a318ac Mon Sep 17 00:00:00 2001 From: Federico Kunze <31522760+fedekunze@users.noreply.github.com> Date: Wed, 7 Aug 2019 13:12:44 +0200 Subject: [PATCH 27/36] Update x/gov/module.go Co-Authored-By: colin axner --- x/gov/module.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x/gov/module.go b/x/gov/module.go index d0aeacf3511c..637fe0a839f6 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -92,7 +92,7 @@ func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { //___________________________ -// AppModule - app module ob +// AppModule - app module object type AppModule struct { AppModuleBasic keeper Keeper From d28ac5faccbf3f4366341748d5ba5536ecc951ed Mon Sep 17 00:00:00 2001 From: Federico Kunze <31522760+fedekunze@users.noreply.github.com> Date: Wed, 7 Aug 2019 13:13:01 +0200 Subject: [PATCH 28/36] Update x/gov/types/tally.go Co-Authored-By: colin axner --- x/gov/types/tally.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x/gov/types/tally.go b/x/gov/types/tally.go index 35b44894482f..63f20d4b7f82 100644 --- a/x/gov/types/tally.go +++ b/x/gov/types/tally.go @@ -68,7 +68,7 @@ func (tr TallyResult) Equals(comp TallyResult) bool { tr.No.Equal(comp.No) && tr.NoWithVeto.Equal(comp.NoWithVeto) } - +// String implements stringer interface func (tr TallyResult) String() string { return fmt.Sprintf(`Tally Result: Yes: %s From 11ddcd16e8365f2ed767bf9256bd8bbeaf02d715 Mon Sep 17 00:00:00 2001 From: Federico Kunze <31522760+fedekunze@users.noreply.github.com> Date: Wed, 7 Aug 2019 13:13:10 +0200 Subject: [PATCH 29/36] Update x/gov/test_common.go Co-Authored-By: colin axner --- x/gov/test_common.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x/gov/test_common.go b/x/gov/test_common.go index ddde4025e155..9ea31b57875c 100644 --- a/x/gov/test_common.go +++ b/x/gov/test_common.go @@ -178,7 +178,7 @@ func (b sortByteArrays) Swap(i, j int) { b[j], b[i] = b[i], b[j] } -// SortByteArrays - +// SortByteArrays - sorts the provided byte array func SortByteArrays(src [][]byte) [][]byte { sorted := sortByteArrays(src) sort.Sort(sorted) From bfae5e3bebdd85893b0bc9c00ccccd48465c8817 Mon Sep 17 00:00:00 2001 From: Federico Kunze <31522760+fedekunze@users.noreply.github.com> Date: Wed, 7 Aug 2019 13:13:23 +0200 Subject: [PATCH 30/36] Update x/gov/types/params.go Co-Authored-By: colin axner --- x/gov/types/params.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x/gov/types/params.go b/x/gov/types/params.go index e4ad5ef2ff5e..a7fe1da7b5b3 100644 --- a/x/gov/types/params.go +++ b/x/gov/types/params.go @@ -118,7 +118,7 @@ func DefaultVotingParams() VotingParams { return NewVotingParams(DefaultPeriod) } -// String implements stringer insterface +// String implements stringer interface func (vp VotingParams) String() string { return fmt.Sprintf(`Voting Params: Voting Period: %s`, vp.VotingPeriod) From a015d0e56e413a14298f387fa427ab8033f34a66 Mon Sep 17 00:00:00 2001 From: Federico Kunze <31522760+fedekunze@users.noreply.github.com> Date: Wed, 7 Aug 2019 13:13:39 +0200 Subject: [PATCH 31/36] Update x/gov/types/expected_keepers.go Co-Authored-By: colin axner --- x/gov/types/expected_keepers.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x/gov/types/expected_keepers.go b/x/gov/types/expected_keepers.go index be4bf6a2ef6c..4bb34fc4275d 100644 --- a/x/gov/types/expected_keepers.go +++ b/x/gov/types/expected_keepers.go @@ -14,7 +14,7 @@ type ParamSubspace interface { Set(ctx sdk.Context, key []byte, param interface{}) } -// SupplyKeeper defines the supply Keeper for module accounts (noalias) +// SupplyKeeper defines the expected supply keeper for module accounts (noalias) type SupplyKeeper interface { GetModuleAddress(name string) sdk.AccAddress GetModuleAccount(ctx sdk.Context, name string) supplyexported.ModuleAccountI From dfbddbbe01af8a4419cee7e8a5badc7d9e235179 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Wed, 7 Aug 2019 14:05:16 +0200 Subject: [PATCH 32/36] address @colin-axner comments --- x/gov/keeper/vote_test.go | 7 ++++--- x/gov/module.go | 12 ++++++------ x/gov/types/errors.go | 3 +-- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/x/gov/keeper/vote_test.go b/x/gov/keeper/vote_test.go index f69b5a427b59..c15978e42db9 100644 --- a/x/gov/keeper/vote_test.go +++ b/x/gov/keeper/vote_test.go @@ -19,13 +19,14 @@ func TestVotes(t *testing.T) { var invalidOption types.VoteOption invalidOption = 0x10 - require.Error(t, keeper.AddVote(ctx, proposalID, TestAddrs[0], types.OptionYes)) - require.Error(t, keeper.AddVote(ctx, 10, TestAddrs[0], types.OptionYes)) - require.Error(t, keeper.AddVote(ctx, 10, TestAddrs[0], invalidOption)) + require.Error(t, keeper.AddVote(ctx, proposalID, TestAddrs[0], types.OptionYes), "proposal not on voting period") + require.Error(t, keeper.AddVote(ctx, 10, TestAddrs[0], types.OptionYes), "invalid proposal ID") proposal.Status = types.StatusVotingPeriod keeper.SetProposal(ctx, proposal) + require.Error(t, keeper.AddVote(ctx, proposalID, TestAddrs[0], invalidOption), "invalid option") + // Test first vote require.NoError(t, keeper.AddVote(ctx, proposalID, TestAddrs[0], types.OptionAbstain)) vote, found := keeper.GetVote(ctx, proposalID, TestAddrs[0]) diff --git a/x/gov/module.go b/x/gov/module.go index 637fe0a839f6..16e304313032 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -51,17 +51,17 @@ func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) { // DefaultGenesis - default genesis state func (AppModuleBasic) DefaultGenesis() json.RawMessage { - return types.ModuleCdc.MustMarshalJSON(DefaultGenesisState()) + return ModuleCdc.MustMarshalJSON(DefaultGenesisState()) } // ValidateGenesis - module validate genesis func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { var data GenesisState - err := types.ModuleCdc.UnmarshalJSON(bz, &data) + err := ModuleCdc.UnmarshalJSON(bz, &data) if err != nil { return err } - return types.ValidateGenesis(data) + return ValidateGenesis(data) } // RegisterRESTRoutes - register rest routes @@ -110,7 +110,7 @@ func NewAppModule(keeper Keeper, supplyKeeper types.SupplyKeeper) AppModule { // Name - module name func (AppModule) Name() string { - return types.ModuleName + return ModuleName } // RegisterInvariants registers module invariants @@ -141,7 +141,7 @@ func (am AppModule) NewQuerierHandler() sdk.Querier { // InitGenesis - module init-genesis func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate { var genesisState GenesisState - types.ModuleCdc.MustUnmarshalJSON(data, &genesisState) + ModuleCdc.MustUnmarshalJSON(data, &genesisState) InitGenesis(ctx, am.keeper, am.supplyKeeper, genesisState) return []abci.ValidatorUpdate{} } @@ -149,7 +149,7 @@ func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.Va // ExportGenesis - module export genesis func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { gs := ExportGenesis(ctx, am.keeper) - return types.ModuleCdc.MustMarshalJSON(gs) + return ModuleCdc.MustMarshalJSON(gs) } // BeginBlock - module begin-block diff --git a/x/gov/types/errors.go b/x/gov/types/errors.go index 7c07ce1cd5fc..27102c7c5900 100644 --- a/x/gov/types/errors.go +++ b/x/gov/types/errors.go @@ -1,4 +1,3 @@ -//nolint package types // DONTCOVER @@ -41,7 +40,7 @@ func ErrAlreadyActiveProposal(codespace sdk.CodespaceType, proposalID uint64) sd return sdk.NewError(codespace, CodeAlreadyActiveProposal, fmt.Sprintf("proposal %d has been already active", proposalID)) } -// ErrInvalidProposalContent error for invalid proposal title or description +// ErrInvalidProposalContent error for invalid proposal title or description func ErrInvalidProposalContent(cs sdk.CodespaceType, msg string) sdk.Error { return sdk.NewError(cs, CodeInvalidContent, fmt.Sprintf("invalid proposal content: %s", msg)) } From 41704278ac9c66103395ef6f7a21d42b9edf3d1e Mon Sep 17 00:00:00 2001 From: Alexander Bezobchuk Date: Wed, 7 Aug 2019 09:46:27 -0400 Subject: [PATCH 33/36] Update .pending/improvements/modules/_4665-update-gov --- .pending/improvements/modules/_4665-update-gov | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pending/improvements/modules/_4665-update-gov b/.pending/improvements/modules/_4665-update-gov index 01b7e094ef03..0f571452bfbe 100644 --- a/.pending/improvements/modules/_4665-update-gov +++ b/.pending/improvements/modules/_4665-update-gov @@ -1 +1 @@ -#4665 update `x/gov` to match module spec \ No newline at end of file +#4665 Prepare the `x/gov` module to match module spec. From b8025b5c2b9af6fe167410cafc02adfd45ed670e Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Wed, 7 Aug 2019 16:55:17 +0200 Subject: [PATCH 34/36] update expected keeper --- simapp/app.go | 2 +- x/gov/keeper/keeper.go | 2 +- x/gov/keeper/test_common.go | 3 ++- x/gov/test_common.go | 3 ++- x/gov/types/expected_keepers.go | 2 -- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/simapp/app.go b/simapp/app.go index 7bf1c2f7e972..a4193f63db61 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -136,7 +136,7 @@ func NewSimApp( mintSubspace := app.paramsKeeper.Subspace(mint.DefaultParamspace) distrSubspace := app.paramsKeeper.Subspace(distr.DefaultParamspace) slashingSubspace := app.paramsKeeper.Subspace(slashing.DefaultParamspace) - govSubspace := app.paramsKeeper.Subspace(gov.DefaultParamspace) + govSubspace := app.paramsKeeper.Subspace(gov.DefaultParamspace).WithKeyTable(gov.ParamKeyTable()) crisisSubspace := app.paramsKeeper.Subspace(crisis.DefaultParamspace) // add keepers diff --git a/x/gov/keeper/keeper.go b/x/gov/keeper/keeper.go index e797f5fe3b29..df8d2e9a1da7 100644 --- a/x/gov/keeper/keeper.go +++ b/x/gov/keeper/keeper.go @@ -58,7 +58,7 @@ func NewKeeper( return Keeper{ storeKey: key, - paramSpace: paramSpace.WithKeyTable(types.ParamKeyTable()), + paramSpace: paramSpace, // CONTRACT: must have the param key table already initialized supplyKeeper: supplyKeeper, sk: sk, cdc: cdc, diff --git a/x/gov/keeper/test_common.go b/x/gov/keeper/test_common.go index d84a85188f50..e822af3f6baa 100644 --- a/x/gov/keeper/test_common.go +++ b/x/gov/keeper/test_common.go @@ -152,7 +152,8 @@ func createTestInput(t *testing.T, isCheckTx bool, initPower int64) (sdk.Context rtr := types.NewRouter(). AddRoute(types.RouterKey, types.ProposalHandler) - keeper := NewKeeper(cdc, keyGov, pk.Subspace(types.DefaultParamspace), supplyKeeper, sk, types.DefaultCodespace, rtr) + keeper := NewKeeper(cdc, keyGov, pk.Subspace(types.DefaultParamspace).WithKeyTable(types.ParamKeyTable()), + supplyKeeper, sk, types.DefaultCodespace, rtr) keeper.SetProposalID(ctx, types.DefaultStartingProposalID) keeper.SetDepositParams(ctx, types.DefaultDepositParams()) diff --git a/x/gov/test_common.go b/x/gov/test_common.go index 9ea31b57875c..4462f0cda623 100644 --- a/x/gov/test_common.go +++ b/x/gov/test_common.go @@ -80,7 +80,8 @@ func getMockApp(t *testing.T, numGenAccs int, genState types.GenesisState, genAc supplyKeeper := supply.NewKeeper(mApp.Cdc, keySupply, mApp.AccountKeeper, bk, maccPerms) sk := staking.NewKeeper(mApp.Cdc, keyStaking, tKeyStaking, supplyKeeper, pk.Subspace(staking.DefaultParamspace), staking.DefaultCodespace) - keeper := keep.NewKeeper(mApp.Cdc, keyGov, pk.Subspace(DefaultParamspace), supplyKeeper, sk, types.DefaultCodespace, rtr) + keeper := keep.NewKeeper(mApp.Cdc, keyGov, pk.Subspace(DefaultParamspace).WithKeyTable(ParamKeyTable()), + supplyKeeper, sk, types.DefaultCodespace, rtr) mApp.Router().AddRoute(types.RouterKey, NewHandler(keeper)) mApp.QueryRouter().AddRoute(types.QuerierRoute, keep.NewQuerier(keeper)) diff --git a/x/gov/types/expected_keepers.go b/x/gov/types/expected_keepers.go index 4bb34fc4275d..8b28faea8ec7 100644 --- a/x/gov/types/expected_keepers.go +++ b/x/gov/types/expected_keepers.go @@ -2,14 +2,12 @@ package types import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/params/subspace" stakingexported "github.com/cosmos/cosmos-sdk/x/staking/exported" supplyexported "github.com/cosmos/cosmos-sdk/x/supply/exported" ) // ParamSubspace defines the expected Subspace interface for parameters (noalias) type ParamSubspace interface { - WithKeyTable(table subspace.KeyTable) subspace.Subspace Get(ctx sdk.Context, key []byte, ptr interface{}) Set(ctx sdk.Context, key []byte, param interface{}) } From dfe86d68d4f09040e0ead743f18ac544cdeec84f Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Thu, 8 Aug 2019 13:36:21 +0200 Subject: [PATCH 35/36] address @rigelrozanski comments --- .pending/breaking/store/_4665-gov-keys | 1 + x/gov/abci_test.go | 9 ++---- x/gov/alias.go | 2 ++ x/gov/client/rest/tx.go | 12 +++----- x/gov/handler.go | 6 +--- x/gov/keeper/keeper.go | 8 +++-- x/gov/keeper/keeper_test.go | 5 ++-- x/gov/keeper/proposal.go | 7 ++--- x/gov/keeper/proposal_test.go | 4 +-- x/gov/types/keys.go | 41 +++++++++++++------------- x/gov/types/proposal.go | 16 +++++----- 11 files changed, 52 insertions(+), 59 deletions(-) create mode 100644 .pending/breaking/store/_4665-gov-keys diff --git a/.pending/breaking/store/_4665-gov-keys b/.pending/breaking/store/_4665-gov-keys new file mode 100644 index 000000000000..7dca5cf33264 --- /dev/null +++ b/.pending/breaking/store/_4665-gov-keys @@ -0,0 +1 @@ +#4665 Update gov keys to use big endian instead of little endian. \ No newline at end of file diff --git a/x/gov/abci_test.go b/x/gov/abci_test.go index 44244d3107bf..42616b36c00b 100644 --- a/x/gov/abci_test.go +++ b/x/gov/abci_test.go @@ -1,7 +1,6 @@ package gov import ( - "encoding/binary" "testing" "time" @@ -155,7 +154,7 @@ func TestTickPassedDepositPeriod(t *testing.T) { res := govHandler(ctx, newProposalMsg) require.True(t, res.IsOK()) - proposalID := binary.LittleEndian.Uint64(res.Data) + proposalID := GetProposalIDFromBytes(res.Data) inactiveQueue = input.keeper.InactiveProposalQueueIterator(ctx, ctx.BlockHeader().Time) require.False(t, inactiveQueue.Valid()) @@ -200,7 +199,7 @@ func TestTickPassedVotingPeriod(t *testing.T) { res := govHandler(ctx, newProposalMsg) require.True(t, res.IsOK()) - proposalID := binary.LittleEndian.Uint64(res.Data) + proposalID := GetProposalIDFromBytes(res.Data) newHeader := ctx.BlockHeader() newHeader.Time = ctx.BlockHeader().Time.Add(time.Duration(1) * time.Second) @@ -221,9 +220,7 @@ func TestTickPassedVotingPeriod(t *testing.T) { activeQueue = input.keeper.ActiveProposalQueueIterator(ctx, ctx.BlockHeader().Time) require.True(t, activeQueue.Valid()) - var activeProposalID uint64 - - require.NoError(t, input.mApp.Cdc.UnmarshalBinaryLengthPrefixed(activeQueue.Value(), &activeProposalID)) + activeProposalID := GetProposalIDFromBytes(activeQueue.Value()) proposal, ok := input.keeper.GetProposal(ctx, activeProposalID) require.True(t, ok) require.Equal(t, StatusVotingPeriod, proposal.Status) diff --git a/x/gov/alias.go b/x/gov/alias.go index a502351c1843..c8942f63fc7e 100644 --- a/x/gov/alias.go +++ b/x/gov/alias.go @@ -82,6 +82,8 @@ var ( NewGenesisState = types.NewGenesisState DefaultGenesisState = types.DefaultGenesisState ValidateGenesis = types.ValidateGenesis + GetProposalIDBytes = types.GetProposalIDBytes + GetProposalIDFromBytes = types.GetProposalIDFromBytes ProposalKey = types.ProposalKey ActiveProposalByTimeKey = types.ActiveProposalByTimeKey ActiveProposalQueueKey = types.ActiveProposalQueueKey diff --git a/x/gov/client/rest/tx.go b/x/gov/client/rest/tx.go index 55bd3bef45f0..c705bddf4e2d 100644 --- a/x/gov/client/rest/tx.go +++ b/x/gov/client/rest/tx.go @@ -1,7 +1,6 @@ package rest import ( - "errors" "fmt" "net/http" @@ -20,13 +19,12 @@ func registerTxRoutes(cliCtx context.CLIContext, r *mux.Router, phs []ProposalRE for _, ph := range phs { propSubRtr.HandleFunc(fmt.Sprintf("/%s", ph.SubRoute), ph.Handler).Methods("POST") } - + r.HandleFunc("/gov/proposals", postProposalHandlerFn(cliCtx)).Methods("POST") r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/deposits", RestProposalID), depositHandlerFn(cliCtx)).Methods("POST") r.HandleFunc(fmt.Sprintf("/gov/proposals/{%s}/votes", RestProposalID), voteHandlerFn(cliCtx)).Methods("POST") } - func postProposalHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req PostProposalReq @@ -58,8 +56,7 @@ func depositHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { strProposalID := vars[RestProposalID] if len(strProposalID) == 0 { - err := errors.New("proposalId required but not specified") - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + rest.WriteErrorResponse(w, http.StatusBadRequest, "proposalId required but not specified") return } @@ -95,8 +92,7 @@ func voteHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { strProposalID := vars[RestProposalID] if len(strProposalID) == 0 { - err := errors.New("proposalId required but not specified") - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + rest.WriteErrorResponse(w, http.StatusBadRequest, "proposalId required but not specified") return } @@ -130,4 +126,4 @@ func voteHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { utils.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) } -} \ No newline at end of file +} diff --git a/x/gov/handler.go b/x/gov/handler.go index 0c3ea7e9dab1..cd116264c359 100644 --- a/x/gov/handler.go +++ b/x/gov/handler.go @@ -1,7 +1,6 @@ package gov import ( - "encoding/binary" "fmt" sdk "github.com/cosmos/cosmos-sdk/types" @@ -58,11 +57,8 @@ func handleMsgSubmitProposal(ctx sdk.Context, keeper Keeper, msg MsgSubmitPropos ) } - proposalIDBz := make([]byte, 8) - binary.LittleEndian.PutUint64(proposalIDBz, proposal.ProposalID) - return sdk.Result{ - Data: proposalIDBz, + Data: GetProposalIDBytes(proposal.ProposalID), Events: ctx.EventManager().Events(), } } diff --git a/x/gov/keeper/keeper.go b/x/gov/keeper/keeper.go index df8d2e9a1da7..b322d3e6b4cd 100644 --- a/x/gov/keeper/keeper.go +++ b/x/gov/keeper/keeper.go @@ -41,6 +41,8 @@ type Keeper struct { // - depositing funds into proposals, and activating upon sufficient funds being deposited // - users voting on proposals, with weight proportional to stake in the system // - and tallying the result of the vote. +// +// CONTRACT: the parameter Subspace must have the param key table already initialized func NewKeeper( cdc *codec.Codec, key sdk.StoreKey, paramSpace types.ParamSubspace, supplyKeeper types.SupplyKeeper, sk types.StakingKeeper, codespace sdk.CodespaceType, rtr types.Router, @@ -58,7 +60,7 @@ func NewKeeper( return Keeper{ storeKey: key, - paramSpace: paramSpace, // CONTRACT: must have the param key table already initialized + paramSpace: paramSpace, supplyKeeper: supplyKeeper, sk: sk, cdc: cdc, @@ -87,7 +89,7 @@ func (keeper Keeper) GetGovernanceAccount(ctx sdk.Context) exported.ModuleAccoun // InsertActiveProposalQueue inserts a ProposalID into the active proposal queue at endTime func (keeper Keeper) InsertActiveProposalQueue(ctx sdk.Context, proposalID uint64, endTime time.Time) { store := ctx.KVStore(keeper.storeKey) - bz := keeper.cdc.MustMarshalBinaryLengthPrefixed(proposalID) + bz := types.GetProposalIDBytes(proposalID) store.Set(types.ActiveProposalQueueKey(proposalID, endTime), bz) } @@ -100,7 +102,7 @@ func (keeper Keeper) RemoveFromActiveProposalQueue(ctx sdk.Context, proposalID u // InsertInactiveProposalQueue Inserts a ProposalID into the inactive proposal queue at endTime func (keeper Keeper) InsertInactiveProposalQueue(ctx sdk.Context, proposalID uint64, endTime time.Time) { store := ctx.KVStore(keeper.storeKey) - bz := keeper.cdc.MustMarshalBinaryLengthPrefixed(proposalID) + bz := types.GetProposalIDBytes(proposalID) store.Set(types.InactiveProposalQueueKey(proposalID, endTime), bz) } diff --git a/x/gov/keeper/keeper_test.go b/x/gov/keeper/keeper_test.go index a99f43c12e4a..9832c6df3ade 100644 --- a/x/gov/keeper/keeper_test.go +++ b/x/gov/keeper/keeper_test.go @@ -3,6 +3,7 @@ package keeper import ( "testing" + "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/stretchr/testify/require" ) @@ -31,8 +32,8 @@ func TestProposalQueues(t *testing.T) { inactiveIterator := keeper.InactiveProposalQueueIterator(ctx, proposal.DepositEndTime) require.True(t, inactiveIterator.Valid()) - var proposalID uint64 - keeper.cdc.UnmarshalBinaryLengthPrefixed(inactiveIterator.Value(), &proposalID) + + proposalID := types.GetProposalIDFromBytes(inactiveIterator.Value()) require.Equal(t, proposalID, proposal.ProposalID) inactiveIterator.Close() diff --git a/x/gov/keeper/proposal.go b/x/gov/keeper/proposal.go index ddc18c8600eb..4ad9ea8b9b2c 100644 --- a/x/gov/keeper/proposal.go +++ b/x/gov/keeper/proposal.go @@ -1,7 +1,6 @@ package keeper import ( - "encoding/binary" "fmt" sdk "github.com/cosmos/cosmos-sdk/types" @@ -156,16 +155,14 @@ func (keeper Keeper) GetProposalID(ctx sdk.Context) (proposalID uint64, err sdk. if bz == nil { return 0, types.ErrInvalidGenesis(keeper.codespace, "initial proposal ID hasn't been set") } - proposalID = binary.LittleEndian.Uint64(bz) + proposalID = types.GetProposalIDFromBytes(bz) return proposalID, nil } // SetProposalID sets the new proposal ID to the store func (keeper Keeper) SetProposalID(ctx sdk.Context, proposalID uint64) { store := ctx.KVStore(keeper.storeKey) - bz := make([]byte, 8) - binary.LittleEndian.PutUint64(bz, proposalID) - store.Set(types.ProposalIDKey, bz) + store.Set(types.ProposalIDKey, types.GetProposalIDBytes(proposalID)) } func (keeper Keeper) activateVotingPeriod(ctx sdk.Context, proposal types.Proposal) { diff --git a/x/gov/keeper/proposal_test.go b/x/gov/keeper/proposal_test.go index 26beba86eab8..f36b9d8ab592 100644 --- a/x/gov/keeper/proposal_test.go +++ b/x/gov/keeper/proposal_test.go @@ -43,8 +43,8 @@ func TestActivateVotingPeriod(t *testing.T) { activeIterator := keeper.ActiveProposalQueueIterator(ctx, proposal.VotingEndTime) require.True(t, activeIterator.Valid()) - var proposalID uint64 - keeper.cdc.UnmarshalBinaryLengthPrefixed(activeIterator.Value(), &proposalID) + + proposalID := types.GetProposalIDFromBytes(activeIterator.Value()) require.Equal(t, proposalID, proposal.ProposalID) activeIterator.Close() } diff --git a/x/gov/types/keys.go b/x/gov/types/keys.go index 41f81c2fbf28..98f6f0d88c14 100644 --- a/x/gov/types/keys.go +++ b/x/gov/types/keys.go @@ -52,11 +52,21 @@ var ( var lenTime = len(sdk.FormatTimeBytes(time.Now())) +// GetProposalIDBytes returns the byte representation of the proposalID +func GetProposalIDBytes(proposalID uint64) (proposalIDBz []byte) { + proposalIDBz = make([]byte, 8) + binary.BigEndian.PutUint64(proposalIDBz, proposalID) + return +} + +// GetProposalIDFromBytes returns proposalID in uint64 format from a byte array +func GetProposalIDFromBytes(bz []byte) (proposalID uint64) { + return binary.BigEndian.Uint64(bz) +} + // ProposalKey gets a specific proposal from the store func ProposalKey(proposalID uint64) []byte { - bz := make([]byte, 8) - binary.LittleEndian.PutUint64(bz, proposalID) - return append(ProposalsKeyPrefix, bz...) + return append(ProposalsKeyPrefix, GetProposalIDBytes(proposalID)...) } // ActiveProposalByTimeKey gets the active proposal queue key by endTime @@ -66,10 +76,7 @@ func ActiveProposalByTimeKey(endTime time.Time) []byte { // ActiveProposalQueueKey returns the key for a proposalID in the activeProposalQueue func ActiveProposalQueueKey(proposalID uint64, endTime time.Time) []byte { - bz := make([]byte, 8) - binary.LittleEndian.PutUint64(bz, proposalID) - - return append(ActiveProposalByTimeKey(endTime), bz...) + return append(ActiveProposalByTimeKey(endTime), GetProposalIDBytes(proposalID)...) } // InactiveProposalByTimeKey gets the inactive proposal queue key by endTime @@ -79,17 +86,12 @@ func InactiveProposalByTimeKey(endTime time.Time) []byte { // InactiveProposalQueueKey returns the key for a proposalID in the inactiveProposalQueue func InactiveProposalQueueKey(proposalID uint64, endTime time.Time) []byte { - bz := make([]byte, 8) - binary.LittleEndian.PutUint64(bz, proposalID) - - return append(InactiveProposalByTimeKey(endTime), bz...) + return append(InactiveProposalByTimeKey(endTime), GetProposalIDBytes(proposalID)...) } // DepositsKey gets the first part of the deposits key based on the proposalID func DepositsKey(proposalID uint64) []byte { - bz := make([]byte, 8) - binary.LittleEndian.PutUint64(bz, proposalID) - return append(DepositsKeyPrefix, bz...) + return append(DepositsKeyPrefix, GetProposalIDBytes(proposalID)...) } // DepositKey key of a specific deposit from the store @@ -99,9 +101,7 @@ func DepositKey(proposalID uint64, depositorAddr sdk.AccAddress) []byte { // VotesKey gets the first part of the votes key based on the proposalID func VotesKey(proposalID uint64) []byte { - bz := make([]byte, 8) - binary.LittleEndian.PutUint64(bz, proposalID) - return append(VotesKeyPrefix, bz...) + return append(VotesKeyPrefix, GetProposalIDBytes(proposalID)...) } // VoteKey key of a specific vote from the store @@ -117,7 +117,7 @@ func SplitProposalKey(key []byte) (proposalID uint64) { panic(fmt.Sprintf("unexpected key length (%d ≠ 8)", len(key[1:]))) } - return binary.LittleEndian.Uint64(key[1:]) + return GetProposalIDFromBytes(key[1:]) } // SplitActiveProposalQueueKey split the active proposal key and returns the proposal id and endTime @@ -151,7 +151,8 @@ func splitKeyWithTime(key []byte) (proposalID uint64, endTime time.Time) { if err != nil { panic(err) } - proposalID = binary.LittleEndian.Uint64(key[1+lenTime:]) + + proposalID = GetProposalIDFromBytes(key[1+lenTime:]) return } @@ -160,7 +161,7 @@ func splitKeyWithAddress(key []byte) (proposalID uint64, addr sdk.AccAddress) { panic(fmt.Sprintf("unexpected key length (%d ≠ %d)", len(key), 8+sdk.AddrLen)) } - proposalID = binary.LittleEndian.Uint64(key[1:9]) + proposalID = GetProposalIDFromBytes(key[1:9]) addr = sdk.AccAddress(key[9:]) return } diff --git a/x/gov/types/proposal.go b/x/gov/types/proposal.go index 314a120f10da..0a1a544460c8 100644 --- a/x/gov/types/proposal.go +++ b/x/gov/types/proposal.go @@ -205,7 +205,7 @@ const ( ProposalTypeSoftwareUpgrade string = "SoftwareUpgrade" ) -// TextProposal defines a standard text proposal whose changes need to be +// TextProposal defines a standard text proposal whose changes need to be // manually updated in case of approval type TextProposal struct { Title string `json:"title" yaml:"title"` @@ -221,16 +221,16 @@ func NewTextProposal(title, description string) Content { var _ Content = TextProposal{} // GetTitle returns the proposal title -func (tp TextProposal) GetTitle() string { return tp.Title } +func (tp TextProposal) GetTitle() string { return tp.Title } // GetDescription returns the proposal description -func (tp TextProposal) GetDescription() string { return tp.Description } +func (tp TextProposal) GetDescription() string { return tp.Description } // ProposalRoute returns the proposal router key -func (tp TextProposal) ProposalRoute() string { return RouterKey } +func (tp TextProposal) ProposalRoute() string { return RouterKey } // ProposalType is "Text" -func (tp TextProposal) ProposalType() string { return ProposalTypeText } +func (tp TextProposal) ProposalType() string { return ProposalTypeText } // ValidateBasic validates the content's title and description of the proposal func (tp TextProposal) ValidateBasic() sdk.Error { return ValidateAbstract(DefaultCodespace, tp) } @@ -262,16 +262,16 @@ func NewSoftwareUpgradeProposal(title, description string) Content { var _ Content = SoftwareUpgradeProposal{} // GetTitle returns the proposal title -func (sup SoftwareUpgradeProposal) GetTitle() string { return sup.Title } +func (sup SoftwareUpgradeProposal) GetTitle() string { return sup.Title } // GetDescription returns the proposal description func (sup SoftwareUpgradeProposal) GetDescription() string { return sup.Description } // ProposalRoute returns the proposal router key -func (sup SoftwareUpgradeProposal) ProposalRoute() string { return RouterKey } +func (sup SoftwareUpgradeProposal) ProposalRoute() string { return RouterKey } // ProposalType is "SoftwareUpgrade" -func (sup SoftwareUpgradeProposal) ProposalType() string { return ProposalTypeSoftwareUpgrade } +func (sup SoftwareUpgradeProposal) ProposalType() string { return ProposalTypeSoftwareUpgrade } // ValidateBasic validates the content's title and description of the proposal func (sup SoftwareUpgradeProposal) ValidateBasic() sdk.Error { From a76f19d543b680bce6c2e00c1cefa430f2eb7605 Mon Sep 17 00:00:00 2001 From: Federico Kunze Date: Thu, 8 Aug 2019 21:23:14 +0200 Subject: [PATCH 36/36] update pending --- .pending/breaking/modules/_4665-gov-refactor | 3 +++ .pending/breaking/store/_4665-gov-keys | 1 - .pending/improvements/modules/_4665-update-gov | 1 - 3 files changed, 3 insertions(+), 2 deletions(-) create mode 100644 .pending/breaking/modules/_4665-gov-refactor delete mode 100644 .pending/breaking/store/_4665-gov-keys delete mode 100644 .pending/improvements/modules/_4665-update-gov diff --git a/.pending/breaking/modules/_4665-gov-refactor b/.pending/breaking/modules/_4665-gov-refactor new file mode 100644 index 000000000000..a2e6fa548116 --- /dev/null +++ b/.pending/breaking/modules/_4665-gov-refactor @@ -0,0 +1,3 @@ +#4665 Refactored `x/gov` module structure and dev-UX: + - Prepare for module spec integration + - Update gov keys to use big endian encoding instead of little endian \ No newline at end of file diff --git a/.pending/breaking/store/_4665-gov-keys b/.pending/breaking/store/_4665-gov-keys deleted file mode 100644 index 7dca5cf33264..000000000000 --- a/.pending/breaking/store/_4665-gov-keys +++ /dev/null @@ -1 +0,0 @@ -#4665 Update gov keys to use big endian instead of little endian. \ No newline at end of file diff --git a/.pending/improvements/modules/_4665-update-gov b/.pending/improvements/modules/_4665-update-gov deleted file mode 100644 index 0f571452bfbe..000000000000 --- a/.pending/improvements/modules/_4665-update-gov +++ /dev/null @@ -1 +0,0 @@ -#4665 Prepare the `x/gov` module to match module spec.