github.com/Finschia/finschia-sdk@v0.49.1/x/staking/keeper/test_common.go (about) 1 package keeper // noalias 2 3 import ( 4 "bytes" 5 "math/rand" 6 7 sdk "github.com/Finschia/finschia-sdk/types" 8 "github.com/Finschia/finschia-sdk/x/staking/types" 9 ) 10 11 // does a certain by-power index record exist 12 func ValidatorByPowerIndexExists(ctx sdk.Context, keeper Keeper, power []byte) bool { 13 store := ctx.KVStore(keeper.storeKey) 14 return store.Has(power) 15 } 16 17 // update validator for testing 18 func TestingUpdateValidator(keeper Keeper, ctx sdk.Context, validator types.Validator, apply bool) types.Validator { 19 keeper.SetValidator(ctx, validator) 20 21 // Remove any existing power key for validator. 22 store := ctx.KVStore(keeper.storeKey) 23 deleted := false 24 25 iterator := sdk.KVStorePrefixIterator(store, types.ValidatorsByPowerIndexKey) 26 defer iterator.Close() 27 28 for ; iterator.Valid(); iterator.Next() { 29 valAddr := types.ParseValidatorPowerRankKey(iterator.Key()) 30 if bytes.Equal(valAddr, validator.GetOperator()) { 31 if deleted { 32 panic("found duplicate power index key") 33 } else { 34 deleted = true 35 } 36 37 store.Delete(iterator.Key()) 38 } 39 } 40 41 keeper.SetValidatorByPowerIndex(ctx, validator) 42 43 if !apply { 44 ctx, _ = ctx.CacheContext() 45 } 46 _, err := keeper.ApplyAndReturnValidatorSetUpdates(ctx) 47 if err != nil { 48 panic(err) 49 } 50 51 validator, found := keeper.GetValidator(ctx, validator.GetOperator()) 52 if !found { 53 panic("validator expected but not found") 54 } 55 56 return validator 57 } 58 59 // RandomValidator returns a random validator given access to the keeper and ctx 60 func RandomValidator(r *rand.Rand, keeper Keeper, ctx sdk.Context) (val types.Validator, ok bool) { 61 vals := keeper.GetAllValidators(ctx) 62 if len(vals) == 0 { 63 return types.Validator{}, false 64 } 65 66 i := r.Intn(len(vals)) 67 68 return vals[i], true 69 }