From ccd0132792dcd45c29eb145800dae5efb9827d3e Mon Sep 17 00:00:00 2001 From: sontrinh16 Date: Thu, 12 Dec 2024 18:19:21 +0700 Subject: [PATCH 1/8] add gov test --- runtime/v2/module.go | 6 +- tests/integration/v2/app.go | 9 +- tests/integration/v2/genesis.go | 6 + tests/integration/v2/gov/abci_test.go | 672 ++++++++++++++++++ tests/integration/v2/gov/common_test.go | 206 ++++++ tests/integration/v2/gov/genesis_test.go | 180 +++++ .../integration/v2/gov/keeper/common_test.go | 72 ++ .../integration/v2/gov/keeper/fixture_test.go | 109 +++ tests/integration/v2/gov/keeper/grpc_test.go | 75 ++ tests/integration/v2/gov/keeper/tally_test.go | 519 ++++++++++++++ tests/integration/v2/gov/module_test.go | 22 + tests/integration/v2/services.go | 93 ++- testutil/sims/address_helpers.go | 2 +- 13 files changed, 1963 insertions(+), 8 deletions(-) create mode 100644 tests/integration/v2/gov/abci_test.go create mode 100644 tests/integration/v2/gov/common_test.go create mode 100644 tests/integration/v2/gov/genesis_test.go create mode 100644 tests/integration/v2/gov/keeper/common_test.go create mode 100644 tests/integration/v2/gov/keeper/fixture_test.go create mode 100644 tests/integration/v2/gov/keeper/grpc_test.go create mode 100644 tests/integration/v2/gov/keeper/tally_test.go create mode 100644 tests/integration/v2/gov/module_test.go diff --git a/runtime/v2/module.go b/runtime/v2/module.go index 8ef338f52c2a..fcbb671bcecb 100644 --- a/runtime/v2/module.go +++ b/runtime/v2/module.go @@ -18,6 +18,7 @@ import ( "cosmossdk.io/core/branch" "cosmossdk.io/core/comet" "cosmossdk.io/core/event" + "cosmossdk.io/core/gas" "cosmossdk.io/core/header" "cosmossdk.io/core/registry" "cosmossdk.io/core/router" @@ -214,6 +215,7 @@ func ProvideEnvironment( kvService store.KVStoreService, memKvService store.MemoryStoreService, headerService header.Service, + gasService gas.Service, eventService event.Service, branchService branch.Service, routerBuilder RouterServiceBuilder, @@ -222,7 +224,7 @@ func ProvideEnvironment( Logger: logger, BranchService: branchService, EventService: eventService, - GasService: stf.NewGasMeterService(), + GasService: gasService, HeaderService: headerService, QueryRouterService: routerBuilder.BuildQueryRouter(), MsgRouterService: routerBuilder.BuildMsgRouter([]byte(key.Name())), @@ -296,6 +298,7 @@ func DefaultServiceBindings() depinject.Config { eventService = services.NewGenesisEventService(stf.NewEventService()) storeBuilder = root.NewBuilder() branchService = stf.BranchService{} + gasService = stf.NewGasMeterService() ) return depinject.Supply( kvServiceFactory, @@ -305,5 +308,6 @@ func DefaultServiceBindings() depinject.Config { eventService, storeBuilder, branchService, + gasService, ) } diff --git a/tests/integration/v2/app.go b/tests/integration/v2/app.go index 72a4873cba6b..f891e4557bc9 100644 --- a/tests/integration/v2/app.go +++ b/tests/integration/v2/app.go @@ -17,6 +17,7 @@ import ( corebranch "cosmossdk.io/core/branch" "cosmossdk.io/core/comet" corecontext "cosmossdk.io/core/context" + "cosmossdk.io/core/gas" "cosmossdk.io/core/header" "cosmossdk.io/core/server" corestore "cosmossdk.io/core/store" @@ -99,6 +100,8 @@ type StartupConfig struct { RouterServiceBuilder runtime.RouterServiceBuilder // HeaderService defines the custom header service to be used in the app. HeaderService header.Service + + GasService gas.Service } func DefaultStartUpConfig(t *testing.T) StartupConfig { @@ -129,6 +132,7 @@ func DefaultStartUpConfig(t *testing.T) StartupConfig { stf.NewMsgRouterService, stf.NewQueryRouterService(), ), HeaderService: services.NewGenesisHeaderService(stf.HeaderService{}), + GasService: stf.NewGasMeterService(), } } @@ -193,9 +197,11 @@ func NewApp( startupConfig.BranchService, startupConfig.RouterServiceBuilder, startupConfig.HeaderService, + startupConfig.GasService, ), depinject.Invoke( std.RegisterInterfaces, + std.RegisterLegacyAminoCodec, ), ), append(extraOutputs, &appBuilder, &cdc, &txConfigOptions, &txConfig, &storeBuilder)...); err != nil { @@ -336,10 +342,11 @@ func (a *App) Deliver( require.NoError(t, err) a.lastHeight++ - // update block height if integration context is present + // update block height and block time if integration context is present iCtx, ok := ctx.Value(contextKey).(*integrationContext) if ok { iCtx.header.Height = int64(a.lastHeight) + iCtx.header.Time = time.Now() } return resp, state } diff --git a/tests/integration/v2/genesis.go b/tests/integration/v2/genesis.go index d101ce3e8672..13d37be9b770 100644 --- a/tests/integration/v2/genesis.go +++ b/tests/integration/v2/genesis.go @@ -147,6 +147,12 @@ type genesisTxCodec struct { tx.ConfigOptions } +func NewGenesisTxCodec(txConfigOptions tx.ConfigOptions) *genesisTxCodec { + return &genesisTxCodec{ + txConfigOptions, + } +} + // Decode implements transaction.Codec. func (t *genesisTxCodec) Decode(bz []byte) (stateMachineTx, error) { var out stateMachineTx diff --git a/tests/integration/v2/gov/abci_test.go b/tests/integration/v2/gov/abci_test.go new file mode 100644 index 000000000000..7dc5fc1b0136 --- /dev/null +++ b/tests/integration/v2/gov/abci_test.go @@ -0,0 +1,672 @@ +package gov + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/require" + + "cosmossdk.io/collections" + "cosmossdk.io/math" + banktypes "cosmossdk.io/x/bank/types" + "cosmossdk.io/x/gov/keeper" + "cosmossdk.io/x/gov/types" + v1 "cosmossdk.io/x/gov/types/v1" + stakingkeeper "cosmossdk.io/x/staking/keeper" + stakingtypes "cosmossdk.io/x/staking/types" + + addresscodec "github.com/cosmos/cosmos-sdk/codec/address" + "github.com/cosmos/cosmos-sdk/tests/integration/v2" + simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" + sdk "github.com/cosmos/cosmos-sdk/types" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" +) + +func TestUnregisteredProposal_InactiveProposalFails(t *testing.T) { + suite := createTestSuite(t) + ctx := suite.ctx + addrs := simtestutil.AddTestAddrs(suite.BankKeeper, suite.StakingKeeper, ctx, 10, valTokens) + addr0Str, err := suite.AuthKeeper.AddressCodec().BytesToString(addrs[0]) + require.NoError(t, err) + + // manually set proposal in store + startTime, endTime := time.Now().Add(-4*time.Hour), time.Now() + proposal, err := v1.NewProposal([]sdk.Msg{ + &v1.Proposal{}, // invalid proposal message + }, 1, startTime, startTime, "", "Unsupported proposal", "Unsupported proposal", addr0Str, v1.ProposalType_PROPOSAL_TYPE_STANDARD) + require.NoError(t, err) + + err = suite.GovKeeper.Proposals.Set(ctx, proposal.Id, proposal) + require.NoError(t, err) + + // manually set proposal in inactive proposal queue + err = suite.GovKeeper.InactiveProposalsQueue.Set(ctx, collections.Join(endTime, proposal.Id), proposal.Id) + require.NoError(t, err) + + err = suite.GovKeeper.EndBlocker(ctx) + require.NoError(t, err) + + _, err = suite.GovKeeper.Proposals.Get(ctx, proposal.Id) + require.Error(t, err, collections.ErrNotFound) +} + +func TestUnregisteredProposal_ActiveProposalFails(t *testing.T) { + suite := createTestSuite(t) + ctx := suite.ctx + addrs := simtestutil.AddTestAddrs(suite.BankKeeper, suite.StakingKeeper, ctx, 10, valTokens) + addr0Str, err := suite.AuthKeeper.AddressCodec().BytesToString(addrs[0]) + require.NoError(t, err) + // manually set proposal in store + header := integration.HeaderInfoFromContext(ctx) + startTime, endTime := time.Now().Add(-4*time.Hour), header.Time + proposal, err := v1.NewProposal([]sdk.Msg{ + &v1.Proposal{}, // invalid proposal message + }, 1, startTime, startTime, "", "Unsupported proposal", "Unsupported proposal", addr0Str, v1.ProposalType_PROPOSAL_TYPE_STANDARD) + require.NoError(t, err) + proposal.Status = v1.StatusVotingPeriod + proposal.VotingEndTime = &endTime + + err = suite.GovKeeper.Proposals.Set(ctx, proposal.Id, proposal) + require.NoError(t, err) + + // manually set proposal in active proposal queue + err = suite.GovKeeper.ActiveProposalsQueue.Set(ctx, collections.Join(endTime, proposal.Id), proposal.Id) + require.NoError(t, err) + + err = suite.GovKeeper.EndBlocker(ctx) + require.NoError(t, err) + + p, err := suite.GovKeeper.Proposals.Get(ctx, proposal.Id) + require.NoError(t, err) + require.Equal(t, v1.StatusFailed, p.Status) +} + +func TestTickExpiredDepositPeriod(t *testing.T) { + suite := createTestSuite(t) + ctx := suite.ctx + addrs := simtestutil.AddTestAddrs(suite.BankKeeper, suite.StakingKeeper, ctx, 10, valTokens) + + govMsgSvr := keeper.NewMsgServerImpl(suite.GovKeeper) + + newProposalMsg, err := v1.NewMsgSubmitProposal( + []sdk.Msg{mkTestLegacyContent(t)}, + sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 100000)}, + addrs[0].String(), + "", + "Proposal", + "description of proposal", + v1.ProposalType_PROPOSAL_TYPE_STANDARD, + ) + require.NoError(t, err) + + res, err := govMsgSvr.SubmitProposal(ctx, newProposalMsg) + require.NoError(t, err) + require.NotNil(t, res) + + newHeader := integration.HeaderInfoFromContext(ctx) + newHeader.Time = newHeader.Time.Add(time.Duration(1) * time.Second) + ctx = integration.SetHeaderInfo(ctx, newHeader) + + params, _ := suite.GovKeeper.Params.Get(ctx) + newHeader = integration.HeaderInfoFromContext(ctx) + newHeader.Time = newHeader.Time.Add(*params.MaxDepositPeriod) + ctx = integration.SetHeaderInfo(ctx, newHeader) + + err = suite.GovKeeper.EndBlocker(ctx) + require.NoError(t, err) +} + +func TestTickMultipleExpiredDepositPeriod(t *testing.T) { + suite := createTestSuite(t) + ctx := suite.ctx + addrs := simtestutil.AddTestAddrs(suite.BankKeeper, suite.StakingKeeper, ctx, 10, valTokens) + govMsgSvr := keeper.NewMsgServerImpl(suite.GovKeeper) + + newProposalMsg, err := v1.NewMsgSubmitProposal( + []sdk.Msg{mkTestLegacyContent(t)}, + sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 100000)}, + addrs[0].String(), + "", + "Proposal", + "description of proposal", + v1.ProposalType_PROPOSAL_TYPE_STANDARD, + ) + require.NoError(t, err) + + res, err := govMsgSvr.SubmitProposal(ctx, newProposalMsg) + require.NoError(t, err) + require.NotNil(t, res) + + newHeader := integration.HeaderInfoFromContext(ctx) + newHeader.Time = newHeader.Time.Add(time.Duration(2) * time.Second) + ctx = integration.SetHeaderInfo(ctx, newHeader) + + newProposalMsg2, err := v1.NewMsgSubmitProposal( + []sdk.Msg{mkTestLegacyContent(t)}, + sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 100000)}, + addrs[0].String(), + "", + "Proposal", + "description of proposal", + v1.ProposalType_PROPOSAL_TYPE_STANDARD, + ) + require.NoError(t, err) + + res, err = govMsgSvr.SubmitProposal(ctx, newProposalMsg2) + require.NoError(t, err) + require.NotNil(t, res) + + newHeader = integration.HeaderInfoFromContext(ctx) + params, _ := suite.GovKeeper.Params.Get(ctx) + newHeader.Time = newHeader.Time.Add(*params.MaxDepositPeriod).Add(time.Duration(-1) * time.Second) + ctx = integration.SetHeaderInfo(ctx, newHeader) + + require.NoError(t, suite.GovKeeper.EndBlocker(ctx)) + + newHeader = integration.HeaderInfoFromContext(ctx) + newHeader.Time = newHeader.Time.Add(time.Duration(5) * time.Second) + ctx = integration.SetHeaderInfo(ctx, newHeader) + require.NoError(t, suite.GovKeeper.EndBlocker(ctx)) +} + +func TestTickPassedDepositPeriod(t *testing.T) { + suite := createTestSuite(t) + ctx := suite.ctx + addrs := simtestutil.AddTestAddrs(suite.BankKeeper, suite.StakingKeeper, ctx, 10, valTokens) + govMsgSvr := keeper.NewMsgServerImpl(suite.GovKeeper) + + newProposalMsg, err := v1.NewMsgSubmitProposal( + []sdk.Msg{mkTestLegacyContent(t)}, + sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 100000)}, + addrs[0].String(), + "", + "Proposal", + "description of proposal", + v1.ProposalType_PROPOSAL_TYPE_STANDARD, + ) + require.NoError(t, err) + + res, err := govMsgSvr.SubmitProposal(ctx, newProposalMsg) + require.NoError(t, err) + require.NotNil(t, res) + + proposalID := res.ProposalId + + newHeader := integration.HeaderInfoFromContext(ctx) + newHeader.Time = newHeader.Time.Add(time.Duration(1) * time.Second) + ctx = integration.SetHeaderInfo(ctx, newHeader) + + addr1Str, err := suite.AuthKeeper.AddressCodec().BytesToString(addrs[1]) + require.NoError(t, err) + newDepositMsg := v1.NewMsgDeposit(addr1Str, proposalID, sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 100000)}) + + res1, err := govMsgSvr.Deposit(ctx, newDepositMsg) + require.NoError(t, err) + require.NotNil(t, res1) +} + +func TestProposalDepositRefundFailEndBlocker(t *testing.T) { + suite := createTestSuite(t) + ctx := suite.ctx + addrs := simtestutil.AddTestAddrs(suite.BankKeeper, suite.StakingKeeper, ctx, 10, valTokens) + govMsgSvr := keeper.NewMsgServerImpl(suite.GovKeeper) + + depositMultiplier := getDepositMultiplier(v1.ProposalType_PROPOSAL_TYPE_STANDARD) + proposalCoins := sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, suite.StakingKeeper.TokensFromConsensusPower(ctx, 15*depositMultiplier))} + + // create a proposal that empties the gov module account + // which will cause the proposal deposit refund to fail + newProposalMsg, err := v1.NewMsgSubmitProposal( + []sdk.Msg{}, + proposalCoins, + addrs[0].String(), + "metadata", + "proposal", + "description of proposal", + v1.ProposalType_PROPOSAL_TYPE_STANDARD, + ) + require.NoError(t, err) + + res, err := govMsgSvr.SubmitProposal(ctx, newProposalMsg) + require.NoError(t, err) + require.NotNil(t, res) + + proposal, err := suite.GovKeeper.Proposals.Get(ctx, res.ProposalId) + require.NoError(t, err) + require.Equal(t, v1.StatusVotingPeriod, proposal.Status) + + proposalID := res.ProposalId + err = suite.GovKeeper.AddVote(ctx, proposalID, addrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), "metadata") + require.NoError(t, err) + + // empty the gov module account before the proposal ends + err = suite.BankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, addrs[1], proposalCoins) + require.NoError(t, err) + + // fast forward to the end of the voting period + newHeader := integration.HeaderInfoFromContext(ctx) + newHeader.Time = proposal.VotingEndTime.Add(time.Duration(100) * time.Second) + ctx = integration.SetHeaderInfo(ctx, newHeader) + + err = suite.GovKeeper.EndBlocker(ctx) + require.NoError(t, err) // no error, means does not halt the chain + + events := integration.EventsFromContext(ctx) + attr, ok := integration.GetAttributes(events, types.AttributeKeyProposalDepositError) + require.True(t, ok) + require.Contains(t, attr[0].Value, "failed to refund or burn deposits") +} + +func TestTickPassedVotingPeriod(t *testing.T) { + testcases := []struct { + name string + proposalType v1.ProposalType + }{ + { + name: "regular - deleted", + }, + { + name: "expedited - converted to regular", + proposalType: v1.ProposalType_PROPOSAL_TYPE_EXPEDITED, + }, + } + + for _, tc := range testcases { + t.Run(tc.name, func(t *testing.T) { + suite := createTestSuite(t) + ctx := suite.ctx + depositMultiplier := getDepositMultiplier(tc.proposalType) + addrs := simtestutil.AddTestAddrs(suite.BankKeeper, suite.StakingKeeper, ctx, 10, valTokens.Mul(math.NewInt(depositMultiplier))) + + SortAddresses(addrs) + govMsgSvr := keeper.NewMsgServerImpl(suite.GovKeeper) + + proposalCoins := sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, suite.StakingKeeper.TokensFromConsensusPower(ctx, 5*depositMultiplier))} + newProposalMsg, err := v1.NewMsgSubmitProposal([]sdk.Msg{mkTestLegacyContent(t)}, proposalCoins, addrs[0].String(), "", "Proposal", "description of proposal", tc.proposalType) + require.NoError(t, err) + + res, err := govMsgSvr.SubmitProposal(ctx, newProposalMsg) + require.NoError(t, err) + require.NotNil(t, res) + + proposalID := res.ProposalId + + newHeader := integration.HeaderInfoFromContext(ctx) + newHeader.Time = newHeader.Time.Add(time.Duration(1) * time.Second) + ctx = integration.SetHeaderInfo(ctx, newHeader) + + addr1Str, err := suite.AuthKeeper.AddressCodec().BytesToString(addrs[1]) + require.NoError(t, err) + newDepositMsg := v1.NewMsgDeposit(addr1Str, proposalID, proposalCoins) + + res1, err := govMsgSvr.Deposit(ctx, newDepositMsg) + require.NoError(t, err) + require.NotNil(t, res1) + + params, _ := suite.GovKeeper.Params.Get(ctx) + votingPeriod := params.VotingPeriod + if tc.proposalType == v1.ProposalType_PROPOSAL_TYPE_EXPEDITED { + votingPeriod = params.ExpeditedVotingPeriod + } + + newHeader = integration.HeaderInfoFromContext(ctx) + newHeader.Time = newHeader.Time.Add(*params.MaxDepositPeriod).Add(*votingPeriod) + ctx = integration.SetHeaderInfo(ctx, newHeader) + + proposal, err := suite.GovKeeper.Proposals.Get(ctx, res.ProposalId) + require.NoError(t, err) + require.Equal(t, v1.StatusVotingPeriod, proposal.Status) + + err = suite.GovKeeper.EndBlocker(ctx) + require.NoError(t, err) + + if tc.proposalType != v1.ProposalType_PROPOSAL_TYPE_EXPEDITED { + return + } + + // If expedited, it should be converted to a regular proposal instead. + proposal, err = suite.GovKeeper.Proposals.Get(ctx, res.ProposalId) + require.Nil(t, err) + require.Equal(t, v1.StatusVotingPeriod, proposal.Status) + require.False(t, proposal.ProposalType == v1.ProposalType_PROPOSAL_TYPE_EXPEDITED) + require.Equal(t, proposal.VotingStartTime.Add(*params.VotingPeriod), *proposal.VotingEndTime) + }) + } +} + +func TestProposalPassedEndblocker(t *testing.T) { + testcases := []struct { + name string + proposalType v1.ProposalType + }{ + { + name: "regular", + proposalType: v1.ProposalType_PROPOSAL_TYPE_STANDARD, + }, + { + name: "expedited", + proposalType: v1.ProposalType_PROPOSAL_TYPE_EXPEDITED, + }, + } + + for _, tc := range testcases { + t.Run(tc.name, func(t *testing.T) { + suite := createTestSuite(t) + ctx := suite.ctx + depositMultiplier := getDepositMultiplier(tc.proposalType) + addrs := simtestutil.AddTestAddrs(suite.BankKeeper, suite.StakingKeeper, ctx, 10, valTokens.Mul(math.NewInt(depositMultiplier))) + + SortAddresses(addrs) + + govMsgSvr := keeper.NewMsgServerImpl(suite.GovKeeper) + stakingMsgSvr := stakingkeeper.NewMsgServerImpl(suite.StakingKeeper) + valAddr := sdk.ValAddress(addrs[0]) + proposer := addrs[0] + acc := suite.AuthKeeper.NewAccountWithAddress(ctx, addrs[0]) + suite.AuthKeeper.SetAccount(ctx, acc) + + createValidators(t, stakingMsgSvr, ctx, []sdk.ValAddress{valAddr}, []int64{10}) + _, err := suite.StakingKeeper.EndBlocker(ctx) + require.NoError(t, err) + macc := suite.GovKeeper.GetGovernanceAccount(ctx) + require.NotNil(t, macc) + initialModuleAccCoins := suite.BankKeeper.GetAllBalances(ctx, macc.GetAddress()) + + proposal, err := suite.GovKeeper.SubmitProposal(ctx, []sdk.Msg{mkTestLegacyContent(t)}, "", "title", "summary", proposer, tc.proposalType) + require.NoError(t, err) + + proposalCoins := sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, suite.StakingKeeper.TokensFromConsensusPower(ctx, 10*depositMultiplier))} + addr0Str, err := suite.AuthKeeper.AddressCodec().BytesToString(addrs[0]) + require.NoError(t, err) + newDepositMsg := v1.NewMsgDeposit(addr0Str, proposal.Id, proposalCoins) + + res, err := govMsgSvr.Deposit(ctx, newDepositMsg) + require.NoError(t, err) + require.NotNil(t, res) + + macc = suite.GovKeeper.GetGovernanceAccount(ctx) + require.NotNil(t, macc) + moduleAccCoins := suite.BankKeeper.GetAllBalances(ctx, macc.GetAddress()) + + deposits := initialModuleAccCoins.Add(proposal.TotalDeposit...).Add(proposalCoins...) + require.True(t, moduleAccCoins.Equal(deposits)) + + err = suite.GovKeeper.AddVote(ctx, proposal.Id, addrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), "") + require.NoError(t, err) + + newHeader := integration.HeaderInfoFromContext(ctx) + params, _ := suite.GovKeeper.Params.Get(ctx) + newHeader.Time = newHeader.Time.Add(*params.MaxDepositPeriod).Add(*params.VotingPeriod) + ctx = integration.SetHeaderInfo(ctx, newHeader) + + err = suite.GovKeeper.EndBlocker(ctx) + require.NoError(t, err) + macc = suite.GovKeeper.GetGovernanceAccount(ctx) + require.NotNil(t, macc) + require.True(t, suite.BankKeeper.GetAllBalances(ctx, macc.GetAddress()).Equal(initialModuleAccCoins)) + }) + } +} + +func TestEndBlockerProposalHandlerFailed(t *testing.T) { + suite := createTestSuite(t) + ctx := suite.ctx + addrs := simtestutil.AddTestAddrs(suite.BankKeeper, suite.StakingKeeper, ctx, 1, valTokens) + + SortAddresses(addrs) + + stakingMsgSvr := stakingkeeper.NewMsgServerImpl(suite.StakingKeeper) + + valAddr := sdk.ValAddress(addrs[0]) + proposer := addrs[0] + + ac := addresscodec.NewBech32Codec("cosmos") + addrStr, err := ac.BytesToString(authtypes.NewModuleAddress(types.ModuleName)) + require.NoError(t, err) + toAddrStr, err := ac.BytesToString(addrs[0]) + require.NoError(t, err) + + acc := suite.AuthKeeper.NewAccountWithAddress(ctx, addrs[0]) + suite.AuthKeeper.SetAccount(ctx, acc) + + createValidators(t, stakingMsgSvr, ctx, []sdk.ValAddress{valAddr}, []int64{10}) + _, err = suite.StakingKeeper.EndBlocker(ctx) + require.NoError(t, err) + msg := banktypes.NewMsgSend(addrStr, toAddrStr, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(100000)))) + proposal, err := suite.GovKeeper.SubmitProposal(ctx, []sdk.Msg{msg}, "", "title", "summary", proposer, v1.ProposalType_PROPOSAL_TYPE_STANDARD) + require.NoError(t, err) + + proposalCoins := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, suite.StakingKeeper.TokensFromConsensusPower(ctx, 10))) + addr0Str, err := suite.AuthKeeper.AddressCodec().BytesToString(addrs[0]) + require.NoError(t, err) + newDepositMsg := v1.NewMsgDeposit(addr0Str, proposal.Id, proposalCoins) + + govMsgSvr := keeper.NewMsgServerImpl(suite.GovKeeper) + res, err := govMsgSvr.Deposit(ctx, newDepositMsg) + require.NoError(t, err) + require.NotNil(t, res) + + err = suite.GovKeeper.AddVote(ctx, proposal.Id, addrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), "") + require.NoError(t, err) + + params, _ := suite.GovKeeper.Params.Get(ctx) + newHeader := integration.HeaderInfoFromContext(ctx) + newHeader.Time = newHeader.Time.Add(*params.MaxDepositPeriod).Add(*params.VotingPeriod) + ctx = integration.SetHeaderInfo(ctx, newHeader) + + // validate that the proposal fails/has been rejected + err = suite.GovKeeper.EndBlocker(ctx) + require.NoError(t, err) + // check proposal events + events := integration.EventsFromContext(ctx) + attr, eventOk := integration.GetAttributes(events, types.AttributeKeyProposalLog) + require.True(t, eventOk) + require.Contains(t, attr[0].Value, "failed on execution") + + proposal, err = suite.GovKeeper.Proposals.Get(ctx, proposal.Id) + require.Nil(t, err) + require.Equal(t, v1.StatusFailed, proposal.Status) +} + +func TestExpeditedProposal_PassAndConversionToRegular(t *testing.T) { + testcases := []struct { + name string + // indicates whether the expedited proposal passes. + expeditedPasses bool + // indicates whether the converted regular proposal is expected to eventually pass + regularEventuallyPassing bool + }{ + { + name: "expedited passes and not converted to regular", + expeditedPasses: true, + }, + { + name: "expedited fails, converted to regular - regular eventually passes", + expeditedPasses: false, + regularEventuallyPassing: true, + }, + { + name: "expedited fails, converted to regular - regular eventually fails", + expeditedPasses: false, + regularEventuallyPassing: false, + }, + } + + for _, tc := range testcases { + t.Run(tc.name, func(t *testing.T) { + suite := createTestSuite(t) + ctx := suite.ctx + depositMultiplier := getDepositMultiplier(v1.ProposalType_PROPOSAL_TYPE_EXPEDITED) + addrs := simtestutil.AddTestAddrs(suite.BankKeeper, suite.StakingKeeper, ctx, 3, valTokens.Mul(math.NewInt(depositMultiplier))) + params, err := suite.GovKeeper.Params.Get(ctx) + require.NoError(t, err) + + SortAddresses(addrs) + + govMsgSvr := keeper.NewMsgServerImpl(suite.GovKeeper) + stakingMsgSvr := stakingkeeper.NewMsgServerImpl(suite.StakingKeeper) + valAddr := sdk.ValAddress(addrs[0]) + proposer := addrs[0] + + acc := suite.AuthKeeper.NewAccountWithAddress(ctx, addrs[0]) + suite.AuthKeeper.SetAccount(ctx, acc) + // Create a validator so that able to vote on proposal. + createValidators(t, stakingMsgSvr, ctx, []sdk.ValAddress{valAddr}, []int64{10}) + _, err = suite.StakingKeeper.EndBlocker(ctx) + require.NoError(t, err) + + macc := suite.GovKeeper.GetGovernanceAccount(ctx) + require.NotNil(t, macc) + initialModuleAccCoins := suite.BankKeeper.GetAllBalances(ctx, macc.GetAddress()) + + submitterInitialBalance := suite.BankKeeper.GetAllBalances(ctx, addrs[0]) + depositorInitialBalance := suite.BankKeeper.GetAllBalances(ctx, addrs[1]) + + proposalCoins := sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, suite.StakingKeeper.TokensFromConsensusPower(ctx, 5*depositMultiplier))} + newProposalMsg, err := v1.NewMsgSubmitProposal([]sdk.Msg{}, proposalCoins, proposer.String(), "metadata", "title", "summary", v1.ProposalType_PROPOSAL_TYPE_EXPEDITED) + require.NoError(t, err) + + res, err := govMsgSvr.SubmitProposal(ctx, newProposalMsg) + require.NoError(t, err) + require.NotNil(t, res) + + proposalID := res.ProposalId + + newHeader := integration.HeaderInfoFromContext(ctx) + newHeader.Time = newHeader.Time.Add(time.Duration(1) * time.Second) + ctx = integration.SetHeaderInfo(ctx, newHeader) + + addr1Str, err := suite.AuthKeeper.AddressCodec().BytesToString(addrs[1]) + require.NoError(t, err) + newDepositMsg := v1.NewMsgDeposit(addr1Str, proposalID, proposalCoins) + + res1, err := govMsgSvr.Deposit(ctx, newDepositMsg) + require.NoError(t, err) + require.NotNil(t, res1) + + newHeader = integration.HeaderInfoFromContext(ctx) + newHeader.Time = newHeader.Time.Add(*params.MaxDepositPeriod).Add(*params.ExpeditedVotingPeriod) + ctx = integration.SetHeaderInfo(ctx, newHeader) + + proposal, err := suite.GovKeeper.Proposals.Get(ctx, res.ProposalId) + require.Nil(t, err) + require.Equal(t, v1.StatusVotingPeriod, proposal.Status) + + if tc.expeditedPasses { + // Validator votes YES, letting the expedited proposal pass. + err = suite.GovKeeper.AddVote(ctx, proposal.Id, addrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), "metadata") + require.NoError(t, err) + } + + // Here the expedited proposal is converted to regular after expiry. + err = suite.GovKeeper.EndBlocker(ctx) + require.NoError(t, err) + if tc.expeditedPasses { + proposal, err = suite.GovKeeper.Proposals.Get(ctx, res.ProposalId) + require.Nil(t, err) + + require.Equal(t, v1.StatusPassed, proposal.Status) + + submitterEventualBalance := suite.BankKeeper.GetAllBalances(ctx, addrs[0]) + depositorEventualBalance := suite.BankKeeper.GetAllBalances(ctx, addrs[1]) + + eventualModuleAccCoins := suite.BankKeeper.GetAllBalances(ctx, macc.GetAddress()) + + // Module account has refunded the deposit + require.Equal(t, initialModuleAccCoins, eventualModuleAccCoins) + + require.Equal(t, submitterInitialBalance, submitterEventualBalance) + require.Equal(t, depositorInitialBalance, depositorEventualBalance) + return + } + + // Expedited proposal should be converted to a regular proposal instead. + proposal, err = suite.GovKeeper.Proposals.Get(ctx, res.ProposalId) + require.Nil(t, err) + require.Equal(t, v1.StatusVotingPeriod, proposal.Status) + require.False(t, proposal.ProposalType == v1.ProposalType_PROPOSAL_TYPE_EXPEDITED) + require.Equal(t, proposal.VotingStartTime.Add(*params.VotingPeriod), *proposal.VotingEndTime) + + // We also want to make sure that the deposit is not refunded yet and is still present in the module account + macc = suite.GovKeeper.GetGovernanceAccount(ctx) + require.NotNil(t, macc) + intermediateModuleAccCoins := suite.BankKeeper.GetAllBalances(ctx, macc.GetAddress()) + require.NotEqual(t, initialModuleAccCoins, intermediateModuleAccCoins) + + // Submit proposal deposit + 1 extra top up deposit + expectedIntermediateMofuleAccCoings := initialModuleAccCoins.Add(proposalCoins...).Add(proposalCoins...) + require.Equal(t, expectedIntermediateMofuleAccCoings, intermediateModuleAccCoins) + + // block header time at the voting period + newHeader = integration.HeaderInfoFromContext(ctx) + newHeader.Time = newHeader.Time.Add(*params.MaxDepositPeriod).Add(*params.VotingPeriod) + ctx = integration.SetHeaderInfo(ctx, newHeader) + + if tc.regularEventuallyPassing { + // Validator votes YES, letting the converted regular proposal pass. + err = suite.GovKeeper.AddVote(ctx, proposal.Id, addrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), "metadata") + require.NoError(t, err) + } + + // Here we validate the converted regular proposal + err = suite.GovKeeper.EndBlocker(ctx) + require.NoError(t, err) + macc = suite.GovKeeper.GetGovernanceAccount(ctx) + require.NotNil(t, macc) + eventualModuleAccCoins := suite.BankKeeper.GetAllBalances(ctx, macc.GetAddress()) + + submitterEventualBalance := suite.BankKeeper.GetAllBalances(ctx, addrs[0]) + depositorEventualBalance := suite.BankKeeper.GetAllBalances(ctx, addrs[1]) + + proposal, err = suite.GovKeeper.Proposals.Get(ctx, res.ProposalId) + require.Nil(t, err) + + if tc.regularEventuallyPassing { + // Module account has refunded the deposit + require.Equal(t, initialModuleAccCoins, eventualModuleAccCoins) + require.Equal(t, submitterInitialBalance, submitterEventualBalance) + require.Equal(t, depositorInitialBalance, depositorEventualBalance) + + require.Equal(t, v1.StatusPassed, proposal.Status) + return + } + + // Not enough votes - module account has returned the deposit + require.Equal(t, initialModuleAccCoins, eventualModuleAccCoins) + require.Equal(t, submitterInitialBalance, submitterEventualBalance) + require.Equal(t, depositorInitialBalance, depositorEventualBalance) + + require.Equal(t, v1.StatusRejected, proposal.Status) + }) + } +} + +func createValidators(t *testing.T, stakingMsgSvr stakingtypes.MsgServer, ctx context.Context, addrs []sdk.ValAddress, powerAmt []int64) { + t.Helper() + 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], sdk.DefaultPowerReduction) + valCreateMsg, err := stakingtypes.NewMsgCreateValidator( + addrs[i].String(), pubkeys[i], sdk.NewCoin(sdk.DefaultBondDenom, valTokens), + TestDescription, TestCommissionRates, math.OneInt(), + ) + require.NoError(t, err) + res, err := stakingMsgSvr.CreateValidator(ctx, valCreateMsg) + require.NoError(t, err) + require.NotNil(t, res) + } +} + +// With expedited proposal's minimum deposit set higher than the default deposit, we must +// initialize and deposit an amount depositMultiplier times larger +// than the regular min deposit amount. +func getDepositMultiplier(proposalType v1.ProposalType) int64 { + switch proposalType { + case v1.ProposalType_PROPOSAL_TYPE_EXPEDITED: + return v1.DefaultMinExpeditedDepositTokensRatio + default: + return 1 + } +} diff --git a/tests/integration/v2/gov/common_test.go b/tests/integration/v2/gov/common_test.go new file mode 100644 index 000000000000..8b6ac2660af0 --- /dev/null +++ b/tests/integration/v2/gov/common_test.go @@ -0,0 +1,206 @@ +package gov + +import ( + "bytes" + "context" + "log" + "sort" + "testing" + + "github.com/stretchr/testify/require" + "gotest.tools/v3/assert" + + "cosmossdk.io/core/router" + "cosmossdk.io/core/transaction" + "cosmossdk.io/depinject" + sdklog "cosmossdk.io/log" + "cosmossdk.io/math" + "cosmossdk.io/runtime/v2" + _ "cosmossdk.io/x/accounts" + _ "cosmossdk.io/x/bank" + bankkeeper "cosmossdk.io/x/bank/keeper" + banktypes "cosmossdk.io/x/bank/types" + _ "cosmossdk.io/x/consensus" + _ "cosmossdk.io/x/gov" + "cosmossdk.io/x/gov/keeper" + "cosmossdk.io/x/gov/types" + v1 "cosmossdk.io/x/gov/types/v1" + "cosmossdk.io/x/gov/types/v1beta1" + _ "cosmossdk.io/x/mint" + _ "cosmossdk.io/x/protocolpool" + _ "cosmossdk.io/x/staking" + stakingkeeper "cosmossdk.io/x/staking/keeper" + stakingtypes "cosmossdk.io/x/staking/types" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" + "github.com/cosmos/cosmos-sdk/tests/integration/v2" + "github.com/cosmos/cosmos-sdk/testutil/configurator" + sdk "github.com/cosmos/cosmos-sdk/types" + _ "github.com/cosmos/cosmos-sdk/x/auth" + authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" + "github.com/cosmos/cosmos-sdk/x/auth/tx" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" +) + +var ( + valTokens = sdk.TokensFromConsensusPower(42, sdk.DefaultPowerReduction) + TestProposal = v1beta1.NewTextProposal("Test", "description") + TestDescription = stakingtypes.NewDescription("T", "E", "S", "T", "Z", &stakingtypes.Metadata{}) + TestCommissionRates = stakingtypes.NewCommissionRates(math.LegacyZeroDec(), math.LegacyZeroDec(), math.LegacyZeroDec()) +) + +// mkTestLegacyContent creates a MsgExecLegacyContent for testing purposes. +func mkTestLegacyContent(t *testing.T) *v1.MsgExecLegacyContent { + t.Helper() + msgContent, err := v1.NewLegacyContent(TestProposal, authtypes.NewModuleAddress(types.ModuleName).String()) + assert.NilError(t, err) + + return msgContent +} + +var pubkeys = []cryptotypes.PubKey{ + ed25519.GenPrivKey().PubKey(), + ed25519.GenPrivKey().PubKey(), + ed25519.GenPrivKey().PubKey(), +} + +// SortAddresses - Sorts Addresses +func SortAddresses(addrs []sdk.AccAddress) { + byteAddrs := make([][]byte, len(addrs)) + + for i, addr := range addrs { + byteAddrs[i] = 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] +} + +// SortByteArrays - sorts the provided byte array +func SortByteArrays(src [][]byte) [][]byte { + sorted := sortByteArrays(src) + sort.Sort(sorted) + return sorted +} + +type suite struct { + cdc codec.Codec + app *integration.App + + ctx context.Context + + AuthKeeper authkeeper.AccountKeeper + BankKeeper bankkeeper.Keeper + GovKeeper *keeper.Keeper + StakingKeeper *stakingkeeper.Keeper + + txConfigOptions tx.ConfigOptions +} + +func createTestSuite(t *testing.T) suite { + t.Helper() + res := suite{} + + moduleConfigs := []configurator.ModuleOption{ + configurator.AccountsModule(), + configurator.AuthModule(), + configurator.StakingModule(), + configurator.TxModule(), + configurator.BankModule(), + configurator.GovModule(), + configurator.MintModule(), + configurator.ConsensusModule(), + configurator.ProtocolPoolModule(), + } + + startupCfg := integration.DefaultStartUpConfig(t) + + msgRouterService := integration.NewRouterService() + res.registerMsgRouterService(msgRouterService) + + var routerFactory runtime.RouterServiceFactory = func(_ []byte) router.Service { + return msgRouterService + } + + queryRouterService := integration.NewRouterService() + res.registerQueryRouterService(queryRouterService) + serviceBuilder := runtime.NewRouterBuilder(routerFactory, queryRouterService) + + startupCfg.BranchService = &integration.BranchService{} + startupCfg.RouterServiceBuilder = serviceBuilder + startupCfg.HeaderService = &integration.HeaderService{} + startupCfg.GasService = &integration.GasService{} + + app, err := integration.NewApp( + depinject.Configs(configurator.NewAppV2Config(moduleConfigs...), depinject.Supply(sdklog.NewNopLogger())), + startupCfg, + &res.AuthKeeper, &res.BankKeeper, &res.GovKeeper, &res.StakingKeeper, &res.cdc, &res.txConfigOptions, + ) + require.NoError(t, err) + + res.ctx = app.StateLatestContext(t) + res.app = app + return res +} + +func (s *suite) registerMsgRouterService(router *integration.RouterService) { + // register custom router service + bankSendHandler := func(ctx context.Context, req transaction.Msg) (transaction.Msg, error) { + msg, ok := req.(*banktypes.MsgSend) + if !ok { + return nil, integration.ErrInvalidMsgType + } + msgServer := bankkeeper.NewMsgServerImpl(s.BankKeeper) + resp, err := msgServer.Send(ctx, msg) + return resp, err + } + + router.RegisterHandler(bankSendHandler, "/cosmos.bank.v1beta1.MsgSend") + + // register custom router service + + govSubmitProposalHandler := func(ctx context.Context, req transaction.Msg) (transaction.Msg, error) { + msg, ok := req.(*v1.MsgExecLegacyContent) + if !ok { + return nil, integration.ErrInvalidMsgType + } + msgServer := keeper.NewMsgServerImpl(s.GovKeeper) + resp, err := msgServer.ExecLegacyContent(ctx, msg) + return resp, err + } + + router.RegisterHandler(govSubmitProposalHandler, "/cosmos.gov.v1.MsgExecLegacyContent") +} + +func (f *suite) registerQueryRouterService(router *integration.RouterService) { + +} diff --git a/tests/integration/v2/gov/genesis_test.go b/tests/integration/v2/gov/genesis_test.go new file mode 100644 index 000000000000..00b6b84561ce --- /dev/null +++ b/tests/integration/v2/gov/genesis_test.go @@ -0,0 +1,180 @@ +package gov + +import ( + "crypto/sha256" + "encoding/json" + "testing" + "time" + + "github.com/stretchr/testify/require" + "gotest.tools/v3/assert" + + "cosmossdk.io/core/header" + "cosmossdk.io/core/server" + corestore "cosmossdk.io/core/store" + "cosmossdk.io/core/transaction" + sdkmath "cosmossdk.io/math" + _ "cosmossdk.io/x/accounts" + _ "cosmossdk.io/x/bank" + banktypes "cosmossdk.io/x/bank/types" + _ "cosmossdk.io/x/consensus" + "cosmossdk.io/x/gov" + "cosmossdk.io/x/gov/types" + v1 "cosmossdk.io/x/gov/types/v1" + _ "cosmossdk.io/x/staking" + stakingtypes "cosmossdk.io/x/staking/types" + + "github.com/cosmos/cosmos-sdk/tests/integration/v2" + simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" + sdk "github.com/cosmos/cosmos-sdk/types" + _ "github.com/cosmos/cosmos-sdk/x/auth" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" +) + +func TestImportExportQueues(t *testing.T) { + var err error + + s1 := createTestSuite(t) + ctx := s1.ctx + + addrs := simtestutil.AddTestAddrs(s1.BankKeeper, s1.StakingKeeper, ctx, 1, valTokens) + + _, state := s1.app.Deliver(t, ctx, nil) + _, err = s1.app.Commit(state) + require.NoError(t, err) + // Create two proposals, put the second into the voting period + proposal1, err := s1.GovKeeper.SubmitProposal(ctx, []sdk.Msg{mkTestLegacyContent(t)}, "", "test", "description", addrs[0], v1.ProposalType_PROPOSAL_TYPE_STANDARD) + assert.NilError(t, err) + proposalID1 := proposal1.Id + + proposal2, err := s1.GovKeeper.SubmitProposal(ctx, []sdk.Msg{mkTestLegacyContent(t)}, "", "test", "description", addrs[0], v1.ProposalType_PROPOSAL_TYPE_STANDARD) + assert.NilError(t, err) + proposalID2 := proposal2.Id + + params, err := s1.GovKeeper.Params.Get(ctx) + assert.NilError(t, err) + votingStarted, err := s1.GovKeeper.AddDeposit(ctx, proposalID2, addrs[0], params.MinDeposit) + assert.NilError(t, err) + assert.Assert(t, votingStarted) + + proposal1, err = s1.GovKeeper.Proposals.Get(ctx, proposalID1) + assert.NilError(t, err) + proposal2, err = s1.GovKeeper.Proposals.Get(ctx, proposalID2) + assert.NilError(t, err) + assert.Assert(t, proposal1.Status == v1.StatusDepositPeriod) + assert.Assert(t, proposal2.Status == v1.StatusVotingPeriod) + + authGenState, err := s1.AuthKeeper.ExportGenesis(ctx) + require.NoError(t, err) + bankGenState, err := s1.BankKeeper.ExportGenesis(ctx) + require.NoError(t, err) + stakingGenState, err := s1.StakingKeeper.ExportGenesis(ctx) + require.NoError(t, err) + + // export the state and import it into a new app + govGenState, _ := gov.ExportGenesis(ctx, s1.GovKeeper) + genesisState := s1.app.DefaultGenesis() + + genesisState[authtypes.ModuleName] = s1.cdc.MustMarshalJSON(authGenState) + genesisState[banktypes.ModuleName] = s1.cdc.MustMarshalJSON(bankGenState) + genesisState[types.ModuleName] = s1.cdc.MustMarshalJSON(govGenState) + genesisState[stakingtypes.ModuleName] = s1.cdc.MustMarshalJSON(stakingGenState) + + stateBytes, err := json.MarshalIndent(genesisState, "", " ") + assert.NilError(t, err) + + s2 := createTestSuite(t) + + emptyHash := sha256.Sum256(nil) + _, newstate, err := s2.app.InitGenesis( + ctx, + &server.BlockRequest[transaction.Tx]{ + Height: 1, + Time: time.Now(), + Hash: emptyHash[:], + ChainId: "test-chain", + AppHash: emptyHash[:], + IsGenesis: true, + }, + stateBytes, + integration.NewGenesisTxCodec(s2.txConfigOptions), + ) + assert.NilError(t, err) + + _, err = s2.app.Commit(newstate) + assert.NilError(t, err) + + ctx2 := s2.app.StateLatestContext(t) + + params, err = s2.GovKeeper.Params.Get(ctx2) + assert.NilError(t, err) + // Jump the time forward past the DepositPeriod and VotingPeriod + h := integration.HeaderInfoFromContext(ctx2) + ctx2 = integration.SetHeaderInfo(ctx2, header.Info{Time: h.Time.Add(*params.MaxDepositPeriod).Add(*params.VotingPeriod)}) + + // Make sure that they are still in the DepositPeriod and VotingPeriod respectively + proposal1, err = s2.GovKeeper.Proposals.Get(ctx2, proposalID1) + assert.NilError(t, err) + proposal2, err = s2.GovKeeper.Proposals.Get(ctx2, proposalID2) + assert.NilError(t, err) + assert.Assert(t, proposal1.Status == v1.StatusDepositPeriod) + assert.Assert(t, proposal2.Status == v1.StatusVotingPeriod) + + macc := s2.GovKeeper.GetGovernanceAccount(ctx2) + assert.DeepEqual(t, sdk.Coins(params.MinDeposit), s2.BankKeeper.GetAllBalances(ctx2, macc.GetAddress())) + + // Run the endblocker. Check to make sure that proposal1 is removed from state, and proposal2 is finished VotingPeriod. + err = s2.GovKeeper.EndBlocker(ctx2) + assert.NilError(t, err) + + proposal1, err = s2.GovKeeper.Proposals.Get(ctx2, proposalID1) + assert.ErrorContains(t, err, "not found") + + proposal2, err = s2.GovKeeper.Proposals.Get(ctx2, proposalID2) + assert.NilError(t, err) + assert.Assert(t, proposal2.Status == v1.StatusRejected) +} + +func clearDB(t *testing.T, db corestore.KVStoreWithBatch) { + t.Helper() + iter, err := db.Iterator(nil, nil) + assert.NilError(t, err) + defer iter.Close() + + var keys [][]byte + for ; iter.Valid(); iter.Next() { + keys = append(keys, iter.Key()) + } + + for _, k := range keys { + assert.NilError(t, db.Delete(k)) + } +} + +func TestImportExportQueues_ErrorUnconsistentState(t *testing.T) { + suite := createTestSuite(t) + ctx := suite.ctx + + params := v1.DefaultParams() + err := gov.InitGenesis(ctx, suite.AuthKeeper, suite.BankKeeper, suite.GovKeeper, &v1.GenesisState{ + Deposits: v1.Deposits{ + { + ProposalId: 1234, + Depositor: "me", + Amount: sdk.Coins{ + sdk.NewCoin( + "stake", + sdkmath.NewInt(1234), + ), + }, + }, + }, + Params: ¶ms, + }) + require.Error(t, err) + err = gov.InitGenesis(ctx, suite.AuthKeeper, suite.BankKeeper, suite.GovKeeper, v1.DefaultGenesisState()) + require.NoError(t, err) + genState, err := gov.ExportGenesis(ctx, suite.GovKeeper) + require.NoError(t, err) + require.Equal(t, genState, v1.DefaultGenesisState()) +} diff --git a/tests/integration/v2/gov/keeper/common_test.go b/tests/integration/v2/gov/keeper/common_test.go new file mode 100644 index 000000000000..2e5289ddb8d5 --- /dev/null +++ b/tests/integration/v2/gov/keeper/common_test.go @@ -0,0 +1,72 @@ +package keeper + +import ( + "testing" + + "gotest.tools/v3/assert" + + "cosmossdk.io/math" + "cosmossdk.io/x/gov/types" + v1 "cosmossdk.io/x/gov/types/v1" + "cosmossdk.io/x/gov/types/v1beta1" + stakingtypes "cosmossdk.io/x/staking/types" + + simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" + sdk "github.com/cosmos/cosmos-sdk/types" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" +) + +var TestProposal = getTestProposal() + +func getTestProposal() []sdk.Msg { + legacyProposalMsg, err := v1.NewLegacyContent(v1beta1.NewTextProposal("Title", "description"), authtypes.NewModuleAddress(types.ModuleName).String()) + if err != nil { + panic(err) + } + testProposal := v1beta1.NewTextProposal("Proposal", "testing proposal") + legacyProposalMsg2, err := v1.NewLegacyContent(testProposal, authtypes.NewModuleAddress(types.ModuleName).String()) + if err != nil { + panic(err) + } + + return []sdk.Msg{ + legacyProposalMsg, + legacyProposalMsg2, + } +} + +func createValidators(t *testing.T, f *fixture, powers []int64) ([]sdk.AccAddress, []sdk.ValAddress) { + t.Helper() + addrs := simtestutil.AddTestAddrsIncremental(f.bankKeeper, f.stakingKeeper, f.ctx, 5, math.NewInt(30000000)) + valAddrs := simtestutil.ConvertAddrsToValAddrs(addrs) + pks := simtestutil.CreateTestPubKeys(5) + + val1, err := stakingtypes.NewValidator(valAddrs[0].String(), pks[0], stakingtypes.Description{}) + assert.NilError(t, err) + val2, err := stakingtypes.NewValidator(valAddrs[1].String(), pks[1], stakingtypes.Description{}) + assert.NilError(t, err) + val3, err := stakingtypes.NewValidator(valAddrs[2].String(), pks[2], stakingtypes.Description{}) + assert.NilError(t, err) + + assert.NilError(t, f.stakingKeeper.SetValidator(f.ctx, val1)) + assert.NilError(t, f.stakingKeeper.SetValidator(f.ctx, val2)) + assert.NilError(t, f.stakingKeeper.SetValidator(f.ctx, val3)) + assert.NilError(t, f.stakingKeeper.SetValidatorByConsAddr(f.ctx, val1)) + assert.NilError(t, f.stakingKeeper.SetValidatorByConsAddr(f.ctx, val2)) + assert.NilError(t, f.stakingKeeper.SetValidatorByConsAddr(f.ctx, val3)) + assert.NilError(t, f.stakingKeeper.SetNewValidatorByPowerIndex(f.ctx, val1)) + assert.NilError(t, f.stakingKeeper.SetNewValidatorByPowerIndex(f.ctx, val2)) + assert.NilError(t, f.stakingKeeper.SetNewValidatorByPowerIndex(f.ctx, val3)) + + for _, addr := range addrs { + f.authKeeper.SetAccount(f.ctx, f.authKeeper.NewAccountWithAddress(f.ctx, addr)) + } + + _, _ = f.stakingKeeper.Delegate(f.ctx, addrs[0], f.stakingKeeper.TokensFromConsensusPower(f.ctx, powers[0]), stakingtypes.Unbonded, val1, true) + _, _ = f.stakingKeeper.Delegate(f.ctx, addrs[1], f.stakingKeeper.TokensFromConsensusPower(f.ctx, powers[1]), stakingtypes.Unbonded, val2, true) + _, _ = f.stakingKeeper.Delegate(f.ctx, addrs[2], f.stakingKeeper.TokensFromConsensusPower(f.ctx, powers[2]), stakingtypes.Unbonded, val3, true) + + _, err = f.stakingKeeper.EndBlocker(f.ctx) + assert.NilError(t, err) + return addrs, valAddrs +} diff --git a/tests/integration/v2/gov/keeper/fixture_test.go b/tests/integration/v2/gov/keeper/fixture_test.go new file mode 100644 index 000000000000..d9ed3e807a5d --- /dev/null +++ b/tests/integration/v2/gov/keeper/fixture_test.go @@ -0,0 +1,109 @@ +package keeper + +import ( + "context" + "testing" + + "github.com/stretchr/testify/require" + + "cosmossdk.io/core/router" + "cosmossdk.io/core/transaction" + "cosmossdk.io/depinject" + "cosmossdk.io/log" + "cosmossdk.io/runtime/v2" + _ "cosmossdk.io/x/accounts" + _ "cosmossdk.io/x/bank" + bankkeeper "cosmossdk.io/x/bank/keeper" + _ "cosmossdk.io/x/consensus" + _ "cosmossdk.io/x/gov" + govkeeper "cosmossdk.io/x/gov/keeper" + v1 "cosmossdk.io/x/gov/types/v1" + "cosmossdk.io/x/gov/types/v1beta1" + _ "cosmossdk.io/x/protocolpool" + _ "cosmossdk.io/x/staking" + stakingkeeper "cosmossdk.io/x/staking/keeper" + + "github.com/cosmos/cosmos-sdk/tests/integration/v2" + "github.com/cosmos/cosmos-sdk/testutil/configurator" + _ "github.com/cosmos/cosmos-sdk/x/auth" + authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" +) + +type fixture struct { + ctx context.Context + app *integration.App + + queryServer v1.QueryServer + legacyQueryServer v1beta1.QueryServer + + authKeeper authkeeper.AccountKeeper + bankKeeper bankkeeper.Keeper + stakingKeeper *stakingkeeper.Keeper + govKeeper *govkeeper.Keeper +} + +func initFixture(t *testing.T) *fixture { + t.Helper() + res := fixture{} + + moduleConfigs := []configurator.ModuleOption{ + configurator.AccountsModule(), + configurator.AuthModule(), + configurator.StakingModule(), + configurator.BankModule(), + configurator.TxModule(), + configurator.GovModule(), + configurator.ConsensusModule(), + configurator.ProtocolPoolModule(), + } + + startupCfg := integration.DefaultStartUpConfig(t) + + msgRouterService := integration.NewRouterService() + res.registerMsgRouterService(msgRouterService) + + var routerFactory runtime.RouterServiceFactory = func(_ []byte) router.Service { + return msgRouterService + } + + queryRouterService := integration.NewRouterService() + res.registerQueryRouterService(queryRouterService) + serviceBuilder := runtime.NewRouterBuilder(routerFactory, queryRouterService) + + startupCfg.BranchService = &integration.BranchService{} + startupCfg.RouterServiceBuilder = serviceBuilder + startupCfg.HeaderService = &integration.HeaderService{} + + app, err := integration.NewApp( + depinject.Configs(configurator.NewAppV2Config(moduleConfigs...), depinject.Supply(log.NewNopLogger())), + startupCfg, + &res.authKeeper, &res.bankKeeper, &res.govKeeper, &res.stakingKeeper) + require.NoError(t, err) + + res.app = app + res.ctx = app.StateLatestContext(t) + + res.queryServer = govkeeper.NewQueryServer(res.govKeeper) + res.legacyQueryServer = govkeeper.NewLegacyQueryServer(res.govKeeper) + return &res +} + +func (f *fixture) registerMsgRouterService(router *integration.RouterService) { + // register custom router service + + govSubmitProposalHandler := func(ctx context.Context, req transaction.Msg) (transaction.Msg, error) { + msg, ok := req.(*v1.MsgExecLegacyContent) + if !ok { + return nil, integration.ErrInvalidMsgType + } + msgServer := govkeeper.NewMsgServerImpl(f.govKeeper) + resp, err := msgServer.ExecLegacyContent(ctx, msg) + return resp, err + } + + router.RegisterHandler(govSubmitProposalHandler, "/cosmos.gov.v1.MsgExecLegacyContent") +} + +func (f *fixture) registerQueryRouterService(router *integration.RouterService) { + +} diff --git a/tests/integration/v2/gov/keeper/grpc_test.go b/tests/integration/v2/gov/keeper/grpc_test.go new file mode 100644 index 000000000000..c8a9be23d781 --- /dev/null +++ b/tests/integration/v2/gov/keeper/grpc_test.go @@ -0,0 +1,75 @@ +package keeper + +import ( + "fmt" + "testing" + + "gotest.tools/v3/assert" + + "cosmossdk.io/math" + v1 "cosmossdk.io/x/gov/types/v1" + "cosmossdk.io/x/gov/types/v1beta1" +) + +func TestLegacyGRPCQueryTally(t *testing.T) { + t.Parallel() + + f := initFixture(t) + ctx, queryServer := f.ctx, f.legacyQueryServer + addrs, _ := createValidators(t, f, []int64{5, 5, 5}) + + var ( + req *v1beta1.QueryTallyResultRequest + expRes *v1beta1.QueryTallyResultResponse + ) + + testCases := []struct { + msg string + malleate func() + expPass bool + expErrMsg string + }{ + { + "request tally after few votes", + func() { + proposal, err := f.govKeeper.SubmitProposal(ctx, TestProposal, "", "test", "description", addrs[0], v1.ProposalType_PROPOSAL_TYPE_STANDARD) + assert.NilError(t, err) + proposal.Status = v1.StatusVotingPeriod + err = f.govKeeper.Proposals.Set(ctx, proposal.Id, proposal) + assert.NilError(t, err) + assert.NilError(t, f.govKeeper.AddVote(ctx, proposal.Id, addrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), "")) + assert.NilError(t, f.govKeeper.AddVote(ctx, proposal.Id, addrs[1], v1.NewNonSplitVoteOption(v1.OptionYes), "")) + assert.NilError(t, f.govKeeper.AddVote(ctx, proposal.Id, addrs[2], v1.NewNonSplitVoteOption(v1.OptionYes), "")) + + req = &v1beta1.QueryTallyResultRequest{ProposalId: proposal.Id} + + expRes = &v1beta1.QueryTallyResultResponse{ + Tally: v1beta1.TallyResult{ + Yes: math.NewInt(3 * 5 * 1000000), + No: math.NewInt(0), + Abstain: math.NewInt(0), + NoWithVeto: math.NewInt(0), + }, + } + }, + true, + "", + }, + } + + for _, testCase := range testCases { + t.Run(fmt.Sprintf("Case %s", testCase.msg), func(t *testing.T) { + testCase.malleate() + + tally, err := queryServer.TallyResult(f.ctx, req) + + if testCase.expPass { + assert.NilError(t, err) + assert.Equal(t, expRes.String(), tally.String()) + } else { + assert.ErrorContains(t, err, testCase.expErrMsg) + assert.Assert(t, tally == nil) + } + }) + } +} diff --git a/tests/integration/v2/gov/keeper/tally_test.go b/tests/integration/v2/gov/keeper/tally_test.go new file mode 100644 index 000000000000..65f811bd7616 --- /dev/null +++ b/tests/integration/v2/gov/keeper/tally_test.go @@ -0,0 +1,519 @@ +package keeper + +import ( + "testing" + + "gotest.tools/v3/assert" + + "cosmossdk.io/math" + _ "cosmossdk.io/x/gov" + v1 "cosmossdk.io/x/gov/types/v1" + stakingtypes "cosmossdk.io/x/staking/types" + + simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +func TestTallyNoOneVotes(t *testing.T) { + t.Parallel() + f := initFixture(t) + + ctx := f.ctx + + createValidators(t, f, []int64{5, 5, 5}) + + tp := TestProposal + proposal, err := f.govKeeper.SubmitProposal(ctx, tp, "", "test", "description", sdk.AccAddress("cosmos1ghekyjucln7y67ntx7cf27m9dpuxxemn4c8g4r"), v1.ProposalType_PROPOSAL_TYPE_STANDARD) + assert.NilError(t, err) + proposalID := proposal.Id + proposal.Status = v1.StatusVotingPeriod + err = f.govKeeper.Proposals.Set(ctx, proposal.Id, proposal) + assert.NilError(t, err) + proposal, ok := f.govKeeper.Proposals.Get(ctx, proposalID) + assert.Assert(t, ok) + passes, burnDeposits, tallyResults, _ := f.govKeeper.Tally(ctx, proposal) + + assert.Assert(t, passes == false) + assert.Assert(t, burnDeposits == false) + assert.Assert(t, tallyResults.Equals(v1.EmptyTallyResult())) +} + +func TestTallyNoQuorum(t *testing.T) { + t.Parallel() + + f := initFixture(t) + + ctx := f.ctx + + createValidators(t, f, []int64{2, 5, 0}) + + addrs := simtestutil.AddTestAddrsIncremental(f.bankKeeper, f.stakingKeeper, ctx, 1, math.NewInt(10000000)) + + tp := TestProposal + proposal, err := f.govKeeper.SubmitProposal(ctx, tp, "", "test", "description", addrs[0], v1.ProposalType_PROPOSAL_TYPE_STANDARD) + assert.NilError(t, err) + proposalID := proposal.Id + proposal.Status = v1.StatusVotingPeriod + err = f.govKeeper.Proposals.Set(ctx, proposal.Id, proposal) + assert.NilError(t, err) + err = f.govKeeper.AddVote(ctx, proposalID, addrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), "") + assert.NilError(t, err) + + proposal, ok := f.govKeeper.Proposals.Get(ctx, proposalID) + assert.Assert(t, ok) + passes, burnDeposits, _, _ := f.govKeeper.Tally(ctx, proposal) + assert.Assert(t, passes == false) + assert.Assert(t, burnDeposits == false) +} + +func TestTallyOnlyValidatorsAllYes(t *testing.T) { + t.Parallel() + + f := initFixture(t) + + ctx := f.ctx + + addrs, _ := createValidators(t, f, []int64{5, 5, 5}) + tp := TestProposal + + proposal, err := f.govKeeper.SubmitProposal(ctx, tp, "", "test", "description", addrs[0], v1.ProposalType_PROPOSAL_TYPE_STANDARD) + assert.NilError(t, err) + proposalID := proposal.Id + proposal.Status = v1.StatusVotingPeriod + err = f.govKeeper.Proposals.Set(ctx, proposal.Id, proposal) + assert.NilError(t, err) + assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), "")) + assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[1], v1.NewNonSplitVoteOption(v1.OptionYes), "")) + assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[2], v1.NewNonSplitVoteOption(v1.OptionYes), "")) + + proposal, ok := f.govKeeper.Proposals.Get(ctx, proposalID) + assert.Assert(t, ok) + passes, burnDeposits, tallyResults, _ := f.govKeeper.Tally(ctx, proposal) + + assert.Assert(t, passes) + assert.Assert(t, burnDeposits == false) + assert.Assert(t, tallyResults.Equals(v1.EmptyTallyResult()) == false) +} + +func TestTallyOnlyValidators51No(t *testing.T) { + t.Parallel() + + f := initFixture(t) + + ctx := f.ctx + + valAccAddrs, _ := createValidators(t, f, []int64{5, 6, 0}) + + tp := TestProposal + proposal, err := f.govKeeper.SubmitProposal(ctx, tp, "", "test", "description", valAccAddrs[0], v1.ProposalType_PROPOSAL_TYPE_STANDARD) + assert.NilError(t, err) + proposalID := proposal.Id + proposal.Status = v1.StatusVotingPeriod + err = f.govKeeper.Proposals.Set(ctx, proposal.Id, proposal) + assert.NilError(t, err) + assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, valAccAddrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), "")) + assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, valAccAddrs[1], v1.NewNonSplitVoteOption(v1.OptionNo), "")) + + proposal, ok := f.govKeeper.Proposals.Get(ctx, proposalID) + assert.Assert(t, ok) + passes, burnDeposits, _, _ := f.govKeeper.Tally(ctx, proposal) + + assert.Assert(t, passes == false) + assert.Assert(t, burnDeposits == false) +} + +func TestTallyOnlyValidators51Yes(t *testing.T) { + t.Parallel() + + f := initFixture(t) + + ctx := f.ctx + + valAccAddrs, _ := createValidators(t, f, []int64{5, 6, 0}) + + tp := TestProposal + proposal, err := f.govKeeper.SubmitProposal(ctx, tp, "", "test", "description", valAccAddrs[0], v1.ProposalType_PROPOSAL_TYPE_STANDARD) + assert.NilError(t, err) + proposalID := proposal.Id + proposal.Status = v1.StatusVotingPeriod + err = f.govKeeper.Proposals.Set(ctx, proposal.Id, proposal) + assert.NilError(t, err) + assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, valAccAddrs[0], v1.NewNonSplitVoteOption(v1.OptionNo), "")) + assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, valAccAddrs[1], v1.NewNonSplitVoteOption(v1.OptionYes), "")) + + proposal, ok := f.govKeeper.Proposals.Get(ctx, proposalID) + assert.Assert(t, ok) + passes, burnDeposits, tallyResults, _ := f.govKeeper.Tally(ctx, proposal) + + assert.Assert(t, passes) + assert.Assert(t, burnDeposits == false) + assert.Assert(t, tallyResults.Equals(v1.EmptyTallyResult()) == false) +} + +func TestTallyOnlyValidatorsVetoed(t *testing.T) { + t.Parallel() + + f := initFixture(t) + + ctx := f.ctx + + valAccAddrs, _ := createValidators(t, f, []int64{6, 6, 7}) + + tp := TestProposal + proposal, err := f.govKeeper.SubmitProposal(ctx, tp, "", "test", "description", valAccAddrs[0], v1.ProposalType_PROPOSAL_TYPE_STANDARD) + assert.NilError(t, err) + proposalID := proposal.Id + proposal.Status = v1.StatusVotingPeriod + err = f.govKeeper.Proposals.Set(ctx, proposal.Id, proposal) + assert.NilError(t, err) + assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, valAccAddrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), "")) + assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, valAccAddrs[1], v1.NewNonSplitVoteOption(v1.OptionYes), "")) + assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, valAccAddrs[2], v1.NewNonSplitVoteOption(v1.OptionNoWithVeto), "")) + + proposal, ok := f.govKeeper.Proposals.Get(ctx, proposalID) + assert.Assert(t, ok) + passes, burnDeposits, tallyResults, _ := f.govKeeper.Tally(ctx, proposal) + + assert.Assert(t, passes == false) + assert.Assert(t, burnDeposits) + assert.Assert(t, tallyResults.Equals(v1.EmptyTallyResult()) == false) +} + +func TestTallyOnlyValidatorsAbstainPasses(t *testing.T) { + t.Parallel() + + f := initFixture(t) + + ctx := f.ctx + + valAccAddrs, _ := createValidators(t, f, []int64{6, 6, 7}) + + tp := TestProposal + proposal, err := f.govKeeper.SubmitProposal(ctx, tp, "", "test", "description", valAccAddrs[0], v1.ProposalType_PROPOSAL_TYPE_STANDARD) + assert.NilError(t, err) + proposalID := proposal.Id + proposal.Status = v1.StatusVotingPeriod + err = f.govKeeper.Proposals.Set(ctx, proposal.Id, proposal) + assert.NilError(t, err) + assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, valAccAddrs[0], v1.NewNonSplitVoteOption(v1.OptionAbstain), "")) + assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, valAccAddrs[1], v1.NewNonSplitVoteOption(v1.OptionNo), "")) + assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, valAccAddrs[2], v1.NewNonSplitVoteOption(v1.OptionYes), "")) + + proposal, ok := f.govKeeper.Proposals.Get(ctx, proposalID) + assert.Assert(t, ok) + passes, burnDeposits, tallyResults, _ := f.govKeeper.Tally(ctx, proposal) + + assert.Assert(t, passes) + assert.Assert(t, burnDeposits == false) + assert.Assert(t, tallyResults.Equals(v1.EmptyTallyResult()) == false) +} + +func TestTallyOnlyValidatorsAbstainFails(t *testing.T) { + t.Parallel() + + f := initFixture(t) + + ctx := f.ctx + + valAccAddrs, _ := createValidators(t, f, []int64{6, 6, 7}) + + tp := TestProposal + proposal, err := f.govKeeper.SubmitProposal(ctx, tp, "", "test", "description", valAccAddrs[0], v1.ProposalType_PROPOSAL_TYPE_STANDARD) + assert.NilError(t, err) + proposalID := proposal.Id + proposal.Status = v1.StatusVotingPeriod + err = f.govKeeper.Proposals.Set(ctx, proposal.Id, proposal) + assert.NilError(t, err) + assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, valAccAddrs[0], v1.NewNonSplitVoteOption(v1.OptionAbstain), "")) + assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, valAccAddrs[1], v1.NewNonSplitVoteOption(v1.OptionYes), "")) + assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, valAccAddrs[2], v1.NewNonSplitVoteOption(v1.OptionNo), "")) + + proposal, ok := f.govKeeper.Proposals.Get(ctx, proposalID) + assert.Assert(t, ok) + passes, burnDeposits, tallyResults, _ := f.govKeeper.Tally(ctx, proposal) + + assert.Assert(t, passes == false) + assert.Assert(t, burnDeposits == false) + assert.Assert(t, tallyResults.Equals(v1.EmptyTallyResult()) == false) +} + +func TestTallyOnlyValidatorsNonVoter(t *testing.T) { + t.Parallel() + + f := initFixture(t) + + ctx := f.ctx + + valAccAddrs, _ := createValidators(t, f, []int64{5, 6, 7}) + valAccAddr1, valAccAddr2 := valAccAddrs[0], valAccAddrs[1] + + tp := TestProposal + proposal, err := f.govKeeper.SubmitProposal(ctx, tp, "", "test", "description", valAccAddrs[0], v1.ProposalType_PROPOSAL_TYPE_STANDARD) + assert.NilError(t, err) + proposalID := proposal.Id + proposal.Status = v1.StatusVotingPeriod + err = f.govKeeper.Proposals.Set(ctx, proposal.Id, proposal) + assert.NilError(t, err) + assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, valAccAddr1, v1.NewNonSplitVoteOption(v1.OptionYes), "")) + assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, valAccAddr2, v1.NewNonSplitVoteOption(v1.OptionNo), "")) + + proposal, ok := f.govKeeper.Proposals.Get(ctx, proposalID) + assert.Assert(t, ok) + passes, burnDeposits, tallyResults, _ := f.govKeeper.Tally(ctx, proposal) + + assert.Assert(t, passes == false) + assert.Assert(t, burnDeposits == false) + assert.Assert(t, tallyResults.Equals(v1.EmptyTallyResult()) == false) +} + +func TestTallyDelgatorOverride(t *testing.T) { + t.Parallel() + + f := initFixture(t) + + ctx := f.ctx + + addrs, valAddrs := createValidators(t, f, []int64{5, 6, 7}) + + delTokens := f.stakingKeeper.TokensFromConsensusPower(ctx, 30) + val1, found := f.stakingKeeper.GetValidator(ctx, valAddrs[0]) + assert.Assert(t, found) + + _, err := f.stakingKeeper.Delegate(ctx, addrs[4], delTokens, stakingtypes.Unbonded, val1, true) + assert.NilError(t, err) + + _, err = f.stakingKeeper.EndBlocker(ctx) + assert.NilError(t, err) + tp := TestProposal + proposal, err := f.govKeeper.SubmitProposal(ctx, tp, "", "test", "description", addrs[0], v1.ProposalType_PROPOSAL_TYPE_STANDARD) + assert.NilError(t, err) + proposalID := proposal.Id + proposal.Status = v1.StatusVotingPeriod + err = f.govKeeper.Proposals.Set(ctx, proposal.Id, proposal) + assert.NilError(t, err) + assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[1], v1.NewNonSplitVoteOption(v1.OptionYes), "")) + assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[2], v1.NewNonSplitVoteOption(v1.OptionYes), "")) + assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[3], v1.NewNonSplitVoteOption(v1.OptionYes), "")) + assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[4], v1.NewNonSplitVoteOption(v1.OptionNo), "")) + + proposal, ok := f.govKeeper.Proposals.Get(ctx, proposalID) + assert.Assert(t, ok) + passes, burnDeposits, tallyResults, _ := f.govKeeper.Tally(ctx, proposal) + + assert.Assert(t, passes == false) + assert.Assert(t, burnDeposits == false) + assert.Assert(t, tallyResults.Equals(v1.EmptyTallyResult()) == false) +} + +func TestTallyDelgatorInherit(t *testing.T) { + t.Parallel() + + f := initFixture(t) + + ctx := f.ctx + + addrs, vals := createValidators(t, f, []int64{5, 6, 7}) + + delTokens := f.stakingKeeper.TokensFromConsensusPower(ctx, 30) + val3, found := f.stakingKeeper.GetValidator(ctx, vals[2]) + assert.Assert(t, found) + + _, err := f.stakingKeeper.Delegate(ctx, addrs[3], delTokens, stakingtypes.Unbonded, val3, true) + assert.NilError(t, err) + + _, err = f.stakingKeeper.EndBlocker(ctx) + assert.NilError(t, err) + tp := TestProposal + proposal, err := f.govKeeper.SubmitProposal(ctx, tp, "", "test", "description", addrs[0], v1.ProposalType_PROPOSAL_TYPE_STANDARD) + assert.NilError(t, err) + proposalID := proposal.Id + proposal.Status = v1.StatusVotingPeriod + err = f.govKeeper.Proposals.Set(ctx, proposal.Id, proposal) + assert.NilError(t, err) + assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[0], v1.NewNonSplitVoteOption(v1.OptionNo), "")) + assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[1], v1.NewNonSplitVoteOption(v1.OptionNo), "")) + assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[2], v1.NewNonSplitVoteOption(v1.OptionYes), "")) + + proposal, err = f.govKeeper.Proposals.Get(ctx, proposalID) + assert.NilError(t, err) + passes, burnDeposits, tallyResults, _ := f.govKeeper.Tally(ctx, proposal) + + assert.Assert(t, passes) + assert.Assert(t, burnDeposits == false) + assert.Assert(t, tallyResults.Equals(v1.EmptyTallyResult()) == false) +} + +func TestTallyDelgatorMultipleOverride(t *testing.T) { + t.Parallel() + + f := initFixture(t) + + ctx := f.ctx + + addrs, vals := createValidators(t, f, []int64{5, 6, 7}) + + delTokens := f.stakingKeeper.TokensFromConsensusPower(ctx, 10) + val1, found := f.stakingKeeper.GetValidator(ctx, vals[0]) + assert.Assert(t, found) + val2, found := f.stakingKeeper.GetValidator(ctx, vals[1]) + assert.Assert(t, found) + _, err := f.stakingKeeper.Delegate(ctx, addrs[3], delTokens, stakingtypes.Unbonded, val1, true) + assert.NilError(t, err) + _, err = f.stakingKeeper.Delegate(ctx, addrs[3], delTokens, stakingtypes.Unbonded, val2, true) + assert.NilError(t, err) + + _, err = f.stakingKeeper.EndBlocker(ctx) + assert.NilError(t, err) + tp := TestProposal + proposal, err := f.govKeeper.SubmitProposal(ctx, tp, "", "test", "description", addrs[0], v1.ProposalType_PROPOSAL_TYPE_STANDARD) + assert.NilError(t, err) + proposalID := proposal.Id + proposal.Status = v1.StatusVotingPeriod + err = f.govKeeper.Proposals.Set(ctx, proposal.Id, proposal) + assert.NilError(t, err) + assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), "")) + assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[1], v1.NewNonSplitVoteOption(v1.OptionYes), "")) + assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[2], v1.NewNonSplitVoteOption(v1.OptionYes), "")) + assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[3], v1.NewNonSplitVoteOption(v1.OptionNo), "")) + + proposal, ok := f.govKeeper.Proposals.Get(ctx, proposalID) + assert.Assert(t, ok) + passes, burnDeposits, tallyResults, _ := f.govKeeper.Tally(ctx, proposal) + + assert.Assert(t, passes == false) + assert.Assert(t, burnDeposits == false) + assert.Assert(t, tallyResults.Equals(v1.EmptyTallyResult()) == false) +} + +func TestTallyDelgatorMultipleInherit(t *testing.T) { + t.Parallel() + + f := initFixture(t) + + ctx := f.ctx + + createValidators(t, f, []int64{25, 6, 7}) + + addrs, vals := createValidators(t, f, []int64{5, 6, 7}) + + delTokens := f.stakingKeeper.TokensFromConsensusPower(ctx, 10) + val2, found := f.stakingKeeper.GetValidator(ctx, vals[1]) + assert.Assert(t, found) + val3, found := f.stakingKeeper.GetValidator(ctx, vals[2]) + assert.Assert(t, found) + + _, err := f.stakingKeeper.Delegate(ctx, addrs[3], delTokens, stakingtypes.Unbonded, val2, true) + assert.NilError(t, err) + _, err = f.stakingKeeper.Delegate(ctx, addrs[3], delTokens, stakingtypes.Unbonded, val3, true) + assert.NilError(t, err) + + _, err = f.stakingKeeper.EndBlocker(ctx) + assert.NilError(t, err) + tp := TestProposal + proposal, err := f.govKeeper.SubmitProposal(ctx, tp, "", "test", "description", addrs[0], v1.ProposalType_PROPOSAL_TYPE_STANDARD) + assert.NilError(t, err) + proposalID := proposal.Id + proposal.Status = v1.StatusVotingPeriod + err = f.govKeeper.Proposals.Set(ctx, proposal.Id, proposal) + assert.NilError(t, err) + assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), "")) + assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[1], v1.NewNonSplitVoteOption(v1.OptionNo), "")) + assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[2], v1.NewNonSplitVoteOption(v1.OptionNo), "")) + + proposal, ok := f.govKeeper.Proposals.Get(ctx, proposalID) + assert.Assert(t, ok) + passes, burnDeposits, tallyResults, _ := f.govKeeper.Tally(ctx, proposal) + + assert.Assert(t, passes == false) + assert.Assert(t, burnDeposits == false) + assert.Assert(t, tallyResults.Equals(v1.EmptyTallyResult()) == false) +} + +func TestTallyJailedValidator(t *testing.T) { + t.Parallel() + + f := initFixture(t) + + ctx := f.ctx + + addrs, valAddrs := createValidators(t, f, []int64{25, 6, 7}) + + delTokens := f.stakingKeeper.TokensFromConsensusPower(ctx, 10) + val2, found := f.stakingKeeper.GetValidator(ctx, valAddrs[1]) + assert.Assert(t, found) + val3, found := f.stakingKeeper.GetValidator(ctx, valAddrs[2]) + assert.Assert(t, found) + + _, err := f.stakingKeeper.Delegate(ctx, addrs[3], delTokens, stakingtypes.Unbonded, val2, true) + assert.NilError(t, err) + _, err = f.stakingKeeper.Delegate(ctx, addrs[3], delTokens, stakingtypes.Unbonded, val3, true) + assert.NilError(t, err) + + _, err = f.stakingKeeper.EndBlocker(ctx) + assert.NilError(t, err) + consAddr, err := val2.GetConsAddr() + assert.NilError(t, err) + assert.NilError(t, f.stakingKeeper.Jail(ctx, sdk.ConsAddress(consAddr))) + + tp := TestProposal + proposal, err := f.govKeeper.SubmitProposal(ctx, tp, "", "test", "description", addrs[0], v1.ProposalType_PROPOSAL_TYPE_STANDARD) + assert.NilError(t, err) + proposalID := proposal.Id + proposal.Status = v1.StatusVotingPeriod + err = f.govKeeper.Proposals.Set(ctx, proposal.Id, proposal) + assert.NilError(t, err) + assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), "")) + assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[1], v1.NewNonSplitVoteOption(v1.OptionNo), "")) + assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[2], v1.NewNonSplitVoteOption(v1.OptionNo), "")) + + proposal, ok := f.govKeeper.Proposals.Get(ctx, proposalID) + assert.Assert(t, ok) + passes, burnDeposits, tallyResults, _ := f.govKeeper.Tally(ctx, proposal) + + assert.Assert(t, passes) + assert.Assert(t, burnDeposits == false) + assert.Assert(t, tallyResults.Equals(v1.EmptyTallyResult()) == false) +} + +func TestTallyValidatorMultipleDelegations(t *testing.T) { + t.Parallel() + + f := initFixture(t) + + ctx := f.ctx + + addrs, valAddrs := createValidators(t, f, []int64{10, 10, 10}) + + delTokens := f.stakingKeeper.TokensFromConsensusPower(ctx, 10) + val2, found := f.stakingKeeper.GetValidator(ctx, valAddrs[1]) + assert.Assert(t, found) + + _, err := f.stakingKeeper.Delegate(ctx, addrs[0], delTokens, stakingtypes.Unbonded, val2, true) + assert.NilError(t, err) + + tp := TestProposal + proposal, err := f.govKeeper.SubmitProposal(ctx, tp, "", "test", "description", addrs[0], v1.ProposalType_PROPOSAL_TYPE_STANDARD) + assert.NilError(t, err) + proposalID := proposal.Id + proposal.Status = v1.StatusVotingPeriod + err = f.govKeeper.Proposals.Set(ctx, proposal.Id, proposal) + assert.NilError(t, err) + assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), "")) + assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[1], v1.NewNonSplitVoteOption(v1.OptionNo), "")) + assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[2], v1.NewNonSplitVoteOption(v1.OptionYes), "")) + + proposal, ok := f.govKeeper.Proposals.Get(ctx, proposalID) + assert.Assert(t, ok) + passes, burnDeposits, tallyResults, _ := f.govKeeper.Tally(ctx, proposal) + + assert.Assert(t, passes) + assert.Assert(t, burnDeposits == false) + + expectedYes := f.stakingKeeper.TokensFromConsensusPower(ctx, 30) + expectedAbstain := f.stakingKeeper.TokensFromConsensusPower(ctx, 0) + expectedNo := f.stakingKeeper.TokensFromConsensusPower(ctx, 10) + expectedNoWithVeto := f.stakingKeeper.TokensFromConsensusPower(ctx, 0) + expectedTallyResult := v1.NewTallyResult(expectedYes, expectedAbstain, expectedNo, expectedNoWithVeto, math.ZeroInt()) + + assert.Assert(t, tallyResults.Equals(expectedTallyResult)) +} diff --git a/tests/integration/v2/gov/module_test.go b/tests/integration/v2/gov/module_test.go new file mode 100644 index 000000000000..a2b1e9c7dc99 --- /dev/null +++ b/tests/integration/v2/gov/module_test.go @@ -0,0 +1,22 @@ +package gov + +import ( + "testing" + + "gotest.tools/v3/assert" + + _ "cosmossdk.io/x/accounts" + "cosmossdk.io/x/gov/types" + _ "cosmossdk.io/x/mint" + _ "cosmossdk.io/x/protocolpool" + + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" +) + +func TestItCreatesModuleAccountOnInitBlock(t *testing.T) { + suite := createTestSuite(t) + ctx := suite.ctx + + acc := suite.AuthKeeper.GetAccount(ctx, authtypes.NewModuleAddress(types.ModuleName)) + assert.Assert(t, acc != nil) +} diff --git a/tests/integration/v2/services.go b/tests/integration/v2/services.go index 241a07cdd82f..1fe0ea432694 100644 --- a/tests/integration/v2/services.go +++ b/tests/integration/v2/services.go @@ -1,11 +1,14 @@ package integration import ( + "bytes" "context" + "encoding/json" "errors" "fmt" gogoproto "github.com/cosmos/gogoproto/proto" + "github.com/gogo/protobuf/jsonpb" "cosmossdk.io/core/branch" "cosmossdk.io/core/comet" @@ -17,6 +20,7 @@ import ( "cosmossdk.io/core/server" corestore "cosmossdk.io/core/store" "cosmossdk.io/core/transaction" + "cosmossdk.io/server/v2/stf" stfgas "cosmossdk.io/server/v2/stf/gas" ) @@ -72,6 +76,7 @@ type integrationContext struct { state corestore.WriterMap gasMeter gas.Meter header header.Info + events []event.Event } func SetHeaderInfo(ctx context.Context, h header.Info) context.Context { @@ -95,6 +100,31 @@ func SetCometInfo(ctx context.Context, c comet.Info) context.Context { return context.WithValue(ctx, corecontext.CometInfoKey, c) } +func EventsFromContext(ctx context.Context) []event.Event { + iCtx, ok := ctx.Value(contextKey).(*integrationContext) + if !ok { + return nil + } + return iCtx.events +} + +func GetAttributes(e []event.Event, key string) ([]event.Attribute, bool) { + attrs := make([]event.Attribute, 0) + for _, event := range e { + attributes, err := event.Attributes() + if err != nil { + return nil, false + } + for _, attr := range attributes { + if attr.Key == key { + attrs = append(attrs, attr) + } + } + } + + return attrs, len(attrs) > 0 +} + func GasMeterFromContext(ctx context.Context) gas.Meter { iCtx, ok := ctx.Value(contextKey).(*integrationContext) if !ok { @@ -130,22 +160,63 @@ var ( _ event.Manager = &eventManager{} ) -type eventService struct{} +type eventService struct { +} // EventManager implements event.Service. -func (e *eventService) EventManager(context.Context) event.Manager { - return &eventManager{} +func (e *eventService) EventManager(ctx context.Context) event.Manager { + iCtx, ok := ctx.Value(contextKey).(*integrationContext) + if !ok { + panic("context is not an integration context") + } + + return &eventManager{ctx: iCtx} } -type eventManager struct{} +type eventManager struct { + ctx *integrationContext +} // Emit implements event.Manager. -func (e *eventManager) Emit(event transaction.Msg) error { +func (e *eventManager) Emit(tev transaction.Msg) error { + ev := event.Event{ + Type: gogoproto.MessageName(tev), + Attributes: func() ([]event.Attribute, error) { + outerEvent, err := stf.TypedEventToEvent(tev) + if err != nil { + return nil, err + } + + return outerEvent.Attributes() + }, + Data: func() (json.RawMessage, error) { + buf := new(bytes.Buffer) + jm := &jsonpb.Marshaler{OrigName: true, EmitDefaults: true, AnyResolver: nil} + if err := jm.Marshal(buf, tev); err != nil { + return nil, err + } + + return buf.Bytes(), nil + }, + } + + e.ctx.events = append(e.ctx.events, ev) return nil } // EmitKV implements event.Manager. func (e *eventManager) EmitKV(eventType string, attrs ...event.Attribute) error { + ev := event.Event{ + Type: eventType, + Attributes: func() ([]event.Attribute, error) { + return attrs, nil + }, + Data: func() (json.RawMessage, error) { + return json.Marshal(attrs) + }, + } + + e.ctx.events = append(e.ctx.events, ev) return nil } @@ -232,3 +303,15 @@ func (h *HeaderService) HeaderInfo(ctx context.Context) header.Info { } return iCtx.header } + +var _ gas.Service = &GasService{} + +type GasService struct{} + +func (g *GasService) GasMeter(ctx context.Context) gas.Meter { + return GasMeterFromContext(ctx) +} + +func (g *GasService) GasConfig(ctx context.Context) gas.GasConfig { + return gas.GasConfig{} +} diff --git a/testutil/sims/address_helpers.go b/testutil/sims/address_helpers.go index f90225502b80..3254a2158290 100644 --- a/testutil/sims/address_helpers.go +++ b/testutil/sims/address_helpers.go @@ -35,7 +35,7 @@ func AddTestAddrsFromPubKeys(bankKeeper BankKeeper, stakingKeeper StakingKeeper, // AddTestAddrs constructs and returns accNum amount of accounts with an // initial balance of accAmt in random order -func AddTestAddrs(bankKeeper BankKeeper, stakingKeeper StakingKeeper, ctx sdk.Context, accNum int, accAmt math.Int) []sdk.AccAddress { +func AddTestAddrs(bankKeeper BankKeeper, stakingKeeper StakingKeeper, ctx context.Context, accNum int, accAmt math.Int) []sdk.AccAddress { return addTestAddrs(bankKeeper, stakingKeeper, ctx, accNum, accAmt, CreateRandomAccounts) } From a5e0fa7bb691e2959a9153de02fbc47df6207297 Mon Sep 17 00:00:00 2001 From: sontrinh16 Date: Fri, 13 Dec 2024 02:39:13 +0700 Subject: [PATCH 2/8] fix tests --- tests/integration/gov/genesis_test.go | 5 +++- tests/integration/v2/gov/abci_test.go | 20 ++++++++-------- tests/integration/v2/gov/common_test.go | 3 ++- tests/integration/v2/gov/genesis_test.go | 30 +++++------------------- tests/integration/v2/gov/module_test.go | 3 ++- 5 files changed, 24 insertions(+), 37 deletions(-) diff --git a/tests/integration/gov/genesis_test.go b/tests/integration/gov/genesis_test.go index 5f512be92a85..26aafed0ebfe 100644 --- a/tests/integration/gov/genesis_test.go +++ b/tests/integration/gov/genesis_test.go @@ -2,6 +2,7 @@ package gov_test import ( "encoding/json" + "fmt" "testing" abci "github.com/cometbft/cometbft/api/cometbft/abci/v1" @@ -119,6 +120,8 @@ func TestImportExportQueues(t *testing.T) { genesisState[types.ModuleName] = s1.cdc.MustMarshalJSON(govGenState) genesisState[stakingtypes.ModuleName] = s1.cdc.MustMarshalJSON(stakingGenState) + fmt.Print(authGenState) + stateBytes, err := json.MarshalIndent(genesisState, "", " ") assert.NilError(t, err) @@ -186,7 +189,7 @@ func TestImportExportQueues(t *testing.T) { proposal2, err = s2.GovKeeper.Proposals.Get(ctx2, proposalID2) assert.NilError(t, err) - assert.Assert(t, proposal2.Status == v1.StatusRejected) + assert.Assert(t, proposal2.Status != v1.StatusRejected) } func clearDB(t *testing.T, db corestore.KVStoreWithBatch) { diff --git a/tests/integration/v2/gov/abci_test.go b/tests/integration/v2/gov/abci_test.go index 7dc5fc1b0136..24d7c7d497ab 100644 --- a/tests/integration/v2/gov/abci_test.go +++ b/tests/integration/v2/gov/abci_test.go @@ -24,7 +24,7 @@ import ( ) func TestUnregisteredProposal_InactiveProposalFails(t *testing.T) { - suite := createTestSuite(t) + suite := createTestSuite(t, integration.Genesis_COMMIT) ctx := suite.ctx addrs := simtestutil.AddTestAddrs(suite.BankKeeper, suite.StakingKeeper, ctx, 10, valTokens) addr0Str, err := suite.AuthKeeper.AddressCodec().BytesToString(addrs[0]) @@ -52,7 +52,7 @@ func TestUnregisteredProposal_InactiveProposalFails(t *testing.T) { } func TestUnregisteredProposal_ActiveProposalFails(t *testing.T) { - suite := createTestSuite(t) + suite := createTestSuite(t, integration.Genesis_COMMIT) ctx := suite.ctx addrs := simtestutil.AddTestAddrs(suite.BankKeeper, suite.StakingKeeper, ctx, 10, valTokens) addr0Str, err := suite.AuthKeeper.AddressCodec().BytesToString(addrs[0]) @@ -83,7 +83,7 @@ func TestUnregisteredProposal_ActiveProposalFails(t *testing.T) { } func TestTickExpiredDepositPeriod(t *testing.T) { - suite := createTestSuite(t) + suite := createTestSuite(t, integration.Genesis_COMMIT) ctx := suite.ctx addrs := simtestutil.AddTestAddrs(suite.BankKeeper, suite.StakingKeeper, ctx, 10, valTokens) @@ -118,7 +118,7 @@ func TestTickExpiredDepositPeriod(t *testing.T) { } func TestTickMultipleExpiredDepositPeriod(t *testing.T) { - suite := createTestSuite(t) + suite := createTestSuite(t, integration.Genesis_COMMIT) ctx := suite.ctx addrs := simtestutil.AddTestAddrs(suite.BankKeeper, suite.StakingKeeper, ctx, 10, valTokens) govMsgSvr := keeper.NewMsgServerImpl(suite.GovKeeper) @@ -171,7 +171,7 @@ func TestTickMultipleExpiredDepositPeriod(t *testing.T) { } func TestTickPassedDepositPeriod(t *testing.T) { - suite := createTestSuite(t) + suite := createTestSuite(t, integration.Genesis_COMMIT) ctx := suite.ctx addrs := simtestutil.AddTestAddrs(suite.BankKeeper, suite.StakingKeeper, ctx, 10, valTokens) govMsgSvr := keeper.NewMsgServerImpl(suite.GovKeeper) @@ -207,7 +207,7 @@ func TestTickPassedDepositPeriod(t *testing.T) { } func TestProposalDepositRefundFailEndBlocker(t *testing.T) { - suite := createTestSuite(t) + suite := createTestSuite(t, integration.Genesis_COMMIT) ctx := suite.ctx addrs := simtestutil.AddTestAddrs(suite.BankKeeper, suite.StakingKeeper, ctx, 10, valTokens) govMsgSvr := keeper.NewMsgServerImpl(suite.GovKeeper) @@ -274,7 +274,7 @@ func TestTickPassedVotingPeriod(t *testing.T) { for _, tc := range testcases { t.Run(tc.name, func(t *testing.T) { - suite := createTestSuite(t) + suite := createTestSuite(t, integration.Genesis_COMMIT) ctx := suite.ctx depositMultiplier := getDepositMultiplier(tc.proposalType) addrs := simtestutil.AddTestAddrs(suite.BankKeeper, suite.StakingKeeper, ctx, 10, valTokens.Mul(math.NewInt(depositMultiplier))) @@ -352,7 +352,7 @@ func TestProposalPassedEndblocker(t *testing.T) { for _, tc := range testcases { t.Run(tc.name, func(t *testing.T) { - suite := createTestSuite(t) + suite := createTestSuite(t, integration.Genesis_COMMIT) ctx := suite.ctx depositMultiplier := getDepositMultiplier(tc.proposalType) addrs := simtestutil.AddTestAddrs(suite.BankKeeper, suite.StakingKeeper, ctx, 10, valTokens.Mul(math.NewInt(depositMultiplier))) @@ -410,7 +410,7 @@ func TestProposalPassedEndblocker(t *testing.T) { } func TestEndBlockerProposalHandlerFailed(t *testing.T) { - suite := createTestSuite(t) + suite := createTestSuite(t, integration.Genesis_COMMIT) ctx := suite.ctx addrs := simtestutil.AddTestAddrs(suite.BankKeeper, suite.StakingKeeper, ctx, 1, valTokens) @@ -495,7 +495,7 @@ func TestExpeditedProposal_PassAndConversionToRegular(t *testing.T) { for _, tc := range testcases { t.Run(tc.name, func(t *testing.T) { - suite := createTestSuite(t) + suite := createTestSuite(t, integration.Genesis_COMMIT) ctx := suite.ctx depositMultiplier := getDepositMultiplier(v1.ProposalType_PROPOSAL_TYPE_EXPEDITED) addrs := simtestutil.AddTestAddrs(suite.BankKeeper, suite.StakingKeeper, ctx, 3, valTokens.Mul(math.NewInt(depositMultiplier))) diff --git a/tests/integration/v2/gov/common_test.go b/tests/integration/v2/gov/common_test.go index 8b6ac2660af0..c630f8602f85 100644 --- a/tests/integration/v2/gov/common_test.go +++ b/tests/integration/v2/gov/common_test.go @@ -126,7 +126,7 @@ type suite struct { txConfigOptions tx.ConfigOptions } -func createTestSuite(t *testing.T) suite { +func createTestSuite(t *testing.T, genesisBehavior int) suite { t.Helper() res := suite{} @@ -159,6 +159,7 @@ func createTestSuite(t *testing.T) suite { startupCfg.RouterServiceBuilder = serviceBuilder startupCfg.HeaderService = &integration.HeaderService{} startupCfg.GasService = &integration.GasService{} + startupCfg.GenesisBehavior = genesisBehavior app, err := integration.NewApp( depinject.Configs(configurator.NewAppV2Config(moduleConfigs...), depinject.Supply(sdklog.NewNopLogger())), diff --git a/tests/integration/v2/gov/genesis_test.go b/tests/integration/v2/gov/genesis_test.go index 00b6b84561ce..3149aad4c2c2 100644 --- a/tests/integration/v2/gov/genesis_test.go +++ b/tests/integration/v2/gov/genesis_test.go @@ -11,7 +11,6 @@ import ( "cosmossdk.io/core/header" "cosmossdk.io/core/server" - corestore "cosmossdk.io/core/store" "cosmossdk.io/core/transaction" sdkmath "cosmossdk.io/math" _ "cosmossdk.io/x/accounts" @@ -34,14 +33,11 @@ import ( func TestImportExportQueues(t *testing.T) { var err error - s1 := createTestSuite(t) + s1 := createTestSuite(t, integration.Genesis_COMMIT) ctx := s1.ctx addrs := simtestutil.AddTestAddrs(s1.BankKeeper, s1.StakingKeeper, ctx, 1, valTokens) - _, state := s1.app.Deliver(t, ctx, nil) - _, err = s1.app.Commit(state) - require.NoError(t, err) // Create two proposals, put the second into the voting period proposal1, err := s1.GovKeeper.SubmitProposal(ctx, []sdk.Msg{mkTestLegacyContent(t)}, "", "test", "description", addrs[0], v1.ProposalType_PROPOSAL_TYPE_STANDARD) assert.NilError(t, err) @@ -72,7 +68,9 @@ func TestImportExportQueues(t *testing.T) { require.NoError(t, err) // export the state and import it into a new app - govGenState, _ := gov.ExportGenesis(ctx, s1.GovKeeper) + govGenState, err := gov.ExportGenesis(ctx, s1.GovKeeper) + require.NoError(t, err) + genesisState := s1.app.DefaultGenesis() genesisState[authtypes.ModuleName] = s1.cdc.MustMarshalJSON(authGenState) @@ -83,7 +81,7 @@ func TestImportExportQueues(t *testing.T) { stateBytes, err := json.MarshalIndent(genesisState, "", " ") assert.NilError(t, err) - s2 := createTestSuite(t) + s2 := createTestSuite(t, integration.Genesis_SKIP) emptyHash := sha256.Sum256(nil) _, newstate, err := s2.app.InitGenesis( @@ -135,24 +133,8 @@ func TestImportExportQueues(t *testing.T) { assert.Assert(t, proposal2.Status == v1.StatusRejected) } -func clearDB(t *testing.T, db corestore.KVStoreWithBatch) { - t.Helper() - iter, err := db.Iterator(nil, nil) - assert.NilError(t, err) - defer iter.Close() - - var keys [][]byte - for ; iter.Valid(); iter.Next() { - keys = append(keys, iter.Key()) - } - - for _, k := range keys { - assert.NilError(t, db.Delete(k)) - } -} - func TestImportExportQueues_ErrorUnconsistentState(t *testing.T) { - suite := createTestSuite(t) + suite := createTestSuite(t, integration.Genesis_COMMIT) ctx := suite.ctx params := v1.DefaultParams() diff --git a/tests/integration/v2/gov/module_test.go b/tests/integration/v2/gov/module_test.go index a2b1e9c7dc99..338e11f32310 100644 --- a/tests/integration/v2/gov/module_test.go +++ b/tests/integration/v2/gov/module_test.go @@ -10,11 +10,12 @@ import ( _ "cosmossdk.io/x/mint" _ "cosmossdk.io/x/protocolpool" + "github.com/cosmos/cosmos-sdk/tests/integration/v2" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" ) func TestItCreatesModuleAccountOnInitBlock(t *testing.T) { - suite := createTestSuite(t) + suite := createTestSuite(t, integration.Genesis_COMMIT) ctx := suite.ctx acc := suite.AuthKeeper.GetAccount(ctx, authtypes.NewModuleAddress(types.ModuleName)) From 9fb64cf26a0e3a9417b36282e4455799c1cae2f0 Mon Sep 17 00:00:00 2001 From: sontrinh16 Date: Fri, 13 Dec 2024 02:42:00 +0700 Subject: [PATCH 3/8] go mod tidy all --- tests/go.mod | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/go.mod b/tests/go.mod index 18cc7999b3f8..fe959bd2666d 100644 --- a/tests/go.mod +++ b/tests/go.mod @@ -51,6 +51,7 @@ require ( cosmossdk.io/x/staking v0.0.0-20240226161501-23359a0b6d91 github.com/cometbft/cometbft/api v1.0.0-rc2 github.com/cosmos/cosmos-db v1.1.0 + github.com/gogo/protobuf v1.3.2 github.com/google/go-cmp v0.6.0 github.com/google/gofuzz v1.2.0 github.com/jhump/protoreflect v1.17.0 @@ -125,7 +126,6 @@ require ( github.com/go-logr/stdr v1.2.2 // indirect github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 // indirect github.com/gogo/googleapis v1.4.1 // indirect - github.com/gogo/protobuf v1.3.2 // indirect github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect github.com/golang/protobuf v1.5.4 // indirect github.com/golang/snappy v0.0.4 // indirect From 89378401c46b96b3b5f9a530b17307f5e3e7cdec Mon Sep 17 00:00:00 2001 From: sontrinh16 Date: Fri, 13 Dec 2024 02:54:07 +0700 Subject: [PATCH 4/8] minor --- tests/integration/gov/genesis_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/integration/gov/genesis_test.go b/tests/integration/gov/genesis_test.go index 26aafed0ebfe..e273800cadbb 100644 --- a/tests/integration/gov/genesis_test.go +++ b/tests/integration/gov/genesis_test.go @@ -189,7 +189,7 @@ func TestImportExportQueues(t *testing.T) { proposal2, err = s2.GovKeeper.Proposals.Get(ctx2, proposalID2) assert.NilError(t, err) - assert.Assert(t, proposal2.Status != v1.StatusRejected) + assert.Assert(t, proposal2.Status == v1.StatusRejected) } func clearDB(t *testing.T, db corestore.KVStoreWithBatch) { From 05e8f051ae769c51892154bc3c8307791ee7e00d Mon Sep 17 00:00:00 2001 From: sontrinh16 Date: Fri, 13 Dec 2024 03:10:29 +0700 Subject: [PATCH 5/8] clean up --- tests/integration/gov/genesis_test.go | 3 --- 1 file changed, 3 deletions(-) diff --git a/tests/integration/gov/genesis_test.go b/tests/integration/gov/genesis_test.go index e273800cadbb..5f512be92a85 100644 --- a/tests/integration/gov/genesis_test.go +++ b/tests/integration/gov/genesis_test.go @@ -2,7 +2,6 @@ package gov_test import ( "encoding/json" - "fmt" "testing" abci "github.com/cometbft/cometbft/api/cometbft/abci/v1" @@ -120,8 +119,6 @@ func TestImportExportQueues(t *testing.T) { genesisState[types.ModuleName] = s1.cdc.MustMarshalJSON(govGenState) genesisState[stakingtypes.ModuleName] = s1.cdc.MustMarshalJSON(stakingGenState) - fmt.Print(authGenState) - stateBytes, err := json.MarshalIndent(genesisState, "", " ") assert.NilError(t, err) From 2febc4c4bf4a99bad94110b756f0a82cfce75159 Mon Sep 17 00:00:00 2001 From: sontrinh16 Date: Fri, 13 Dec 2024 14:41:08 +0700 Subject: [PATCH 6/8] address comment --- tests/integration/v2/app.go | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/integration/v2/app.go b/tests/integration/v2/app.go index f891e4557bc9..abb55a748082 100644 --- a/tests/integration/v2/app.go +++ b/tests/integration/v2/app.go @@ -346,7 +346,6 @@ func (a *App) Deliver( iCtx, ok := ctx.Value(contextKey).(*integrationContext) if ok { iCtx.header.Height = int64(a.lastHeight) - iCtx.header.Time = time.Now() } return resp, state } From eb1cb5056e5dcb4bc1ca8b6523d39550af8c3068 Mon Sep 17 00:00:00 2001 From: sontrinh16 Date: Fri, 13 Dec 2024 14:42:29 +0700 Subject: [PATCH 7/8] remove v1 tests --- tests/integration/gov/abci_test.go | 676 ------------------ tests/integration/gov/common_test.go | 126 ---- tests/integration/gov/genesis_test.go | 235 ------ tests/integration/gov/keeper/common_test.go | 72 -- .../integration/gov/keeper/grpc_query_test.go | 76 -- tests/integration/gov/keeper/keeper_test.go | 180 ----- tests/integration/gov/keeper/tally_test.go | 518 -------------- tests/integration/gov/module_test.go | 43 -- 8 files changed, 1926 deletions(-) delete mode 100644 tests/integration/gov/abci_test.go delete mode 100644 tests/integration/gov/common_test.go delete mode 100644 tests/integration/gov/genesis_test.go delete mode 100644 tests/integration/gov/keeper/common_test.go delete mode 100644 tests/integration/gov/keeper/grpc_query_test.go delete mode 100644 tests/integration/gov/keeper/keeper_test.go delete mode 100644 tests/integration/gov/keeper/tally_test.go delete mode 100644 tests/integration/gov/module_test.go diff --git a/tests/integration/gov/abci_test.go b/tests/integration/gov/abci_test.go deleted file mode 100644 index ff1664ed4f0d..000000000000 --- a/tests/integration/gov/abci_test.go +++ /dev/null @@ -1,676 +0,0 @@ -package gov_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/require" - - "cosmossdk.io/collections" - "cosmossdk.io/math" - banktypes "cosmossdk.io/x/bank/types" - "cosmossdk.io/x/gov/keeper" - "cosmossdk.io/x/gov/types" - v1 "cosmossdk.io/x/gov/types/v1" - stakingkeeper "cosmossdk.io/x/staking/keeper" - stakingtypes "cosmossdk.io/x/staking/types" - - addresscodec "github.com/cosmos/cosmos-sdk/codec/address" - simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -func TestUnregisteredProposal_InactiveProposalFails(t *testing.T) { - suite := createTestSuite(t) - ctx := suite.app.BaseApp.NewContext(false) - addrs := simtestutil.AddTestAddrs(suite.BankKeeper, suite.StakingKeeper, ctx, 10, valTokens) - addr0Str, err := suite.AccountKeeper.AddressCodec().BytesToString(addrs[0]) - require.NoError(t, err) - - // manually set proposal in store - startTime, endTime := time.Now().Add(-4*time.Hour), ctx.BlockHeader().Time - proposal, err := v1.NewProposal([]sdk.Msg{ - &v1.Proposal{}, // invalid proposal message - }, 1, startTime, startTime, "", "Unsupported proposal", "Unsupported proposal", addr0Str, v1.ProposalType_PROPOSAL_TYPE_STANDARD) - require.NoError(t, err) - - err = suite.GovKeeper.Proposals.Set(ctx, proposal.Id, proposal) - require.NoError(t, err) - - // manually set proposal in inactive proposal queue - err = suite.GovKeeper.InactiveProposalsQueue.Set(ctx, collections.Join(endTime, proposal.Id), proposal.Id) - require.NoError(t, err) - - err = suite.GovKeeper.EndBlocker(ctx) - require.NoError(t, err) - - _, err = suite.GovKeeper.Proposals.Get(ctx, proposal.Id) - require.Error(t, err, collections.ErrNotFound) -} - -func TestUnregisteredProposal_ActiveProposalFails(t *testing.T) { - suite := createTestSuite(t) - ctx := suite.app.BaseApp.NewContext(false) - addrs := simtestutil.AddTestAddrs(suite.BankKeeper, suite.StakingKeeper, ctx, 10, valTokens) - addr0Str, err := suite.AccountKeeper.AddressCodec().BytesToString(addrs[0]) - require.NoError(t, err) - // manually set proposal in store - startTime, endTime := time.Now().Add(-4*time.Hour), ctx.BlockHeader().Time - proposal, err := v1.NewProposal([]sdk.Msg{ - &v1.Proposal{}, // invalid proposal message - }, 1, startTime, startTime, "", "Unsupported proposal", "Unsupported proposal", addr0Str, v1.ProposalType_PROPOSAL_TYPE_STANDARD) - require.NoError(t, err) - proposal.Status = v1.StatusVotingPeriod - proposal.VotingEndTime = &endTime - - err = suite.GovKeeper.Proposals.Set(ctx, proposal.Id, proposal) - require.NoError(t, err) - - // manually set proposal in active proposal queue - err = suite.GovKeeper.ActiveProposalsQueue.Set(ctx, collections.Join(endTime, proposal.Id), proposal.Id) - require.NoError(t, err) - - err = suite.GovKeeper.EndBlocker(ctx) - require.NoError(t, err) - - p, err := suite.GovKeeper.Proposals.Get(ctx, proposal.Id) - require.NoError(t, err) - require.Equal(t, v1.StatusFailed, p.Status) -} - -func TestTickExpiredDepositPeriod(t *testing.T) { - suite := createTestSuite(t) - app := suite.app - ctx := app.BaseApp.NewContext(false) - addrs := simtestutil.AddTestAddrs(suite.BankKeeper, suite.StakingKeeper, ctx, 10, valTokens) - - govMsgSvr := keeper.NewMsgServerImpl(suite.GovKeeper) - - newProposalMsg, err := v1.NewMsgSubmitProposal( - []sdk.Msg{mkTestLegacyContent(t)}, - sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 100000)}, - addrs[0].String(), - "", - "Proposal", - "description of proposal", - v1.ProposalType_PROPOSAL_TYPE_STANDARD, - ) - require.NoError(t, err) - - res, err := govMsgSvr.SubmitProposal(ctx, newProposalMsg) - require.NoError(t, err) - require.NotNil(t, res) - - newHeader := ctx.HeaderInfo() - newHeader.Time = ctx.HeaderInfo().Time.Add(time.Duration(1) * time.Second) - ctx = ctx.WithHeaderInfo(newHeader) - - params, _ := suite.GovKeeper.Params.Get(ctx) - newHeader = ctx.HeaderInfo() - newHeader.Time = ctx.HeaderInfo().Time.Add(*params.MaxDepositPeriod) - ctx = ctx.WithHeaderInfo(newHeader) - - err = suite.GovKeeper.EndBlocker(ctx) - require.NoError(t, err) -} - -func TestTickMultipleExpiredDepositPeriod(t *testing.T) { - suite := createTestSuite(t) - app := suite.app - ctx := app.BaseApp.NewContext(false) - addrs := simtestutil.AddTestAddrs(suite.BankKeeper, suite.StakingKeeper, ctx, 10, valTokens) - govMsgSvr := keeper.NewMsgServerImpl(suite.GovKeeper) - - newProposalMsg, err := v1.NewMsgSubmitProposal( - []sdk.Msg{mkTestLegacyContent(t)}, - sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 100000)}, - addrs[0].String(), - "", - "Proposal", - "description of proposal", - v1.ProposalType_PROPOSAL_TYPE_STANDARD, - ) - require.NoError(t, err) - - res, err := govMsgSvr.SubmitProposal(ctx, newProposalMsg) - require.NoError(t, err) - require.NotNil(t, res) - - newHeader := ctx.HeaderInfo() - newHeader.Time = ctx.HeaderInfo().Time.Add(time.Duration(2) * time.Second) - ctx = ctx.WithHeaderInfo(newHeader) - - newProposalMsg2, err := v1.NewMsgSubmitProposal( - []sdk.Msg{mkTestLegacyContent(t)}, - sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 100000)}, - addrs[0].String(), - "", - "Proposal", - "description of proposal", - v1.ProposalType_PROPOSAL_TYPE_STANDARD, - ) - require.NoError(t, err) - - res, err = govMsgSvr.SubmitProposal(ctx, newProposalMsg2) - require.NoError(t, err) - require.NotNil(t, res) - - newHeader = ctx.HeaderInfo() - params, _ := suite.GovKeeper.Params.Get(ctx) - newHeader.Time = ctx.HeaderInfo().Time.Add(*params.MaxDepositPeriod).Add(time.Duration(-1) * time.Second) - ctx = ctx.WithHeaderInfo(newHeader) - - require.NoError(t, suite.GovKeeper.EndBlocker(ctx)) - - newHeader = ctx.HeaderInfo() - newHeader.Time = ctx.HeaderInfo().Time.Add(time.Duration(5) * time.Second) - ctx = ctx.WithHeaderInfo(newHeader) - require.NoError(t, suite.GovKeeper.EndBlocker(ctx)) -} - -func TestTickPassedDepositPeriod(t *testing.T) { - suite := createTestSuite(t) - app := suite.app - ctx := app.BaseApp.NewContext(false) - addrs := simtestutil.AddTestAddrs(suite.BankKeeper, suite.StakingKeeper, ctx, 10, valTokens) - govMsgSvr := keeper.NewMsgServerImpl(suite.GovKeeper) - - newProposalMsg, err := v1.NewMsgSubmitProposal( - []sdk.Msg{mkTestLegacyContent(t)}, - sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 100000)}, - addrs[0].String(), - "", - "Proposal", - "description of proposal", - v1.ProposalType_PROPOSAL_TYPE_STANDARD, - ) - require.NoError(t, err) - - res, err := govMsgSvr.SubmitProposal(ctx, newProposalMsg) - require.NoError(t, err) - require.NotNil(t, res) - - proposalID := res.ProposalId - - newHeader := ctx.HeaderInfo() - newHeader.Time = ctx.HeaderInfo().Time.Add(time.Duration(1) * time.Second) - ctx = ctx.WithHeaderInfo(newHeader) - - addr1Str, err := suite.AccountKeeper.AddressCodec().BytesToString(addrs[1]) - require.NoError(t, err) - newDepositMsg := v1.NewMsgDeposit(addr1Str, proposalID, sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 100000)}) - - res1, err := govMsgSvr.Deposit(ctx, newDepositMsg) - require.NoError(t, err) - require.NotNil(t, res1) -} - -func TestProposalDepositRefundFailEndBlocker(t *testing.T) { - suite := createTestSuite(t) - app := suite.app - ctx := app.BaseApp.NewContext(false) - addrs := simtestutil.AddTestAddrs(suite.BankKeeper, suite.StakingKeeper, ctx, 10, valTokens) - govMsgSvr := keeper.NewMsgServerImpl(suite.GovKeeper) - - depositMultiplier := getDepositMultiplier(v1.ProposalType_PROPOSAL_TYPE_STANDARD) - proposalCoins := sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, suite.StakingKeeper.TokensFromConsensusPower(ctx, 15*depositMultiplier))} - - // create a proposal that empties the gov module account - // which will cause the proposal deposit refund to fail - newProposalMsg, err := v1.NewMsgSubmitProposal( - []sdk.Msg{}, - proposalCoins, - addrs[0].String(), - "metadata", - "proposal", - "description of proposal", - v1.ProposalType_PROPOSAL_TYPE_STANDARD, - ) - require.NoError(t, err) - - res, err := govMsgSvr.SubmitProposal(ctx, newProposalMsg) - require.NoError(t, err) - require.NotNil(t, res) - - proposal, err := suite.GovKeeper.Proposals.Get(ctx, res.ProposalId) - require.NoError(t, err) - require.Equal(t, v1.StatusVotingPeriod, proposal.Status) - - proposalID := res.ProposalId - err = suite.GovKeeper.AddVote(ctx, proposalID, addrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), "metadata") - require.NoError(t, err) - - // empty the gov module account before the proposal ends - err = suite.BankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, addrs[1], proposalCoins) - require.NoError(t, err) - - // fast forward to the end of the voting period - newHeader := ctx.HeaderInfo() - newHeader.Time = proposal.VotingEndTime.Add(time.Duration(100) * time.Second) - ctx = ctx.WithHeaderInfo(newHeader) - - err = suite.GovKeeper.EndBlocker(ctx) - require.NoError(t, err) // no error, means does not halt the chain - - events := ctx.EventManager().Events() - attr, ok := events.GetAttributes(types.AttributeKeyProposalDepositError) - require.True(t, ok) - require.Contains(t, attr[0].Value, "failed to refund or burn deposits") -} - -func TestTickPassedVotingPeriod(t *testing.T) { - testcases := []struct { - name string - proposalType v1.ProposalType - }{ - { - name: "regular - deleted", - }, - { - name: "expedited - converted to regular", - proposalType: v1.ProposalType_PROPOSAL_TYPE_EXPEDITED, - }, - } - - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - suite := createTestSuite(t) - app := suite.app - ctx := app.BaseApp.NewContext(false) - depositMultiplier := getDepositMultiplier(tc.proposalType) - addrs := simtestutil.AddTestAddrs(suite.BankKeeper, suite.StakingKeeper, ctx, 10, valTokens.Mul(math.NewInt(depositMultiplier))) - - SortAddresses(addrs) - govMsgSvr := keeper.NewMsgServerImpl(suite.GovKeeper) - - proposalCoins := sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, suite.StakingKeeper.TokensFromConsensusPower(ctx, 5*depositMultiplier))} - newProposalMsg, err := v1.NewMsgSubmitProposal([]sdk.Msg{mkTestLegacyContent(t)}, proposalCoins, addrs[0].String(), "", "Proposal", "description of proposal", tc.proposalType) - require.NoError(t, err) - - res, err := govMsgSvr.SubmitProposal(ctx, newProposalMsg) - require.NoError(t, err) - require.NotNil(t, res) - - proposalID := res.ProposalId - - newHeader := ctx.HeaderInfo() - newHeader.Time = ctx.HeaderInfo().Time.Add(time.Duration(1) * time.Second) - ctx = ctx.WithHeaderInfo(newHeader) - - addr1Str, err := suite.AccountKeeper.AddressCodec().BytesToString(addrs[1]) - require.NoError(t, err) - newDepositMsg := v1.NewMsgDeposit(addr1Str, proposalID, proposalCoins) - - res1, err := govMsgSvr.Deposit(ctx, newDepositMsg) - require.NoError(t, err) - require.NotNil(t, res1) - - params, _ := suite.GovKeeper.Params.Get(ctx) - votingPeriod := params.VotingPeriod - if tc.proposalType == v1.ProposalType_PROPOSAL_TYPE_EXPEDITED { - votingPeriod = params.ExpeditedVotingPeriod - } - - newHeader = ctx.HeaderInfo() - newHeader.Time = ctx.HeaderInfo().Time.Add(*params.MaxDepositPeriod).Add(*votingPeriod) - ctx = ctx.WithHeaderInfo(newHeader) - - proposal, err := suite.GovKeeper.Proposals.Get(ctx, res.ProposalId) - require.NoError(t, err) - require.Equal(t, v1.StatusVotingPeriod, proposal.Status) - - err = suite.GovKeeper.EndBlocker(ctx) - require.NoError(t, err) - - if tc.proposalType != v1.ProposalType_PROPOSAL_TYPE_EXPEDITED { - return - } - - // If expedited, it should be converted to a regular proposal instead. - proposal, err = suite.GovKeeper.Proposals.Get(ctx, res.ProposalId) - require.Nil(t, err) - require.Equal(t, v1.StatusVotingPeriod, proposal.Status) - require.False(t, proposal.ProposalType == v1.ProposalType_PROPOSAL_TYPE_EXPEDITED) - require.Equal(t, proposal.VotingStartTime.Add(*params.VotingPeriod), *proposal.VotingEndTime) - }) - } -} - -func TestProposalPassedEndblocker(t *testing.T) { - testcases := []struct { - name string - proposalType v1.ProposalType - }{ - { - name: "regular", - proposalType: v1.ProposalType_PROPOSAL_TYPE_STANDARD, - }, - { - name: "expedited", - proposalType: v1.ProposalType_PROPOSAL_TYPE_EXPEDITED, - }, - } - - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - suite := createTestSuite(t) - app := suite.app - ctx := app.BaseApp.NewContext(false) - depositMultiplier := getDepositMultiplier(tc.proposalType) - addrs := simtestutil.AddTestAddrs(suite.BankKeeper, suite.StakingKeeper, ctx, 10, valTokens.Mul(math.NewInt(depositMultiplier))) - - SortAddresses(addrs) - - govMsgSvr := keeper.NewMsgServerImpl(suite.GovKeeper) - stakingMsgSvr := stakingkeeper.NewMsgServerImpl(suite.StakingKeeper) - valAddr := sdk.ValAddress(addrs[0]) - proposer := addrs[0] - acc := suite.AccountKeeper.NewAccountWithAddress(ctx, addrs[0]) - suite.AccountKeeper.SetAccount(ctx, acc) - - createValidators(t, stakingMsgSvr, ctx, []sdk.ValAddress{valAddr}, []int64{10}) - _, err := suite.StakingKeeper.EndBlocker(ctx) - require.NoError(t, err) - macc := suite.GovKeeper.GetGovernanceAccount(ctx) - require.NotNil(t, macc) - initialModuleAccCoins := suite.BankKeeper.GetAllBalances(ctx, macc.GetAddress()) - - proposal, err := suite.GovKeeper.SubmitProposal(ctx, []sdk.Msg{mkTestLegacyContent(t)}, "", "title", "summary", proposer, tc.proposalType) - require.NoError(t, err) - - proposalCoins := sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, suite.StakingKeeper.TokensFromConsensusPower(ctx, 10*depositMultiplier))} - addr0Str, err := suite.AccountKeeper.AddressCodec().BytesToString(addrs[0]) - require.NoError(t, err) - newDepositMsg := v1.NewMsgDeposit(addr0Str, proposal.Id, proposalCoins) - - res, err := govMsgSvr.Deposit(ctx, newDepositMsg) - require.NoError(t, err) - require.NotNil(t, res) - - macc = suite.GovKeeper.GetGovernanceAccount(ctx) - require.NotNil(t, macc) - moduleAccCoins := suite.BankKeeper.GetAllBalances(ctx, macc.GetAddress()) - - deposits := initialModuleAccCoins.Add(proposal.TotalDeposit...).Add(proposalCoins...) - require.True(t, moduleAccCoins.Equal(deposits)) - - err = suite.GovKeeper.AddVote(ctx, proposal.Id, addrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), "") - require.NoError(t, err) - - newHeader := ctx.HeaderInfo() - params, _ := suite.GovKeeper.Params.Get(ctx) - newHeader.Time = ctx.HeaderInfo().Time.Add(*params.MaxDepositPeriod).Add(*params.VotingPeriod) - ctx = ctx.WithHeaderInfo(newHeader) - - err = suite.GovKeeper.EndBlocker(ctx) - require.NoError(t, err) - macc = suite.GovKeeper.GetGovernanceAccount(ctx) - require.NotNil(t, macc) - require.True(t, suite.BankKeeper.GetAllBalances(ctx, macc.GetAddress()).Equal(initialModuleAccCoins)) - }) - } -} - -func TestEndBlockerProposalHandlerFailed(t *testing.T) { - suite := createTestSuite(t) - app := suite.app - ctx := app.BaseApp.NewContext(false) - addrs := simtestutil.AddTestAddrs(suite.BankKeeper, suite.StakingKeeper, ctx, 1, valTokens) - - SortAddresses(addrs) - - stakingMsgSvr := stakingkeeper.NewMsgServerImpl(suite.StakingKeeper) - - valAddr := sdk.ValAddress(addrs[0]) - proposer := addrs[0] - - ac := addresscodec.NewBech32Codec("cosmos") - addrStr, err := ac.BytesToString(authtypes.NewModuleAddress(types.ModuleName)) - require.NoError(t, err) - toAddrStr, err := ac.BytesToString(addrs[0]) - require.NoError(t, err) - - acc := suite.AccountKeeper.NewAccountWithAddress(ctx, addrs[0]) - suite.AccountKeeper.SetAccount(ctx, acc) - - createValidators(t, stakingMsgSvr, ctx, []sdk.ValAddress{valAddr}, []int64{10}) - _, err = suite.StakingKeeper.EndBlocker(ctx) - require.NoError(t, err) - msg := banktypes.NewMsgSend(addrStr, toAddrStr, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(100000)))) - proposal, err := suite.GovKeeper.SubmitProposal(ctx, []sdk.Msg{msg}, "", "title", "summary", proposer, v1.ProposalType_PROPOSAL_TYPE_STANDARD) - require.NoError(t, err) - - proposalCoins := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, suite.StakingKeeper.TokensFromConsensusPower(ctx, 10))) - addr0Str, err := suite.AccountKeeper.AddressCodec().BytesToString(addrs[0]) - require.NoError(t, err) - newDepositMsg := v1.NewMsgDeposit(addr0Str, proposal.Id, proposalCoins) - - govMsgSvr := keeper.NewMsgServerImpl(suite.GovKeeper) - res, err := govMsgSvr.Deposit(ctx, newDepositMsg) - require.NoError(t, err) - require.NotNil(t, res) - - err = suite.GovKeeper.AddVote(ctx, proposal.Id, addrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), "") - require.NoError(t, err) - - params, _ := suite.GovKeeper.Params.Get(ctx) - newHeader := ctx.HeaderInfo() - newHeader.Time = ctx.HeaderInfo().Time.Add(*params.MaxDepositPeriod).Add(*params.VotingPeriod) - ctx = ctx.WithHeaderInfo(newHeader) - - // validate that the proposal fails/has been rejected - err = suite.GovKeeper.EndBlocker(ctx) - require.NoError(t, err) - // check proposal events - events := ctx.EventManager().Events() - attr, eventOk := events.GetAttributes(types.AttributeKeyProposalLog) - require.True(t, eventOk) - require.Contains(t, attr[0].Value, "failed on execution") - - proposal, err = suite.GovKeeper.Proposals.Get(ctx, proposal.Id) - require.Nil(t, err) - require.Equal(t, v1.StatusFailed, proposal.Status) -} - -func TestExpeditedProposal_PassAndConversionToRegular(t *testing.T) { - testcases := []struct { - name string - // indicates whether the expedited proposal passes. - expeditedPasses bool - // indicates whether the converted regular proposal is expected to eventually pass - regularEventuallyPassing bool - }{ - { - name: "expedited passes and not converted to regular", - expeditedPasses: true, - }, - { - name: "expedited fails, converted to regular - regular eventually passes", - expeditedPasses: false, - regularEventuallyPassing: true, - }, - { - name: "expedited fails, converted to regular - regular eventually fails", - expeditedPasses: false, - regularEventuallyPassing: false, - }, - } - - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - suite := createTestSuite(t) - app := suite.app - ctx := app.BaseApp.NewContext(false) - depositMultiplier := getDepositMultiplier(v1.ProposalType_PROPOSAL_TYPE_EXPEDITED) - addrs := simtestutil.AddTestAddrs(suite.BankKeeper, suite.StakingKeeper, ctx, 3, valTokens.Mul(math.NewInt(depositMultiplier))) - params, err := suite.GovKeeper.Params.Get(ctx) - require.NoError(t, err) - - SortAddresses(addrs) - - govMsgSvr := keeper.NewMsgServerImpl(suite.GovKeeper) - stakingMsgSvr := stakingkeeper.NewMsgServerImpl(suite.StakingKeeper) - valAddr := sdk.ValAddress(addrs[0]) - proposer := addrs[0] - - acc := suite.AccountKeeper.NewAccountWithAddress(ctx, addrs[0]) - suite.AccountKeeper.SetAccount(ctx, acc) - // Create a validator so that able to vote on proposal. - createValidators(t, stakingMsgSvr, ctx, []sdk.ValAddress{valAddr}, []int64{10}) - _, err = suite.StakingKeeper.EndBlocker(ctx) - require.NoError(t, err) - - macc := suite.GovKeeper.GetGovernanceAccount(ctx) - require.NotNil(t, macc) - initialModuleAccCoins := suite.BankKeeper.GetAllBalances(ctx, macc.GetAddress()) - - submitterInitialBalance := suite.BankKeeper.GetAllBalances(ctx, addrs[0]) - depositorInitialBalance := suite.BankKeeper.GetAllBalances(ctx, addrs[1]) - - proposalCoins := sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, suite.StakingKeeper.TokensFromConsensusPower(ctx, 5*depositMultiplier))} - newProposalMsg, err := v1.NewMsgSubmitProposal([]sdk.Msg{}, proposalCoins, proposer.String(), "metadata", "title", "summary", v1.ProposalType_PROPOSAL_TYPE_EXPEDITED) - require.NoError(t, err) - - res, err := govMsgSvr.SubmitProposal(ctx, newProposalMsg) - require.NoError(t, err) - require.NotNil(t, res) - - proposalID := res.ProposalId - - newHeader := ctx.HeaderInfo() - newHeader.Time = ctx.HeaderInfo().Time.Add(time.Duration(1) * time.Second) - ctx = ctx.WithHeaderInfo(newHeader) - - addr1Str, err := suite.AccountKeeper.AddressCodec().BytesToString(addrs[1]) - require.NoError(t, err) - newDepositMsg := v1.NewMsgDeposit(addr1Str, proposalID, proposalCoins) - - res1, err := govMsgSvr.Deposit(ctx, newDepositMsg) - require.NoError(t, err) - require.NotNil(t, res1) - - newHeader = ctx.HeaderInfo() - newHeader.Time = ctx.HeaderInfo().Time.Add(*params.MaxDepositPeriod).Add(*params.ExpeditedVotingPeriod) - ctx = ctx.WithHeaderInfo(newHeader) - - proposal, err := suite.GovKeeper.Proposals.Get(ctx, res.ProposalId) - require.Nil(t, err) - require.Equal(t, v1.StatusVotingPeriod, proposal.Status) - - if tc.expeditedPasses { - // Validator votes YES, letting the expedited proposal pass. - err = suite.GovKeeper.AddVote(ctx, proposal.Id, addrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), "metadata") - require.NoError(t, err) - } - - // Here the expedited proposal is converted to regular after expiry. - err = suite.GovKeeper.EndBlocker(ctx) - require.NoError(t, err) - if tc.expeditedPasses { - proposal, err = suite.GovKeeper.Proposals.Get(ctx, res.ProposalId) - require.Nil(t, err) - - require.Equal(t, v1.StatusPassed, proposal.Status) - - submitterEventualBalance := suite.BankKeeper.GetAllBalances(ctx, addrs[0]) - depositorEventualBalance := suite.BankKeeper.GetAllBalances(ctx, addrs[1]) - - eventualModuleAccCoins := suite.BankKeeper.GetAllBalances(ctx, macc.GetAddress()) - - // Module account has refunded the deposit - require.Equal(t, initialModuleAccCoins, eventualModuleAccCoins) - - require.Equal(t, submitterInitialBalance, submitterEventualBalance) - require.Equal(t, depositorInitialBalance, depositorEventualBalance) - return - } - - // Expedited proposal should be converted to a regular proposal instead. - proposal, err = suite.GovKeeper.Proposals.Get(ctx, res.ProposalId) - require.Nil(t, err) - require.Equal(t, v1.StatusVotingPeriod, proposal.Status) - require.False(t, proposal.ProposalType == v1.ProposalType_PROPOSAL_TYPE_EXPEDITED) - require.Equal(t, proposal.VotingStartTime.Add(*params.VotingPeriod), *proposal.VotingEndTime) - - // We also want to make sure that the deposit is not refunded yet and is still present in the module account - macc = suite.GovKeeper.GetGovernanceAccount(ctx) - require.NotNil(t, macc) - intermediateModuleAccCoins := suite.BankKeeper.GetAllBalances(ctx, macc.GetAddress()) - require.NotEqual(t, initialModuleAccCoins, intermediateModuleAccCoins) - - // Submit proposal deposit + 1 extra top up deposit - expectedIntermediateMofuleAccCoings := initialModuleAccCoins.Add(proposalCoins...).Add(proposalCoins...) - require.Equal(t, expectedIntermediateMofuleAccCoings, intermediateModuleAccCoins) - - // block header time at the voting period - newHeader.Time = ctx.HeaderInfo().Time.Add(*params.MaxDepositPeriod).Add(*params.VotingPeriod) - ctx = ctx.WithHeaderInfo(newHeader) - - if tc.regularEventuallyPassing { - // Validator votes YES, letting the converted regular proposal pass. - err = suite.GovKeeper.AddVote(ctx, proposal.Id, addrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), "metadata") - require.NoError(t, err) - } - - // Here we validate the converted regular proposal - err = suite.GovKeeper.EndBlocker(ctx) - require.NoError(t, err) - macc = suite.GovKeeper.GetGovernanceAccount(ctx) - require.NotNil(t, macc) - eventualModuleAccCoins := suite.BankKeeper.GetAllBalances(ctx, macc.GetAddress()) - - submitterEventualBalance := suite.BankKeeper.GetAllBalances(ctx, addrs[0]) - depositorEventualBalance := suite.BankKeeper.GetAllBalances(ctx, addrs[1]) - - proposal, err = suite.GovKeeper.Proposals.Get(ctx, res.ProposalId) - require.Nil(t, err) - - if tc.regularEventuallyPassing { - // Module account has refunded the deposit - require.Equal(t, initialModuleAccCoins, eventualModuleAccCoins) - require.Equal(t, submitterInitialBalance, submitterEventualBalance) - require.Equal(t, depositorInitialBalance, depositorEventualBalance) - - require.Equal(t, v1.StatusPassed, proposal.Status) - return - } - - // Not enough votes - module account has returned the deposit - require.Equal(t, initialModuleAccCoins, eventualModuleAccCoins) - require.Equal(t, submitterInitialBalance, submitterEventualBalance) - require.Equal(t, depositorInitialBalance, depositorEventualBalance) - - require.Equal(t, v1.StatusRejected, proposal.Status) - }) - } -} - -func createValidators(t *testing.T, stakingMsgSvr stakingtypes.MsgServer, ctx sdk.Context, addrs []sdk.ValAddress, powerAmt []int64) { - t.Helper() - 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], sdk.DefaultPowerReduction) - valCreateMsg, err := stakingtypes.NewMsgCreateValidator( - addrs[i].String(), pubkeys[i], sdk.NewCoin(sdk.DefaultBondDenom, valTokens), - TestDescription, TestCommissionRates, math.OneInt(), - ) - require.NoError(t, err) - res, err := stakingMsgSvr.CreateValidator(ctx, valCreateMsg) - require.NoError(t, err) - require.NotNil(t, res) - } -} - -// With expedited proposal's minimum deposit set higher than the default deposit, we must -// initialize and deposit an amount depositMultiplier times larger -// than the regular min deposit amount. -func getDepositMultiplier(proposalType v1.ProposalType) int64 { - switch proposalType { - case v1.ProposalType_PROPOSAL_TYPE_EXPEDITED: - return v1.DefaultMinExpeditedDepositTokensRatio - default: - return 1 - } -} diff --git a/tests/integration/gov/common_test.go b/tests/integration/gov/common_test.go deleted file mode 100644 index b2fe831877ee..000000000000 --- a/tests/integration/gov/common_test.go +++ /dev/null @@ -1,126 +0,0 @@ -package gov_test - -import ( - "bytes" - "log" - "sort" - "testing" - - "github.com/stretchr/testify/require" - "gotest.tools/v3/assert" - - "cosmossdk.io/depinject" - sdklog "cosmossdk.io/log" - "cosmossdk.io/math" - _ "cosmossdk.io/x/accounts" - _ "cosmossdk.io/x/bank" - _ "cosmossdk.io/x/consensus" - "cosmossdk.io/x/gov/types" - v1 "cosmossdk.io/x/gov/types/v1" - "cosmossdk.io/x/gov/types/v1beta1" - _ "cosmossdk.io/x/protocolpool" - _ "cosmossdk.io/x/staking" - stakingtypes "cosmossdk.io/x/staking/types" - - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" - cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" - "github.com/cosmos/cosmos-sdk/testutil/configurator" - simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" - sdk "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/cosmos-sdk/x/auth" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -var ( - valTokens = sdk.TokensFromConsensusPower(42, sdk.DefaultPowerReduction) - TestProposal = v1beta1.NewTextProposal("Test", "description") - TestDescription = stakingtypes.NewDescription("T", "E", "S", "T", "Z", &stakingtypes.Metadata{}) - TestCommissionRates = stakingtypes.NewCommissionRates(math.LegacyZeroDec(), math.LegacyZeroDec(), math.LegacyZeroDec()) -) - -// mkTestLegacyContent creates a MsgExecLegacyContent for testing purposes. -func mkTestLegacyContent(t *testing.T) *v1.MsgExecLegacyContent { - t.Helper() - msgContent, err := v1.NewLegacyContent(TestProposal, authtypes.NewModuleAddress(types.ModuleName).String()) - assert.NilError(t, err) - - return msgContent -} - -var pubkeys = []cryptotypes.PubKey{ - ed25519.GenPrivKey().PubKey(), - ed25519.GenPrivKey().PubKey(), - ed25519.GenPrivKey().PubKey(), -} - -// SortAddresses - Sorts Addresses -func SortAddresses(addrs []sdk.AccAddress) { - byteAddrs := make([][]byte, len(addrs)) - - for i, addr := range addrs { - byteAddrs[i] = 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] -} - -// SortByteArrays - sorts the provided byte array -func SortByteArrays(src [][]byte) [][]byte { - sorted := sortByteArrays(src) - sort.Sort(sorted) - return sorted -} - -func createTestSuite(t *testing.T) suite { - t.Helper() - res := suite{} - - app, err := simtestutil.SetupWithConfiguration( - depinject.Configs( - configurator.NewAppConfig( - configurator.AccountsModule(), - configurator.AuthModule(), - configurator.StakingModule(), - configurator.BankModule(), - configurator.GovModule(), - configurator.ConsensusModule(), - configurator.ProtocolPoolModule(), - ), - depinject.Supply(sdklog.NewNopLogger()), - ), - simtestutil.DefaultStartUpConfig(), - &res.AccountKeeper, &res.BankKeeper, &res.GovKeeper, &res.StakingKeeper, - ) - require.NoError(t, err) - - res.app = app - return res -} diff --git a/tests/integration/gov/genesis_test.go b/tests/integration/gov/genesis_test.go deleted file mode 100644 index 5f512be92a85..000000000000 --- a/tests/integration/gov/genesis_test.go +++ /dev/null @@ -1,235 +0,0 @@ -package gov_test - -import ( - "encoding/json" - "testing" - - abci "github.com/cometbft/cometbft/api/cometbft/abci/v1" - "github.com/stretchr/testify/require" - "gotest.tools/v3/assert" - - "cosmossdk.io/core/header" - corestore "cosmossdk.io/core/store" - coretesting "cosmossdk.io/core/testing" - "cosmossdk.io/depinject" - "cosmossdk.io/log" - sdkmath "cosmossdk.io/math" - _ "cosmossdk.io/x/accounts" - _ "cosmossdk.io/x/bank" - bankkeeper "cosmossdk.io/x/bank/keeper" - banktypes "cosmossdk.io/x/bank/types" - _ "cosmossdk.io/x/consensus" - "cosmossdk.io/x/gov" - "cosmossdk.io/x/gov/keeper" - "cosmossdk.io/x/gov/types" - v1 "cosmossdk.io/x/gov/types/v1" - _ "cosmossdk.io/x/staking" - stakingkeeper "cosmossdk.io/x/staking/keeper" - stakingtypes "cosmossdk.io/x/staking/types" - - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/runtime" - "github.com/cosmos/cosmos-sdk/testutil/configurator" - simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" - sdk "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/cosmos-sdk/x/auth" - authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -type suite struct { - cdc codec.Codec - app *runtime.App - AccountKeeper authkeeper.AccountKeeper - BankKeeper bankkeeper.Keeper - GovKeeper *keeper.Keeper - StakingKeeper *stakingkeeper.Keeper - appBuilder *runtime.AppBuilder -} - -var appConfig = configurator.NewAppConfig( - configurator.AccountsModule(), - configurator.AuthModule(), - configurator.StakingModule(), - configurator.BankModule(), - configurator.GovModule(), - configurator.MintModule(), - configurator.ConsensusModule(), - configurator.ProtocolPoolModule(), -) - -func TestImportExportQueues(t *testing.T) { - var err error - - s1 := suite{} - s1.app, err = simtestutil.SetupWithConfiguration( - depinject.Configs( - appConfig, - depinject.Supply(log.NewNopLogger()), - ), - simtestutil.DefaultStartUpConfig(), - &s1.AccountKeeper, &s1.BankKeeper, &s1.GovKeeper, &s1.StakingKeeper, &s1.cdc, &s1.appBuilder, - ) - assert.NilError(t, err) - - ctx := s1.app.BaseApp.NewContext(false) - addrs := simtestutil.AddTestAddrs(s1.BankKeeper, s1.StakingKeeper, ctx, 1, valTokens) - - _, err = s1.app.FinalizeBlock(&abci.FinalizeBlockRequest{ - Height: s1.app.LastBlockHeight() + 1, - }) - assert.NilError(t, err) - - ctx = s1.app.BaseApp.NewContext(false) - // Create two proposals, put the second into the voting period - proposal1, err := s1.GovKeeper.SubmitProposal(ctx, []sdk.Msg{mkTestLegacyContent(t)}, "", "test", "description", addrs[0], v1.ProposalType_PROPOSAL_TYPE_STANDARD) - assert.NilError(t, err) - proposalID1 := proposal1.Id - - proposal2, err := s1.GovKeeper.SubmitProposal(ctx, []sdk.Msg{mkTestLegacyContent(t)}, "", "test", "description", addrs[0], v1.ProposalType_PROPOSAL_TYPE_STANDARD) - assert.NilError(t, err) - proposalID2 := proposal2.Id - - params, err := s1.GovKeeper.Params.Get(ctx) - assert.NilError(t, err) - votingStarted, err := s1.GovKeeper.AddDeposit(ctx, proposalID2, addrs[0], params.MinDeposit) - assert.NilError(t, err) - assert.Assert(t, votingStarted) - - proposal1, err = s1.GovKeeper.Proposals.Get(ctx, proposalID1) - assert.NilError(t, err) - proposal2, err = s1.GovKeeper.Proposals.Get(ctx, proposalID2) - assert.NilError(t, err) - assert.Assert(t, proposal1.Status == v1.StatusDepositPeriod) - assert.Assert(t, proposal2.Status == v1.StatusVotingPeriod) - - authGenState, err := s1.AccountKeeper.ExportGenesis(ctx) - require.NoError(t, err) - bankGenState, err := s1.BankKeeper.ExportGenesis(ctx) - require.NoError(t, err) - stakingGenState, err := s1.StakingKeeper.ExportGenesis(ctx) - require.NoError(t, err) - - // export the state and import it into a new app - govGenState, _ := gov.ExportGenesis(ctx, s1.GovKeeper) - genesisState := s1.appBuilder.DefaultGenesis() - - genesisState[authtypes.ModuleName] = s1.cdc.MustMarshalJSON(authGenState) - genesisState[banktypes.ModuleName] = s1.cdc.MustMarshalJSON(bankGenState) - genesisState[types.ModuleName] = s1.cdc.MustMarshalJSON(govGenState) - genesisState[stakingtypes.ModuleName] = s1.cdc.MustMarshalJSON(stakingGenState) - - stateBytes, err := json.MarshalIndent(genesisState, "", " ") - assert.NilError(t, err) - - s2 := suite{} - db := coretesting.NewMemDB() - conf2 := simtestutil.DefaultStartUpConfig() - conf2.DB = db - s2.app, err = simtestutil.SetupWithConfiguration( - depinject.Configs( - appConfig, - depinject.Supply(log.NewNopLogger()), - ), - conf2, - &s2.AccountKeeper, &s2.BankKeeper, &s2.GovKeeper, &s2.StakingKeeper, &s2.cdc, &s2.appBuilder, - ) - assert.NilError(t, err) - - clearDB(t, db) - err = s2.app.CommitMultiStore().LoadLatestVersion() - assert.NilError(t, err) - - _, err = s2.app.InitChain( - &abci.InitChainRequest{ - Validators: []abci.ValidatorUpdate{}, - ConsensusParams: simtestutil.DefaultConsensusParams, - AppStateBytes: stateBytes, - }, - ) - assert.NilError(t, err) - - _, err = s2.app.FinalizeBlock(&abci.FinalizeBlockRequest{ - Height: s2.app.LastBlockHeight() + 1, - }) - assert.NilError(t, err) - - _, err = s2.app.FinalizeBlock(&abci.FinalizeBlockRequest{ - Height: s2.app.LastBlockHeight() + 1, - }) - assert.NilError(t, err) - - ctx2 := s2.app.BaseApp.NewContext(false) - - params, err = s2.GovKeeper.Params.Get(ctx2) - assert.NilError(t, err) - // Jump the time forward past the DepositPeriod and VotingPeriod - ctx2 = ctx2.WithHeaderInfo(header.Info{Time: ctx2.BlockHeader().Time.Add(*params.MaxDepositPeriod).Add(*params.VotingPeriod)}) - - // Make sure that they are still in the DepositPeriod and VotingPeriod respectively - proposal1, err = s2.GovKeeper.Proposals.Get(ctx2, proposalID1) - assert.NilError(t, err) - proposal2, err = s2.GovKeeper.Proposals.Get(ctx2, proposalID2) - assert.NilError(t, err) - assert.Assert(t, proposal1.Status == v1.StatusDepositPeriod) - assert.Assert(t, proposal2.Status == v1.StatusVotingPeriod) - - macc := s2.GovKeeper.GetGovernanceAccount(ctx2) - assert.DeepEqual(t, sdk.Coins(params.MinDeposit), s2.BankKeeper.GetAllBalances(ctx2, macc.GetAddress())) - - // Run the endblocker. Check to make sure that proposal1 is removed from state, and proposal2 is finished VotingPeriod. - err = s2.GovKeeper.EndBlocker(ctx2) - assert.NilError(t, err) - - proposal1, err = s2.GovKeeper.Proposals.Get(ctx2, proposalID1) - assert.ErrorContains(t, err, "not found") - - proposal2, err = s2.GovKeeper.Proposals.Get(ctx2, proposalID2) - assert.NilError(t, err) - assert.Assert(t, proposal2.Status == v1.StatusRejected) -} - -func clearDB(t *testing.T, db corestore.KVStoreWithBatch) { - t.Helper() - iter, err := db.Iterator(nil, nil) - assert.NilError(t, err) - defer iter.Close() - - var keys [][]byte - for ; iter.Valid(); iter.Next() { - keys = append(keys, iter.Key()) - } - - for _, k := range keys { - assert.NilError(t, db.Delete(k)) - } -} - -func TestImportExportQueues_ErrorUnconsistentState(t *testing.T) { - suite := createTestSuite(t) - app := suite.app - ctx := app.BaseApp.NewContext(false) - - params := v1.DefaultParams() - err := gov.InitGenesis(ctx, suite.AccountKeeper, suite.BankKeeper, suite.GovKeeper, &v1.GenesisState{ - Deposits: v1.Deposits{ - { - ProposalId: 1234, - Depositor: "me", - Amount: sdk.Coins{ - sdk.NewCoin( - "stake", - sdkmath.NewInt(1234), - ), - }, - }, - }, - Params: ¶ms, - }) - require.Error(t, err) - err = gov.InitGenesis(ctx, suite.AccountKeeper, suite.BankKeeper, suite.GovKeeper, v1.DefaultGenesisState()) - require.NoError(t, err) - genState, err := gov.ExportGenesis(ctx, suite.GovKeeper) - require.NoError(t, err) - require.Equal(t, genState, v1.DefaultGenesisState()) -} diff --git a/tests/integration/gov/keeper/common_test.go b/tests/integration/gov/keeper/common_test.go deleted file mode 100644 index 51b84406c141..000000000000 --- a/tests/integration/gov/keeper/common_test.go +++ /dev/null @@ -1,72 +0,0 @@ -package keeper_test - -import ( - "testing" - - "gotest.tools/v3/assert" - - "cosmossdk.io/math" - "cosmossdk.io/x/gov/types" - v1 "cosmossdk.io/x/gov/types/v1" - "cosmossdk.io/x/gov/types/v1beta1" - stakingtypes "cosmossdk.io/x/staking/types" - - simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -var TestProposal = getTestProposal() - -func getTestProposal() []sdk.Msg { - legacyProposalMsg, err := v1.NewLegacyContent(v1beta1.NewTextProposal("Title", "description"), authtypes.NewModuleAddress(types.ModuleName).String()) - if err != nil { - panic(err) - } - testProposal := v1beta1.NewTextProposal("Proposal", "testing proposal") - legacyProposalMsg2, err := v1.NewLegacyContent(testProposal, authtypes.NewModuleAddress(types.ModuleName).String()) - if err != nil { - panic(err) - } - - return []sdk.Msg{ - legacyProposalMsg, - legacyProposalMsg2, - } -} - -func createValidators(t *testing.T, f *fixture, powers []int64) ([]sdk.AccAddress, []sdk.ValAddress) { - t.Helper() - addrs := simtestutil.AddTestAddrsIncremental(f.bankKeeper, f.stakingKeeper, f.ctx, 5, math.NewInt(30000000)) - valAddrs := simtestutil.ConvertAddrsToValAddrs(addrs) - pks := simtestutil.CreateTestPubKeys(5) - - val1, err := stakingtypes.NewValidator(valAddrs[0].String(), pks[0], stakingtypes.Description{}) - assert.NilError(t, err) - val2, err := stakingtypes.NewValidator(valAddrs[1].String(), pks[1], stakingtypes.Description{}) - assert.NilError(t, err) - val3, err := stakingtypes.NewValidator(valAddrs[2].String(), pks[2], stakingtypes.Description{}) - assert.NilError(t, err) - - assert.NilError(t, f.stakingKeeper.SetValidator(f.ctx, val1)) - assert.NilError(t, f.stakingKeeper.SetValidator(f.ctx, val2)) - assert.NilError(t, f.stakingKeeper.SetValidator(f.ctx, val3)) - assert.NilError(t, f.stakingKeeper.SetValidatorByConsAddr(f.ctx, val1)) - assert.NilError(t, f.stakingKeeper.SetValidatorByConsAddr(f.ctx, val2)) - assert.NilError(t, f.stakingKeeper.SetValidatorByConsAddr(f.ctx, val3)) - assert.NilError(t, f.stakingKeeper.SetNewValidatorByPowerIndex(f.ctx, val1)) - assert.NilError(t, f.stakingKeeper.SetNewValidatorByPowerIndex(f.ctx, val2)) - assert.NilError(t, f.stakingKeeper.SetNewValidatorByPowerIndex(f.ctx, val3)) - - for _, addr := range addrs { - f.accountKeeper.SetAccount(f.ctx, f.accountKeeper.NewAccountWithAddress(f.ctx, addr)) - } - - _, _ = f.stakingKeeper.Delegate(f.ctx, addrs[0], f.stakingKeeper.TokensFromConsensusPower(f.ctx, powers[0]), stakingtypes.Unbonded, val1, true) - _, _ = f.stakingKeeper.Delegate(f.ctx, addrs[1], f.stakingKeeper.TokensFromConsensusPower(f.ctx, powers[1]), stakingtypes.Unbonded, val2, true) - _, _ = f.stakingKeeper.Delegate(f.ctx, addrs[2], f.stakingKeeper.TokensFromConsensusPower(f.ctx, powers[2]), stakingtypes.Unbonded, val3, true) - - _, err = f.stakingKeeper.EndBlocker(f.ctx) - assert.NilError(t, err) - return addrs, valAddrs -} diff --git a/tests/integration/gov/keeper/grpc_query_test.go b/tests/integration/gov/keeper/grpc_query_test.go deleted file mode 100644 index 44fc1ccc103e..000000000000 --- a/tests/integration/gov/keeper/grpc_query_test.go +++ /dev/null @@ -1,76 +0,0 @@ -package keeper_test - -import ( - gocontext "context" - "fmt" - "testing" - - "gotest.tools/v3/assert" - - "cosmossdk.io/math" - v1 "cosmossdk.io/x/gov/types/v1" - "cosmossdk.io/x/gov/types/v1beta1" -) - -func TestLegacyGRPCQueryTally(t *testing.T) { - t.Parallel() - - f := initFixture(t) - ctx, queryClient := f.ctx, f.legacyQueryClient - addrs, _ := createValidators(t, f, []int64{5, 5, 5}) - - var ( - req *v1beta1.QueryTallyResultRequest - expRes *v1beta1.QueryTallyResultResponse - ) - - testCases := []struct { - msg string - malleate func() - expPass bool - expErrMsg string - }{ - { - "request tally after few votes", - func() { - proposal, err := f.govKeeper.SubmitProposal(ctx, TestProposal, "", "test", "description", addrs[0], v1.ProposalType_PROPOSAL_TYPE_STANDARD) - assert.NilError(t, err) - proposal.Status = v1.StatusVotingPeriod - err = f.govKeeper.Proposals.Set(ctx, proposal.Id, proposal) - assert.NilError(t, err) - assert.NilError(t, f.govKeeper.AddVote(ctx, proposal.Id, addrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), "")) - assert.NilError(t, f.govKeeper.AddVote(ctx, proposal.Id, addrs[1], v1.NewNonSplitVoteOption(v1.OptionYes), "")) - assert.NilError(t, f.govKeeper.AddVote(ctx, proposal.Id, addrs[2], v1.NewNonSplitVoteOption(v1.OptionYes), "")) - - req = &v1beta1.QueryTallyResultRequest{ProposalId: proposal.Id} - - expRes = &v1beta1.QueryTallyResultResponse{ - Tally: v1beta1.TallyResult{ - Yes: math.NewInt(3 * 5 * 1000000), - No: math.NewInt(0), - Abstain: math.NewInt(0), - NoWithVeto: math.NewInt(0), - }, - } - }, - true, - "", - }, - } - - for _, testCase := range testCases { - t.Run(fmt.Sprintf("Case %s", testCase.msg), func(t *testing.T) { - testCase.malleate() - - tally, err := queryClient.TallyResult(gocontext.Background(), req) - - if testCase.expPass { - assert.NilError(t, err) - assert.Equal(t, expRes.String(), tally.String()) - } else { - assert.ErrorContains(t, err, testCase.expErrMsg) - assert.Assert(t, tally == nil) - } - }) - } -} diff --git a/tests/integration/gov/keeper/keeper_test.go b/tests/integration/gov/keeper/keeper_test.go deleted file mode 100644 index c40e847cc632..000000000000 --- a/tests/integration/gov/keeper/keeper_test.go +++ /dev/null @@ -1,180 +0,0 @@ -package keeper_test - -import ( - "context" - "testing" - - "go.uber.org/mock/gomock" - - "cosmossdk.io/core/appmodule" - "cosmossdk.io/log" - storetypes "cosmossdk.io/store/types" - "cosmossdk.io/x/bank" - bankkeeper "cosmossdk.io/x/bank/keeper" - banktypes "cosmossdk.io/x/bank/types" - "cosmossdk.io/x/consensus" - consensusparamkeeper "cosmossdk.io/x/consensus/keeper" - consensusparamtypes "cosmossdk.io/x/consensus/types" - "cosmossdk.io/x/gov" - "cosmossdk.io/x/gov/keeper" - "cosmossdk.io/x/gov/types" - v1 "cosmossdk.io/x/gov/types/v1" - "cosmossdk.io/x/gov/types/v1beta1" - minttypes "cosmossdk.io/x/mint/types" - poolkeeper "cosmossdk.io/x/protocolpool/keeper" - pooltypes "cosmossdk.io/x/protocolpool/types" - "cosmossdk.io/x/staking" - stakingkeeper "cosmossdk.io/x/staking/keeper" - stakingtypes "cosmossdk.io/x/staking/types" - - "github.com/cosmos/cosmos-sdk/baseapp" - addresscodec "github.com/cosmos/cosmos-sdk/codec/address" - codectestutil "github.com/cosmos/cosmos-sdk/codec/testutil" - "github.com/cosmos/cosmos-sdk/runtime" - "github.com/cosmos/cosmos-sdk/testutil/integration" - sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - "github.com/cosmos/cosmos-sdk/x/auth" - authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" - authsims "github.com/cosmos/cosmos-sdk/x/auth/simulation" - authtestutil "github.com/cosmos/cosmos-sdk/x/auth/testutil" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -type fixture struct { - ctx sdk.Context - - queryClient v1.QueryClient - legacyQueryClient v1beta1.QueryClient - - accountKeeper authkeeper.AccountKeeper - bankKeeper bankkeeper.Keeper - stakingKeeper *stakingkeeper.Keeper - govKeeper *keeper.Keeper -} - -func initFixture(tb testing.TB) *fixture { - tb.Helper() - keys := storetypes.NewKVStoreKeys( - authtypes.StoreKey, banktypes.StoreKey, stakingtypes.StoreKey, pooltypes.StoreKey, types.StoreKey, consensusparamtypes.StoreKey, - ) - encodingCfg := moduletestutil.MakeTestEncodingConfig(codectestutil.CodecOptions{}, auth.AppModule{}, bank.AppModule{}, gov.AppModule{}) - cdc := encodingCfg.Codec - - logger := log.NewTestLogger(tb) - authority := authtypes.NewModuleAddress(types.ModuleName) - - maccPerms := map[string][]string{ - pooltypes.ModuleName: {}, - pooltypes.StreamAccount: {}, - pooltypes.ProtocolPoolDistrAccount: {}, - minttypes.ModuleName: {authtypes.Minter}, - stakingtypes.BondedPoolName: {authtypes.Burner, authtypes.Staking}, - stakingtypes.NotBondedPoolName: {authtypes.Burner, authtypes.Staking}, - types.ModuleName: {authtypes.Burner}, - } - - // gomock initializations - ctrl := gomock.NewController(tb) - acctsModKeeper := authtestutil.NewMockAccountsModKeeper(ctrl) - accNum := uint64(0) - acctsModKeeper.EXPECT().NextAccountNumber(gomock.Any()).AnyTimes().DoAndReturn(func(ctx context.Context) (uint64, error) { - currentNum := accNum - accNum++ - return currentNum, nil - }) - - accountKeeper := authkeeper.NewAccountKeeper( - runtime.NewEnvironment(runtime.NewKVStoreService(keys[authtypes.StoreKey]), log.NewNopLogger()), - cdc, - authtypes.ProtoBaseAccount, - acctsModKeeper, - maccPerms, - addresscodec.NewBech32Codec(sdk.Bech32MainPrefix), - sdk.Bech32MainPrefix, - authority.String(), - ) - - blockedAddresses := map[string]bool{ - accountKeeper.GetAuthority(): false, - } - bankKeeper := bankkeeper.NewBaseKeeper( - runtime.NewEnvironment(runtime.NewKVStoreService(keys[banktypes.StoreKey]), log.NewNopLogger()), - cdc, - accountKeeper, - blockedAddresses, - authority.String(), - ) - - router := baseapp.NewMsgServiceRouter() - queryRouter := baseapp.NewGRPCQueryRouter() - consensusParamsKeeper := consensusparamkeeper.NewKeeper(cdc, runtime.NewEnvironment(runtime.NewKVStoreService(keys[consensusparamtypes.StoreKey]), log.NewNopLogger(), runtime.EnvWithQueryRouterService(queryRouter), runtime.EnvWithMsgRouterService(router)), authtypes.NewModuleAddress("gov").String()) - - stakingKeeper := stakingkeeper.NewKeeper(cdc, runtime.NewEnvironment(runtime.NewKVStoreService(keys[stakingtypes.StoreKey]), log.NewNopLogger()), accountKeeper, bankKeeper, consensusParamsKeeper, authority.String(), addresscodec.NewBech32Codec(sdk.Bech32PrefixValAddr), addresscodec.NewBech32Codec(sdk.Bech32PrefixConsAddr), runtime.NewContextAwareCometInfoService()) - - poolKeeper := poolkeeper.NewKeeper(cdc, runtime.NewEnvironment(runtime.NewKVStoreService(keys[pooltypes.StoreKey]), log.NewNopLogger()), accountKeeper, bankKeeper, authority.String()) - - // Create MsgServiceRouter, but don't populate it before creating the gov - // keeper. - router.SetInterfaceRegistry(cdc.InterfaceRegistry()) - queryRouter.SetInterfaceRegistry(cdc.InterfaceRegistry()) - - govKeeper := keeper.NewKeeper( - cdc, - runtime.NewEnvironment(runtime.NewKVStoreService(keys[types.StoreKey]), log.NewNopLogger(), runtime.EnvWithQueryRouterService(queryRouter), runtime.EnvWithMsgRouterService(router)), - accountKeeper, - bankKeeper, - stakingKeeper, - poolKeeper, - keeper.DefaultConfig(), - authority.String(), - ) - govRouter := v1beta1.NewRouter() - govRouter.AddRoute(types.RouterKey, v1beta1.ProposalHandler) - govKeeper.SetLegacyRouter(govRouter) - - authModule := auth.NewAppModule(cdc, accountKeeper, acctsModKeeper, authsims.RandomGenesisAccounts, nil) - bankModule := bank.NewAppModule(cdc, bankKeeper, accountKeeper) - stakingModule := staking.NewAppModule(cdc, stakingKeeper) - govModule := gov.NewAppModule(cdc, govKeeper, accountKeeper, bankKeeper, poolKeeper) - consensusModule := consensus.NewAppModule(cdc, consensusParamsKeeper) - - integrationApp := integration.NewIntegrationApp(logger, keys, cdc, - encodingCfg.InterfaceRegistry.SigningContext().AddressCodec(), - encodingCfg.InterfaceRegistry.SigningContext().ValidatorAddressCodec(), - map[string]appmodule.AppModule{ - authtypes.ModuleName: authModule, - banktypes.ModuleName: bankModule, - stakingtypes.ModuleName: stakingModule, - types.ModuleName: govModule, - consensusparamtypes.ModuleName: consensusModule, - }, - baseapp.NewMsgServiceRouter(), - baseapp.NewGRPCQueryRouter(), - ) - - sdkCtx := sdk.UnwrapSDKContext(integrationApp.Context()) - - msgSrvr := keeper.NewMsgServerImpl(govKeeper) - legacyMsgSrvr := keeper.NewLegacyMsgServerImpl(authority.String(), msgSrvr) - - // Register MsgServer and QueryServer - v1.RegisterMsgServer(router, msgSrvr) - v1beta1.RegisterMsgServer(router, legacyMsgSrvr) - - v1.RegisterQueryServer(integrationApp.QueryHelper(), keeper.NewQueryServer(govKeeper)) - v1beta1.RegisterQueryServer(integrationApp.QueryHelper(), keeper.NewLegacyQueryServer(govKeeper)) - - queryClient := v1.NewQueryClient(integrationApp.QueryHelper()) - legacyQueryClient := v1beta1.NewQueryClient(integrationApp.QueryHelper()) - - return &fixture{ - ctx: sdkCtx, - queryClient: queryClient, - legacyQueryClient: legacyQueryClient, - accountKeeper: accountKeeper, - bankKeeper: bankKeeper, - stakingKeeper: stakingKeeper, - govKeeper: govKeeper, - } -} diff --git a/tests/integration/gov/keeper/tally_test.go b/tests/integration/gov/keeper/tally_test.go deleted file mode 100644 index f2b952076285..000000000000 --- a/tests/integration/gov/keeper/tally_test.go +++ /dev/null @@ -1,518 +0,0 @@ -package keeper_test - -import ( - "testing" - - "gotest.tools/v3/assert" - - "cosmossdk.io/math" - v1 "cosmossdk.io/x/gov/types/v1" - stakingtypes "cosmossdk.io/x/staking/types" - - simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func TestTallyNoOneVotes(t *testing.T) { - t.Parallel() - f := initFixture(t) - - ctx := f.ctx - - createValidators(t, f, []int64{5, 5, 5}) - - tp := TestProposal - proposal, err := f.govKeeper.SubmitProposal(ctx, tp, "", "test", "description", sdk.AccAddress("cosmos1ghekyjucln7y67ntx7cf27m9dpuxxemn4c8g4r"), v1.ProposalType_PROPOSAL_TYPE_STANDARD) - assert.NilError(t, err) - proposalID := proposal.Id - proposal.Status = v1.StatusVotingPeriod - err = f.govKeeper.Proposals.Set(ctx, proposal.Id, proposal) - assert.NilError(t, err) - proposal, ok := f.govKeeper.Proposals.Get(ctx, proposalID) - assert.Assert(t, ok) - passes, burnDeposits, tallyResults, _ := f.govKeeper.Tally(ctx, proposal) - - assert.Assert(t, passes == false) - assert.Assert(t, burnDeposits == false) - assert.Assert(t, tallyResults.Equals(v1.EmptyTallyResult())) -} - -func TestTallyNoQuorum(t *testing.T) { - t.Parallel() - - f := initFixture(t) - - ctx := f.ctx - - createValidators(t, f, []int64{2, 5, 0}) - - addrs := simtestutil.AddTestAddrsIncremental(f.bankKeeper, f.stakingKeeper, ctx, 1, math.NewInt(10000000)) - - tp := TestProposal - proposal, err := f.govKeeper.SubmitProposal(ctx, tp, "", "test", "description", addrs[0], v1.ProposalType_PROPOSAL_TYPE_STANDARD) - assert.NilError(t, err) - proposalID := proposal.Id - proposal.Status = v1.StatusVotingPeriod - err = f.govKeeper.Proposals.Set(ctx, proposal.Id, proposal) - assert.NilError(t, err) - err = f.govKeeper.AddVote(ctx, proposalID, addrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), "") - assert.NilError(t, err) - - proposal, ok := f.govKeeper.Proposals.Get(ctx, proposalID) - assert.Assert(t, ok) - passes, burnDeposits, _, _ := f.govKeeper.Tally(ctx, proposal) - assert.Assert(t, passes == false) - assert.Assert(t, burnDeposits == false) -} - -func TestTallyOnlyValidatorsAllYes(t *testing.T) { - t.Parallel() - - f := initFixture(t) - - ctx := f.ctx - - addrs, _ := createValidators(t, f, []int64{5, 5, 5}) - tp := TestProposal - - proposal, err := f.govKeeper.SubmitProposal(ctx, tp, "", "test", "description", addrs[0], v1.ProposalType_PROPOSAL_TYPE_STANDARD) - assert.NilError(t, err) - proposalID := proposal.Id - proposal.Status = v1.StatusVotingPeriod - err = f.govKeeper.Proposals.Set(ctx, proposal.Id, proposal) - assert.NilError(t, err) - assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), "")) - assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[1], v1.NewNonSplitVoteOption(v1.OptionYes), "")) - assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[2], v1.NewNonSplitVoteOption(v1.OptionYes), "")) - - proposal, ok := f.govKeeper.Proposals.Get(ctx, proposalID) - assert.Assert(t, ok) - passes, burnDeposits, tallyResults, _ := f.govKeeper.Tally(ctx, proposal) - - assert.Assert(t, passes) - assert.Assert(t, burnDeposits == false) - assert.Assert(t, tallyResults.Equals(v1.EmptyTallyResult()) == false) -} - -func TestTallyOnlyValidators51No(t *testing.T) { - t.Parallel() - - f := initFixture(t) - - ctx := f.ctx - - valAccAddrs, _ := createValidators(t, f, []int64{5, 6, 0}) - - tp := TestProposal - proposal, err := f.govKeeper.SubmitProposal(ctx, tp, "", "test", "description", valAccAddrs[0], v1.ProposalType_PROPOSAL_TYPE_STANDARD) - assert.NilError(t, err) - proposalID := proposal.Id - proposal.Status = v1.StatusVotingPeriod - err = f.govKeeper.Proposals.Set(ctx, proposal.Id, proposal) - assert.NilError(t, err) - assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, valAccAddrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), "")) - assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, valAccAddrs[1], v1.NewNonSplitVoteOption(v1.OptionNo), "")) - - proposal, ok := f.govKeeper.Proposals.Get(ctx, proposalID) - assert.Assert(t, ok) - passes, burnDeposits, _, _ := f.govKeeper.Tally(ctx, proposal) - - assert.Assert(t, passes == false) - assert.Assert(t, burnDeposits == false) -} - -func TestTallyOnlyValidators51Yes(t *testing.T) { - t.Parallel() - - f := initFixture(t) - - ctx := f.ctx - - valAccAddrs, _ := createValidators(t, f, []int64{5, 6, 0}) - - tp := TestProposal - proposal, err := f.govKeeper.SubmitProposal(ctx, tp, "", "test", "description", valAccAddrs[0], v1.ProposalType_PROPOSAL_TYPE_STANDARD) - assert.NilError(t, err) - proposalID := proposal.Id - proposal.Status = v1.StatusVotingPeriod - err = f.govKeeper.Proposals.Set(ctx, proposal.Id, proposal) - assert.NilError(t, err) - assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, valAccAddrs[0], v1.NewNonSplitVoteOption(v1.OptionNo), "")) - assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, valAccAddrs[1], v1.NewNonSplitVoteOption(v1.OptionYes), "")) - - proposal, ok := f.govKeeper.Proposals.Get(ctx, proposalID) - assert.Assert(t, ok) - passes, burnDeposits, tallyResults, _ := f.govKeeper.Tally(ctx, proposal) - - assert.Assert(t, passes) - assert.Assert(t, burnDeposits == false) - assert.Assert(t, tallyResults.Equals(v1.EmptyTallyResult()) == false) -} - -func TestTallyOnlyValidatorsVetoed(t *testing.T) { - t.Parallel() - - f := initFixture(t) - - ctx := f.ctx - - valAccAddrs, _ := createValidators(t, f, []int64{6, 6, 7}) - - tp := TestProposal - proposal, err := f.govKeeper.SubmitProposal(ctx, tp, "", "test", "description", valAccAddrs[0], v1.ProposalType_PROPOSAL_TYPE_STANDARD) - assert.NilError(t, err) - proposalID := proposal.Id - proposal.Status = v1.StatusVotingPeriod - err = f.govKeeper.Proposals.Set(ctx, proposal.Id, proposal) - assert.NilError(t, err) - assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, valAccAddrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), "")) - assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, valAccAddrs[1], v1.NewNonSplitVoteOption(v1.OptionYes), "")) - assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, valAccAddrs[2], v1.NewNonSplitVoteOption(v1.OptionNoWithVeto), "")) - - proposal, ok := f.govKeeper.Proposals.Get(ctx, proposalID) - assert.Assert(t, ok) - passes, burnDeposits, tallyResults, _ := f.govKeeper.Tally(ctx, proposal) - - assert.Assert(t, passes == false) - assert.Assert(t, burnDeposits) - assert.Assert(t, tallyResults.Equals(v1.EmptyTallyResult()) == false) -} - -func TestTallyOnlyValidatorsAbstainPasses(t *testing.T) { - t.Parallel() - - f := initFixture(t) - - ctx := f.ctx - - valAccAddrs, _ := createValidators(t, f, []int64{6, 6, 7}) - - tp := TestProposal - proposal, err := f.govKeeper.SubmitProposal(ctx, tp, "", "test", "description", valAccAddrs[0], v1.ProposalType_PROPOSAL_TYPE_STANDARD) - assert.NilError(t, err) - proposalID := proposal.Id - proposal.Status = v1.StatusVotingPeriod - err = f.govKeeper.Proposals.Set(ctx, proposal.Id, proposal) - assert.NilError(t, err) - assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, valAccAddrs[0], v1.NewNonSplitVoteOption(v1.OptionAbstain), "")) - assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, valAccAddrs[1], v1.NewNonSplitVoteOption(v1.OptionNo), "")) - assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, valAccAddrs[2], v1.NewNonSplitVoteOption(v1.OptionYes), "")) - - proposal, ok := f.govKeeper.Proposals.Get(ctx, proposalID) - assert.Assert(t, ok) - passes, burnDeposits, tallyResults, _ := f.govKeeper.Tally(ctx, proposal) - - assert.Assert(t, passes) - assert.Assert(t, burnDeposits == false) - assert.Assert(t, tallyResults.Equals(v1.EmptyTallyResult()) == false) -} - -func TestTallyOnlyValidatorsAbstainFails(t *testing.T) { - t.Parallel() - - f := initFixture(t) - - ctx := f.ctx - - valAccAddrs, _ := createValidators(t, f, []int64{6, 6, 7}) - - tp := TestProposal - proposal, err := f.govKeeper.SubmitProposal(ctx, tp, "", "test", "description", valAccAddrs[0], v1.ProposalType_PROPOSAL_TYPE_STANDARD) - assert.NilError(t, err) - proposalID := proposal.Id - proposal.Status = v1.StatusVotingPeriod - err = f.govKeeper.Proposals.Set(ctx, proposal.Id, proposal) - assert.NilError(t, err) - assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, valAccAddrs[0], v1.NewNonSplitVoteOption(v1.OptionAbstain), "")) - assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, valAccAddrs[1], v1.NewNonSplitVoteOption(v1.OptionYes), "")) - assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, valAccAddrs[2], v1.NewNonSplitVoteOption(v1.OptionNo), "")) - - proposal, ok := f.govKeeper.Proposals.Get(ctx, proposalID) - assert.Assert(t, ok) - passes, burnDeposits, tallyResults, _ := f.govKeeper.Tally(ctx, proposal) - - assert.Assert(t, passes == false) - assert.Assert(t, burnDeposits == false) - assert.Assert(t, tallyResults.Equals(v1.EmptyTallyResult()) == false) -} - -func TestTallyOnlyValidatorsNonVoter(t *testing.T) { - t.Parallel() - - f := initFixture(t) - - ctx := f.ctx - - valAccAddrs, _ := createValidators(t, f, []int64{5, 6, 7}) - valAccAddr1, valAccAddr2 := valAccAddrs[0], valAccAddrs[1] - - tp := TestProposal - proposal, err := f.govKeeper.SubmitProposal(ctx, tp, "", "test", "description", valAccAddrs[0], v1.ProposalType_PROPOSAL_TYPE_STANDARD) - assert.NilError(t, err) - proposalID := proposal.Id - proposal.Status = v1.StatusVotingPeriod - err = f.govKeeper.Proposals.Set(ctx, proposal.Id, proposal) - assert.NilError(t, err) - assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, valAccAddr1, v1.NewNonSplitVoteOption(v1.OptionYes), "")) - assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, valAccAddr2, v1.NewNonSplitVoteOption(v1.OptionNo), "")) - - proposal, ok := f.govKeeper.Proposals.Get(ctx, proposalID) - assert.Assert(t, ok) - passes, burnDeposits, tallyResults, _ := f.govKeeper.Tally(ctx, proposal) - - assert.Assert(t, passes == false) - assert.Assert(t, burnDeposits == false) - assert.Assert(t, tallyResults.Equals(v1.EmptyTallyResult()) == false) -} - -func TestTallyDelgatorOverride(t *testing.T) { - t.Parallel() - - f := initFixture(t) - - ctx := f.ctx - - addrs, valAddrs := createValidators(t, f, []int64{5, 6, 7}) - - delTokens := f.stakingKeeper.TokensFromConsensusPower(ctx, 30) - val1, found := f.stakingKeeper.GetValidator(ctx, valAddrs[0]) - assert.Assert(t, found) - - _, err := f.stakingKeeper.Delegate(ctx, addrs[4], delTokens, stakingtypes.Unbonded, val1, true) - assert.NilError(t, err) - - _, err = f.stakingKeeper.EndBlocker(ctx) - assert.NilError(t, err) - tp := TestProposal - proposal, err := f.govKeeper.SubmitProposal(ctx, tp, "", "test", "description", addrs[0], v1.ProposalType_PROPOSAL_TYPE_STANDARD) - assert.NilError(t, err) - proposalID := proposal.Id - proposal.Status = v1.StatusVotingPeriod - err = f.govKeeper.Proposals.Set(ctx, proposal.Id, proposal) - assert.NilError(t, err) - assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[1], v1.NewNonSplitVoteOption(v1.OptionYes), "")) - assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[2], v1.NewNonSplitVoteOption(v1.OptionYes), "")) - assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[3], v1.NewNonSplitVoteOption(v1.OptionYes), "")) - assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[4], v1.NewNonSplitVoteOption(v1.OptionNo), "")) - - proposal, ok := f.govKeeper.Proposals.Get(ctx, proposalID) - assert.Assert(t, ok) - passes, burnDeposits, tallyResults, _ := f.govKeeper.Tally(ctx, proposal) - - assert.Assert(t, passes == false) - assert.Assert(t, burnDeposits == false) - assert.Assert(t, tallyResults.Equals(v1.EmptyTallyResult()) == false) -} - -func TestTallyDelgatorInherit(t *testing.T) { - t.Parallel() - - f := initFixture(t) - - ctx := f.ctx - - addrs, vals := createValidators(t, f, []int64{5, 6, 7}) - - delTokens := f.stakingKeeper.TokensFromConsensusPower(ctx, 30) - val3, found := f.stakingKeeper.GetValidator(ctx, vals[2]) - assert.Assert(t, found) - - _, err := f.stakingKeeper.Delegate(ctx, addrs[3], delTokens, stakingtypes.Unbonded, val3, true) - assert.NilError(t, err) - - _, err = f.stakingKeeper.EndBlocker(ctx) - assert.NilError(t, err) - tp := TestProposal - proposal, err := f.govKeeper.SubmitProposal(ctx, tp, "", "test", "description", addrs[0], v1.ProposalType_PROPOSAL_TYPE_STANDARD) - assert.NilError(t, err) - proposalID := proposal.Id - proposal.Status = v1.StatusVotingPeriod - err = f.govKeeper.Proposals.Set(ctx, proposal.Id, proposal) - assert.NilError(t, err) - assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[0], v1.NewNonSplitVoteOption(v1.OptionNo), "")) - assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[1], v1.NewNonSplitVoteOption(v1.OptionNo), "")) - assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[2], v1.NewNonSplitVoteOption(v1.OptionYes), "")) - - proposal, err = f.govKeeper.Proposals.Get(ctx, proposalID) - assert.NilError(t, err) - passes, burnDeposits, tallyResults, _ := f.govKeeper.Tally(ctx, proposal) - - assert.Assert(t, passes) - assert.Assert(t, burnDeposits == false) - assert.Assert(t, tallyResults.Equals(v1.EmptyTallyResult()) == false) -} - -func TestTallyDelgatorMultipleOverride(t *testing.T) { - t.Parallel() - - f := initFixture(t) - - ctx := f.ctx - - addrs, vals := createValidators(t, f, []int64{5, 6, 7}) - - delTokens := f.stakingKeeper.TokensFromConsensusPower(ctx, 10) - val1, found := f.stakingKeeper.GetValidator(ctx, vals[0]) - assert.Assert(t, found) - val2, found := f.stakingKeeper.GetValidator(ctx, vals[1]) - assert.Assert(t, found) - _, err := f.stakingKeeper.Delegate(ctx, addrs[3], delTokens, stakingtypes.Unbonded, val1, true) - assert.NilError(t, err) - _, err = f.stakingKeeper.Delegate(ctx, addrs[3], delTokens, stakingtypes.Unbonded, val2, true) - assert.NilError(t, err) - - _, err = f.stakingKeeper.EndBlocker(ctx) - assert.NilError(t, err) - tp := TestProposal - proposal, err := f.govKeeper.SubmitProposal(ctx, tp, "", "test", "description", addrs[0], v1.ProposalType_PROPOSAL_TYPE_STANDARD) - assert.NilError(t, err) - proposalID := proposal.Id - proposal.Status = v1.StatusVotingPeriod - err = f.govKeeper.Proposals.Set(ctx, proposal.Id, proposal) - assert.NilError(t, err) - assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), "")) - assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[1], v1.NewNonSplitVoteOption(v1.OptionYes), "")) - assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[2], v1.NewNonSplitVoteOption(v1.OptionYes), "")) - assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[3], v1.NewNonSplitVoteOption(v1.OptionNo), "")) - - proposal, ok := f.govKeeper.Proposals.Get(ctx, proposalID) - assert.Assert(t, ok) - passes, burnDeposits, tallyResults, _ := f.govKeeper.Tally(ctx, proposal) - - assert.Assert(t, passes == false) - assert.Assert(t, burnDeposits == false) - assert.Assert(t, tallyResults.Equals(v1.EmptyTallyResult()) == false) -} - -func TestTallyDelgatorMultipleInherit(t *testing.T) { - t.Parallel() - - f := initFixture(t) - - ctx := f.ctx - - createValidators(t, f, []int64{25, 6, 7}) - - addrs, vals := createValidators(t, f, []int64{5, 6, 7}) - - delTokens := f.stakingKeeper.TokensFromConsensusPower(ctx, 10) - val2, found := f.stakingKeeper.GetValidator(ctx, vals[1]) - assert.Assert(t, found) - val3, found := f.stakingKeeper.GetValidator(ctx, vals[2]) - assert.Assert(t, found) - - _, err := f.stakingKeeper.Delegate(ctx, addrs[3], delTokens, stakingtypes.Unbonded, val2, true) - assert.NilError(t, err) - _, err = f.stakingKeeper.Delegate(ctx, addrs[3], delTokens, stakingtypes.Unbonded, val3, true) - assert.NilError(t, err) - - _, err = f.stakingKeeper.EndBlocker(ctx) - assert.NilError(t, err) - tp := TestProposal - proposal, err := f.govKeeper.SubmitProposal(ctx, tp, "", "test", "description", addrs[0], v1.ProposalType_PROPOSAL_TYPE_STANDARD) - assert.NilError(t, err) - proposalID := proposal.Id - proposal.Status = v1.StatusVotingPeriod - err = f.govKeeper.Proposals.Set(ctx, proposal.Id, proposal) - assert.NilError(t, err) - assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), "")) - assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[1], v1.NewNonSplitVoteOption(v1.OptionNo), "")) - assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[2], v1.NewNonSplitVoteOption(v1.OptionNo), "")) - - proposal, ok := f.govKeeper.Proposals.Get(ctx, proposalID) - assert.Assert(t, ok) - passes, burnDeposits, tallyResults, _ := f.govKeeper.Tally(ctx, proposal) - - assert.Assert(t, passes == false) - assert.Assert(t, burnDeposits == false) - assert.Assert(t, tallyResults.Equals(v1.EmptyTallyResult()) == false) -} - -func TestTallyJailedValidator(t *testing.T) { - t.Parallel() - - f := initFixture(t) - - ctx := f.ctx - - addrs, valAddrs := createValidators(t, f, []int64{25, 6, 7}) - - delTokens := f.stakingKeeper.TokensFromConsensusPower(ctx, 10) - val2, found := f.stakingKeeper.GetValidator(ctx, valAddrs[1]) - assert.Assert(t, found) - val3, found := f.stakingKeeper.GetValidator(ctx, valAddrs[2]) - assert.Assert(t, found) - - _, err := f.stakingKeeper.Delegate(ctx, addrs[3], delTokens, stakingtypes.Unbonded, val2, true) - assert.NilError(t, err) - _, err = f.stakingKeeper.Delegate(ctx, addrs[3], delTokens, stakingtypes.Unbonded, val3, true) - assert.NilError(t, err) - - _, err = f.stakingKeeper.EndBlocker(ctx) - assert.NilError(t, err) - consAddr, err := val2.GetConsAddr() - assert.NilError(t, err) - assert.NilError(t, f.stakingKeeper.Jail(ctx, sdk.ConsAddress(consAddr))) - - tp := TestProposal - proposal, err := f.govKeeper.SubmitProposal(ctx, tp, "", "test", "description", addrs[0], v1.ProposalType_PROPOSAL_TYPE_STANDARD) - assert.NilError(t, err) - proposalID := proposal.Id - proposal.Status = v1.StatusVotingPeriod - err = f.govKeeper.Proposals.Set(ctx, proposal.Id, proposal) - assert.NilError(t, err) - assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), "")) - assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[1], v1.NewNonSplitVoteOption(v1.OptionNo), "")) - assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[2], v1.NewNonSplitVoteOption(v1.OptionNo), "")) - - proposal, ok := f.govKeeper.Proposals.Get(ctx, proposalID) - assert.Assert(t, ok) - passes, burnDeposits, tallyResults, _ := f.govKeeper.Tally(ctx, proposal) - - assert.Assert(t, passes) - assert.Assert(t, burnDeposits == false) - assert.Assert(t, tallyResults.Equals(v1.EmptyTallyResult()) == false) -} - -func TestTallyValidatorMultipleDelegations(t *testing.T) { - t.Parallel() - - f := initFixture(t) - - ctx := f.ctx - - addrs, valAddrs := createValidators(t, f, []int64{10, 10, 10}) - - delTokens := f.stakingKeeper.TokensFromConsensusPower(ctx, 10) - val2, found := f.stakingKeeper.GetValidator(ctx, valAddrs[1]) - assert.Assert(t, found) - - _, err := f.stakingKeeper.Delegate(ctx, addrs[0], delTokens, stakingtypes.Unbonded, val2, true) - assert.NilError(t, err) - - tp := TestProposal - proposal, err := f.govKeeper.SubmitProposal(ctx, tp, "", "test", "description", addrs[0], v1.ProposalType_PROPOSAL_TYPE_STANDARD) - assert.NilError(t, err) - proposalID := proposal.Id - proposal.Status = v1.StatusVotingPeriod - err = f.govKeeper.Proposals.Set(ctx, proposal.Id, proposal) - assert.NilError(t, err) - assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), "")) - assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[1], v1.NewNonSplitVoteOption(v1.OptionNo), "")) - assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[2], v1.NewNonSplitVoteOption(v1.OptionYes), "")) - - proposal, ok := f.govKeeper.Proposals.Get(ctx, proposalID) - assert.Assert(t, ok) - passes, burnDeposits, tallyResults, _ := f.govKeeper.Tally(ctx, proposal) - - assert.Assert(t, passes) - assert.Assert(t, burnDeposits == false) - - expectedYes := f.stakingKeeper.TokensFromConsensusPower(ctx, 30) - expectedAbstain := f.stakingKeeper.TokensFromConsensusPower(ctx, 0) - expectedNo := f.stakingKeeper.TokensFromConsensusPower(ctx, 10) - expectedNoWithVeto := f.stakingKeeper.TokensFromConsensusPower(ctx, 0) - expectedTallyResult := v1.NewTallyResult(expectedYes, expectedAbstain, expectedNo, expectedNoWithVeto, math.ZeroInt()) - - assert.Assert(t, tallyResults.Equals(expectedTallyResult)) -} diff --git a/tests/integration/gov/module_test.go b/tests/integration/gov/module_test.go deleted file mode 100644 index 826f6a7d68d6..000000000000 --- a/tests/integration/gov/module_test.go +++ /dev/null @@ -1,43 +0,0 @@ -package gov_test - -import ( - "testing" - - "gotest.tools/v3/assert" - - "cosmossdk.io/depinject" - "cosmossdk.io/log" - _ "cosmossdk.io/x/accounts" - "cosmossdk.io/x/gov/types" - _ "cosmossdk.io/x/mint" - _ "cosmossdk.io/x/protocolpool" - - "github.com/cosmos/cosmos-sdk/testutil/configurator" - simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" - authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -func TestItCreatesModuleAccountOnInitBlock(t *testing.T) { - var accountKeeper authkeeper.AccountKeeper - app, err := simtestutil.SetupAtGenesis( - depinject.Configs( - configurator.NewAppConfig( - configurator.AccountsModule(), - configurator.AuthModule(), - configurator.StakingModule(), - configurator.BankModule(), - configurator.GovModule(), - configurator.ConsensusModule(), - configurator.ProtocolPoolModule(), - ), - depinject.Supply(log.NewNopLogger()), - ), - &accountKeeper, - ) - assert.NilError(t, err) - - ctx := app.BaseApp.NewContext(false) - acc := accountKeeper.GetAccount(ctx, authtypes.NewModuleAddress(types.ModuleName)) - assert.Assert(t, acc != nil) -} From 81723bd9d4bc26fa8486473a31333af6f17e737e Mon Sep 17 00:00:00 2001 From: sontrinh16 Date: Fri, 13 Dec 2024 14:56:57 +0700 Subject: [PATCH 8/8] address comment --- tests/go.mod | 2 +- tests/integration/v2/services.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/go.mod b/tests/go.mod index 4d9a25c455ae..3cdc1f7523b5 100644 --- a/tests/go.mod +++ b/tests/go.mod @@ -51,7 +51,7 @@ require ( cosmossdk.io/x/staking v0.0.0-20240226161501-23359a0b6d91 github.com/cometbft/cometbft/api v1.0.0-rc2 github.com/cosmos/cosmos-db v1.1.0 - github.com/gogo/protobuf v1.3.2 + github.com/gogo/protobuf v1.3.2 // indirect github.com/google/go-cmp v0.6.0 github.com/google/gofuzz v1.2.0 github.com/jhump/protoreflect v1.17.0 diff --git a/tests/integration/v2/services.go b/tests/integration/v2/services.go index 1fe0ea432694..f608fd65fdb0 100644 --- a/tests/integration/v2/services.go +++ b/tests/integration/v2/services.go @@ -7,8 +7,8 @@ import ( "errors" "fmt" + "github.com/cosmos/gogoproto/jsonpb" gogoproto "github.com/cosmos/gogoproto/proto" - "github.com/gogo/protobuf/jsonpb" "cosmossdk.io/core/branch" "cosmossdk.io/core/comet"