Skip to content

Commit

Permalink
add comments and unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
kingpinXD committed Dec 12, 2024
1 parent 30f1e65 commit f32e676
Show file tree
Hide file tree
Showing 16 changed files with 149 additions and 228 deletions.
1 change: 1 addition & 0 deletions changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
* [3205](https://github.com/zeta-chain/node/issues/3205) - move Bitcoin revert address test to advanced group to avoid upgrade test failure
* [3254](https://github.com/zeta-chain/node/pull/3254) - rename v2 E2E tests as evm tests and rename old evm tests as legacy
* [3095](https://github.com/zeta-chain/node/pull/3095) - initialize simulation tests for custom zetachain modules
* [3207](https://github.com/zeta-chain/node/pull/3207) - add simulation test operations for all messages in crosschain and observer module

## Refactor

Expand Down
15 changes: 15 additions & 0 deletions pkg/chains/chain_filters_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,21 @@ func TestFilterChains(t *testing.T) {
return chains.ChainListByConsensus(chains.Consensus_solana_consensus, []chains.Chain{})
},
},
{
name: "Filter vm evm chains",
filters: []chains.ChainFilter{
chains.FilterByVM(chains.Vm_evm),
},
expected: func() []chains.Chain {
var chainList []chains.Chain
for _, chain := range chains.ExternalChainList([]chains.Chain{}) {
if chain.Vm == chains.Vm_evm {
chainList = append(chainList, chain)
}
}
return chainList
},
},
{
name: "Apply multiple filters external chains and gateway observer",
filters: []chains.ChainFilter{
Expand Down
28 changes: 28 additions & 0 deletions pkg/coin/coint_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package coin_test

import (
"testing"

"github.com/zeta-chain/node/pkg/coin"
)

func TestCoinType_SupportsRefund(t *testing.T) {
tests := []struct {
name string
c coin.CoinType
want bool
}{
{"ERC20", coin.CoinType_ERC20, true},
{"Gas", coin.CoinType_Gas, true},
{"Zeta", coin.CoinType_Zeta, true},
{"Cmd", coin.CoinType_Cmd, false},
{"Unknown", coin.CoinType(100), false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.c.SupportsRefund(); got != tt.want {
t.Errorf("CoinType.SupportsRefund() = %v, want %v", got, tt.want)
}
})
}
}
64 changes: 4 additions & 60 deletions simulation/simulation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,10 @@ func TestAppStateDeterminism(t *testing.T) {
}

// TestFullAppSimulation runs a full simApp simulation with the provided configuration.
// This is the basic test which just runs the simulation and checks for any errors
// This test does the following
// 1. It runs a full simulation with the provided configuration
// 2. It exports the state and validators
// 3. Verifies that the run and export were successful
func TestFullAppSimulation(t *testing.T) {

config := zetasimulation.NewConfigFromFlags()
Expand Down Expand Up @@ -586,62 +589,3 @@ func TestAppSimulationAfterImport(t *testing.T) {
)
require.NoError(t, err)
}

// DiffKVStores compares two KVstores and returns all the key/value pairs
// that differ from one another. It also skips value comparison for a set of provided prefixes.
func CountKVStores(a sdk.KVStore, b sdk.KVStore, _ [][]byte) (int, int) {
iterA := a.Iterator(nil, nil)

defer iterA.Close()

iterB := b.Iterator(nil, nil)

defer iterB.Close()

countA := 0
countB := 0

for iterA.Valid() {
countA++
iterA.Next()
}

for iterB.Valid() {
countB++
iterB.Next()
}
return countA, countB
}

func FindDiffKeys(a sdk.KVStore, b sdk.KVStore) {

keysA := map[string]bool{}
keysB := map[string]bool{}
iterA := a.Iterator(nil, nil)

defer iterA.Close()

iterB := b.Iterator(nil, nil)

defer iterB.Close()

for iterA.Valid() {
k := string(iterA.Key())
iterA.Next()
keysA[k] = true

}

for iterB.Valid() {
kb := string(iterB.Key())
iterB.Next()
keysB[kb] = true
}

for k := range keysA {
if _, ok := keysB[k]; !ok {
fmt.Println("Key in A not in B", k)
}
}

}
104 changes: 37 additions & 67 deletions simulation/state.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,12 @@ package simulation
import (
"encoding/json"
"fmt"
"io"
"math/rand"
"os"
"testing"
"time"

"cosmossdk.io/math"
cmtjson "github.com/cometbft/cometbft/libs/json"
tmtypes "github.com/cometbft/cometbft/types"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
Expand All @@ -23,7 +18,6 @@ import (
"github.com/stretchr/testify/require"
evmtypes "github.com/zeta-chain/ethermint/x/evm/types"

zetaapp "github.com/zeta-chain/node/app"
zetachains "github.com/zeta-chain/node/pkg/chains"
"github.com/zeta-chain/node/pkg/coin"
"github.com/zeta-chain/node/pkg/crypto"
Expand All @@ -40,6 +34,9 @@ const (
InitiallyBondedValidators = "initially_bonded_validators"
)

// updateBankState updates the bank genesis state.
// It adds the following
// - The not bonded balance for the not bonded pool
func updateBankState(
t *testing.T,
rawState map[string]json.RawMessage,
Expand Down Expand Up @@ -71,6 +68,8 @@ func updateBankState(
return bankState
}

// updateEVMState updates the evm genesis state.
// It replaces the EvmDenom with BondDenom
func updateEVMState(
t *testing.T,
rawState map[string]json.RawMessage,
Expand All @@ -89,6 +88,10 @@ func updateEVMState(
return evmState
}

// updateStakingState updates the staking genesis state.
// It adds the following
// - The not bonded balance for the not bonded pool
// It additionally returns the non-bonded coins as well
func updateStakingState(
t *testing.T,
rawState map[string]json.RawMessage,
Expand Down Expand Up @@ -116,6 +119,15 @@ func updateStakingState(
return stakingState, notBondedCoins
}

// updateObserverState updates the observer genesis state.
// It adds the following
// - A random observer set which is a subset of the current validator set
// - A randomised node account for each observer
// - A random TSS
// - A TSS history for the TSS created
// - Chain nonces for each chain
// - Pending nonces for each chain
// - Crosschain flags, inbound and outbound enabled
func updateObserverState(
t *testing.T,
rawState map[string]json.RawMessage,
Expand Down Expand Up @@ -158,7 +170,6 @@ func updateObserverState(
GranteePubkey: &crypto.PubKeySet{},
NodeStatus: observertypes.NodeStatus_Active,
}
//fmt.Println(nodeAccounts[i].GranteePubkey)
}
// Create a random tss
tss, err := sample.TSSFromRand(r)
Expand Down Expand Up @@ -200,6 +211,9 @@ func updateObserverState(
return observerState
}

// updateAuthorityState updates the authority genesis state.
// It adds the following
// - A policy for each policy type, the address is a random account address selected from the simulation accounts list
func updateAuthorityState(
t *testing.T,
rawState map[string]json.RawMessage,
Expand Down Expand Up @@ -235,6 +249,9 @@ func updateAuthorityState(
return authorityState
}

// updateCrossChainState updates the crosschain genesis state.
// It adds the following
// - A gas price list for each chain
func updateCrossChainState(
t *testing.T,
rawState map[string]json.RawMessage,
Expand All @@ -247,18 +264,24 @@ func updateCrossChainState(
crossChainState := new(crosschaintypes.GenesisState)
cdc.MustUnmarshalJSON(crossChainStateBz, crossChainState)

var gasPriceList []*crosschaintypes.GasPrice

// Add a gasprice for each chain
chains := zetachains.DefaultChainsList()
for _, chain := range chains {
gasPriceList = append(gasPriceList, sample.GasPriceFromRand(r, chain.ChainId))
gasPriceList := make([]*crosschaintypes.GasPrice, len(chains))
for i, chain := range chains {
gasPriceList[i] = sample.GasPriceFromRand(r, chain.ChainId)
}

crossChainState.GasPriceList = gasPriceList

return crossChainState
}

// updateFungibleState updates the fungible genesis state.
// It adds the following
// - A random system contract address
// - A random connector zevm address
// - A random gateway address
// - A foreign coin for each chain under the default chain list.
func updateFungibleState(
t *testing.T,
rawState map[string]json.RawMessage,
Expand Down Expand Up @@ -296,6 +319,8 @@ func updateFungibleState(
return fungibleState
}

// updateRawState updates the raw genesis state for the application.
// This is used to inject values needed to run the simulation tests.
func updateRawState(
t *testing.T,
rawState map[string]json.RawMessage,
Expand Down Expand Up @@ -340,7 +365,7 @@ func AppStateFn(

chainID = config.ChainID

// if exported state is provided then use it
// if exported state is provided, then use it
if exportedState != nil {
return exportedState, accs, chainID, genesisTimestamp
}
Expand Down Expand Up @@ -431,58 +456,3 @@ func AppStateRandomizedFn(
}
return appState, accs
}

// AppStateFromGenesisFileFn util function to generate the genesis AppState
// from a genesis.json file.
func AppStateFromGenesisFileFn(
r io.Reader,
cdc codec.JSONCodec,
genesisFile string,
) (tmtypes.GenesisDoc, []simtypes.Account, error) {
bytes, err := os.ReadFile(genesisFile) // #nosec G304 -- genesisFile value is controlled
if err != nil {
panic(err)
}

var genesis tmtypes.GenesisDoc
// NOTE: Comet uses a custom JSON decoder for GenesisDoc
err = cmtjson.Unmarshal(bytes, &genesis)
if err != nil {
panic(err)
}

var appState zetaapp.GenesisState
err = json.Unmarshal(genesis.AppState, &appState)
if err != nil {
panic(err)
}

var authGenesis authtypes.GenesisState
if appState[authtypes.ModuleName] != nil {
cdc.MustUnmarshalJSON(appState[authtypes.ModuleName], &authGenesis)
}

newAccs := make([]simtypes.Account, len(authGenesis.Accounts))
for i, acc := range authGenesis.Accounts {
// Pick a random private key, since we don't know the actual key
// This should be fine as it's only used for mock Tendermint validators
// and these keys are never actually used to sign by mock Tendermint.
privkeySeed := make([]byte, 15)
if _, err := r.Read(privkeySeed); err != nil {
panic(err)
}

privKey := secp256k1.GenPrivKeyFromSecret(privkeySeed)

a, ok := acc.GetCachedValue().(authtypes.AccountI)
if !ok {
return genesis, nil, fmt.Errorf("expected account")
}

// create simulator accounts
simAcc := simtypes.Account{PrivKey: privKey, PubKey: privKey.PubKey(), Address: a.GetAddress()}
newAccs[i] = simAcc
}

return genesis, newAccs, nil
}
1 change: 0 additions & 1 deletion testutil/sample/crosschain.go
Original file line number Diff line number Diff line change
Expand Up @@ -357,7 +357,6 @@ func InboundVote(coinType coin.CoinType, from, to int64) types.MsgVoteInbound {
}
}

// InboundVoteFromRand creates a simulated inbound vote message. This function uses the provided source of randomness to generate the vot
// InboundVoteFromRand creates a simulated inbound vote message. This function uses the provided source of randomness to generate the vote
func InboundVoteFromRand(from, to int64, r *rand.Rand, asset string) types.MsgVoteInbound {
coinType := CoinTypeFromRand(r)
Expand Down
8 changes: 0 additions & 8 deletions testutil/sample/crypto.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,14 +129,6 @@ func SolanaAddress(t *testing.T) string {
return privKey.PublicKey().String()
}

func SolAddressFromRand(r *rand.Rand) string {
privKey, err := solana.NewRandomPrivateKey()
if err != nil {
panic(err)
}
return privKey.PublicKey().String()
}

// SolanaSignature returns a sample solana signature
func SolanaSignature(t *testing.T) solana.Signature {
// Generate a random keypair
Expand Down
Loading

0 comments on commit f32e676

Please sign in to comment.