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

Fork x/gov #4

Merged
merged 12 commits into from
Feb 9, 2024
2 changes: 1 addition & 1 deletion ante/ante.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ import (
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth/ante"
govkeeper "github.com/cosmos/cosmos-sdk/x/gov/keeper"
paramtypes "github.com/cosmos/cosmos-sdk/x/params/types"

"github.com/atomone-hub/govgen/v1/types/errors"
govkeeper "github.com/atomone-hub/govgen/v1/x/gov/keeper"
)

// HandlerOptions extend the SDK's AnteHandler options by requiring the IBC
Expand Down
2 changes: 1 addition & 1 deletion ante/fee_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import (
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/tx"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
"github.com/cosmos/cosmos-sdk/simapp"
"github.com/cosmos/cosmos-sdk/testutil/testdata"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/tx/signing"
Expand All @@ -20,6 +19,7 @@ import (
"github.com/atomone-hub/govgen/v1/ante"
govgenapp "github.com/atomone-hub/govgen/v1/app"
govgenhelpers "github.com/atomone-hub/govgen/v1/app/helpers"
"github.com/cosmos/cosmos-sdk/simapp"
)

type FeeIntegrationTestSuite struct {
Expand Down
2 changes: 1 addition & 1 deletion ante/gov_ante.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ import (
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/authz"
govkeeper "github.com/cosmos/cosmos-sdk/x/gov/keeper"
govtypes "github.com/cosmos/cosmos-sdk/x/gov/types"

"github.com/atomone-hub/govgen/v1/types/errors"
govkeeper "github.com/atomone-hub/govgen/v1/x/gov/keeper"
)

// initial deposit must be greater than or equal to 1% of the minimum deposit
Expand Down
2 changes: 1 addition & 1 deletion app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ import (
"github.com/cosmos/cosmos-sdk/server/api"
"github.com/cosmos/cosmos-sdk/server/config"
servertypes "github.com/cosmos/cosmos-sdk/server/types"
"github.com/cosmos/cosmos-sdk/simapp"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
"github.com/cosmos/cosmos-sdk/version"
Expand All @@ -46,6 +45,7 @@ import (
"github.com/atomone-hub/govgen/v1/app/keepers"
govgenappparams "github.com/atomone-hub/govgen/v1/app/params"
"github.com/atomone-hub/govgen/v1/app/upgrades"
"github.com/cosmos/cosmos-sdk/simapp"
)

var (
Expand Down
305 changes: 305 additions & 0 deletions app/helpers/test_helpers.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
package helpers

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

Expand All @@ -13,13 +18,19 @@ import (
tmtypes "github.com/tendermint/tendermint/types"
dbm "github.com/tendermint/tm-db"

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"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
"github.com/cosmos/cosmos-sdk/simapp/helpers"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/errors"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
minttypes "github.com/cosmos/cosmos-sdk/x/mint/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"

govgenapp "github.com/atomone-hub/govgen/v1/app"
Expand Down Expand Up @@ -62,8 +73,10 @@ func (pv PV) GetPubKey() (crypto.PubKey, error) {
return cryptocodec.ToTmPubKeyInterface(pv.PrivKey.PubKey())
}

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

// Get implements AppOptions
func (EmptyAppOptions) Get(_ string) interface{} { return nil }

func Setup(t *testing.T) *govgenapp.GovGenApp {
Expand Down Expand Up @@ -206,3 +219,295 @@ func genesisStateWithValSet(t *testing.T,

return genesisState
}

func setupNoValset(withGenesis bool, invCheckPeriod uint) (*govgenapp.GovGenApp, govgenapp.GenesisState) {
db := dbm.NewMemDB()
encCdc := govgenapp.MakeTestEncodingConfig()
app := govgenapp.NewGovGenApp(log.NewNopLogger(), db, nil, true, map[int64]bool{}, govgenapp.DefaultNodeHome, invCheckPeriod, encCdc, EmptyAppOptions{})
if withGenesis {
return app, govgenapp.NewDefaultGenesisState()
}
return app, govgenapp.GenesisState{}
}

func SetupNoValset(isCheckTx bool) *govgenapp.GovGenApp {
app, genesisState := setupNoValset(!isCheckTx, 5)
if !isCheckTx {
// init chain must be called to stop deliverState from being nil
stateBytes, err := json.MarshalIndent(genesisState, "", " ")
if err != nil {
panic(err)
}

// Initialize the chain
app.InitChain(
abci.RequestInitChain{
Validators: []abci.ValidatorUpdate{},
ConsensusParams: DefaultConsensusParams,
AppStateBytes: stateBytes,
},
)
}

return app
}

type GenerateAccountStrategy func(int) []sdk.AccAddress

// createRandomAccounts is a strategy used by addTestAddrs() in order to generated addresses in random order.
func createRandomAccounts(accNum int) []sdk.AccAddress {
testAddrs := make([]sdk.AccAddress, accNum)
for i := 0; i < accNum; i++ {
pk := ed25519.GenPrivKey().PubKey()
testAddrs[i] = sdk.AccAddress(pk.Address())
}

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.AccAddressFromHex(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 *govgenapp.GovGenApp, ctx sdk.Context, pubKeys []cryptotypes.PubKey, accAmt sdk.Int) {
initCoins := sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), accAmt))

for _, pk := range pubKeys {
initAccountWithCoins(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 *govgenapp.GovGenApp, ctx sdk.Context, accNum int, accAmt sdk.Int) []sdk.AccAddress {
return addTestAddrs(app, ctx, accNum, accAmt, createRandomAccounts)
}

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

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

initCoins := sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), accAmt))

for _, addr := range testAddrs {
initAccountWithCoins(app, ctx, addr, initCoins)
}

return testAddrs
}

func initAccountWithCoins(app *govgenapp.GovGenApp, 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)
}
}

// 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.AccAddressFromHex(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 *govgenapp.GovGenApp, addr sdk.AccAddress, balances sdk.Coins) {
ctxCheck := app.BaseApp.NewContext(true, tmproto.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 tmproto.Header, msgs []sdk.Msg,
chainID string, accNums, accSeqs []uint64, expSimPass, expPass bool, priv ...cryptotypes.PrivKey,
) (sdk.GasInfo, *sdk.Result, error) {
tx, err := helpers.GenSignedMockTx(
rand.New(rand.NewSource(time.Now().UnixNano())),
txCfg,
msgs,
sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 0)},
helpers.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.Deliver(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 = helpers.GenSignedMockTx(
rand.New(rand.NewSource(time.Now().UnixNano())),
txGen,
msgs,
sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 0)},
helpers.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(errors.Wrap(errors.ErrInvalidPubKey, "invalid pubkey size"))
}
return &ed25519.PubKey{Key: pkBytes}
}

// FundAccount is a utility function that funds an account by minting and
// sending the coins to the address. This should be used for testing purposes
// only!
//
// TODO: Instead of using the mint module account, which has the
// permission of minting, create a "faucet" account. (@fdymylja)
func FundAccount(bankKeeper bankkeeper.Keeper, ctx sdk.Context, addr sdk.AccAddress, amounts sdk.Coins) error {
if err := bankKeeper.MintCoins(ctx, minttypes.ModuleName, amounts); err != nil {
return err
}

return bankKeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, addr, amounts)
}

// FundModuleAccount is a utility function that funds a module account by
// minting and sending the coins to the address. This should be used for testing
// purposes only!
//
// TODO: Instead of using the mint module account, which has the
// permission of minting, create a "faucet" account. (@fdymylja)
func FundModuleAccount(bankKeeper bankkeeper.Keeper, ctx sdk.Context, recipientMod string, amounts sdk.Coins) error {
if err := bankKeeper.MintCoins(ctx, minttypes.ModuleName, amounts); err != nil {
return err
}

return bankKeeper.SendCoinsFromModuleToModule(ctx, minttypes.ModuleName, recipientMod, amounts)
}
Loading
Loading