(no commit message provided)

This commit is contained in:
Prad Nukala
2024-07-05 22:20:13 -04:00
committed by Prad Nukala (aider)
commit 5fd43dfd6b
457 changed files with 115535 additions and 0 deletions
+74
View File
@@ -0,0 +1,74 @@
package app
import (
"errors"
ibcante "github.com/cosmos/ibc-go/v8/modules/core/ante"
"github.com/cosmos/ibc-go/v8/modules/core/keeper"
circuitante "cosmossdk.io/x/circuit/ante"
circuitkeeper "cosmossdk.io/x/circuit/keeper"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth/ante"
stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper"
sdkmath "cosmossdk.io/math"
poaante "github.com/strangelove-ventures/poa/ante"
globalfeeante "github.com/strangelove-ventures/globalfee/x/globalfee/ante"
globalfeekeeper "github.com/strangelove-ventures/globalfee/x/globalfee/keeper"
)
// HandlerOptions extend the SDK's AnteHandler options by requiring the IBC
// channel keeper.
type HandlerOptions struct {
ante.HandlerOptions
IBCKeeper *keeper.Keeper
CircuitKeeper *circuitkeeper.Keeper
StakingKeeper *stakingkeeper.Keeper
GlobalFeeKeeper globalfeekeeper.Keeper
BypassMinFeeMsgTypes []string
}
// NewAnteHandler constructor
func NewAnteHandler(options HandlerOptions) (sdk.AnteHandler, error) {
if options.AccountKeeper == nil {
return nil, errors.New("account keeper is required for ante builder")
}
if options.BankKeeper == nil {
return nil, errors.New("bank keeper is required for ante builder")
}
if options.SignModeHandler == nil {
return nil, errors.New("sign mode handler is required for ante builder")
}
if options.CircuitKeeper == nil {
return nil, errors.New("circuit keeper is required for ante builder")
}
poaDoGenTxRateValidation := false
poaRateFloor := sdkmath.LegacyMustNewDecFromStr("0.10")
poaRateCeil := sdkmath.LegacyMustNewDecFromStr("0.50")
anteDecorators := []sdk.AnteDecorator{
ante.NewSetUpContextDecorator(), // outermost AnteDecorator. SetUpContext must be called first
circuitante.NewCircuitBreakerDecorator(options.CircuitKeeper),
ante.NewExtensionOptionsDecorator(options.ExtensionOptionChecker),
ante.NewValidateBasicDecorator(),
ante.NewTxTimeoutHeightDecorator(),
ante.NewValidateMemoDecorator(options.AccountKeeper),
ante.NewConsumeGasForTxSizeDecorator(options.AccountKeeper),
globalfeeante.NewFeeDecorator(options.BypassMinFeeMsgTypes, options.GlobalFeeKeeper, options.StakingKeeper, 2_000_000),
// ante.NewDeductFeeDecorator(options.AccountKeeper, options.BankKeeper, options.FeegrantKeeper, options.TxFeeChecker),
ante.NewSetPubKeyDecorator(options.AccountKeeper), // SetPubKeyDecorator must be called before all signature verification decorators
ante.NewValidateSigCountDecorator(options.AccountKeeper),
ante.NewSigGasConsumeDecorator(options.AccountKeeper, options.SigGasConsumer),
ante.NewSigVerificationDecorator(options.AccountKeeper, options.SignModeHandler),
ante.NewIncrementSequenceDecorator(options.AccountKeeper),
ibcante.NewRedundantRelayDecorator(options.IBCKeeper),
poaante.NewPOADisableStakingDecorator(),
poaante.NewCommissionLimitDecorator(poaDoGenTxRateValidation, poaRateFloor, poaRateCeil),
}
return sdk.ChainAnteDecorators(anteDecorators...), nil
}
+1456
View File
File diff suppressed because it is too large Load Diff
+62
View File
@@ -0,0 +1,62 @@
package app
import (
"testing"
abci "github.com/cometbft/cometbft/abci/types"
dbm "github.com/cosmos/cosmos-db"
"github.com/stretchr/testify/require"
"cosmossdk.io/log"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
)
func TestAppExport(t *testing.T) {
db := dbm.NewMemDB()
logger := log.NewTestLogger(t)
gapp := NewChainAppWithCustomOptions(t, false, SetupOptions{
Logger: logger.With("instance", "first"),
DB: db,
AppOpts: simtestutil.NewAppOptionsWithFlagHome(t.TempDir()),
})
// finalize block so we have CheckTx state set
_, err := gapp.FinalizeBlock(&abci.RequestFinalizeBlock{
Height: 1,
})
require.NoError(t, err)
_, err = gapp.Commit()
require.NoError(t, err)
// Making a new app object with the db, so that initchain hasn't been called
newGapp := NewChainApp(
logger, db, nil, true, simtestutil.NewAppOptionsWithFlagHome(t.TempDir()),
)
_, err = newGapp.ExportAppStateAndValidators(false, []string{}, nil)
require.NoError(t, err, "ExportAppStateAndValidators should not have an error")
}
// ensure that blocked addresses are properly set in bank keeper
func TestBlockedAddrs(t *testing.T) {
gapp := Setup(t)
for acc := range BlockedAddresses() {
t.Run(acc, func(t *testing.T) {
var addr sdk.AccAddress
if modAddr, err := sdk.AccAddressFromBech32(acc); err == nil {
addr = modAddr
} else {
addr = gapp.AccountKeeper.GetModuleAddress(acc)
}
require.True(t, gapp.BankKeeper.BlockedAddr(addr), "ensure that blocked addresses are properly set in bank keeper")
})
}
}
func TestGetMaccPerms(t *testing.T) {
dup := GetMaccPerms()
require.Equal(t, maccPerms, dup, "duplicated module account permissions differed from actual module account permissions")
}
+59
View File
@@ -0,0 +1,59 @@
package decorators
import (
"fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/authz"
"github.com/cosmos/gogoproto/proto"
)
// MsgFilterDecorator is an ante.go decorator template for filtering messages.
type MsgFilterDecorator struct {
blockedTypes []sdk.Msg
}
// FilterDecorator returns a new MsgFilterDecorator. This errors if the transaction
// contains any of the blocked message types.
//
// Example:
// - decorators.FilterDecorator(&banktypes.MsgSend{})
// This would block any MsgSend messages from being included in a transaction if set in ante.go
func FilterDecorator(blockedMsgTypes ...sdk.Msg) MsgFilterDecorator {
return MsgFilterDecorator{
blockedTypes: blockedMsgTypes,
}
}
func (mfd MsgFilterDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (newCtx sdk.Context, err error) {
if mfd.HasDisallowedMessage(ctx, tx.GetMsgs()) {
currHeight := ctx.BlockHeight()
return ctx, fmt.Errorf("tx contains unsupported message types at height %d", currHeight)
}
return next(ctx, tx, simulate)
}
func (mfd MsgFilterDecorator) HasDisallowedMessage(ctx sdk.Context, msgs []sdk.Msg) bool {
for _, msg := range msgs {
// check nested messages in a recursive manner
if execMsg, ok := msg.(*authz.MsgExec); ok {
msgs, err := execMsg.GetMessages()
if err != nil {
return true
}
if mfd.HasDisallowedMessage(ctx, msgs) {
return true
}
}
for _, blockedType := range mfd.blockedTypes {
if proto.MessageName(msg) == proto.MessageName(blockedType) {
return true
}
}
}
return false
}
+55
View File
@@ -0,0 +1,55 @@
package decorators_test
import (
"testing"
sdkmath "cosmossdk.io/math"
"github.com/cometbft/cometbft/crypto/secp256k1"
sdk "github.com/cosmos/cosmos-sdk/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/stretchr/testify/suite"
app "github.com/onsonr/hway/app"
"github.com/onsonr/hway/app/decorators"
)
type AnteTestSuite struct {
suite.Suite
ctx sdk.Context
app *app.SonrApp
}
func (s *AnteTestSuite) SetupTest() {
isCheckTx := false
s.app = app.Setup(s.T())
s.ctx = s.app.BaseApp.NewContext(isCheckTx)
}
func TestAnteTestSuite(t *testing.T) {
suite.Run(t, new(AnteTestSuite))
}
// Test the change rate decorator with standard edit msgs,
func (s *AnteTestSuite) TestAnteMsgFilterLogic() {
acc := sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address())
// test blocking any BankSend Messages
ante := decorators.FilterDecorator(&banktypes.MsgSend{})
msg := banktypes.NewMsgSend(
acc,
acc,
sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(1))),
)
_, err := ante.AnteHandle(s.ctx, decorators.NewMockTx(msg), false, decorators.EmptyAnte)
s.Require().Error(err)
// validate other messages go through still (such as MsgMultiSend)
msgMultiSend := banktypes.NewMsgMultiSend(
banktypes.NewInput(acc, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(1)))),
[]banktypes.Output{banktypes.NewOutput(acc, sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(1))))},
)
_, err = ante.AnteHandle(s.ctx, decorators.NewMockTx(msgMultiSend), false, decorators.EmptyAnte)
s.Require().NoError(err)
}
+35
View File
@@ -0,0 +1,35 @@
package decorators
import (
sdk "github.com/cosmos/cosmos-sdk/types"
protov2 "google.golang.org/protobuf/proto"
)
// Define an empty ante handle
var (
EmptyAnte = func(ctx sdk.Context, tx sdk.Tx, simulate bool) (sdk.Context, error) {
return ctx, nil
}
)
type MockTx struct {
msgs []sdk.Msg
}
func NewMockTx(msgs ...sdk.Msg) MockTx {
return MockTx{
msgs: msgs,
}
}
func (tx MockTx) GetMsgs() []sdk.Msg {
return tx.msgs
}
func (tx MockTx) GetMsgsV2() ([]protov2.Message, error) {
return nil, nil
}
func (tx MockTx) ValidateBasic() error {
return nil
}
+38
View File
@@ -0,0 +1,38 @@
package app
import (
"testing"
dbm "github.com/cosmos/cosmos-db"
"cosmossdk.io/log"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
"github.com/onsonr/hway/app/params"
)
// MakeEncodingConfig creates a new EncodingConfig with all modules registered. For testing only
func MakeEncodingConfig(t testing.TB) params.EncodingConfig {
t.Helper()
// we "pre"-instantiate the application for getting the injected/configured encoding configuration
// note, this is not necessary when using app wiring, as depinject can be directly used (see root_v2.go)
tempApp := NewChainApp(
log.NewNopLogger(),
dbm.NewMemDB(),
nil,
true,
simtestutil.NewAppOptionsWithFlagHome(t.TempDir()),
)
return makeEncodingConfig(tempApp)
}
func makeEncodingConfig(tempApp *SonrApp) params.EncodingConfig {
encodingConfig := params.EncodingConfig{
InterfaceRegistry: tempApp.InterfaceRegistry(),
Codec: tempApp.AppCodec(),
TxConfig: tempApp.TxConfig(),
Amino: tempApp.LegacyAmino(),
}
return encodingConfig
}
+253
View File
@@ -0,0 +1,253 @@
package app
import (
"encoding/json"
"fmt"
"log"
cmtproto "github.com/cometbft/cometbft/proto/tendermint/types"
storetypes "cosmossdk.io/store/types"
servertypes "github.com/cosmos/cosmos-sdk/server/types"
sdk "github.com/cosmos/cosmos-sdk/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"
)
// ExportAppStateAndValidators exports the state of the application for a genesis
// file.
func (app *SonrApp) ExportAppStateAndValidators(forZeroHeight bool, jailAllowedAddrs, modulesToExport []string) (servertypes.ExportedApp, error) {
// as if they could withdraw from the start of the next block
ctx := app.NewContextLegacy(true, cmtproto.Header{Height: app.LastBlockHeight()})
// We export at last height + 1, because that's the height at which
// CometBFT will start InitChain.
height := app.LastBlockHeight() + 1
if forZeroHeight {
height = 0
app.prepForZeroHeightGenesis(ctx, jailAllowedAddrs)
}
genState, err := app.ModuleManager.ExportGenesisForModules(ctx, app.appCodec, modulesToExport)
if err != nil {
return servertypes.ExportedApp{}, err
}
appState, err := json.MarshalIndent(genState, "", " ")
if err != nil {
return servertypes.ExportedApp{}, err
}
validators, err := staking.WriteValidators(ctx, app.StakingKeeper)
return servertypes.ExportedApp{
AppState: appState,
Validators: validators,
Height: height,
ConsensusParams: app.BaseApp.GetConsensusParams(ctx),
}, err
}
// prepare for fresh start at zero height
// NOTE zero height genesis is a temporary feature which will be deprecated
//
// in favor of export at a block height
func (app *SonrApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []string) {
applyAllowedAddrs := false
// check if there is a allowed address list
if len(jailAllowedAddrs) > 0 {
applyAllowedAddrs = true
}
allowedAddrsMap := make(map[string]bool)
for _, addr := range jailAllowedAddrs {
_, err := sdk.ValAddressFromBech32(addr)
if err != nil {
log.Fatal(err)
}
allowedAddrsMap[addr] = true
}
// Just to be safe, assert the invariants on current state.
app.CrisisKeeper.AssertInvariants(ctx)
// Handle fee distribution state.
// withdraw all validator commission
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, err := app.StakingKeeper.GetAllDelegations(ctx)
if err != nil {
panic(err)
}
for _, delegation := range dels {
valAddr, err := sdk.ValAddressFromBech32(delegation.ValidatorAddress)
if err != nil {
panic(err)
}
delAddr := sdk.MustAccAddressFromBech32(delegation.DelegatorAddress)
if _, err = app.DistrKeeper.WithdrawDelegationRewards(ctx, delAddr, valAddr); err != nil {
panic(err)
}
}
// clear validator slash events
app.DistrKeeper.DeleteAllValidatorSlashEvents(ctx)
// clear validator historical rewards
app.DistrKeeper.DeleteAllValidatorHistoricalRewards(ctx)
// set context height to zero
height := ctx.BlockHeight()
ctx = ctx.WithBlockHeight(0)
// reinitialize all validators
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, 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...)
if err := app.DistrKeeper.FeePool.Set(ctx, feePool); err != nil {
panic(err)
}
if err := app.DistrKeeper.Hooks().AfterValidatorCreated(ctx, valBz); err != nil {
panic(err)
}
return false
})
if err != nil {
panic(err)
}
// reinitialize all delegations
for _, del := range dels {
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
ctx = ctx.WithBlockHeight(height)
// Handle staking state.
// iterate through redelegations, reset creation height
err = app.StakingKeeper.IterateRedelegations(ctx, func(_ int64, red stakingtypes.Redelegation) (stop bool) {
for i := range red.Entries {
red.Entries[i].CreationHeight = 0
}
err = app.StakingKeeper.SetRedelegation(ctx, red)
if err != nil {
panic(err)
}
return false
})
if err != nil {
panic(err)
}
// iterate through unbonding delegations, reset creation height
err = app.StakingKeeper.IterateUnbondingDelegations(ctx, func(_ int64, ubd stakingtypes.UnbondingDelegation) (stop bool) {
for i := range ubd.Entries {
ubd.Entries[i].CreationHeight = 0
}
err = app.StakingKeeper.SetUnbondingDelegation(ctx, ubd)
if err != nil {
panic(err)
}
return false
})
if err != nil {
panic(err)
}
// Iterate through validators by power descending, reset bond heights, and
// update bond intra-tx counters.
store := ctx.KVStore(app.GetKey(stakingtypes.StoreKey))
iter := storetypes.KVStoreReversePrefixIterator(store, stakingtypes.ValidatorsKey)
for ; iter.Valid(); iter.Next() {
addr := sdk.ValAddress(stakingtypes.AddressFromValidatorsKey(iter.Key()))
validator, err := app.StakingKeeper.GetValidator(ctx, addr)
if err != nil {
panic("expected validator, not found")
}
validator.UnbondingHeight = 0
if applyAllowedAddrs && !allowedAddrsMap[addr.String()] {
validator.Jailed = true
}
err = app.StakingKeeper.SetValidator(ctx, validator)
if err != nil {
panic(err)
}
}
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)
if err != nil {
log.Fatal(err)
}
// Handle slashing state.
// reset start height on signing infos
err = app.SlashingKeeper.IterateValidatorSigningInfos(
ctx,
func(addr sdk.ConsAddress, info slashingtypes.ValidatorSigningInfo) (stop bool) {
info.StartHeight = 0
if err := app.SlashingKeeper.SetValidatorSigningInfo(ctx, addr, info); err != nil {
panic(err)
}
return false
},
)
if err != nil {
panic(err)
}
}
+14
View File
@@ -0,0 +1,14 @@
package app
import (
"encoding/json"
)
// GenesisState of the blockchain is represented here as a map of raw json
// messages key'd by a identifier string.
// The identifier is used to determine which module genesis information belongs
// to so it may be appropriately routed during init chain.
// Within this application default genesis information is retrieved from
// the ModuleBasicManager which populates json from each BasicModule
// object provided to it during init.
type GenesisState map[string]json.RawMessage
+19
View File
@@ -0,0 +1,19 @@
/*
Package params defines the simulation parameters in the gaia.
It contains the default weights used for each transaction used on the module's
simulation. These weights define the chance for a transaction to be simulated at
any gived operation.
You can repace the default values for the weights by providing a params.json
file with the weights defined for each of the transaction operations:
{
"op_weight_msg_send": 60,
"op_weight_msg_delegate": 100,
}
In the example above, the `MsgSend` has 60% chance to be simulated, while the
`MsgDelegate` will always be simulated.
*/
package params
+16
View File
@@ -0,0 +1,16 @@
package params
import (
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/codec/types"
)
// EncodingConfig specifies the concrete encoding types to use for a given app.
// This is provided for compatibility between protobuf and amino implementations.
type EncodingConfig struct {
InterfaceRegistry types.InterfaceRegistry
Codec codec.Codec
TxConfig client.TxConfig
Amino *codec.LegacyAmino
}
+42
View File
@@ -0,0 +1,42 @@
package params
import (
"github.com/cosmos/gogoproto/proto"
"cosmossdk.io/x/tx/signing"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/codec/address"
"github.com/cosmos/cosmos-sdk/codec/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth/tx"
)
// MakeEncodingConfig creates an EncodingConfig for an amino based test configuration.
func MakeEncodingConfig() EncodingConfig {
amino := codec.NewLegacyAmino()
interfaceRegistry, err := types.NewInterfaceRegistryWithOptions(types.InterfaceRegistryOptions{
ProtoFiles: proto.HybridResolver,
SigningOptions: signing.Options{
AddressCodec: address.Bech32Codec{
Bech32Prefix: sdk.GetConfig().GetBech32AccountAddrPrefix(),
},
ValidatorAddressCodec: address.Bech32Codec{
Bech32Prefix: sdk.GetConfig().GetBech32ValidatorAddrPrefix(),
},
},
})
if err != nil {
panic(err)
}
marshaler := codec.NewProtoCodec(interfaceRegistry)
txCfg := tx.NewTxConfig(marshaler, tx.DefaultSignModes)
return EncodingConfig{
InterfaceRegistry: interfaceRegistry,
Codec: marshaler,
TxConfig: txCfg,
Amino: amino,
}
}
+364
View File
@@ -0,0 +1,364 @@
package app
import (
"encoding/json"
"flag"
"fmt"
"os"
"runtime/debug"
"strings"
"testing"
abci "github.com/cometbft/cometbft/abci/types"
cmtproto "github.com/cometbft/cometbft/proto/tendermint/types"
dbm "github.com/cosmos/cosmos-db"
"github.com/spf13/viper"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"cosmossdk.io/log"
"cosmossdk.io/store"
storetypes "cosmossdk.io/store/types"
"cosmossdk.io/x/feegrant"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/server"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
authzkeeper "github.com/cosmos/cosmos-sdk/x/authz/keeper"
"github.com/cosmos/cosmos-sdk/x/simulation"
simcli "github.com/cosmos/cosmos-sdk/x/simulation/client/cli"
slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
)
// SimAppChainID hardcoded chainID for simulation
const SimAppChainID = "simulation-app"
var FlagEnableStreamingValue bool
// Get flags every time the simulator is run
func init() {
simcli.GetSimulatorFlags()
flag.BoolVar(&FlagEnableStreamingValue, "EnableStreaming", false, "Enable streaming service")
}
// fauxMerkleModeOpt returns a BaseApp option to use a dbStoreAdapter instead of
// an IAVLStore for faster simulation speed.
func fauxMerkleModeOpt(bapp *baseapp.BaseApp) {
bapp.SetFauxMerkleMode()
}
// interBlockCacheOpt returns a BaseApp option function that sets the persistent
// inter-block write-through cache.
func interBlockCacheOpt() func(*baseapp.BaseApp) {
return baseapp.SetInterBlockCache(store.NewCommitKVStoreCacheManager())
}
func TestFullAppSimulation(t *testing.T) {
config, db, _, app := setupSimulationApp(t, "skipping application simulation")
// run randomized simulation
_, simParams, simErr := simulation.SimulateFromSeed(
t,
os.Stdout,
app.BaseApp,
simtestutil.AppStateFn(app.AppCodec(), 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(),
config,
app.AppCodec(),
)
// export state and simParams before the simulation error is checked
err := simtestutil.CheckExportSimulation(app, config, simParams)
require.NoError(t, err)
require.NoError(t, simErr)
if config.Commit {
simtestutil.PrintStats(db)
}
}
func TestAppImportExport(t *testing.T) {
config, db, appOptions, app := setupSimulationApp(t, "skipping application import/export simulation")
// Run randomized simulation
_, simParams, simErr := simulation.SimulateFromSeed(
t,
os.Stdout,
app.BaseApp,
simtestutil.AppStateFn(app.AppCodec(), 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(),
config,
app.AppCodec(),
)
// export state and simParams before the simulation error is checked
err := simtestutil.CheckExportSimulation(app, config, simParams)
require.NoError(t, err)
require.NoError(t, simErr)
if config.Commit {
simtestutil.PrintStats(db)
}
t.Log("exporting genesis...\n")
exported, err := app.ExportAppStateAndValidators(false, []string{}, []string{})
require.NoError(t, err)
t.Log("importing genesis...\n")
newDB, newDir, _, _, err := simtestutil.SetupSimulation(config, "leveldb-app-sim-2", "Simulation-2", simcli.FlagVerboseValue, simcli.FlagEnabledValue)
require.NoError(t, err, "simulation setup failed")
defer func() {
require.NoError(t, newDB.Close())
require.NoError(t, os.RemoveAll(newDir))
}()
newApp := NewChainApp(log.NewNopLogger(), newDB, nil, true, appOptions, nil, fauxMerkleModeOpt, baseapp.SetChainID(SimAppChainID))
initReq := &abci.RequestInitChain{
AppStateBytes: exported.AppState,
}
ctxA := app.NewContextLegacy(true, cmtproto.Header{Height: app.LastBlockHeight()})
ctxB := newApp.NewContextLegacy(true, cmtproto.Header{Height: app.LastBlockHeight()})
_, err = newApp.InitChainer(ctxB, initReq)
if err != nil {
if strings.Contains(err.Error(), "validator set is empty after InitGenesis") {
t.Log("Skipping simulation as all validators have been unbonded")
t.Logf("err: %s stacktrace: %s\n", err, string(debug.Stack()))
return
}
}
require.NoError(t, err)
err = newApp.StoreConsensusParams(ctxB, exported.ConsensusParams)
require.NoError(t, err)
t.Log("comparing stores...")
// skip certain prefixes
skipPrefixes := map[string][][]byte{
stakingtypes.StoreKey: {
stakingtypes.UnbondingQueueKey, stakingtypes.RedelegationQueueKey, stakingtypes.ValidatorQueueKey,
stakingtypes.HistoricalInfoKey, stakingtypes.UnbondingIDKey, stakingtypes.UnbondingIndexKey,
stakingtypes.UnbondingTypeKey, stakingtypes.ValidatorUpdatesKey,
},
authzkeeper.StoreKey: {authzkeeper.GrantQueuePrefix},
feegrant.StoreKey: {feegrant.FeeAllowanceQueueKeyPrefix},
slashingtypes.StoreKey: {slashingtypes.ValidatorMissedBlockBitmapKeyPrefix},
}
storeKeys := app.GetStoreKeys()
require.NotEmpty(t, storeKeys)
for _, appKeyA := range storeKeys {
// only compare kvstores
if _, ok := appKeyA.(*storetypes.KVStoreKey); !ok {
continue
}
keyName := appKeyA.Name()
appKeyB := newApp.GetKey(keyName)
storeA := ctxA.KVStore(appKeyA)
storeB := ctxB.KVStore(appKeyB)
failedKVAs, failedKVBs := simtestutil.DiffKVStores(storeA, storeB, skipPrefixes[keyName])
if !assert.Equal(t, len(failedKVAs), len(failedKVBs), "unequal sets of key-values to compare in %q", keyName) {
for _, v := range failedKVBs {
t.Logf("store missmatch: %q\n", v)
}
t.FailNow()
}
t.Logf("compared %d different key/value pairs between %s and %s\n", len(failedKVAs), appKeyA, appKeyB)
if !assert.Equal(t, 0, len(failedKVAs), simtestutil.GetSimulationLog(keyName, app.SimulationManager().StoreDecoders, failedKVAs, failedKVBs)) {
for _, v := range failedKVAs {
t.Logf("store missmatch: %q\n", v)
}
t.FailNow()
}
}
}
func TestAppSimulationAfterImport(t *testing.T) {
config, db, appOptions, app := setupSimulationApp(t, "skipping application simulation after import")
// Run randomized simulation
stopEarly, simParams, simErr := simulation.SimulateFromSeed(
t,
os.Stdout,
app.BaseApp,
simtestutil.AppStateFn(app.AppCodec(), 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(),
config,
app.AppCodec(),
)
// export state and simParams before the simulation error is checked
err := simtestutil.CheckExportSimulation(app, config, simParams)
require.NoError(t, err)
require.NoError(t, simErr)
if config.Commit {
simtestutil.PrintStats(db)
}
if stopEarly {
fmt.Println("can't export or import a zero-validator genesis, exiting test...")
return
}
fmt.Printf("exporting genesis...\n")
exported, err := app.ExportAppStateAndValidators(true, []string{}, []string{})
require.NoError(t, err)
fmt.Printf("importing genesis...\n")
newDB, newDir, _, _, err := simtestutil.SetupSimulation(config, "leveldb-app-sim-2", "Simulation-2", simcli.FlagVerboseValue, simcli.FlagEnabledValue)
require.NoError(t, err, "simulation setup failed")
defer func() {
require.NoError(t, newDB.Close())
require.NoError(t, os.RemoveAll(newDir))
}()
newApp := NewChainApp(log.NewNopLogger(), newDB, nil, true, appOptions, nil, fauxMerkleModeOpt, baseapp.SetChainID(SimAppChainID))
_, err = newApp.InitChain(&abci.RequestInitChain{
ChainId: SimAppChainID,
AppStateBytes: exported.AppState,
})
require.NoError(t, err)
_, _, err = simulation.SimulateFromSeed(
t,
os.Stdout,
newApp.BaseApp,
simtestutil.AppStateFn(app.AppCodec(), 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(),
config,
app.AppCodec(),
)
require.NoError(t, err)
}
func setupSimulationApp(t *testing.T, msg string) (simtypes.Config, dbm.DB, simtestutil.AppOptionsMap, *SonrApp) {
config := simcli.NewConfigFromFlags()
config.ChainID = SimAppChainID
db, dir, logger, skip, err := simtestutil.SetupSimulation(config, "leveldb-app-sim", "Simulation", simcli.FlagVerboseValue, simcli.FlagEnabledValue)
if skip {
t.Skip(msg)
}
require.NoError(t, err, "simulation setup failed")
t.Cleanup(func() {
require.NoError(t, db.Close())
require.NoError(t, os.RemoveAll(dir))
})
appOptions := make(simtestutil.AppOptionsMap, 0)
appOptions[flags.FlagHome] = dir // ensure a unique folder
appOptions[server.FlagInvCheckPeriod] = simcli.FlagPeriodValue
app := NewChainApp(logger, db, nil, true, appOptions, nil, fauxMerkleModeOpt, baseapp.SetChainID(SimAppChainID))
return config, db, appOptions, app
}
// TODO: Make another test for the fuzzer itself, which just has noOp txs
// and doesn't depend on the application.
func TestAppStateDeterminism(t *testing.T) {
if !simcli.FlagEnabledValue {
t.Skip("skipping application simulation")
}
config := simcli.NewConfigFromFlags()
config.InitialBlockHeight = 1
config.ExportParamsPath = ""
config.OnOperation = false
config.AllInvariants = false
config.ChainID = SimAppChainID
numSeeds := 3
numTimesToRunPerSeed := 3 // This used to be set to 5, but we've temporarily reduced it to 3 for the sake of faster CI.
appHashList := make([]json.RawMessage, numTimesToRunPerSeed)
// We will be overriding the random seed and just run a single simulation on the provided seed value
if config.Seed != simcli.DefaultSeedValue {
numSeeds = 1
}
appOptions := viper.New()
if FlagEnableStreamingValue {
m := make(map[string]interface{})
m["streaming.abci.keys"] = []string{"*"}
m["streaming.abci.plugin"] = "abci_v1"
m["streaming.abci.stop-node-on-err"] = true
for key, value := range m {
appOptions.SetDefault(key, value)
}
}
appOptions.SetDefault(flags.FlagHome, t.TempDir()) // ensure a unique folder
appOptions.SetDefault(server.FlagInvCheckPeriod, simcli.FlagPeriodValue)
for i := 0; i < numSeeds; i++ {
config.Seed += int64(i)
for j := 0; j < numTimesToRunPerSeed; j++ {
var logger log.Logger
if simcli.FlagVerboseValue {
logger = log.NewTestLogger(t)
} else {
logger = log.NewNopLogger()
}
db := dbm.NewMemDB()
app := NewChainApp(logger, db, nil, true, appOptions, nil, interBlockCacheOpt(), baseapp.SetChainID(SimAppChainID))
fmt.Printf(
"running non-determinism simulation; seed %d: %d/%d, attempt: %d/%d\n",
config.Seed, i+1, numSeeds, j+1, numTimesToRunPerSeed,
)
_, _, err := simulation.SimulateFromSeed(
t,
os.Stdout,
app.BaseApp,
simtestutil.AppStateFn(app.AppCodec(), 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(),
config,
app.AppCodec(),
)
require.NoError(t, err)
if config.Commit {
simtestutil.PrintStats(db)
}
appHash := app.LastCommitID().Hash
appHashList[j] = appHash
if j != 0 {
require.Equal(
t, string(appHashList[0]), string(appHashList[j]),
"non-determinism in seed %d: %d/%d, attempt: %d/%d\n", config.Seed, i+1, numSeeds, j+1, numTimesToRunPerSeed,
)
}
}
}
}
+432
View File
@@ -0,0 +1,432 @@
package app
import (
"encoding/json"
"fmt"
"math/rand"
"os"
"path/filepath"
"testing"
"time"
abci "github.com/cometbft/cometbft/abci/types"
cmtjson "github.com/cometbft/cometbft/libs/json"
cmttypes "github.com/cometbft/cometbft/types"
dbm "github.com/cosmos/cosmos-db"
"github.com/stretchr/testify/require"
"cosmossdk.io/log"
sdkmath "cosmossdk.io/math"
pruningtypes "cosmossdk.io/store/pruning/types"
"cosmossdk.io/store/snapshots"
snapshottypes "cosmossdk.io/store/snapshots/types"
bam "github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec"
"github.com/cosmos/cosmos-sdk/crypto/keys/ed25519"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
"github.com/cosmos/cosmos-sdk/server"
servertypes "github.com/cosmos/cosmos-sdk/server/types"
"github.com/cosmos/cosmos-sdk/testutil/mock"
"github.com/cosmos/cosmos-sdk/testutil/network"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module/testutil"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
minttypes "github.com/cosmos/cosmos-sdk/x/mint/types"
slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
)
// SetupOptions defines arguments that are passed into `ChainApp` constructor.
type SetupOptions struct {
Logger log.Logger
DB *dbm.MemDB
AppOpts servertypes.AppOptions
}
func setup(
t testing.TB,
chainID string,
withGenesis bool,
invCheckPeriod uint,
) (*SonrApp, GenesisState) {
db := dbm.NewMemDB()
nodeHome := t.TempDir()
snapshotDir := filepath.Join(nodeHome, "data", "snapshots")
snapshotDB, err := dbm.NewDB("metadata", dbm.GoLevelDBBackend, snapshotDir)
require.NoError(t, err)
t.Cleanup(func() { snapshotDB.Close() })
snapshotStore, err := snapshots.NewStore(snapshotDB, snapshotDir)
require.NoError(t, err)
appOptions := make(simtestutil.AppOptionsMap, 0)
appOptions[flags.FlagHome] = nodeHome // ensure unique folder
appOptions[server.FlagInvCheckPeriod] = invCheckPeriod
app := NewChainApp(
log.NewNopLogger(),
db,
nil,
true,
appOptions,
bam.SetChainID(chainID),
bam.SetSnapshot(snapshotStore, snapshottypes.SnapshotOptions{KeepRecent: 2}),
)
if withGenesis {
return app, app.DefaultGenesis()
}
return app, GenesisState{}
}
// NewChainAppWithCustomOptions initializes a new ChainApp with custom options.
func NewChainAppWithCustomOptions(t *testing.T, isCheckTx bool, options SetupOptions) *SonrApp {
t.Helper()
privVal := mock.NewPV()
pubKey, err := privVal.GetPubKey()
require.NoError(t, err)
// create validator set with single validator
validator := cmttypes.NewValidator(pubKey, 1)
valSet := cmttypes.NewValidatorSet([]*cmttypes.Validator{validator})
// generate genesis account
senderPrivKey := secp256k1.GenPrivKey()
acc := authtypes.NewBaseAccount(senderPrivKey.PubKey().Address().Bytes(), senderPrivKey.PubKey(), 0, 0)
balance := banktypes.Balance{
Address: acc.GetAddress().String(),
Coins: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(100000000000000))),
}
app := NewChainApp(
options.Logger,
options.DB,
nil, true,
options.AppOpts,
)
genesisState := app.DefaultGenesis()
genesisState, err = GenesisStateWithValSet(app.AppCodec(), genesisState, valSet, []authtypes.GenesisAccount{acc}, balance)
require.NoError(t, err)
if !isCheckTx {
// init chain must be called to stop deliverState from being nil
stateBytes, err := cmtjson.MarshalIndent(genesisState, "", " ")
require.NoError(t, err)
// Initialize the chain
_, err = app.InitChain(
&abci.RequestInitChain{
Validators: []abci.ValidatorUpdate{},
ConsensusParams: simtestutil.DefaultConsensusParams,
AppStateBytes: stateBytes,
})
require.NoError(t, err)
}
return app
}
// Setup initializes a new ChainApp. A Nop logger is set in ChainApp.
func Setup(
t *testing.T,
) *SonrApp {
t.Helper()
privVal := mock.NewPV()
pubKey, err := privVal.GetPubKey()
require.NoError(t, err)
// create validator set with single validator
validator := cmttypes.NewValidator(pubKey, 1)
valSet := cmttypes.NewValidatorSet([]*cmttypes.Validator{validator})
// generate genesis account
senderPrivKey := secp256k1.GenPrivKey()
acc := authtypes.NewBaseAccount(senderPrivKey.PubKey().Address().Bytes(), senderPrivKey.PubKey(), 0, 0)
balance := banktypes.Balance{
Address: acc.GetAddress().String(),
Coins: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(100000000000000))),
}
chainID := "testing"
app := SetupWithGenesisValSet(
t,
valSet,
[]authtypes.GenesisAccount{acc},
chainID,
balance,
)
return app
}
// SetupWithGenesisValSet initializes a new ChainApp with a validator set and genesis accounts
// that also act as delegators. For simplicity, each validator is bonded with a delegation
// of one consensus engine unit in the default token of the ChainApp from first genesis
// account. A Nop logger is set in ChainApp.
func SetupWithGenesisValSet(
t *testing.T,
valSet *cmttypes.ValidatorSet,
genAccs []authtypes.GenesisAccount,
chainID string,
balances ...banktypes.Balance,
) *SonrApp {
t.Helper()
app, genesisState := setup(
t, chainID, true, 5,
)
genesisState, err := GenesisStateWithValSet(app.AppCodec(), genesisState, valSet, genAccs, balances...)
require.NoError(t, err)
stateBytes, err := json.MarshalIndent(genesisState, "", " ")
require.NoError(t, err)
// init chain will set the validator set and initialize the genesis accounts
consensusParams := simtestutil.DefaultConsensusParams
consensusParams.Block.MaxGas = 100 * simtestutil.DefaultGenTxGas
_, err = app.InitChain(&abci.RequestInitChain{
ChainId: chainID,
Time: time.Now().UTC(),
Validators: []abci.ValidatorUpdate{},
ConsensusParams: consensusParams,
InitialHeight: app.LastBlockHeight() + 1,
AppStateBytes: stateBytes,
})
require.NoError(t, err)
_, err = app.FinalizeBlock(&abci.RequestFinalizeBlock{
Height: app.LastBlockHeight() + 1,
Hash: app.LastCommitID().Hash,
NextValidatorsHash: valSet.Hash(),
})
require.NoError(t, err)
return app
}
// SetupWithEmptyStore set up a chain app instance with empty DB
func SetupWithEmptyStore(t testing.TB) *SonrApp {
app, _ := setup(t, "testing", false, 0)
return app
}
// GenesisStateWithSingleValidator initializes GenesisState with a single validator and genesis accounts
// that also act as delegators.
func GenesisStateWithSingleValidator(t *testing.T, app *SonrApp) GenesisState {
t.Helper()
privVal := mock.NewPV()
pubKey, err := privVal.GetPubKey()
require.NoError(t, err)
// create validator set with single validator
validator := cmttypes.NewValidator(pubKey, 1)
valSet := cmttypes.NewValidatorSet([]*cmttypes.Validator{validator})
// generate genesis account
senderPrivKey := secp256k1.GenPrivKey()
acc := authtypes.NewBaseAccount(senderPrivKey.PubKey().Address().Bytes(), senderPrivKey.PubKey(), 0, 0)
balances := []banktypes.Balance{
{
Address: acc.GetAddress().String(),
Coins: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdkmath.NewInt(100000000000000))),
},
}
genesisState := app.DefaultGenesis()
genesisState, err = GenesisStateWithValSet(app.AppCodec(), genesisState, valSet, []authtypes.GenesisAccount{acc}, balances...)
require.NoError(t, err)
return genesisState
}
// AddTestAddrsIncremental constructs and returns accNum amount of accounts with an
// initial balance of accAmt in random order
func AddTestAddrsIncremental(app *SonrApp, ctx sdk.Context, accNum int, accAmt sdkmath.Int) []sdk.AccAddress {
return addTestAddrs(app, ctx, accNum, accAmt, simtestutil.CreateIncrementalAccounts)
}
func addTestAddrs(app *SonrApp, ctx sdk.Context, accNum int, accAmt sdkmath.Int, strategy simtestutil.GenerateAccountStrategy) []sdk.AccAddress {
testAddrs := strategy(accNum)
bondDenom, err := app.StakingKeeper.BondDenom(ctx)
if err != nil {
panic(err)
}
initCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, accAmt))
for _, addr := range testAddrs {
initAccountWithCoins(app, ctx, addr, initCoins)
}
return testAddrs
}
func initAccountWithCoins(app *SonrApp, ctx sdk.Context, addr sdk.AccAddress, coins sdk.Coins) {
err := app.BankKeeper.MintCoins(ctx, minttypes.ModuleName, coins)
if err != nil {
panic(err)
}
err = app.BankKeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, addr, coins)
if err != nil {
panic(err)
}
}
// NewTestNetworkFixture returns a new ChainApp AppConstructor for network simulation tests
func NewTestNetworkFixture() network.TestFixture {
dir, err := os.MkdirTemp("", "simapp")
if err != nil {
panic(fmt.Sprintf("failed creating temporary directory: %v", err))
}
defer os.RemoveAll(dir)
app := NewChainApp(log.NewNopLogger(), dbm.NewMemDB(), nil, true, simtestutil.NewAppOptionsWithFlagHome(dir), nil)
appCtr := func(val network.ValidatorI) servertypes.Application {
return NewChainApp(
val.GetCtx().Logger, dbm.NewMemDB(), nil, true,
simtestutil.NewAppOptionsWithFlagHome(val.GetCtx().Config.RootDir),
bam.SetPruning(pruningtypes.NewPruningOptionsFromString(val.GetAppConfig().Pruning)),
bam.SetMinGasPrices(val.GetAppConfig().MinGasPrices),
bam.SetChainID(val.GetCtx().Viper.GetString(flags.FlagChainID)),
)
}
return network.TestFixture{
AppConstructor: appCtr,
GenesisState: app.DefaultGenesis(),
EncodingConfig: testutil.TestEncodingConfig{
InterfaceRegistry: app.InterfaceRegistry(),
Codec: app.AppCodec(),
TxConfig: app.TxConfig(),
Amino: app.LegacyAmino(),
},
}
}
// SignAndDeliverWithoutCommit signs and delivers a transaction. No commit
func SignAndDeliverWithoutCommit(t *testing.T, txCfg client.TxConfig, app *bam.BaseApp, msgs []sdk.Msg, fees sdk.Coins, chainID string, accNums, accSeqs []uint64, blockTime time.Time, priv ...cryptotypes.PrivKey) (*abci.ResponseFinalizeBlock, error) {
tx, err := simtestutil.GenSignedMockTx(
rand.New(rand.NewSource(time.Now().UnixNano())),
txCfg,
msgs,
fees,
simtestutil.DefaultGenTxGas,
chainID,
accNums,
accSeqs,
priv...,
)
require.NoError(t, err)
bz, err := txCfg.TxEncoder()(tx)
require.NoError(t, err)
return app.FinalizeBlock(&abci.RequestFinalizeBlock{
Height: app.LastBlockHeight() + 1,
Time: blockTime,
Txs: [][]byte{bz},
})
}
// GenesisStateWithValSet returns a new genesis state with the validator set
// copied from simtestutil with delegation not added to supply
func GenesisStateWithValSet(
codec codec.Codec,
genesisState map[string]json.RawMessage,
valSet *cmttypes.ValidatorSet,
genAccs []authtypes.GenesisAccount,
balances ...banktypes.Balance,
) (map[string]json.RawMessage, error) {
// set genesis accounts
authGenesis := authtypes.NewGenesisState(authtypes.DefaultParams(), genAccs)
genesisState[authtypes.ModuleName] = codec.MustMarshalJSON(authGenesis)
validators := make([]stakingtypes.Validator, 0, len(valSet.Validators))
delegations := make([]stakingtypes.Delegation, 0, len(valSet.Validators))
bondAmt := sdk.DefaultPowerReduction
for _, val := range valSet.Validators {
pk, err := cryptocodec.FromCmtPubKeyInterface(val.PubKey)
if err != nil {
return nil, fmt.Errorf("failed to convert pubkey: %w", err)
}
pkAny, err := codectypes.NewAnyWithValue(pk)
if err != nil {
return nil, fmt.Errorf("failed to create new any: %w", err)
}
validator := stakingtypes.Validator{
OperatorAddress: sdk.ValAddress(val.Address).String(),
ConsensusPubkey: pkAny,
Jailed: false,
Status: stakingtypes.Bonded,
Tokens: bondAmt,
DelegatorShares: sdkmath.LegacyOneDec(),
Description: stakingtypes.Description{},
UnbondingHeight: int64(0),
UnbondingTime: time.Unix(0, 0).UTC(),
Commission: stakingtypes.NewCommission(sdkmath.LegacyZeroDec(), sdkmath.LegacyZeroDec(), sdkmath.LegacyZeroDec()),
MinSelfDelegation: sdkmath.ZeroInt(),
}
validators = append(validators, validator)
delegations = append(delegations, stakingtypes.NewDelegation(genAccs[0].GetAddress().String(), sdk.ValAddress(val.Address).String(), sdkmath.LegacyOneDec()))
}
// set validators and delegations
stakingGenesis := stakingtypes.NewGenesisState(stakingtypes.DefaultParams(), validators, delegations)
genesisState[stakingtypes.ModuleName] = codec.MustMarshalJSON(stakingGenesis)
signingInfos := make([]slashingtypes.SigningInfo, len(valSet.Validators))
for i, val := range valSet.Validators {
signingInfos[i] = slashingtypes.SigningInfo{
Address: sdk.ConsAddress(val.Address).String(),
ValidatorSigningInfo: slashingtypes.ValidatorSigningInfo{},
}
}
slashingGenesis := slashingtypes.NewGenesisState(slashingtypes.DefaultParams(), signingInfos, nil)
genesisState[slashingtypes.ModuleName] = codec.MustMarshalJSON(slashingGenesis)
// add bonded amount to bonded pool module account
balances = append(balances, banktypes.Balance{
Address: authtypes.NewModuleAddress(stakingtypes.BondedPoolName).String(),
Coins: sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, bondAmt.MulRaw(int64(len(valSet.Validators))))},
})
totalSupply := sdk.NewCoins()
for _, b := range balances {
// add genesis acc tokens to total supply
totalSupply = totalSupply.Add(b.Coins...)
}
// update total supply
bankGenesis := banktypes.NewGenesisState(banktypes.DefaultGenesisState().Params, balances, totalSupply, []banktypes.Metadata{}, []banktypes.SendEnabled{})
genesisState[banktypes.ModuleName] = codec.MustMarshalJSON(bankGenesis)
return genesisState, nil
}
type account struct {
priv *secp256k1.PrivKey
addr sdk.AccAddress
valKey *ed25519.PrivKey
}
func GenAccount() account {
priv := secp256k1.GenPrivKey()
return account{
priv: priv,
addr: sdk.AccAddress(priv.PubKey().Address()),
valKey: ed25519.GenPrivKey(),
}
}
+35
View File
@@ -0,0 +1,35 @@
package app
import (
capabilitykeeper "github.com/cosmos/ibc-go/modules/capability/keeper"
ibckeeper "github.com/cosmos/ibc-go/v8/modules/core/keeper"
"github.com/cosmos/cosmos-sdk/baseapp"
authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper"
bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper"
stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper"
)
func (app *SonrApp) GetIBCKeeper() *ibckeeper.Keeper {
return app.IBCKeeper
}
func (app *SonrApp) GetScopedIBCKeeper() capabilitykeeper.ScopedKeeper {
return app.ScopedIBCKeeper
}
func (app *SonrApp) GetBaseApp() *baseapp.BaseApp {
return app.BaseApp
}
func (app *SonrApp) GetBankKeeper() bankkeeper.Keeper {
return app.BankKeeper
}
func (app *SonrApp) GetStakingKeeper() *stakingkeeper.Keeper {
return app.StakingKeeper
}
func (app *SonrApp) GetAccountKeeper() authkeeper.AccountKeeper {
return app.AccountKeeper
}
+61
View File
@@ -0,0 +1,61 @@
package app
import (
"fmt"
upgradetypes "cosmossdk.io/x/upgrade/types"
"github.com/onsonr/hway/app/upgrades"
"github.com/onsonr/hway/app/upgrades/noop"
)
// Upgrades list of chain upgrades
var Upgrades = []upgrades.Upgrade{}
// RegisterUpgradeHandlers registers the chain upgrade handlers
func (app *SonrApp) RegisterUpgradeHandlers() {
// setupLegacyKeyTables(&app.ParamsKeeper)
if len(Upgrades) == 0 {
// always have a unique upgrade registered for the current version to test in system tests
Upgrades = append(Upgrades, noop.NewUpgrade(app.Version()))
}
keepers := upgrades.AppKeepers{
AccountKeeper: &app.AccountKeeper,
ParamsKeeper: &app.ParamsKeeper,
ConsensusParamsKeeper: &app.ConsensusParamsKeeper,
CapabilityKeeper: app.CapabilityKeeper,
IBCKeeper: app.IBCKeeper,
Codec: app.appCodec,
GetStoreKey: app.GetKey,
}
app.GetStoreKeys()
// register all upgrade handlers
for _, upgrade := range Upgrades {
app.UpgradeKeeper.SetUpgradeHandler(
upgrade.UpgradeName,
upgrade.CreateUpgradeHandler(
app.ModuleManager,
app.configurator,
&keepers,
),
)
}
upgradeInfo, err := app.UpgradeKeeper.ReadUpgradeInfoFromDisk()
if err != nil {
panic(fmt.Sprintf("failed to read upgrade info from disk %s", err))
}
if app.UpgradeKeeper.IsSkipHeight(upgradeInfo.Height) {
return
}
// register store loader for current upgrade
for _, upgrade := range Upgrades {
if upgradeInfo.Name == upgrade.UpgradeName {
app.SetStoreLoader(upgradetypes.UpgradeStoreLoader(upgradeInfo.Height, &upgrade.StoreUpgrades)) // nolint:gosec
break
}
}
}
+34
View File
@@ -0,0 +1,34 @@
package noop
import (
"context"
storetypes "cosmossdk.io/store/types"
upgradetypes "cosmossdk.io/x/upgrade/types"
"github.com/cosmos/cosmos-sdk/types/module"
"github.com/onsonr/hway/app/upgrades"
)
// NewUpgrade constructor
func NewUpgrade(semver string) upgrades.Upgrade {
return upgrades.Upgrade{
UpgradeName: semver,
CreateUpgradeHandler: CreateUpgradeHandler,
StoreUpgrades: storetypes.StoreUpgrades{
Added: []string{},
Deleted: []string{},
},
}
}
func CreateUpgradeHandler(
mm upgrades.ModuleManager,
configurator module.Configurator,
ak *upgrades.AppKeepers,
) upgradetypes.UpgradeHandler {
return func(ctx context.Context, plan upgradetypes.Plan, fromVM module.VersionMap) (module.VersionMap, error) {
return mm.RunMigrations(ctx, configurator, fromVM)
}
}
+44
View File
@@ -0,0 +1,44 @@
package upgrades
import (
"context"
capabilitykeeper "github.com/cosmos/ibc-go/modules/capability/keeper"
ibckeeper "github.com/cosmos/ibc-go/v8/modules/core/keeper"
storetypes "cosmossdk.io/store/types"
upgradetypes "cosmossdk.io/x/upgrade/types"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/types/module"
authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper"
consensusparamkeeper "github.com/cosmos/cosmos-sdk/x/consensus/keeper"
paramskeeper "github.com/cosmos/cosmos-sdk/x/params/keeper"
)
type AppKeepers struct {
AccountKeeper *authkeeper.AccountKeeper
ParamsKeeper *paramskeeper.Keeper
ConsensusParamsKeeper *consensusparamkeeper.Keeper
Codec codec.Codec
GetStoreKey func(storeKey string) *storetypes.KVStoreKey
CapabilityKeeper *capabilitykeeper.Keeper
IBCKeeper *ibckeeper.Keeper
}
type ModuleManager interface {
RunMigrations(ctx context.Context, cfg module.Configurator, fromVM module.VersionMap) (module.VersionMap, error)
GetVersionMap() module.VersionMap
}
// Upgrade defines a struct containing necessary fields that a SoftwareUpgradeProposal
// must have written, in order for the state migration to go smoothly.
// An upgrade must implement this struct, and then set it in the app.go.
// The app.go will then define the handler.
type Upgrade struct {
// Upgrade version name, for the upgrade handler, e.g. `v7`
UpgradeName string
// CreateUpgradeHandler defines the function that creates an upgrade handler
CreateUpgradeHandler func(ModuleManager, module.Configurator, *AppKeepers) upgradetypes.UpgradeHandler
StoreUpgrades storetypes.StoreUpgrades
}