Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

v2.12.0 #910

Closed
wants to merge 29 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
501 changes: 286 additions & 215 deletions app/app.go

Large diffs are not rendered by default.

118 changes: 67 additions & 51 deletions app/app_test.go
Original file line number Diff line number Diff line change
@@ -1,53 +1,69 @@
package app

//
//import (
// "os"
// "testing"
//
// "github.com/stretchr/testify/require"
//
// dbm "github.com/cometbft/cometbft-db"
// "github.com/cometbft/cometbft/libs/log"
//)
//
//func TestSimAppExport(t *testing.T) {
// encCfg := MakeEncodingConfig()
// db := dbm.NewMemDB()
// logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout))
// app := NewSimappWithCustomOptions(t, false, SetupOptions{
// Logger: logger,
// DB: db,
// InvCheckPeriod: 0,
// EncConfig: encCfg,
// HomePath: DefaultNodeHome,
// SkipUpgradeHeights: map[int64]bool{},
// AppOpts: EmptyAppOptions{},
// })
//
// for acc := range maccPerms {
// require.True(
// t,
// app.BankKeeper.BlockedAddr(app.AccountKeeper.GetModuleAddress(acc)),
// "ensure that blocked addresses are properly set in bank keeper",
// )
// }
//
// app.Commit()
//
// logger2 := log.NewTMLogger(log.NewSyncWriter(os.Stdout))
// // make a new app object with the db so that initchain hasn't been called
// app2 := NewShentuApp(logger2, db, nil, true, map[int64]bool{}, DefaultNodeHome, 1, encCfg, EmptyAppOptions{})
// _, err := app2.ExportAppStateAndValidators(false, []string{})
// require.NoError(t, err, "ExportAppStateAndValidators should not have an error")
// //_, err = app2.ExportAppStateAndValidators(true, []string{})
// //require.NoError(t, err, "ExportAppStateAndValidators for zero height should not have an error")
//}
//
//func TestGetMaccPerms(t *testing.T) {
// dup := make(map[string][]string)
// for k, v := range maccPerms {
// dup[k] = v
// }
// require.Equal(t, maccPerms, dup, "duplicated module account permissions differed from actual module account permissions")
//}
import (
"fmt"
"testing"

"cosmossdk.io/log"
"github.com/stretchr/testify/require"

dbm "github.com/cosmos/cosmos-db"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/ibc-go/v8/testing/simapp"
)

func TestSimAppExportAndBlockedAddrs(t *testing.T) {
db := dbm.NewMemDB()
logger := log.NewTestLogger(t)
app := NewShentuAppWithCustomOptions(t, false, simapp.SetupOptions{
Logger: logger.With("instance", "first"),
DB: db,
AppOpts: simtestutil.NewAppOptionsWithFlagHome(t.TempDir()),
})

// BlockedAddresses returns a map of addresses in app v1 and a map of modules name in app di.
for acc := range app.ModuleAccountAddrs() {
var addr sdk.AccAddress
if modAddr, err := sdk.AccAddressFromBech32(acc); err == nil {
addr = modAddr
} else {
addr = app.AccountKeeper.GetModuleAddress(acc)
}

require.True(
t,
app.BankKeeper.BlockedAddr(addr),
fmt.Sprintf("ensure that blocked addresses are properly set in bank keeper: %s should be blocked", acc),
)
}

t.Log(app.AuthKeeper)
}

func TestSimAppExport(t *testing.T) {
db := dbm.NewMemDB()
logger := log.NewTestLogger(t)
appOpts := simapp.SetupOptions{
Logger: logger.With("instance", "first"),
DB: db,
AppOpts: simtestutil.NewAppOptionsWithFlagHome(t.TempDir()),
}
app := NewShentuAppWithCustomOptions(t, false, appOpts)

for acc := range maccPerms {
require.True(
t,
app.BankKeeper.BlockedAddr(app.AccountKeeper.GetModuleAddress(acc)),
"ensure that blocked addresses are properly set in bank keeper",
)
}

//logger2 := log.NewTestLogger(t)
// make a new app object with the db so that initchain hasn't been called
//app2 := NewShentuApp(logger2, db, nil, true, simtestutil.NewAppOptionsWithFlagHome(""), baseapp.SetChainID("test"))
//_, err := app2.ExportAppStateAndValidators(false, []string{}, []string{})
//require.NoError(t, err, "ExportAppStateAndValidators should not have an error")
//_, err = app2.ExportAppStateAndValidators(true, []string{}, []string{})
//require.NoError(t, err, "ExportAppStateAndValidators for zero height should not have an error")
}
2 changes: 0 additions & 2 deletions app/encoding.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,5 @@ func MakeEncodingConfig() params.EncodingConfig {
encodingConfig := params.MakeEncodingConfig()
std.RegisterLegacyAminoCodec(encodingConfig.Amino)
std.RegisterInterfaces(encodingConfig.InterfaceRegistry)
ModuleBasics.RegisterLegacyAminoCodec(encodingConfig.Amino)
ModuleBasics.RegisterInterfaces(encodingConfig.InterfaceRegistry)
return encodingConfig
}
96 changes: 73 additions & 23 deletions app/export.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@ package app

import (
"encoding/json"
"fmt"
"log"

storetypes "cosmossdk.io/store/types"
tmproto "github.com/cometbft/cometbft/proto/tendermint/types"

servertypes "github.com/cosmos/cosmos-sdk/server/types"
sdk "github.com/cosmos/cosmos-sdk/types"
distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types"
slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types"
"github.com/cosmos/cosmos-sdk/x/staking"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
Expand All @@ -17,7 +18,7 @@ import (
// ExportAppStateAndValidators exports the application state for a genesis file.
func (app *ShentuApp) ExportAppStateAndValidators(forZeroHeight bool, jailWhiteList []string, modulesToExport []string) (servertypes.ExportedApp, error) {
// as if they could withdraw from the start of the next block
ctx := app.NewContext(true, tmproto.Header{Height: app.LastBlockHeight()})
ctx := app.NewContextLegacy(true, tmproto.Header{Height: app.LastBlockHeight()})

// We export at last height + 1, because that's the height at which
// Tendermint will start InitChain.
Expand All @@ -28,7 +29,10 @@ func (app *ShentuApp) ExportAppStateAndValidators(forZeroHeight bool, jailWhiteL
app.prepForZeroHeightGenesis(ctx, jailWhiteList)
}

genState := app.mm.ExportGenesisForModules(ctx, app.appCodec, modulesToExport)
genState, err := app.mm.ExportGenesisForModules(ctx, app.appCodec, modulesToExport)
if err != nil {
return servertypes.ExportedApp{}, err
}
appState, err := json.MarshalIndent(genState, "", " ")
if err != nil {
return servertypes.ExportedApp{}, err
Expand Down Expand Up @@ -72,21 +76,33 @@ func (app *ShentuApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs
/* Handle fee distribution state. */

// withdraw all validator commission
app.StakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) {
_, err := app.DistrKeeper.WithdrawValidatorCommission(ctx, val.GetOperator())
if err != distrtypes.ErrNoValidatorCommission && err != nil {
err := app.StakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) {
valBz, err := app.StakingKeeper.ValidatorAddressCodec().StringToBytes(val.GetOperator())
if err != nil {
panic(err)
}
_, _ = app.DistrKeeper.WithdrawValidatorCommission(ctx, valBz)
return false
})
if err != nil {
panic(err)
}

// withdraw all delegator rewards
dels := app.StakingKeeper.GetAllDelegations(ctx)
dels, err := app.StakingKeeper.GetAllDelegations(ctx)
if err != nil {
panic(err)
}

for _, delegation := range dels {
_, err := app.DistrKeeper.WithdrawDelegationRewards(ctx, delegation.GetDelegatorAddr(), delegation.GetValidatorAddr())
valAddr, err := sdk.ValAddressFromBech32(delegation.ValidatorAddress)
if err != nil {
panic(err)
}

delAddr := sdk.MustAccAddressFromBech32(delegation.DelegatorAddress)

_, _ = app.DistrKeeper.WithdrawDelegationRewards(ctx, delAddr, valAddr)
}

// clear validator slash events
Expand All @@ -100,23 +116,48 @@ func (app *ShentuApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs
ctx = ctx.WithBlockHeight(0)

// reinitialize all validators
app.StakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) {
err = app.StakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) {
valBz, err := app.StakingKeeper.ValidatorAddressCodec().StringToBytes(val.GetOperator())
if err != nil {
panic(err)
}
// donate any unwithdrawn outstanding reward fraction tokens to the community pool
scraps := app.DistrKeeper.GetValidatorOutstandingRewardsCoins(ctx, val.GetOperator())
feePool := app.DistrKeeper.GetFeePool(ctx)
scraps, err := app.DistrKeeper.GetValidatorOutstandingRewardsCoins(ctx, valBz)
if err != nil {
panic(err)
}
feePool, err := app.DistrKeeper.FeePool.Get(ctx)
if err != nil {
panic(err)
}
feePool.CommunityPool = feePool.CommunityPool.Add(scraps...)
app.DistrKeeper.SetFeePool(ctx, feePool)
if err := app.DistrKeeper.FeePool.Set(ctx, feePool); err != nil {
panic(err)
}

if err := app.DistrKeeper.Hooks().AfterValidatorCreated(ctx, val.GetOperator()); err != nil {
if err := app.DistrKeeper.Hooks().AfterValidatorCreated(ctx, valBz); err != nil {
panic(err)
}
return false
})

// reinitialize all delegations
for _, del := range dels {
app.DistrKeeper.Hooks().BeforeDelegationCreated(ctx, del.GetDelegatorAddr(), del.GetValidatorAddr())
app.DistrKeeper.Hooks().AfterDelegationModified(ctx, del.GetDelegatorAddr(), del.GetValidatorAddr())
valAddr, err := sdk.ValAddressFromBech32(del.ValidatorAddress)
if err != nil {
panic(err)
}
delAddr := sdk.MustAccAddressFromBech32(del.DelegatorAddress)

if err := app.DistrKeeper.Hooks().BeforeDelegationCreated(ctx, delAddr, valAddr); err != nil {
// never called as BeforeDelegationCreated always returns nil
panic(fmt.Errorf("error while incrementing period: %w", err))
}

if err := app.DistrKeeper.Hooks().AfterDelegationModified(ctx, delAddr, valAddr); err != nil {
// never called as AfterDelegationModified always returns nil
panic(fmt.Errorf("error while creating a new delegation period record: %w", err))
}
}

// reset context height
Expand All @@ -129,7 +170,10 @@ func (app *ShentuApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs
for i := range red.Entries {
red.Entries[i].CreationHeight = 0
}
app.StakingKeeper.SetRedelegation(ctx, red)
err = app.StakingKeeper.SetRedelegation(ctx, red)
if err != nil {
panic(err)
}
return false
})

Expand All @@ -138,20 +182,23 @@ func (app *ShentuApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs
for i := range ubd.Entries {
ubd.Entries[i].CreationHeight = 0
}
app.StakingKeeper.SetUnbondingDelegation(ctx, ubd)
err = app.StakingKeeper.SetUnbondingDelegation(ctx, ubd)
if err != nil {
panic(err)
}
return false
})

// Iterate through validators by power descending, reset bond heights, and
// update bond intra-tx counters.
store := ctx.KVStore(app.keys[stakingtypes.StoreKey])
iter := sdk.KVStoreReversePrefixIterator(store, stakingtypes.ValidatorsKey)
store := ctx.KVStore(app.GetKey(stakingtypes.StoreKey))
iter := storetypes.KVStoreReversePrefixIterator(store, stakingtypes.ValidatorsKey)
counter := int16(0)

for ; iter.Valid(); iter.Next() {
addr := sdk.ValAddress(stakingtypes.AddressFromValidatorsKey(iter.Key()))
validator, found := app.StakingKeeper.GetValidator(ctx, addr)
if !found {
validator, err := app.StakingKeeper.GetValidator(ctx, addr)
if err != nil {
panic("expected validator, not found")
}

Expand All @@ -164,9 +211,12 @@ func (app *ShentuApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs
counter++
}

iter.Close()
if err := iter.Close(); err != nil {
app.Logger().Error("error while closing the key-value store reverse prefix iterator: ", err)
return
}

_, err := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
_, err = app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
if err != nil {
log.Fatal(err)
}
Expand Down
52 changes: 23 additions & 29 deletions app/export_test.go
Original file line number Diff line number Diff line change
@@ -1,31 +1,25 @@
package app

import (
"testing"

"github.com/stretchr/testify/require"
)

func TestExportAppStateAndValidators(t *testing.T) {
testCases := []struct {
name string
forZeroHeight bool
}{
{
"for zero height",
true,
},
{
"for non-zero height",
false,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
app := Setup(t, false)
app.Commit()
_, err := app.ExportAppStateAndValidators(tc.forZeroHeight, []string{}, []string{})
require.NoError(t, err, "ExportAppStateAndValidators should not have an error")
})
}
}
//func TestExportAppStateAndValidators(t *testing.T) {
// testCases := []struct {
// name string
// forZeroHeight bool
// }{
// {
// "for zero height",
// true,
// },
// {
// "for non-zero height",
// false,
// },
// }
// for _, tc := range testCases {
// t.Run(tc.name, func(t *testing.T) {
// app := Setup(t, false)
// app.Commit()
// _, err := app.ExportAppStateAndValidators(tc.forZeroHeight, []string{}, []string{})
// require.NoError(t, err, "ExportAppStateAndValidators should not have an error")
// })
// }
//}
Loading
Loading