/
test_common.go
725 lines (627 loc) · 25.6 KB
/
test_common.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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
package keeper
import (
"bytes"
"testing"
"time"
sdkmath "cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
ccodec "github.com/cosmos/cosmos-sdk/crypto/codec"
"github.com/cosmos/cosmos-sdk/crypto/keys/ed25519"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
ccrypto "github.com/cosmos/cosmos-sdk/crypto/types"
"github.com/cosmos/cosmos-sdk/std"
"github.com/cosmos/cosmos-sdk/store"
storetypes "github.com/cosmos/cosmos-sdk/store/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
"github.com/cosmos/cosmos-sdk/x/auth"
authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"github.com/cosmos/cosmos-sdk/x/auth/vesting"
"github.com/cosmos/cosmos-sdk/x/bank"
bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/cosmos/cosmos-sdk/x/capability"
"github.com/cosmos/cosmos-sdk/x/crisis"
"github.com/cosmos/cosmos-sdk/x/distribution"
distrclient "github.com/cosmos/cosmos-sdk/x/distribution/client"
distrkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper"
distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types"
"github.com/cosmos/cosmos-sdk/x/evidence"
"github.com/cosmos/cosmos-sdk/x/genutil"
"github.com/cosmos/cosmos-sdk/x/gov"
govclient "github.com/cosmos/cosmos-sdk/x/gov/client"
govkeeper "github.com/cosmos/cosmos-sdk/x/gov/keeper"
govtypes "github.com/cosmos/cosmos-sdk/x/gov/types"
govtypesv1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1"
govtypesv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1"
"github.com/cosmos/cosmos-sdk/x/mint"
"github.com/cosmos/cosmos-sdk/x/params"
paramsclient "github.com/cosmos/cosmos-sdk/x/params/client"
paramskeeper "github.com/cosmos/cosmos-sdk/x/params/keeper"
paramstypes "github.com/cosmos/cosmos-sdk/x/params/types"
paramsproposal "github.com/cosmos/cosmos-sdk/x/params/types/proposal"
"github.com/cosmos/cosmos-sdk/x/slashing"
slashingkeeper "github.com/cosmos/cosmos-sdk/x/slashing/keeper"
slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types"
"github.com/cosmos/cosmos-sdk/x/staking"
stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper"
"github.com/cosmos/cosmos-sdk/x/staking/teststaking"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
"github.com/cosmos/cosmos-sdk/x/upgrade"
upgradeclient "github.com/cosmos/cosmos-sdk/x/upgrade/client"
gethcommon "github.com/ethereum/go-ethereum/common"
"github.com/stretchr/testify/require"
"github.com/tendermint/tendermint/libs/log"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
dbm "github.com/tendermint/tm-db"
"github.com/peggyjv/gravity-bridge/module/v4/x/gravity/types"
)
var (
// ModuleBasics is a mock module basic manager for testing
ModuleBasics = module.NewBasicManager(
auth.AppModuleBasic{},
genutil.AppModuleBasic{},
bank.AppModuleBasic{},
capability.AppModuleBasic{},
staking.AppModuleBasic{},
mint.AppModuleBasic{},
distribution.AppModuleBasic{},
gov.NewAppModuleBasic(
[]govclient.ProposalHandler{
paramsclient.ProposalHandler, distrclient.ProposalHandler, upgradeclient.LegacyProposalHandler, upgradeclient.LegacyCancelProposalHandler,
},
),
params.AppModuleBasic{},
crisis.AppModuleBasic{},
slashing.AppModuleBasic{},
upgrade.AppModuleBasic{},
evidence.AppModuleBasic{},
vesting.AppModuleBasic{},
)
// Ensure that StakingKeeperMock implements required interface
_ types.StakingKeeper = &StakingKeeperMock{}
)
var (
// ConsPrivKeys generate ed25519 ConsPrivKeys to be used for validator operator keys
ConsPrivKeys = []ccrypto.PrivKey{
ed25519.GenPrivKey(),
ed25519.GenPrivKey(),
ed25519.GenPrivKey(),
ed25519.GenPrivKey(),
ed25519.GenPrivKey(),
}
// ConsPubKeys holds the consensus public keys to be used for validator operator keys
ConsPubKeys = []ccrypto.PubKey{
ConsPrivKeys[0].PubKey(),
ConsPrivKeys[1].PubKey(),
ConsPrivKeys[2].PubKey(),
ConsPrivKeys[3].PubKey(),
ConsPrivKeys[4].PubKey(),
}
// AccPrivKeys generate secp256k1 pubkeys to be used for account pub keys
AccPrivKeys = []ccrypto.PrivKey{
secp256k1.GenPrivKey(),
secp256k1.GenPrivKey(),
secp256k1.GenPrivKey(),
secp256k1.GenPrivKey(),
secp256k1.GenPrivKey(),
}
// AccPubKeys holds the pub keys for the account keys
AccPubKeys = []ccrypto.PubKey{
AccPrivKeys[0].PubKey(),
AccPrivKeys[1].PubKey(),
AccPrivKeys[2].PubKey(),
AccPrivKeys[3].PubKey(),
AccPrivKeys[4].PubKey(),
}
// AccAddrs holds the sdk.AccAddresses
AccAddrs = []sdk.AccAddress{
sdk.AccAddress(AccPubKeys[0].Address()),
sdk.AccAddress(AccPubKeys[1].Address()),
sdk.AccAddress(AccPubKeys[2].Address()),
sdk.AccAddress(AccPubKeys[3].Address()),
sdk.AccAddress(AccPubKeys[4].Address()),
}
// ValAddrs holds the sdk.ValAddresses
ValAddrs = []sdk.ValAddress{
sdk.ValAddress(AccPubKeys[0].Address()),
sdk.ValAddress(AccPubKeys[1].Address()),
sdk.ValAddress(AccPubKeys[2].Address()),
sdk.ValAddress(AccPubKeys[3].Address()),
sdk.ValAddress(AccPubKeys[4].Address()),
}
// TODO: generate the eth priv keys here and
// derive the address from them.
// EthAddrs holds etheruem addresses
EthAddrs = []gethcommon.Address{
gethcommon.BytesToAddress(bytes.Repeat([]byte{byte(1)}, 20)),
gethcommon.BytesToAddress(bytes.Repeat([]byte{byte(2)}, 20)),
gethcommon.BytesToAddress(bytes.Repeat([]byte{byte(3)}, 20)),
gethcommon.BytesToAddress(bytes.Repeat([]byte{byte(4)}, 20)),
gethcommon.BytesToAddress(bytes.Repeat([]byte{byte(5)}, 20)),
}
// TokenContractAddrs holds example token contract addresses
TokenContractAddrs = []string{
"0x6b175474e89094c44da98b954eedeac495271d0f", // DAI
"0x0bc529c00c6401aef6d220be8c6ea1667f6ad93e", // YFI
"0x1f9840a85d5af5bf1d1762f925bdaddc4201f984", // UNI
"0xc00e94cb662c3520282e6f5717214004a7f26888", // COMP
"0xc011a73ee8576fb46f5e1c5751ca3b9fe0af2a6f", // SNX
}
// InitTokens holds the number of tokens to initialize an account with
InitTokens = sdk.TokensFromConsensusPower(110, sdk.DefaultPowerReduction)
// InitCoins holds the number of coins to initialize an account with
InitCoins = sdk.NewCoins(sdk.NewCoin(TestingStakeParams.BondDenom, InitTokens))
// StakingAmount holds the staking power to start a validator with
StakingAmount = sdk.TokensFromConsensusPower(10, sdk.DefaultPowerReduction)
// StakingCoins holds the staking coins to start a validator with
StakingCoins = sdk.NewCoins(sdk.NewCoin(TestingStakeParams.BondDenom, StakingAmount))
// TestingStakeParams is a set of staking params for testing
TestingStakeParams = stakingtypes.Params{
UnbondingTime: 100,
MaxValidators: 10,
MaxEntries: 10,
HistoricalEntries: 10000,
BondDenom: "stake",
MinCommissionRate: sdk.ZeroDec(),
}
// TestingGravityParams is a set of gravity params for testing
TestingGravityParams = types.Params{
GravityId: "testgravityid",
ContractSourceHash: "62328f7bc12efb28f86111d08c29b39285680a906ea0e524e0209d6f6657b713",
BridgeEthereumAddress: "0x8858eeb3dfffa017d4bce9801d340d36cf895ccf",
BridgeChainId: 11,
ConfirmedOutgoingTxWindow: 10,
SignedSignerSetTxsWindow: 10,
UnbondSlashingSignerSetTxsWindow: 10,
EthereumSignaturesWindow: 10,
TargetEthTxTimeout: 60001,
AverageBlockTime: 5000,
AverageEthereumBlockTime: 15000,
SlashFractionSignerSetTx: sdk.NewDecWithPrec(1, 2),
SlashFractionBatch: sdk.NewDecWithPrec(1, 2),
SlashFractionEthereumSignature: sdk.NewDecWithPrec(1, 2),
SlashFractionConflictingEthereumSignature: sdk.NewDecWithPrec(1, 2),
}
)
// TestInput stores the various keepers required to test gravity
type TestInput struct {
GravityKeeper Keeper
AccountKeeper authkeeper.AccountKeeper
StakingKeeper stakingkeeper.Keeper
SlashingKeeper slashingkeeper.Keeper
DistKeeper distrkeeper.Keeper
BankKeeper bankkeeper.BaseKeeper
GovKeeper govkeeper.Keeper
Context sdk.Context
Marshaler codec.Codec
LegacyAmino *codec.LegacyAmino
GravityStoreKey *storetypes.KVStoreKey
}
func (input TestInput) AddSendToEthTxsToPool(t *testing.T, ctx sdk.Context, tokenContract gethcommon.Address, sender sdk.AccAddress, receiver gethcommon.Address, ids ...uint64) {
for i, id := range ids {
amount := types.NewERC20Token(uint64(i+100), tokenContract).GravityCoin()
fee := types.NewERC20Token(id, tokenContract).GravityCoin()
_, err := input.GravityKeeper.createSendToEthereum(ctx, sender, receiver.Hex(), amount, fee)
require.NoError(t, err)
}
}
func (input TestInput) AddBalanceToBank(ctx sdk.Context, addr sdk.AccAddress, balances sdk.Coins) error {
return fundAccount(ctx, input.BankKeeper, addr, balances)
}
// SetupFiveValChain does all the initialization for a 5 Validator chain using the keys here
func SetupFiveValChain(t *testing.T) (TestInput, sdk.Context) {
t.Helper()
input := CreateTestEnv(t)
// Set the params for our modules
input.StakingKeeper.SetParams(input.Context, TestingStakeParams)
sh := teststaking.NewHelper(t, input.Context, input.StakingKeeper)
sh.Denom = TestingStakeParams.BondDenom
for i := range []int{0, 1, 2, 3, 4} {
// Initialize the account for the key
acc := input.AccountKeeper.NewAccount(
input.Context,
authtypes.NewBaseAccount(AccAddrs[i], AccPubKeys[i], uint64(i), 0),
)
// Set the balance for the account
require.NoError(t, fundAccount(input.Context, input.BankKeeper, acc.GetAddress(), InitCoins))
// Set the account in state
input.AccountKeeper.SetAccount(input.Context, acc)
// Create a validator for that account using some of the tokens in the account
// and the staking handler. Give the 5th validator a smaller stake so we can
// test unbonding hooks.
if i == 4 {
amt := sdk.TokensFromConsensusPower(1, sdk.DefaultPowerReduction)
sh.CreateValidator(ValAddrs[i], AccPubKeys[i], amt, true)
} else {
sh.CreateValidator(ValAddrs[i], AccPubKeys[i], StakingAmount, true)
}
}
// Run the staking endblocker to ensure valset is correct in state
staking.EndBlocker(input.Context, input.StakingKeeper)
// Register eth addresses for each validator
for i, addr := range ValAddrs {
input.GravityKeeper.setValidatorEthereumAddress(input.Context, addr, EthAddrs[i])
input.GravityKeeper.SetOrchestratorValidatorAddress(input.Context, addr, AccAddrs[i])
input.GravityKeeper.setEthereumOrchestratorAddress(input.Context, EthAddrs[i], AccAddrs[i])
}
// Return the test input
return input, input.Context
}
// CreateTestEnv creates the keeper testing environment for gravity
func CreateTestEnv(t *testing.T) TestInput {
t.Helper()
// Initialize store keys
gravityKey := sdk.NewKVStoreKey(types.StoreKey)
keyAcc := sdk.NewKVStoreKey(authtypes.StoreKey)
keyStaking := sdk.NewKVStoreKey(stakingtypes.StoreKey)
keyBank := sdk.NewKVStoreKey(banktypes.StoreKey)
keyDistro := sdk.NewKVStoreKey(distrtypes.StoreKey)
keyParams := sdk.NewKVStoreKey(paramstypes.StoreKey)
tkeyParams := sdk.NewTransientStoreKey(paramstypes.TStoreKey)
keyGov := sdk.NewKVStoreKey(govtypes.StoreKey)
keySlashing := sdk.NewKVStoreKey(slashingtypes.StoreKey)
// Initialize memory database and mount stores on it
db := dbm.NewMemDB()
ms := store.NewCommitMultiStore(db)
ms.MountStoreWithDB(gravityKey, storetypes.StoreTypeIAVL, db)
ms.MountStoreWithDB(keyAcc, storetypes.StoreTypeIAVL, db)
ms.MountStoreWithDB(keyParams, storetypes.StoreTypeIAVL, db)
ms.MountStoreWithDB(keyStaking, storetypes.StoreTypeIAVL, db)
ms.MountStoreWithDB(keyBank, storetypes.StoreTypeIAVL, db)
ms.MountStoreWithDB(keyDistro, storetypes.StoreTypeIAVL, db)
ms.MountStoreWithDB(tkeyParams, storetypes.StoreTypeTransient, db)
ms.MountStoreWithDB(keyGov, storetypes.StoreTypeIAVL, db)
ms.MountStoreWithDB(keySlashing, storetypes.StoreTypeIAVL, db)
err := ms.LoadLatestVersion()
require.Nil(t, err)
// Create sdk.Context
ctx := sdk.NewContext(ms, tmproto.Header{
Height: 1234567,
Time: time.Date(2020, time.April, 22, 12, 0, 0, 0, time.UTC),
}, false, log.TestingLogger())
cdc := MakeTestCodec()
marshaler := MakeTestMarshaler()
paramsKeeper := paramskeeper.NewKeeper(marshaler, cdc, keyParams, tkeyParams)
paramsKeeper.Subspace(authtypes.ModuleName)
paramsKeeper.Subspace(banktypes.ModuleName)
paramsKeeper.Subspace(stakingtypes.ModuleName)
paramsKeeper.Subspace(distrtypes.ModuleName)
paramsKeeper.Subspace(govtypes.ModuleName)
paramsKeeper.Subspace(types.DefaultParamspace)
paramsKeeper.Subspace(slashingtypes.ModuleName)
// this is also used to initialize module accounts for all the map keys
maccPerms := map[string][]string{
authtypes.FeeCollectorName: nil,
distrtypes.ModuleName: nil,
stakingtypes.BondedPoolName: {authtypes.Burner, authtypes.Staking},
stakingtypes.NotBondedPoolName: {authtypes.Burner, authtypes.Staking},
govtypes.ModuleName: {authtypes.Burner},
types.ModuleName: {authtypes.Minter, authtypes.Burner},
}
accountKeeper := authkeeper.NewAccountKeeper(
marshaler,
keyAcc, // target store
getSubspace(paramsKeeper, authtypes.ModuleName),
authtypes.ProtoBaseAccount, // prototype
maccPerms,
"gravity",
)
blockedAddr := make(map[string]bool, len(maccPerms))
for acc := range maccPerms {
blockedAddr[authtypes.NewModuleAddress(acc).String()] = true
}
bankKeeper := bankkeeper.NewBaseKeeper(
marshaler,
keyBank,
accountKeeper,
getSubspace(paramsKeeper, banktypes.ModuleName),
blockedAddr,
)
bankKeeper.SetParams(ctx, banktypes.Params{DefaultSendEnabled: true})
stakingKeeper := stakingkeeper.NewKeeper(marshaler, keyStaking, accountKeeper, bankKeeper, getSubspace(paramsKeeper, stakingtypes.ModuleName))
stakingKeeper.SetParams(ctx, TestingStakeParams)
distKeeper := distrkeeper.NewKeeper(marshaler, keyDistro, getSubspace(paramsKeeper, distrtypes.ModuleName), accountKeeper, bankKeeper, stakingKeeper, authtypes.FeeCollectorName)
distKeeper.SetParams(ctx, distrtypes.DefaultParams())
// set genesis items required for distribution
distKeeper.SetFeePool(ctx, distrtypes.InitialFeePool())
// total supply to track this
totalSupply := sdk.NewCoins(sdk.NewInt64Coin("stake", 100000000))
// set up initial accounts
for name, perms := range maccPerms {
mod := authtypes.NewEmptyModuleAccount(name, perms...)
if name == stakingtypes.NotBondedPoolName {
require.NoError(t, fundModAccount(ctx, bankKeeper, mod.GetName(), totalSupply))
} else if name == distrtypes.ModuleName {
// some big pot to pay out
amt := sdk.NewCoins(sdk.NewInt64Coin("stake", 500000))
require.NoError(t, fundModAccount(ctx, bankKeeper, mod.GetName(), amt))
}
accountKeeper.SetModuleAccount(ctx, mod)
}
// receiver/sender module account maps for the bridge
receiverModuleAccounts := map[string]string{
authtypes.NewModuleAddress(distrtypes.ModuleName).String(): distrtypes.ModuleName,
}
senderModuleAccounts := receiverModuleAccounts
stakeAddr := authtypes.NewModuleAddress(stakingtypes.BondedPoolName)
moduleAcct := accountKeeper.GetAccount(ctx, stakeAddr)
require.NotNil(t, moduleAcct)
// Load default wasm config
router := baseapp.NewMsgServiceRouter()
govRouter := govtypesv1beta1.NewRouter().
AddRoute(paramsproposal.RouterKey, params.NewParamChangeProposalHandler(paramsKeeper)).
AddRoute(govtypes.RouterKey, govtypesv1beta1.ProposalHandler)
govKeeper := govkeeper.NewKeeper(
marshaler, keyGov, getSubspace(paramsKeeper, govtypes.ModuleName).WithKeyTable(govtypesv1.ParamKeyTable()), accountKeeper, bankKeeper, stakingKeeper, govRouter, router, govtypes.DefaultConfig(),
)
govKeeper.SetProposalID(ctx, govtypesv1beta1.DefaultStartingProposalID)
govKeeper.SetDepositParams(ctx, govtypesv1.DefaultDepositParams())
govKeeper.SetVotingParams(ctx, govtypesv1.DefaultVotingParams())
govKeeper.SetTallyParams(ctx, govtypesv1.DefaultTallyParams())
slashingKeeper := slashingkeeper.NewKeeper(
marshaler,
keySlashing,
&stakingKeeper,
getSubspace(paramsKeeper, slashingtypes.ModuleName).WithKeyTable(slashingtypes.ParamKeyTable()),
)
k := NewKeeper(
marshaler,
gravityKey,
getSubspace(paramsKeeper, types.DefaultParamspace),
accountKeeper,
stakingKeeper,
bankKeeper,
slashingKeeper,
distKeeper,
sdk.DefaultPowerReduction,
receiverModuleAccounts,
senderModuleAccounts,
)
stakingKeeper = *stakingKeeper.SetHooks(
stakingtypes.NewMultiStakingHooks(
distKeeper.Hooks(),
slashingKeeper.Hooks(),
k.Hooks(),
),
)
k.SetParams(ctx, TestingGravityParams)
return TestInput{
GravityKeeper: k,
AccountKeeper: accountKeeper,
BankKeeper: bankKeeper,
StakingKeeper: stakingKeeper,
SlashingKeeper: slashingKeeper,
DistKeeper: distKeeper,
GovKeeper: govKeeper,
Context: ctx,
Marshaler: marshaler,
LegacyAmino: cdc,
GravityStoreKey: gravityKey,
}
}
// getSubspace returns a param subspace for a given module name.
func getSubspace(k paramskeeper.Keeper, moduleName string) paramstypes.Subspace {
subspace, _ := k.GetSubspace(moduleName)
return subspace
}
// MakeTestCodec creates a legacy amino codec for testing
func MakeTestCodec() *codec.LegacyAmino {
var cdc = codec.NewLegacyAmino()
auth.AppModuleBasic{}.RegisterLegacyAminoCodec(cdc)
bank.AppModuleBasic{}.RegisterLegacyAminoCodec(cdc)
staking.AppModuleBasic{}.RegisterLegacyAminoCodec(cdc)
distribution.AppModuleBasic{}.RegisterLegacyAminoCodec(cdc)
sdk.RegisterLegacyAminoCodec(cdc)
ccodec.RegisterCrypto(cdc)
params.AppModuleBasic{}.RegisterLegacyAminoCodec(cdc)
//types.RegisterCodec(cdc)
return cdc
}
// MakeTestMarshaler creates a proto codec for use in testing
func MakeTestMarshaler() codec.Codec {
interfaceRegistry := codectypes.NewInterfaceRegistry()
std.RegisterInterfaces(interfaceRegistry)
ModuleBasics.RegisterInterfaces(interfaceRegistry)
types.RegisterInterfaces(interfaceRegistry)
return codec.NewProtoCodec(interfaceRegistry)
}
// MintVouchersFromAir creates new gravity vouchers given erc20tokens
func MintVouchersFromAir(t *testing.T, ctx sdk.Context, k Keeper, dest sdk.AccAddress, amount types.ERC20Token) sdk.Coin {
coin := amount.GravityCoin()
vouchers := sdk.Coins{coin}
err := k.bankKeeper.MintCoins(ctx, types.ModuleName, vouchers)
require.NoError(t, err)
err = k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, dest, vouchers)
require.NoError(t, err)
return coin
}
// NewStakingKeeperMock creates a new mock staking keeper
func NewStakingKeeperMock(operators ...sdk.ValAddress) *StakingKeeperMock {
r := &StakingKeeperMock{
BondedValidators: make([]stakingtypes.Validator, 0),
ValidatorPower: make(map[string]int64),
}
const defaultTestPower = 100
for _, a := range operators {
r.BondedValidators = append(r.BondedValidators, stakingtypes.Validator{
ConsensusPubkey: codectypes.UnsafePackAny(ed25519.GenPrivKey().PubKey()),
OperatorAddress: a.String(),
Status: stakingtypes.Bonded,
})
r.ValidatorPower[a.String()] = defaultTestPower
}
return r
}
// MockStakingValidatorData creates mock validator data
type MockStakingValidatorData struct {
Operator sdk.ValAddress
Power int64
}
// NewStakingKeeperWeightedMock creates a new mock staking keeper with some mock validator data
func NewStakingKeeperWeightedMock(t ...MockStakingValidatorData) *StakingKeeperMock {
r := &StakingKeeperMock{
BondedValidators: make([]stakingtypes.Validator, len(t)),
ValidatorPower: make(map[string]int64, len(t)),
}
for i, a := range t {
pk, err := codectypes.NewAnyWithValue(ed25519.GenPrivKey().PubKey())
if err != nil {
panic(err)
}
r.BondedValidators[i] = stakingtypes.Validator{
ConsensusPubkey: pk,
OperatorAddress: a.Operator.String(),
Status: stakingtypes.Bonded,
}
r.ValidatorPower[a.Operator.String()] = a.Power
}
return r
}
// StakingKeeperMock is a mock staking keeper for use in the tests
type StakingKeeperMock struct {
BondedValidators []stakingtypes.Validator
ValidatorPower map[string]int64
}
// GetBondedValidatorsByPower implements the interface for staking keeper required by gravity
func (s *StakingKeeperMock) GetBondedValidatorsByPower(ctx sdk.Context) []stakingtypes.Validator {
return s.BondedValidators
}
// GetLastValidatorPower implements the interface for staking keeper required by gravity
func (s *StakingKeeperMock) GetLastValidatorPower(ctx sdk.Context, operator sdk.ValAddress) int64 {
v, ok := s.ValidatorPower[operator.String()]
if !ok {
panic("unknown address")
}
return v
}
// GetLastTotalPower implements the interface for staking keeper required by gravity
func (s *StakingKeeperMock) GetLastTotalPower(ctx sdk.Context) (power sdkmath.Int) {
var total int64
for _, v := range s.ValidatorPower {
total += v
}
return sdk.NewInt(total)
}
// IterateValidators staisfies the interface
func (s *StakingKeeperMock) IterateValidators(ctx sdk.Context, cb func(index int64, validator stakingtypes.ValidatorI) (stop bool)) {
for i, val := range s.BondedValidators {
stop := cb(int64(i), val)
if stop {
break
}
}
}
// IterateBondedValidatorsByPower staisfies the interface
func (s *StakingKeeperMock) IterateBondedValidatorsByPower(ctx sdk.Context, cb func(index int64, validator stakingtypes.ValidatorI) (stop bool)) {
for i, val := range s.BondedValidators {
stop := cb(int64(i), val)
if stop {
break
}
}
}
// IterateLastValidators staisfies the interface
func (s *StakingKeeperMock) IterateLastValidators(ctx sdk.Context, cb func(index int64, validator stakingtypes.ValidatorI) (stop bool)) {
for i, val := range s.BondedValidators {
stop := cb(int64(i), val)
if stop {
break
}
}
}
// Validator staisfies the interface
func (s *StakingKeeperMock) Validator(ctx sdk.Context, addr sdk.ValAddress) stakingtypes.ValidatorI {
for _, val := range s.BondedValidators {
if val.GetOperator().Equals(addr) {
return val
}
}
return nil
}
// ValidatorByConsAddr staisfies the interface
func (s *StakingKeeperMock) ValidatorByConsAddr(ctx sdk.Context, addr sdk.ConsAddress) stakingtypes.ValidatorI {
for _, val := range s.BondedValidators {
cons, err := val.GetConsAddr()
if err != nil {
panic(err)
}
if cons.Equals(addr) {
return val
}
}
return nil
}
func (s *StakingKeeperMock) GetParams(ctx sdk.Context) stakingtypes.Params {
return stakingtypes.DefaultParams()
}
func (s *StakingKeeperMock) GetValidator(ctx sdk.Context, addr sdk.ValAddress) (validator stakingtypes.Validator, found bool) {
panic("unexpected call")
}
func (s *StakingKeeperMock) ValidatorQueueIterator(ctx sdk.Context, endTime time.Time, endHeight int64) sdk.Iterator {
store := ctx.KVStore(sdk.NewKVStoreKey("staking"))
return store.Iterator(stakingtypes.ValidatorQueueKey, sdk.InclusiveEndBytes(stakingtypes.GetValidatorQueueKey(endTime, endHeight)))
}
// Slash staisfies the interface
func (s *StakingKeeperMock) Slash(sdk.Context, sdk.ConsAddress, int64, int64, sdk.Dec) sdkmath.Int {
return sdkmath.ZeroInt()
}
// Jail staisfies the interface
func (s *StakingKeeperMock) Jail(sdk.Context, sdk.ConsAddress) {}
// AlwaysPanicStakingMock is a mock staking keeper that panics on usage
type AlwaysPanicStakingMock struct{}
// GetLastTotalPower implements the interface for staking keeper required by gravity
func (s AlwaysPanicStakingMock) GetLastTotalPower(ctx sdk.Context) (power sdkmath.Int) {
panic("unexpected call")
}
// GetBondedValidatorsByPower implements the interface for staking keeper required by gravity
func (s AlwaysPanicStakingMock) GetBondedValidatorsByPower(ctx sdk.Context) []stakingtypes.Validator {
panic("unexpected call")
}
// GetLastValidatorPower implements the interface for staking keeper required by gravity
func (s AlwaysPanicStakingMock) GetLastValidatorPower(ctx sdk.Context, operator sdk.ValAddress) int64 {
panic("unexpected call")
}
// IterateValidators staisfies the interface
func (s AlwaysPanicStakingMock) IterateValidators(sdk.Context, func(index int64, validator stakingtypes.ValidatorI) (stop bool)) {
panic("unexpected call")
}
// IterateBondedValidatorsByPower staisfies the interface
func (s AlwaysPanicStakingMock) IterateBondedValidatorsByPower(sdk.Context, func(index int64, validator stakingtypes.ValidatorI) (stop bool)) {
panic("unexpected call")
}
// IterateLastValidators staisfies the interface
func (s AlwaysPanicStakingMock) IterateLastValidators(sdk.Context, func(index int64, validator stakingtypes.ValidatorI) (stop bool)) {
panic("unexpected call")
}
// Validator staisfies the interface
func (s AlwaysPanicStakingMock) Validator(sdk.Context, sdk.ValAddress) stakingtypes.ValidatorI {
panic("unexpected call")
}
// ValidatorByConsAddr staisfies the interface
func (s AlwaysPanicStakingMock) ValidatorByConsAddr(sdk.Context, sdk.ConsAddress) stakingtypes.ValidatorI {
panic("unexpected call")
}
// Slash staisfies the interface
func (s AlwaysPanicStakingMock) Slash(sdk.Context, sdk.ConsAddress, int64, int64, sdk.Dec) {
panic("unexpected call")
}
// Jail staisfies the interface
func (s AlwaysPanicStakingMock) Jail(sdk.Context, sdk.ConsAddress) {
panic("unexpected call")
}
func fundAccount(ctx sdk.Context, bankKeeper types.BankKeeper, addr sdk.AccAddress, amounts sdk.Coins) error {
if err := bankKeeper.MintCoins(ctx, types.ModuleName, amounts); err != nil {
return err
}
return bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, addr, amounts)
}
func fundModAccount(ctx sdk.Context, bankKeeper types.BankKeeper, recipientMod string, amounts sdk.Coins) error {
if err := bankKeeper.MintCoins(ctx, types.ModuleName, amounts); err != nil {
return err
}
return bankKeeper.SendCoinsFromModuleToModule(ctx, types.ModuleName, recipientMod, amounts)
}