/
test_helpers.go
288 lines (268 loc) · 11.9 KB
/
test_helpers.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
package test
import (
"bytes"
"encoding/hex"
tokenregistryTypes "github.com/Sifchain/sifnode/x/tokenregistry/types"
"math/rand"
"time"
adminkeeper "github.com/Sifchain/sifnode/x/admin/keeper"
admintypes "github.com/Sifchain/sifnode/x/admin/types"
"strconv"
"testing"
"github.com/Sifchain/sifnode/app"
"github.com/Sifchain/sifnode/x/ethbridge/keeper"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
simappparams "github.com/cosmos/cosmos-sdk/simapp/params"
authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper"
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"
paramskeeper "github.com/cosmos/cosmos-sdk/x/params/keeper"
paramstypes "github.com/cosmos/cosmos-sdk/x/params/types"
"github.com/stretchr/testify/require"
"github.com/tendermint/tendermint/libs/log"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"github.com/cosmos/cosmos-sdk/crypto/keys/ed25519"
abci "github.com/tendermint/tendermint/abci/types"
dbm "github.com/tendermint/tm-db"
"github.com/cosmos/cosmos-sdk/store"
sdk "github.com/cosmos/cosmos-sdk/types"
stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
tmtypes "github.com/tendermint/tendermint/types"
"github.com/Sifchain/sifnode/x/ethbridge/types"
oraclekeeper "github.com/Sifchain/sifnode/x/oracle/keeper"
oracleTypes "github.com/Sifchain/sifnode/x/oracle/types"
)
const (
TestID = "oracleID"
AlternateTestID = "altOracleID"
TestString = "{value: 5}"
AlternateTestString = "{value: 7}"
AnotherAlternateTestString = "{value: 9}"
TestCethReceiverAddress = "cosmos1gn8409qq9hnrxde37kuxwx5hrxpfpv8426szuv"
)
// CreateTestKeepers greates an Mock App, OracleKeeper, bankKeeper and ValidatorAddresses to be used for test input
func CreateTestKeepers(t *testing.T, consensusNeeded float64, validatorAmounts []int64, extraMaccPerm string) (sdk.Context, keeper.Keeper, bankkeeper.Keeper, authkeeper.AccountKeeper, oraclekeeper.Keeper, simappparams.EncodingConfig, []sdk.ValAddress) {
PKs := CreateTestPubKeys(500)
keyStaking := sdk.NewKVStoreKey(stakingtypes.StoreKey)
// TODO: staking.TStoreKey removed in favor of?
tkeyStaking := sdk.NewTransientStoreKey("transient_staking")
keyAcc := sdk.NewKVStoreKey(authtypes.StoreKey)
keyParams := sdk.NewKVStoreKey(paramstypes.StoreKey)
tkeyParams := sdk.NewTransientStoreKey(paramstypes.TStoreKey)
keyBank := sdk.NewKVStoreKey(banktypes.StoreKey)
keyOracle := sdk.NewKVStoreKey(oracleTypes.StoreKey)
keyEthBridge := sdk.NewKVStoreKey(types.StoreKey)
adminKey := sdk.NewKVStoreKey(admintypes.StoreKey)
db := dbm.NewMemDB()
ms := store.NewCommitMultiStore(db)
ms.MountStoreWithDB(tkeyStaking, sdk.StoreTypeTransient, nil)
ms.MountStoreWithDB(keyStaking, sdk.StoreTypeIAVL, db)
ms.MountStoreWithDB(keyAcc, sdk.StoreTypeIAVL, db)
ms.MountStoreWithDB(keyParams, sdk.StoreTypeIAVL, db)
ms.MountStoreWithDB(tkeyParams, sdk.StoreTypeTransient, db)
ms.MountStoreWithDB(keyBank, sdk.StoreTypeIAVL, db)
ms.MountStoreWithDB(keyOracle, sdk.StoreTypeIAVL, db)
ms.MountStoreWithDB(keyEthBridge, sdk.StoreTypeIAVL, db)
err := ms.LoadLatestVersion()
require.NoError(t, err)
ctx := sdk.NewContext(ms, tmproto.Header{ChainID: "foochainid"}, false, nil)
ctx = ctx.WithConsensusParams(
&abci.ConsensusParams{
Validator: &tmproto.ValidatorParams{
PubKeyTypes: []string{tmtypes.ABCIPubKeyTypeEd25519},
},
},
)
ctx = ctx.WithLogger(log.NewNopLogger())
encCfg := MakeTestEncodingConfig()
bridgeAccount := authtypes.NewEmptyModuleAccount(types.ModuleName, authtypes.Burner, authtypes.Minter)
feeCollectorAcc := authtypes.NewEmptyModuleAccount(authtypes.FeeCollectorName)
notBondedPool := authtypes.NewEmptyModuleAccount(stakingtypes.NotBondedPoolName, authtypes.Burner, authtypes.Staking)
bondPool := authtypes.NewEmptyModuleAccount(stakingtypes.BondedPoolName, authtypes.Burner, authtypes.Staking)
blacklistedAddrs := make(map[string]bool)
blacklistedAddrs[feeCollectorAcc.GetAddress().String()] = true
blacklistedAddrs[notBondedPool.GetAddress().String()] = true
blacklistedAddrs[bondPool.GetAddress().String()] = true
maccPerms := map[string][]string{
authtypes.FeeCollectorName: nil,
stakingtypes.NotBondedPoolName: {authtypes.Burner, authtypes.Staking},
stakingtypes.BondedPoolName: {authtypes.Burner, authtypes.Staking},
types.ModuleName: {authtypes.Burner, authtypes.Minter},
}
if extraMaccPerm != "" {
maccPerms[extraMaccPerm] = []string{authtypes.Burner, authtypes.Minter}
}
paramsKeeper := paramskeeper.NewKeeper(encCfg.Marshaler, encCfg.Amino, keyParams, tkeyParams)
//accountKeeper gets maccParams in 0.40, module accounts moved from supplykeeper to authkeeper
accountKeeper := authkeeper.NewAccountKeeper(
encCfg.Marshaler, // amino codec
keyAcc, // target store
paramsKeeper.Subspace(authtypes.ModuleName),
authtypes.ProtoBaseAccount, // prototype,
maccPerms,
)
bankKeeper := bankkeeper.NewBaseKeeper(
encCfg.Marshaler,
keyBank,
accountKeeper,
paramsKeeper.Subspace(banktypes.ModuleName),
blacklistedAddrs,
)
adminKeeper := adminkeeper.NewKeeper(encCfg.Marshaler, adminKey)
initTokens := sdk.TokensFromConsensusPower(10000, sdk.DefaultPowerReduction)
totalSupply := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, initTokens.MulRaw(int64(100))))
// bankKeeper.SetSupply(ctx, banktypes.NewSupply(totalSupply))
stakingKeeper := stakingkeeper.NewKeeper(encCfg.Marshaler, keyStaking, accountKeeper, bankKeeper, paramsKeeper.Subspace(stakingtypes.ModuleName))
stakingKeeper.SetParams(ctx, stakingtypes.DefaultParams())
oracleKeeper := oraclekeeper.NewKeeper(encCfg.Marshaler, keyOracle, stakingKeeper, consensusNeeded)
// set module accounts
accountKeeper.SetModuleAccount(ctx, bridgeAccount)
accountKeeper.SetModuleAccount(ctx, feeCollectorAcc)
accountKeeper.SetModuleAccount(ctx, bondPool)
accountKeeper.SetModuleAccount(ctx, notBondedPool)
err = bankKeeper.MintCoins(ctx, types.ModuleName, totalSupply)
require.NoError(t, err)
err = bankKeeper.SendCoinsFromModuleToModule(ctx, types.ModuleName, stakingtypes.NotBondedPoolName, totalSupply)
require.NoError(t, err)
ethbridgeKeeper := keeper.NewKeeper(encCfg.Marshaler, bankKeeper, oracleKeeper, accountKeeper, adminKeeper, keyEthBridge)
cethReceiverAccount, _ := sdk.AccAddressFromBech32(types.TestAddress)
ethbridgeKeeper.SetCethReceiverAccount(ctx, cethReceiverAccount)
// Setup validators
valAddrs := make([]sdk.ValAddress, len(validatorAmounts))
for i, amount := range validatorAmounts {
valPubKey := PKs[i]
valAddr := sdk.ValAddress(valPubKey.Address().Bytes())
valAddrs[i] = valAddr
valTokens := sdk.TokensFromConsensusPower(amount, sdk.DefaultPowerReduction)
// test how the validator is set from a purely unbonbed pool
validator, err := stakingtypes.NewValidator(valAddr, valPubKey, stakingtypes.Description{})
require.NoError(t, err)
validator, _ = validator.AddTokensFromDel(valTokens)
stakingKeeper.SetValidator(ctx, validator)
stakingKeeper.SetValidatorByPowerIndex(ctx, validator)
_, err = stakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
if err != nil {
panic("Failed to apply validator set updates")
}
}
oracleKeeper.SetOracleWhiteList(ctx, valAddrs)
return ctx, ethbridgeKeeper, bankKeeper, accountKeeper, oracleKeeper, encCfg, valAddrs
}
func CreateTestApp(isCheckTx bool) (*app.SifchainApp, sdk.Context) {
sifchainApp := app.Setup(isCheckTx)
ctx := sifchainApp.BaseApp.NewContext(isCheckTx, tmproto.Header{})
sifchainApp.AccountKeeper.SetParams(ctx, authtypes.DefaultParams())
initTokens := sdk.TokensFromConsensusPower(1000, sdk.DefaultPowerReduction)
_ = app.AddTestAddrs(sifchainApp, ctx, 6, initTokens)
return sifchainApp, ctx
}
// nolint: unparam
func CreateTestAddrs(numAddrs int) ([]sdk.AccAddress, []sdk.ValAddress) {
var addresses []sdk.AccAddress
var valAddresses []sdk.ValAddress
var buffer bytes.Buffer
// start at 100, so we can make up to 999 test addresses with valid test addresses
for i := 100; i < (numAddrs + 100); i++ {
numString := strconv.Itoa(i)
buffer.WriteString("A58856F0FD53BF058B4909A21AEC019107BA6") //base address string
buffer.WriteString(numString) //adding on final two digits to make addresses unique
address, _ := sdk.AccAddressFromHex(buffer.String())
valAddress := sdk.ValAddress(address)
addresses = append(addresses, address)
valAddresses = append(valAddresses, valAddress)
buffer.Reset()
}
return addresses, valAddresses
}
// nolint: unparam
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, NewPubKey(buffer.String()))
buffer.Reset()
}
return publicKeys
}
func NewPubKey(pk string) (res cryptotypes.PubKey) {
pkBytes, err := hex.DecodeString(pk)
if err != nil {
panic(err)
}
//res, err = crypto.PubKeyFromBytes(pkBytes)
return &ed25519.PubKey{
Key: pkBytes,
}
}
// create a codec used only for testing
func MakeTestEncodingConfig() simappparams.EncodingConfig {
return app.MakeTestEncodingConfig()
}
const (
AddressKey1 = "A58856F0FD53BF058B4909A21AEC019107BA6"
)
//// returns context and app with params set on account keeper
func CreateSimulatorApp(isCheckTx bool) (sdk.Context, *app.SifchainApp) {
sifchainApp := app.Setup(isCheckTx)
ctx := sifchainApp.BaseApp.NewContext(isCheckTx, tmproto.Header{})
sifchainApp.TokenRegistryKeeper.SetRegistry(ctx, tokenregistryTypes.Registry{
Entries: []*tokenregistryTypes.RegistryEntry{
{Denom: "ceth", Decimals: 18, Permissions: []tokenregistryTypes.Permission{tokenregistryTypes.Permission_CLP}},
{Denom: "cdash", Decimals: 18, Permissions: []tokenregistryTypes.Permission{tokenregistryTypes.Permission_CLP}},
{Denom: "eth", Decimals: 18, Permissions: []tokenregistryTypes.Permission{tokenregistryTypes.Permission_CLP}},
{Denom: "cacoin", Decimals: 18, Permissions: []tokenregistryTypes.Permission{tokenregistryTypes.Permission_CLP}},
{Denom: "dash", Decimals: 18, Permissions: []tokenregistryTypes.Permission{tokenregistryTypes.Permission_CLP}},
{Denom: "atom", Decimals: 18, Permissions: []tokenregistryTypes.Permission{tokenregistryTypes.Permission_CLP}},
{Denom: "cusdc", Decimals: 18, Permissions: []tokenregistryTypes.Permission{tokenregistryTypes.Permission_CLP}},
},
})
return ctx, sifchainApp
}
func CreateTestAppEthBridge(isCheckTx bool) (sdk.Context, keeper.Keeper) {
sifapp, ctx := CreateTestApp(isCheckTx)
return ctx, sifapp.EthbridgeKeeper
}
func GenerateRandomTokens(numberOfTokens int) []string {
var tokenList []string
tokens := []string{"ceth", "cbtc", "ceos", "cbch", "cbnb", "cusdt", "cada", "ctrx", "cacoin", "cbcoin", "ccoin", "cdcoin"}
rand.Seed(time.Now().Unix())
for i := 0; i < numberOfTokens; i++ {
// initialize global pseudo random generator
randToken := tokens[rand.Intn(len(tokens))]
tokenList = append(tokenList, randToken)
}
return tokenList
}
func GenerateAddress(key string) sdk.AccAddress {
if key == "" {
key = AddressKey1
}
var buffer bytes.Buffer
buffer.WriteString(key)
buffer.WriteString(strconv.Itoa(100))
res, _ := sdk.AccAddressFromHex(buffer.String())
bech := res.String()
addr := buffer.String()
res, err := sdk.AccAddressFromHex(addr)
if err != nil {
panic(err)
}
bechexpected := res.String()
if bech != bechexpected {
panic("Bech encoding doesn't match reference")
}
bechres, err := sdk.AccAddressFromBech32(bech)
if err != nil {
panic(err)
}
if !bytes.Equal(bechres, res) {
panic("Bech decode and hex decode don't match")
}
return res
}