Skip to content

Commit

Permalink
feat(liveness): better tests | general code cleanup (#1532)
Browse files Browse the repository at this point in the history
  • Loading branch information
danwt authored Nov 25, 2024
1 parent 06ae845 commit 6734dc3
Show file tree
Hide file tree
Showing 56 changed files with 663 additions and 1,635 deletions.
2 changes: 1 addition & 1 deletion app/ante/ante_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ func TestAnteTestSuite(t *testing.T) {

// SetupTest setups a new test, with new app, context, and anteHandler.
func (s *AnteTestSuite) SetupTestCheckTx(isCheckTx bool) {
s.app = apptesting.Setup(s.T(), isCheckTx)
s.app = apptesting.Setup(s.T())
s.ctx = s.app.BaseApp.NewContext(isCheckTx, cometbftproto.Header{}).WithBlockHeight(1).WithChainID(apptesting.TestChainID)

txConfig := s.app.GetTxConfig()
Expand Down
265 changes: 14 additions & 251 deletions app/apptesting/test_helpers.go
Original file line number Diff line number Diff line change
@@ -1,39 +1,29 @@
package apptesting

import (
"bytes"
"encoding/hex"
"encoding/json"
"fmt"
"math/rand"
"strconv"
"testing"
"time"

errorsmod "cosmossdk.io/errors"

"cosmossdk.io/math"
cometbftproto "github.com/cometbft/cometbft/proto/tendermint/types"
usim "github.com/cosmos/cosmos-sdk/testutil/sims"

dbm "github.com/cometbft/cometbft-db"
abci "github.com/cometbft/cometbft/abci/types"
"github.com/cometbft/cometbft/libs/log"
cometbftproto "github.com/cometbft/cometbft/proto/tendermint/types"
cometbfttypes "github.com/cometbft/cometbft/types"
"github.com/dymensionxyz/dymension/v3/app/params"
"github.com/stretchr/testify/require"

bam "github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/client"
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/types"
"github.com/cosmos/cosmos-sdk/testutil/mock"
simapp "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/errors"
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"
Expand All @@ -43,28 +33,15 @@ import (
evmtypes "github.com/evmos/ethermint/x/evm/types"
)

// DefaultConsensusParams defines the default Tendermint consensus params used in
// SimApp testing.
var DefaultConsensusParams = &cometbftproto.ConsensusParams{
Block: &cometbftproto.BlockParams{
MaxBytes: 200000,
MaxGas: -1,
},
Evidence: &cometbftproto.EvidenceParams{
MaxAgeNumBlocks: 302400,
MaxAgeDuration: 504 * time.Hour, // 3 weeks is the max duration
MaxBytes: 10000,
},
Validator: &cometbftproto.ValidatorParams{
PubKeyTypes: []string{
cometbfttypes.ABCIPubKeyTypeEd25519,
},
},
}

var TestChainID = "dymension_100-1"

// SetupOptions defines arguments that are passed into `Simapp` constructor.
var DefaultConsensusParams = func() *cometbftproto.ConsensusParams {
ret := usim.DefaultConsensusParams
ret.Block.MaxGas = -1
return ret
}()

// Passed into `Simapp` constructor.
type SetupOptions struct {
Logger log.Logger
DB *dbm.MemDB
Expand All @@ -83,7 +60,8 @@ func SetupTestingApp() (*app.App, app.GenesisState) {
encCdc := app.MakeEncodingConfig()
params.SetAddressPrefixes()

newApp := app.New(log.NewNopLogger(), db, nil, true, map[int64]bool{}, app.DefaultNodeHome, InvariantCheckInterval, encCdc, EmptyAppOptions{}, bam.SetChainID(TestChainID))
newApp := app.New(log.NewNopLogger(), db, nil, true, map[int64]bool{}, app.DefaultNodeHome, InvariantCheckInterval, encCdc,
usim.EmptyAppOptions{}, bam.SetChainID(TestChainID))
defaultGenesisState := app.NewDefaultGenesisState(encCdc.Codec)

incentivesGenesisStateJson := defaultGenesisState[incentivestypes.ModuleName]
Expand All @@ -103,7 +81,7 @@ func SetupTestingApp() (*app.App, app.GenesisState) {
}

// Setup initializes a new SimApp. A Nop logger is set in SimApp.
func Setup(t *testing.T, isCheckTx bool) *app.App {
func Setup(t *testing.T) *app.App {
t.Helper()

privVal := mock.NewPV()
Expand All @@ -122,9 +100,9 @@ func Setup(t *testing.T, isCheckTx bool) *app.App {
Coins: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1000000000000000000))),
}

app := SetupWithGenesisValSet(t, valSet, []authtypes.GenesisAccount{acc}, balance)
a := SetupWithGenesisValSet(t, valSet, []authtypes.GenesisAccount{acc}, balance)

return app
return a
}

func genesisStateWithValSet(t *testing.T,
Expand Down Expand Up @@ -217,22 +195,6 @@ func SetupWithGenesisValSet(t *testing.T, valSet *cometbfttypes.ValidatorSet, ge
return app
}

// SetupWithGenesisAccounts initializes a new SimApp with the provided genesis
// accounts and possible balances.
func SetupWithGenesisAccounts(t *testing.T, genAccs []authtypes.GenesisAccount, balances ...banktypes.Balance) *app.App {
t.Helper()

privVal := mock.NewPV()
pubKey, err := privVal.GetPubKey()
require.NoError(t, err)

// create validator set with single validator
validator := cometbfttypes.NewValidator(pubKey, 1)
valSet := cometbfttypes.NewValidatorSet([]*cometbfttypes.Validator{validator})

return SetupWithGenesisValSet(t, valSet, genAccs, balances...)
}

type GenerateAccountStrategy func(int) []sdk.AccAddress

// CreateRandomAccounts is a strategy used by addTestAddrs() in order to generated addresses in random order.
Expand All @@ -246,49 +208,12 @@ func CreateRandomAccounts(accNum int) []sdk.AccAddress {
return testAddrs
}

// createIncrementalAccounts is a strategy used by addTestAddrs() in order to generated addresses in ascending order.
func createIncrementalAccounts(accNum int) []sdk.AccAddress {
var addresses []sdk.AccAddress
var buffer bytes.Buffer

// start at 100 so we can make up to 999 test addresses with valid test addresses
for i := 100; i < (accNum + 100); i++ {
numString := strconv.Itoa(i)
buffer.WriteString("A58856F0FD53BF058B4909A21AEC019107BA6") // base address string

buffer.WriteString(numString) // adding on final two digits to make addresses unique
res, _ := sdk.AccAddressFromHexUnsafe(buffer.String())
bech := res.String()
addr, _ := TestAddr(buffer.String(), bech)

addresses = append(addresses, addr)
buffer.Reset()
}

return addresses
}

// AddTestAddrsFromPubKeys adds the addresses into the SimApp providing only the public keys.
func AddTestAddrsFromPubKeys(app *app.App, ctx sdk.Context, pubKeys []cryptotypes.PubKey, accAmt math.Int) {
initCoins := sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), accAmt))

for _, pk := range pubKeys {
FundAccount(app, ctx, sdk.AccAddress(pk.Address()), initCoins)
}
}

// AddTestAddrs constructs and returns accNum amount of accounts with an
// initial balance of accAmt in random order
func AddTestAddrs(app *app.App, ctx sdk.Context, accNum int, accAmt math.Int) []sdk.AccAddress {
return addTestAddrs(app, ctx, accNum, accAmt, CreateRandomAccounts)
}

// AddTestAddrsIncremental constructs and returns accNum amount of accounts with an
// initial balance of accAmt in random order
func AddTestAddrsIncremental(app *app.App, ctx sdk.Context, accNum int, accAmt math.Int) []sdk.AccAddress {
return addTestAddrs(app, ctx, accNum, accAmt, createIncrementalAccounts)
}

func addTestAddrs(app *app.App, ctx sdk.Context, accNum int, accAmt math.Int, strategy GenerateAccountStrategy) []sdk.AccAddress {
testAddrs := strategy(accNum)

Expand All @@ -312,165 +237,3 @@ func FundAccount(app *app.App, ctx sdk.Context, addr sdk.AccAddress, coins sdk.C
panic(err)
}
}

// ConvertAddrsToValAddrs converts the provided addresses to ValAddress.
func ConvertAddrsToValAddrs(addrs []sdk.AccAddress) []sdk.ValAddress {
valAddrs := make([]sdk.ValAddress, len(addrs))

for i, addr := range addrs {
valAddrs[i] = sdk.ValAddress(addr)
}

return valAddrs
}

func TestAddr(addr string, bech string) (sdk.AccAddress, error) {
res, err := sdk.AccAddressFromHexUnsafe(addr)
if err != nil {
return nil, err
}
bechexpected := res.String()
if bech != bechexpected {
return nil, fmt.Errorf("bech encoding doesn't match reference")
}

bechres, err := sdk.AccAddressFromBech32(bech)
if err != nil {
return nil, err
}
if !bytes.Equal(bechres, res) {
return nil, err
}

return res, nil
}

// CheckBalance checks the balance of an account.
func CheckBalance(t *testing.T, app *app.App, addr sdk.AccAddress, balances sdk.Coins) {
ctxCheck := app.BaseApp.NewContext(true, cometbftproto.Header{})
require.True(t, balances.IsEqual(app.BankKeeper.GetAllBalances(ctxCheck, addr)))
}

// SignCheckDeliver checks a generated signed transaction and simulates a
// block commitment with the given transaction. A test assertion is made using
// the parameter 'expPass' against the result. A corresponding result is
// returned.
func SignCheckDeliver(
t *testing.T, txCfg client.TxConfig, app *bam.BaseApp, header cometbftproto.Header, msgs []sdk.Msg,
chainID string, accNums, accSeqs []uint64, expSimPass, expPass bool, priv ...cryptotypes.PrivKey,
) (sdk.GasInfo, *sdk.Result, error) {
tx, err := simapp.GenSignedMockTx(
// nolint: errcheck, gosec
rand.New(rand.NewSource(time.Now().UnixNano())),
txCfg,
msgs,
sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 0)},
simapp.DefaultGenTxGas,
chainID,
accNums,
accSeqs,
priv...,
)
require.NoError(t, err)
txBytes, err := txCfg.TxEncoder()(tx)
require.Nil(t, err)

// Must simulate now as CheckTx doesn't run Msgs anymore
_, res, err := app.Simulate(txBytes)

if expSimPass {
require.NoError(t, err)
require.NotNil(t, res)
} else {
require.Error(t, err)
require.Nil(t, res)
}

// Simulate a sending a transaction and committing a block
app.BeginBlock(abci.RequestBeginBlock{Header: header})
gInfo, res, err := app.SimDeliver(txCfg.TxEncoder(), tx)

if expPass {
require.NoError(t, err)
require.NotNil(t, res)
} else {
require.Error(t, err)
require.Nil(t, res)
}

app.EndBlock(abci.RequestEndBlock{})
app.Commit()

return gInfo, res, err
}

// GenSequenceOfTxs generates a set of signed transactions of messages, such
// that they differ only by having the sequence numbers incremented between
// every transaction.
func GenSequenceOfTxs(txGen client.TxConfig, msgs []sdk.Msg, accNums []uint64, initSeqNums []uint64, numToGenerate int, priv ...cryptotypes.PrivKey) ([]sdk.Tx, error) {
txs := make([]sdk.Tx, numToGenerate)
var err error
for i := 0; i < numToGenerate; i++ {
txs[i], err = simapp.GenSignedMockTx(
// nolint: gosec
rand.New(rand.NewSource(time.Now().UnixNano())),
txGen,
msgs,
sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 0)},
simapp.DefaultGenTxGas,
"",
accNums,
initSeqNums,
priv...,
)
if err != nil {
break
}
incrementAllSequenceNumbers(initSeqNums)
}

return txs, err
}

func incrementAllSequenceNumbers(initSeqNums []uint64) {
for i := 0; i < len(initSeqNums); i++ {
initSeqNums[i]++
}
}

// CreateTestPubKeys returns a total of numPubKeys public keys in ascending order.
func CreateTestPubKeys(numPubKeys int) []cryptotypes.PubKey {
var publicKeys []cryptotypes.PubKey
var buffer bytes.Buffer

// start at 10 to avoid changing 1 to 01, 2 to 02, etc
for i := 100; i < (numPubKeys + 100); i++ {
numString := strconv.Itoa(i)
buffer.WriteString("0B485CFC0EECC619440448436F8FC9DF40566F2369E72400281454CB552AF") // base pubkey string
buffer.WriteString(numString) // adding on final two digits to make pubkeys unique
publicKeys = append(publicKeys, NewPubKeyFromHex(buffer.String()))
buffer.Reset()
}

return publicKeys
}

// NewPubKeyFromHex returns a PubKey from a hex string.
func NewPubKeyFromHex(pk string) (res cryptotypes.PubKey) {
pkBytes, err := hex.DecodeString(pk)
if err != nil {
panic(err)
}
if len(pkBytes) != ed25519.PubKeySize {
panic(errorsmod.Wrap(errors.ErrInvalidPubKey, "invalid pubkey size"))
}
return &ed25519.PubKey{Key: pkBytes}
}

// EmptyAppOptions is a stub implementing AppOptions
type EmptyAppOptions struct{}

// Get implements AppOptions
func (ao EmptyAppOptions) Get(o string) interface{} {
return nil
}
9 changes: 9 additions & 0 deletions app/apptesting/test_suite.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ import (
"strings"
"time"

abci "github.com/cometbft/cometbft/abci/types"
"github.com/cometbft/cometbft/libs/rand"
tmproto "github.com/cometbft/cometbft/proto/tendermint/types"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/crypto/keys/ed25519"
"github.com/cosmos/cosmos-sdk/crypto/types"
Expand Down Expand Up @@ -38,6 +40,13 @@ type KeeperTestHelper struct {
Ctx sdk.Context
}

func (s *KeeperTestHelper) NextBlock(dt time.Duration) {
s.App.EndBlocker(s.Ctx, abci.RequestEndBlock{Height: s.Ctx.BlockHeight()})
s.Ctx = s.Ctx.WithBlockTime(s.Ctx.BlockTime().Add(dt)).WithBlockHeight(s.Ctx.BlockHeight() + 1)
h := tmproto.Header{Height: s.Ctx.BlockHeight(), Time: s.Ctx.BlockTime(), ChainID: s.Ctx.ChainID()}
s.App.BeginBlocker(s.Ctx, abci.RequestBeginBlock{Header: h})
}

func (s *KeeperTestHelper) CreateDefaultRollappAndProposer() (string, string) {
rollappId := s.CreateDefaultRollapp()
proposer := s.CreateDefaultSequencer(s.Ctx, rollappId)
Expand Down
4 changes: 2 additions & 2 deletions app/keepers/modules.go
Original file line number Diff line number Diff line change
Expand Up @@ -201,10 +201,10 @@ func (a *AppKeepers) SetupModules(
params.NewAppModule(a.ParamsKeeper),
packetforwardmiddleware.NewAppModule(a.PacketForwardMiddlewareKeeper, a.GetSubspace(packetforwardtypes.ModuleName)),
ibctransfer.NewAppModule(a.TransferKeeper),
rollappmodule.NewAppModule(appCodec, a.RollappKeeper, a.AccountKeeper, a.BankKeeper),
rollappmodule.NewAppModule(appCodec, a.RollappKeeper),
iro.NewAppModule(appCodec, *a.IROKeeper),

sequencermodule.NewAppModule(appCodec, a.SequencerKeeper, a.AccountKeeper, a.BankKeeper),
sequencermodule.NewAppModule(appCodec, a.SequencerKeeper),
sponsorship.NewAppModule(a.SponsorshipKeeper),
streamermodule.NewAppModule(a.StreamerKeeper, a.AccountKeeper, a.BankKeeper, a.EpochsKeeper),
delayedackmodule.NewAppModule(appCodec, a.DelayedAckKeeper, a.delayedAckMiddleware),
Expand Down
Loading

0 comments on commit 6734dc3

Please sign in to comment.