Skip to content

Commit

Permalink
refactor(x/staking)!: removes the use of Accounts String() method (#1…
Browse files Browse the repository at this point in the history
  • Loading branch information
JulianToledano authored Mar 19, 2024
1 parent a7f9d92 commit 65ab253
Show file tree
Hide file tree
Showing 59 changed files with 680 additions and 427 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,9 @@ Every module contains its own CHANGELOG.md. Please refer to the module you are i

### API Breaking Changes

* (types) [#19742](https://github.com/cosmos/cosmos-sdk/pull/19742) Removes the use of `Accounts.String`
* `MsgSimulatorFn` now takes an `address.Codec` as argument and also returns an error.
* `SimulationState` now has address and validator codecs as fields.
* (types) [#19447](https://github.com/cosmos/cosmos-sdk/pull/19447) `module.testutil.MakeTestEncodingConfig` now takes `CodecOptions` as argument.
* (types) [#19512](https://github.com/cosmos/cosmos-sdk/pull/19512) Remove basic manager and all related functions (`module.BasicManager`, `module.NewBasicManager`, `module.NewBasicManagerFromManager`, `NewGenesisOnlyAppModule`).
* The module manager now can do everything that the basic manager was doing.
Expand Down
10 changes: 10 additions & 0 deletions UPGRADING.md
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,16 @@ If you were depending on `cosmossdk.io/api/tendermint`, please use the buf gener

#### `**all**`

##### Simulation

As an effort to remove the use of the global config, `sdk.Address.String` method must be removed. As a consequence, `MsgSimulatorFn` has been updated to return an error and use an `address.Codec` to set
`staking.MsgUpdateParams.Authority`.

```diff
-type MsgSimulatorFn func(r *rand.Rand, ctx sdk.Context, accs []Account) sdk.Msg
+type MsgSimulatorFn func(r *rand.Rand, ctx sdk.Context, accs []Account, cdc address.Codec) (sdk.Msg, error)
```

##### Core API

Core API has been introduced for modules since v0.47. With the deprecation of `sdk.Context`, we strongly recommend to use the `cosmossdk.io/core/appmodule` interfaces for the modules. This will allow the modules to work out of the box with server/v2 and baseapp, as well as limit their dependencies on the SDK.
Expand Down
2 changes: 1 addition & 1 deletion simapp/sim_bench_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ func BenchmarkFullAppSimulation(b *testing.B) {
b,
os.Stdout,
app.BaseApp,
simtestutil.AppStateFn(app.AppCodec(), app.SimulationManager(), app.DefaultGenesis()),
simtestutil.AppStateFn(app.AppCodec(), app.AuthKeeper.AddressCodec(), app.StakingKeeper.ValidatorAddressCodec(), app.SimulationManager(), app.DefaultGenesis()),
simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1
simtestutil.SimulationOperations(app, app.AppCodec(), config),
BlockedAddresses(),
Expand Down
10 changes: 5 additions & 5 deletions simapp/sim_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ func TestFullAppSimulation(t *testing.T) {
t,
os.Stdout,
app.BaseApp,
simtestutil.AppStateFn(app.AppCodec(), app.SimulationManager(), app.DefaultGenesis()),
simtestutil.AppStateFn(app.AppCodec(), app.AuthKeeper.AddressCodec(), app.StakingKeeper.ValidatorAddressCodec(), app.SimulationManager(), app.DefaultGenesis()),
simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1
simtestutil.SimulationOperations(app, app.AppCodec(), config),
BlockedAddresses(),
Expand Down Expand Up @@ -134,7 +134,7 @@ func TestAppImportExport(t *testing.T) {
t,
os.Stdout,
app.BaseApp,
simtestutil.AppStateFn(app.AppCodec(), app.SimulationManager(), app.DefaultGenesis()),
simtestutil.AppStateFn(app.AppCodec(), app.AuthKeeper.AddressCodec(), app.StakingKeeper.ValidatorAddressCodec(), app.SimulationManager(), app.DefaultGenesis()),
simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1
simtestutil.SimulationOperations(app, app.AppCodec(), config),
BlockedAddresses(),
Expand Down Expand Up @@ -255,7 +255,7 @@ func TestAppSimulationAfterImport(t *testing.T) {
t,
os.Stdout,
app.BaseApp,
simtestutil.AppStateFn(app.AppCodec(), app.SimulationManager(), app.DefaultGenesis()),
simtestutil.AppStateFn(app.AppCodec(), app.AuthKeeper.AddressCodec(), app.StakingKeeper.ValidatorAddressCodec(), app.SimulationManager(), app.DefaultGenesis()),
simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1
simtestutil.SimulationOperations(app, app.AppCodec(), config),
BlockedAddresses(),
Expand Down Expand Up @@ -307,7 +307,7 @@ func TestAppSimulationAfterImport(t *testing.T) {
t,
os.Stdout,
newApp.BaseApp,
simtestutil.AppStateFn(app.AppCodec(), app.SimulationManager(), app.DefaultGenesis()),
simtestutil.AppStateFn(app.AppCodec(), app.AuthKeeper.AddressCodec(), app.StakingKeeper.ValidatorAddressCodec(), app.SimulationManager(), app.DefaultGenesis()),
simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1
simtestutil.SimulationOperations(newApp, newApp.AppCodec(), config),
BlockedAddresses(),
Expand Down Expand Up @@ -386,7 +386,7 @@ func TestAppStateDeterminism(t *testing.T) {
t,
os.Stdout,
app.BaseApp,
simtestutil.AppStateFn(app.AppCodec(), app.SimulationManager(), app.DefaultGenesis()),
simtestutil.AppStateFn(app.AppCodec(), app.AuthKeeper.AddressCodec(), app.StakingKeeper.ValidatorAddressCodec(), app.SimulationManager(), app.DefaultGenesis()),
simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1
simtestutil.SimulationOperations(app, app.AppCodec(), config),
BlockedAddresses(),
Expand Down
12 changes: 10 additions & 2 deletions tests/integration/evidence/keeper/infraction_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,11 @@ func TestHandleDoubleSign(t *testing.T) {
totalBond := validator.TokensFromShares(del.GetShares()).TruncateInt()
tstaking.Ctx = ctx
tstaking.Denom = stakingParams.BondDenom
tstaking.Undelegate(sdk.AccAddress(operatorAddr), operatorAddr, totalBond, true)
accAddr, err := f.accountKeeper.AddressCodec().BytesToString(operatorAddr)
assert.NilError(t, err)
opAddr, err := f.stakingKeeper.ValidatorAddressCodec().BytesToString(operatorAddr)
assert.NilError(t, err)
tstaking.Undelegate(accAddr, opAddr, totalBond, true)

// query evidence from store
iter, err := f.evidenceKeeper.Evidences.Iterate(ctx, nil)
Expand Down Expand Up @@ -424,7 +428,11 @@ func TestHandleDoubleSignAfterRotation(t *testing.T) {
totalBond := validator.TokensFromShares(del.GetShares()).TruncateInt()
tstaking.Ctx = ctx
tstaking.Denom = stakingParams.BondDenom
tstaking.Undelegate(sdk.AccAddress(operatorAddr), operatorAddr, totalBond, true)
accAddr, err := f.accountKeeper.AddressCodec().BytesToString(operatorAddr)
assert.NilError(t, err)
opAddr, err := f.stakingKeeper.ValidatorAddressCodec().BytesToString(operatorAddr)
assert.NilError(t, err)
tstaking.Undelegate(accAddr, opAddr, totalBond, true)

// query evidence from store
var evidences []exported.Evidence
Expand Down
20 changes: 16 additions & 4 deletions tests/integration/slashing/keeper/keeper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,11 @@ func TestUnJailNotBonded(t *testing.T) {

// unbond below minimum self-delegation
assert.Equal(t, p.BondDenom, tstaking.Denom)
tstaking.Undelegate(sdk.AccAddress(addr), addr, f.stakingKeeper.TokensFromConsensusPower(f.ctx, 1), true)
accAddr, err := f.accountKeeper.AddressCodec().BytesToString(addr)
assert.NilError(t, err)
valAddr, err := f.stakingKeeper.ValidatorAddressCodec().BytesToString(addr)
require.NoError(t, err)
tstaking.Undelegate(accAddr, valAddr, f.stakingKeeper.TokensFromConsensusPower(f.ctx, 1), true)

_, err = f.stakingKeeper.EndBlocker(f.ctx)
assert.NilError(t, err)
Expand All @@ -220,8 +224,12 @@ func TestUnJailNotBonded(t *testing.T) {
assert.NilError(t, err)
newHeight = f.ctx.BlockHeight() + 1
f.ctx = f.ctx.WithBlockHeight(newHeight).WithHeaderInfo(coreheader.Info{Height: newHeight})
// bond to meet minimum self-delegation
tstaking.DelegateWithPower(sdk.AccAddress(addr), addr, 1)
// bond to meet minimum self-delegationa
accAddr, err = f.accountKeeper.AddressCodec().BytesToString(addr)
assert.NilError(t, err)
valAddr, err = f.stakingKeeper.ValidatorAddressCodec().BytesToString(addr)
assert.NilError(t, err)
tstaking.DelegateWithPower(accAddr, valAddr, 1)

_, err = f.stakingKeeper.EndBlocker(f.ctx)
assert.NilError(t, err)
Expand Down Expand Up @@ -430,7 +438,11 @@ func TestValidatorDippingInAndOut(t *testing.T) {
f.ctx = f.ctx.WithBlockHeight(height).WithHeaderInfo(coreheader.Info{Height: height})

// validator added back in
tstaking.DelegateWithPower(sdk.AccAddress(pks[2].Address()), valAddr, 50)
accAddr, err := f.accountKeeper.AddressCodec().BytesToString(sdk.AccAddress(pks[2].Address()))
assert.NilError(t, err)
vAddr, err := f.stakingKeeper.ValidatorAddressCodec().BytesToString(valAddr)
assert.NilError(t, err)
tstaking.DelegateWithPower(accAddr, vAddr, 50)

validatorUpdates, err = f.stakingKeeper.EndBlocker(f.ctx)
require.NoError(t, err)
Expand Down
5 changes: 3 additions & 2 deletions tests/sims/gov/operations_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"github.com/cosmos/gogoproto/proto"
"github.com/stretchr/testify/require"

"cosmossdk.io/core/address"
"cosmossdk.io/core/header"
"cosmossdk.io/depinject"
"cosmossdk.io/log"
Expand Down Expand Up @@ -55,8 +56,8 @@ func (m MockWeightedProposals) DefaultWeight() int {
}

func (m MockWeightedProposals) MsgSimulatorFn() simtypes.MsgSimulatorFn {
return func(r *rand.Rand, _ sdk.Context, _ []simtypes.Account) sdk.Msg {
return nil
return func(r *rand.Rand, _ sdk.Context, _ []simtypes.Account, _ address.Codec) (sdk.Msg, error) {
return nil, nil
}
}

Expand Down
10 changes: 6 additions & 4 deletions testutil/sims/simulation_helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,12 @@ func SetupSimulation(config simtypes.Config, dirPrefix, dbName string, verbose,
func SimulationOperations(app runtime.AppSimI, cdc codec.Codec, config simtypes.Config) []simtypes.WeightedOperation {
signingCtx := cdc.InterfaceRegistry().SigningContext()
simState := module.SimulationState{
AppParams: make(simtypes.AppParams),
Cdc: cdc,
TxConfig: authtx.NewTxConfig(cdc, signingCtx.AddressCodec(), signingCtx.ValidatorAddressCodec(), authtx.DefaultSignModes), // TODO(tip): we should extract this from app
BondDenom: sdk.DefaultBondDenom,
AppParams: make(simtypes.AppParams),
Cdc: cdc,
AddressCodec: signingCtx.AddressCodec(),
ValidatorCodec: signingCtx.ValidatorAddressCodec(),
TxConfig: authtx.NewTxConfig(cdc, signingCtx.AddressCodec(), signingCtx.ValidatorAddressCodec(), authtx.DefaultSignModes), // TODO(tip): we should extract this from app
BondDenom: sdk.DefaultBondDenom,
}

if config.ParamsFile != "" {
Expand Down
34 changes: 20 additions & 14 deletions testutil/sims/state_helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (

"github.com/cosmos/gogoproto/proto"

"cosmossdk.io/core/address"
"cosmossdk.io/math"
authtypes "cosmossdk.io/x/auth/types"
banktypes "cosmossdk.io/x/bank/types"
Expand All @@ -36,19 +37,20 @@ const (

// AppStateFn returns the initial application state using a genesis or the simulation parameters.
// It calls AppStateFnWithExtendedCb with nil rawStateCb.
func AppStateFn(cdc codec.JSONCodec, simManager *module.SimulationManager, genesisState map[string]json.RawMessage) simtypes.AppStateFn {
return AppStateFnWithExtendedCb(cdc, simManager, genesisState, nil)
func AppStateFn(cdc codec.JSONCodec, addresCodec, validatorCodec address.Codec, simManager *module.SimulationManager, genesisState map[string]json.RawMessage) simtypes.AppStateFn {
return AppStateFnWithExtendedCb(cdc, addresCodec, validatorCodec, simManager, genesisState, nil)
}

// AppStateFnWithExtendedCb returns the initial application state using a genesis or the simulation parameters.
// It calls AppStateFnWithExtendedCbs with nil moduleStateCb.
func AppStateFnWithExtendedCb(
cdc codec.JSONCodec,
addresCodec, validatorCodec address.Codec,
simManager *module.SimulationManager,
genesisState map[string]json.RawMessage,
rawStateCb func(rawState map[string]json.RawMessage),
) simtypes.AppStateFn {
return AppStateFnWithExtendedCbs(cdc, simManager, genesisState, nil, rawStateCb)
return AppStateFnWithExtendedCbs(cdc, addresCodec, validatorCodec, simManager, genesisState, nil, rawStateCb)
}

// AppStateFnWithExtendedCbs returns the initial application state using a genesis or the simulation parameters.
Expand All @@ -59,6 +61,7 @@ func AppStateFnWithExtendedCb(
// rawStateCb is the callback function to extend rawState.
func AppStateFnWithExtendedCbs(
cdc codec.JSONCodec,
addressCodec, validatorCodec address.Codec,
simManager *module.SimulationManager,
genesisState map[string]json.RawMessage,
moduleStateCb func(moduleName string, genesisState interface{}),
Expand Down Expand Up @@ -103,11 +106,11 @@ func AppStateFnWithExtendedCbs(
if err != nil {
panic(err)
}
appState, simAccs = AppStateRandomizedFn(simManager, r, cdc, accs, genesisTimestamp, appParams, genesisState)
appState, simAccs = AppStateRandomizedFn(simManager, r, cdc, accs, genesisTimestamp, appParams, genesisState, addressCodec, validatorCodec)

default:
appParams := make(simtypes.AppParams)
appState, simAccs = AppStateRandomizedFn(simManager, r, cdc, accs, genesisTimestamp, appParams, genesisState)
appState, simAccs = AppStateRandomizedFn(simManager, r, cdc, accs, genesisTimestamp, appParams, genesisState, addressCodec, validatorCodec)
}

rawState := make(map[string]json.RawMessage)
Expand Down Expand Up @@ -195,6 +198,7 @@ func AppStateRandomizedFn(
genesisTimestamp time.Time,
appParams simtypes.AppParams,
genesisState map[string]json.RawMessage,
addressCodec, validatorCodec address.Codec,
) (json.RawMessage, []simtypes.Account) {
numAccs := int64(len(accs))
// generate a random amount of initial stake coins and a random initial
Expand Down Expand Up @@ -226,15 +230,17 @@ func AppStateRandomizedFn(
)

simState := &module.SimulationState{
AppParams: appParams,
Cdc: cdc,
Rand: r,
GenState: genesisState,
Accounts: accs,
InitialStake: initialStake,
NumBonded: numInitiallyBonded,
BondDenom: sdk.DefaultBondDenom,
GenTimestamp: genesisTimestamp,
AppParams: appParams,
Cdc: cdc,
AddressCodec: addressCodec,
ValidatorCodec: validatorCodec,
Rand: r,
GenState: genesisState,
Accounts: accs,
InitialStake: initialStake,
NumBonded: numInitiallyBonded,
BondDenom: sdk.DefaultBondDenom,
GenTimestamp: genesisTimestamp,
}

simManager.GenerateGenesisStates(simState)
Expand Down
3 changes: 3 additions & 0 deletions types/module/simulation.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"sort"
"time"

"cosmossdk.io/core/address"
"cosmossdk.io/core/appmodule"
sdkmath "cosmossdk.io/math"

Expand Down Expand Up @@ -145,6 +146,8 @@ func (sm *SimulationManager) WeightedOperations(simState SimulationState) []simu
type SimulationState struct {
AppParams simulation.AppParams
Cdc codec.JSONCodec // application codec
AddressCodec address.Codec // address codec
ValidatorCodec address.Codec // validator address codec
TxConfig client.TxConfig // Shared TxConfig; this is expensive to create and stateless, so create it once up front.
Rand *rand.Rand // random number
GenState map[string]json.RawMessage // genesis state
Expand Down
4 changes: 3 additions & 1 deletion types/simulation/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import (

"github.com/cosmos/gogoproto/proto"

"cosmossdk.io/core/address"

"github.com/cosmos/cosmos-sdk/baseapp"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/kv"
Expand Down Expand Up @@ -39,7 +41,7 @@ type WeightedProposalMsg interface {
MsgSimulatorFn() MsgSimulatorFn // msg simulator function
}

type MsgSimulatorFn func(r *rand.Rand, ctx sdk.Context, accs []Account) sdk.Msg
type MsgSimulatorFn func(r *rand.Rand, ctx sdk.Context, accs []Account, cdc address.Codec) (sdk.Msg, error)

type SimValFn func(r *rand.Rand) string

Expand Down
19 changes: 11 additions & 8 deletions x/auth/simulation/genesis_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"cosmossdk.io/x/auth/types"

"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/codec/testutil"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/types/module"
simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
Expand All @@ -23,18 +24,20 @@ func TestRandomizedGenState(t *testing.T) {
registry := codectypes.NewInterfaceRegistry()
types.RegisterInterfaces(registry)
cdc := codec.NewProtoCodec(registry)

cdcOpts := testutil.CodecOptions{}
s := rand.NewSource(1)
r := rand.New(s)

simState := module.SimulationState{
AppParams: make(simtypes.AppParams),
Cdc: cdc,
Rand: r,
NumBonded: 3,
Accounts: simtypes.RandomAccounts(r, 3),
InitialStake: sdkmath.NewInt(1000),
GenState: make(map[string]json.RawMessage),
AppParams: make(simtypes.AppParams),
Cdc: cdc,
AddressCodec: cdcOpts.GetAddressCodec(),
ValidatorCodec: cdcOpts.GetValidatorCodec(),
Rand: r,
NumBonded: 3,
Accounts: simtypes.RandomAccounts(r, 3),
InitialStake: sdkmath.NewInt(1000),
GenState: make(map[string]json.RawMessage),
}

simulation.RandomizedGenState(&simState, simulation.RandomGenesisAccounts)
Expand Down
5 changes: 3 additions & 2 deletions x/auth/simulation/proposals.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package simulation
import (
"math/rand"

coreaddress "cosmossdk.io/core/address"
"cosmossdk.io/x/auth/types"

sdk "github.com/cosmos/cosmos-sdk/types"
Expand Down Expand Up @@ -30,7 +31,7 @@ func ProposalMsgs() []simtypes.WeightedProposalMsg {
}

// SimulateMsgUpdateParams returns a random MsgUpdateParams
func SimulateMsgUpdateParams(r *rand.Rand, _ sdk.Context, _ []simtypes.Account) sdk.Msg {
func SimulateMsgUpdateParams(r *rand.Rand, _ sdk.Context, _ []simtypes.Account, _ coreaddress.Codec) (sdk.Msg, error) {
// use the default gov module account address as authority
var authority sdk.AccAddress = address.Module("gov")

Expand All @@ -44,5 +45,5 @@ func SimulateMsgUpdateParams(r *rand.Rand, _ sdk.Context, _ []simtypes.Account)
return &types.MsgUpdateParams{
Authority: authority.String(),
Params: params,
}
}, nil
}
4 changes: 3 additions & 1 deletion x/auth/simulation/proposals_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"cosmossdk.io/x/auth/simulation"
"cosmossdk.io/x/auth/types"

codectestutil "github.com/cosmos/cosmos-sdk/codec/testutil"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/address"
simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
Expand All @@ -32,7 +33,8 @@ func TestProposalMsgs(t *testing.T) {
assert.Equal(t, simulation.OpWeightMsgUpdateParams, w0.AppParamsKey())
assert.Equal(t, simulation.DefaultWeightMsgUpdateParams, w0.DefaultWeight())

msg := w0.MsgSimulatorFn()(r, ctx, accounts)
msg, err := w0.MsgSimulatorFn()(r, ctx, accounts, codectestutil.CodecOptions{}.GetAddressCodec())
assert.NilError(t, err)
msgUpdateParams, ok := msg.(*types.MsgUpdateParams)
assert.Assert(t, ok)

Expand Down
Loading

0 comments on commit 65ab253

Please sign in to comment.