Skip to content

Commit 95c44e5

Browse files
mergify[bot]fastfadingvioletsjulienrbrt
authored
fix(x/gov,x/distribution): Balance assertions on genesis import shouldn't be exact (backport #22832) (#23194)
Co-authored-by: violet <158512193+fastfadingviolets@users.noreply.github.com> Co-authored-by: Julien Robert <julien@rbrt.fr>
1 parent 394c22a commit 95c44e5

File tree

5 files changed

+203
-5
lines changed

5 files changed

+203
-5
lines changed
Lines changed: 190 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,190 @@
1+
package distribution_test
2+
3+
import (
4+
"encoding/json"
5+
"testing"
6+
7+
corestore "cosmossdk.io/core/store"
8+
coretesting "cosmossdk.io/core/testing"
9+
"cosmossdk.io/depinject"
10+
"cosmossdk.io/log"
11+
sdkmath "cosmossdk.io/math"
12+
"cosmossdk.io/x/distribution/keeper"
13+
"cosmossdk.io/x/distribution/types"
14+
stakingkeeper "cosmossdk.io/x/staking/keeper"
15+
abci "github.com/cometbft/cometbft/api/cometbft/abci/v1"
16+
"github.com/cosmos/cosmos-sdk/codec"
17+
"github.com/cosmos/cosmos-sdk/runtime"
18+
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
19+
sdk "github.com/cosmos/cosmos-sdk/types"
20+
"github.com/stretchr/testify/suite"
21+
22+
bankkeeper "cosmossdk.io/x/bank/keeper"
23+
_ "github.com/cosmos/cosmos-sdk/x/auth"
24+
authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper"
25+
)
26+
27+
type ImportExportSuite struct {
28+
suite.Suite
29+
30+
cdc codec.Codec
31+
app *runtime.App
32+
addrs []sdk.AccAddress
33+
AccountKeeper authkeeper.AccountKeeper
34+
BankKeeper bankkeeper.Keeper
35+
DistributionKeeper keeper.Keeper
36+
StakingKeeper *stakingkeeper.Keeper
37+
appBuilder *runtime.AppBuilder
38+
}
39+
40+
func TestDistributionImportExport(t *testing.T) {
41+
suite.Run(t, new(ImportExportSuite))
42+
}
43+
44+
func (s *ImportExportSuite) SetupTest() {
45+
var err error
46+
valTokens := sdk.TokensFromConsensusPower(42, sdk.DefaultPowerReduction)
47+
s.app, err = simtestutil.SetupWithConfiguration(
48+
depinject.Configs(
49+
AppConfig,
50+
depinject.Supply(log.NewNopLogger()),
51+
),
52+
simtestutil.DefaultStartUpConfig(),
53+
&s.AccountKeeper, &s.BankKeeper, &s.DistributionKeeper, &s.StakingKeeper,
54+
&s.cdc, &s.appBuilder,
55+
)
56+
s.Require().NoError(err)
57+
58+
ctx := s.app.BaseApp.NewContext(false)
59+
s.addrs = simtestutil.AddTestAddrs(s.BankKeeper, s.StakingKeeper, ctx, 1, valTokens)
60+
61+
_, err = s.app.FinalizeBlock(&abci.FinalizeBlockRequest{
62+
Height: s.app.LastBlockHeight() + 1,
63+
})
64+
s.Require().NoError(err)
65+
}
66+
67+
func (s *ImportExportSuite) TestHappyPath() {
68+
ctx := s.app.NewContext(true)
69+
// Imagine a situation where rewards were, e.g. 100 / 3 = 33, but the fee collector sent 100 to the distribution module.
70+
// There're 99 tokens in rewards, but 100 in the module; let's simulate a situation where there are 34 tokens left in the module,
71+
// and a single validator has 33 tokens of rewards.
72+
rewards := sdk.NewDecCoinsFromCoins(sdk.NewCoin("stake", sdkmath.NewInt(33)))
73+
74+
// We'll pretend s.addrs[0] is the fee collector module.
75+
err := s.BankKeeper.SendCoinsFromAccountToModule(ctx, s.addrs[0], types.ModuleName, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(34))))
76+
s.Require().NoError(err)
77+
78+
validators, err := s.StakingKeeper.GetAllValidators(ctx)
79+
s.Require().NoError(err)
80+
val := validators[0]
81+
82+
err = s.DistributionKeeper.AllocateTokensToValidator(ctx, val, rewards)
83+
s.Require().NoError(err)
84+
85+
_, err = s.app.FinalizeBlock(&abci.FinalizeBlockRequest{
86+
Height: s.app.LastBlockHeight() + 1,
87+
})
88+
s.Require().NoError(err)
89+
90+
valBz, err := s.StakingKeeper.ValidatorAddressCodec().StringToBytes(val.GetOperator())
91+
s.Require().NoError(err)
92+
outstanding, err := s.DistributionKeeper.ValidatorOutstandingRewards.Get(ctx, valBz)
93+
s.Require().NoError(err)
94+
s.Require().Equal(rewards, outstanding.Rewards)
95+
96+
genesisState, err := s.app.ModuleManager.ExportGenesis(ctx)
97+
s.Require().NoError(err)
98+
stateBytes, err := json.MarshalIndent(genesisState, "", " ")
99+
s.Require().NoError(err)
100+
101+
db := coretesting.NewMemDB()
102+
conf2 := simtestutil.DefaultStartUpConfig()
103+
conf2.DB = db
104+
app2, err := simtestutil.SetupWithConfiguration(
105+
depinject.Configs(
106+
AppConfig,
107+
depinject.Supply(log.NewNopLogger()),
108+
),
109+
conf2,
110+
)
111+
s.Require().NoError(err)
112+
113+
s.clearDB(db)
114+
err = app2.CommitMultiStore().LoadLatestVersion()
115+
s.Require().NoError(err)
116+
117+
_, err = app2.InitChain(
118+
&abci.InitChainRequest{
119+
Validators: []abci.ValidatorUpdate{},
120+
ConsensusParams: simtestutil.DefaultConsensusParams,
121+
AppStateBytes: stateBytes,
122+
},
123+
)
124+
s.Require().NoError(err)
125+
}
126+
127+
func (s *ImportExportSuite) TestInsufficientFunds() {
128+
ctx := s.app.NewContext(true)
129+
rewards := sdk.NewCoin("stake", sdkmath.NewInt(35))
130+
131+
validators, err := s.StakingKeeper.GetAllValidators(ctx)
132+
s.Require().NoError(err)
133+
134+
err = s.DistributionKeeper.AllocateTokensToValidator(ctx, validators[0], sdk.NewDecCoinsFromCoins(rewards))
135+
s.Require().NoError(err)
136+
137+
// We'll pretend s.addrs[0] is the fee collector module.
138+
err = s.BankKeeper.SendCoinsFromAccountToModule(ctx, s.addrs[0], types.ModuleName, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(34))))
139+
s.Require().NoError(err)
140+
141+
_, err = s.app.FinalizeBlock(&abci.FinalizeBlockRequest{
142+
Height: s.app.LastBlockHeight() + 1,
143+
})
144+
s.Require().NoError(err)
145+
146+
genesisState, err := s.app.ModuleManager.ExportGenesis(ctx)
147+
s.Require().NoError(err)
148+
stateBytes, err := json.MarshalIndent(genesisState, "", " ")
149+
s.Require().NoError(err)
150+
151+
db := coretesting.NewMemDB()
152+
conf2 := simtestutil.DefaultStartUpConfig()
153+
conf2.DB = db
154+
app2, err := simtestutil.SetupWithConfiguration(
155+
depinject.Configs(
156+
AppConfig,
157+
depinject.Supply(log.NewNopLogger()),
158+
),
159+
conf2,
160+
)
161+
s.Require().NoError(err)
162+
163+
s.clearDB(db)
164+
err = app2.CommitMultiStore().LoadLatestVersion()
165+
s.Require().NoError(err)
166+
167+
_, err = app2.InitChain(
168+
&abci.InitChainRequest{
169+
Validators: []abci.ValidatorUpdate{},
170+
ConsensusParams: simtestutil.DefaultConsensusParams,
171+
AppStateBytes: stateBytes,
172+
},
173+
)
174+
s.Require().ErrorContains(err, "distribution module balance is less than module holdings")
175+
}
176+
177+
func (s *ImportExportSuite) clearDB(db corestore.KVStoreWithBatch) {
178+
iter, err := db.Iterator(nil, nil)
179+
s.Require().NoError(err)
180+
defer iter.Close()
181+
182+
var keys [][]byte
183+
for ; iter.Valid(); iter.Next() {
184+
keys = append(keys, iter.Key())
185+
}
186+
187+
for _, k := range keys {
188+
s.Require().NoError(db.Delete(k))
189+
}
190+
}

x/distribution/CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,10 @@ Ref: https://keepachangelog.com/en/1.0.0/
2525

2626
## [Unreleased]
2727

28+
### Improvements
29+
30+
* [#22832](https://github.com/cosmos/cosmos-sdk/pull/22832) Ensure the distribution module has at least as many tokens as outstanding rewards at genesis import
31+
2832
## [v0.2.0-rc.1](https://github.com/cosmos/cosmos-sdk/releases/tag/x/distribution/v0.2.0-rc.1) - 2024-12-18
2933

3034
### Improvements

x/distribution/keeper/genesis.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -126,8 +126,8 @@ func (k Keeper) InitGenesis(ctx context.Context, data types.GenesisState) error
126126
if balances.IsZero() {
127127
k.authKeeper.SetModuleAccount(ctx, moduleAcc)
128128
}
129-
if !balances.Equal(moduleHoldingsInt) {
130-
return fmt.Errorf("distribution module balance does not match the module holdings: %s <-> %s", balances, moduleHoldingsInt)
129+
if balances.IsAllLT(moduleHoldingsInt) {
130+
return fmt.Errorf("distribution module balance is less than module holdings: %s < %s", balances, moduleHoldingsInt)
131131
}
132132
return nil
133133
}

x/gov/CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,10 @@ Ref: https://keepachangelog.com/en/1.0.0/
2525

2626
## [Unreleased]
2727

28+
### Improvements
29+
30+
* [#22832](https://github.com/cosmos/cosmos-sdk/pull/22832) Ensure the governance module has at least as many tokens as are deposited at genesis import.
31+
2832
## [v0.2.0-rc.1](https://github.com/cosmos/cosmos-sdk/releases/tag/x/gov/v0.2.0-rc.1) - 2024-12-18
2933

3034
### Features

x/gov/genesis.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -79,9 +79,9 @@ func InitGenesis(ctx context.Context, ak types.AccountKeeper, bk types.BankKeepe
7979
ak.SetModuleAccount(ctx, moduleAcc)
8080
}
8181

82-
// check if total deposits equals balance, if it doesn't return an error
83-
if !balance.Equal(totalDeposits) {
84-
return fmt.Errorf("expected module account was %s but we got %s", balance.String(), totalDeposits.String())
82+
// check if the module account can cover the total deposits
83+
if !balance.IsAllGTE(totalDeposits) {
84+
return fmt.Errorf("expected gov module to hold at least %s, but it holds %s", totalDeposits, balance)
8585
}
8686
return nil
8787
}

0 commit comments

Comments
 (0)