Use any as validator pubkey (#7597)

* protobuf pubkey type update

* wip2

* wip3

* solving types.NewValidator issues

* remove bech32 from validator type assignment

* update Validator interface

* Changelog update

* wip4

* update genutil

* fix simapp & x/ibc/testing tests

* update staking

* changelog update

* fix import cycle in tests

* fix amino panic on TestValidatorMarshalUnmarshalJSON

* fix TestValidatorMarshalUnmarshalJSON consensus_pubkey check

* Add UnpackInterfaces to HistoricalInfo

* fix TestHistoricalInfo

* update todos

* fix: Expecting ed25519.PubKey to implement proto.Message

* fix linter issues

* Fix migrate test

* Update CHANGELOG.md

Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com>

* review comments

* cosmetic changes

* add UnpackInterfaces got GenesisRandomized test

* Validator.Equal reuses Validator.MinEqual

* fix test

* use Validator.Equal in tests

* Fix staking simulation TestRandomizedGenState

* Remove TODO

* use HistoricalInfo.Equal

* use proto.Equal

* rename Validator.GetConsPubKey to TmConsPubKey

* prefer require.Equal over reflect.DeepEqual

* SetHistoricalInfo using a pointer

* Fix TestQueryDelegation test

* Fix TestQueryValidators test

* Fix TestSimulateMsgUnjail test

* experiement with LegacyAmino instances

* Register codecs in all simapp tests

* Fix cli_test compilation problems

* fix typo sdk -> std

* fix typo

* fix TestPlanStringer

* Rename to MakeEncodingConfig

* Remove RegisterCodecsTests

* Use gRPC in GetCmdQueryValidators

* Empty status

* fix info log check

* linter fixes

* rename simapparams to simappparams

* Update simapp/test_helpers.go

Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com>

* comments updates

* use valAddr1 instead of sdk.ValAddress(pk1.Address().Bytes())

Co-authored-by: Cory Levinson <cjlevinson@gmail.com>
Co-authored-by: Amaury Martiny <amaury.martiny@protonmail.com>
Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com>
This commit is contained in:
Robert Zaremba 2020-10-23 14:07:52 +02:00 committed by GitHub
parent 5bebf2bd39
commit 6bc8ff2dfe
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
77 changed files with 1547 additions and 1304 deletions

View File

@ -44,6 +44,11 @@ Ref: https://keepachangelog.com/en/1.0.0/
### API Breaking
* (AppModule) [\#7518](https://github.com/cosmos/cosmos-sdk/pull/7518) [\#7584](https://github.com/cosmos/cosmos-sdk/pull/7584) Rename `AppModule.RegisterQueryServices` to `AppModule.RegisterServices`, as this method now registers multiple services (the gRPC query service and the protobuf Msg service). A `Configurator` struct is used to hold the different services.
* (x/staking/types) [\#7447](https://github.com/cosmos/cosmos-sdk/issues/7447) Remove bech32 PubKey support:
* `ValidatorI` interface update. `GetConsPubKey` renamed to `TmConsPubKey` (consensus public key must be a tendermint key). `TmConsPubKey`, `GetConsAddr` methods return error.
* `Validator` update. Methods changed in `ValidatorI` (as described above) and `ToTmValidator` return error.
* `Validator.ConsensusPubkey` type changed from `string` to `codectypes.Any`.
* `MsgCreateValidator.Pubkey` type changed from `string` to `codectypes.Any`.
### Features
@ -165,7 +170,7 @@ of the Cosmos SDK since launch. Please read through this changelog and [release
* `NewAnteHandler` and `NewSigVerificationDecorator` both now take a `SignModeHandler` parameter.
* `SignatureVerificationGasConsumer` now has the signature: `func(meter sdk.GasMeter, sig signing.SignatureV2, params types.Params) error`.
* The `SigVerifiableTx` interface now has a `GetSignaturesV2() ([]signing.SignatureV2, error)` method and no longer has the `GetSignBytes` method.
### State Machine Breaking
* __General__
@ -358,7 +363,7 @@ falling below their minimum self-delegation and never having been bonded. The va
* (x/auth) [\#6861](https://github.com/cosmos/cosmos-sdk/pull/6861) Remove public key Bech32 encoding for all account types for JSON serialization, instead relying on direct Amino encoding. In addition, JSON serialization utilizes Amino instead of the Go stdlib, so integers are treated as strings.
### Improvements
### Improvements
* (client) [\#6853](https://github.com/cosmos/cosmos-sdk/pull/6853) Add --unsafe-cors flag.

View File

@ -52,19 +52,6 @@ func (ctx Context) QueryABCI(req abci.RequestQuery) (abci.ResponseQuery, error)
return ctx.queryABCI(req)
}
// QuerySubspace performs a query to a Tendermint node with the provided
// store name and subspace. It returns key value pair and height of the query
// upon success or an error if the query fails.
func (ctx Context) QuerySubspace(subspace []byte, storeName string) (res []sdk.KVPair, height int64, err error) {
resRaw, height, err := ctx.queryStore(subspace, storeName, "subspace")
if err != nil {
return res, height, err
}
ctx.LegacyAmino.MustUnmarshalBinaryBare(resRaw, &res)
return
}
// GetFromAddress returns the from address from the context's name.
func (ctx Context) GetFromAddress() sdk.AccAddress {
return ctx.FromAddress

View File

@ -139,6 +139,7 @@ func (cdc *LegacyAmino) MustUnmarshalBinaryLengthPrefixed(bz []byte, ptr interfa
}
}
// MarshalJSON implements codec.Marshaler interface
func (cdc *LegacyAmino) MarshalJSON(o interface{}) ([]byte, error) {
err := cdc.jsonMarshalAnys(o)
if err != nil {
@ -155,6 +156,7 @@ func (cdc *LegacyAmino) MustMarshalJSON(o interface{}) []byte {
return bz
}
// UnmarshalJSON implements codec.Marshaler interface
func (cdc *LegacyAmino) UnmarshalJSON(bz []byte, ptr interface{}) error {
err := cdc.Amino.UnmarshalJSON(bz, ptr)
if err != nil {

View File

@ -15,12 +15,12 @@ func RegisterInterfaces(registry codectypes.InterfaceRegistry) {
// TODO We now register both Tendermint's PubKey and our own PubKey. In the
// long-term, we should move away from Tendermint's PubKey, and delete
// these lines.
registry.RegisterInterface("tendermint.crypto.Pubkey", (*tmcrypto.PubKey)(nil))
registry.RegisterInterface("tendermint.crypto.PubKey", (*tmcrypto.PubKey)(nil))
registry.RegisterImplementations((*tmcrypto.PubKey)(nil), &ed25519.PubKey{})
registry.RegisterImplementations((*tmcrypto.PubKey)(nil), &secp256k1.PubKey{})
registry.RegisterImplementations((*tmcrypto.PubKey)(nil), &multisig.LegacyAminoPubKey{})
registry.RegisterInterface("cosmos.crypto.Pubkey", (*cryptotypes.PubKey)(nil))
registry.RegisterInterface("cosmos.crypto.PubKey", (*cryptotypes.PubKey)(nil))
registry.RegisterImplementations((*cryptotypes.PubKey)(nil), &ed25519.PubKey{})
registry.RegisterImplementations((*cryptotypes.PubKey)(nil), &secp256k1.PubKey{})
registry.RegisterImplementations((*cryptotypes.PubKey)(nil), &multisig.LegacyAminoPubKey{})

View File

@ -2,10 +2,13 @@ syntax = "proto3";
package cosmos.staking.v1beta1;
import "gogoproto/gogo.proto";
import "tendermint/types/types.proto";
import "google/protobuf/timestamp.proto";
import "google/protobuf/any.proto";
import "google/protobuf/duration.proto";
import "google/protobuf/timestamp.proto";
import "cosmos_proto/cosmos.proto";
import "cosmos/base/v1beta1/coin.proto";
import "tendermint/types/types.proto";
option go_package = "github.com/cosmos/cosmos-sdk/x/staking/types";
@ -73,10 +76,12 @@ message Validator {
option (gogoproto.goproto_getters) = false;
string operator_address = 1 [(gogoproto.moretags) = "yaml:\"operator_address\""];
string consensus_pubkey = 2 [(gogoproto.moretags) = "yaml:\"consensus_pubkey\""];
bool jailed = 3;
BondStatus status = 4;
string tokens = 5 [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", (gogoproto.nullable) = false];
google.protobuf.Any consensus_pubkey = 2 [
(cosmos_proto.accepts_interface) = "cosmos.crypto.PubKey",
(gogoproto.moretags) = "yaml:\"consensus_pubkey\""];
bool jailed = 3;
BondStatus status = 4;
string tokens = 5 [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", (gogoproto.nullable) = false];
string delegator_shares = 6 [
(gogoproto.moretags) = "yaml:\"delegator_shares\"",
(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec",

View File

@ -1,11 +1,13 @@
syntax = "proto3";
package cosmos.staking.v1beta1;
import "gogoproto/gogo.proto";
import "cosmos/base/v1beta1/coin.proto";
import "google/protobuf/timestamp.proto";
import "cosmos/staking/v1beta1/staking.proto";
import "google/protobuf/any.proto";
import "google/protobuf/timestamp.proto";
import "gogoproto/gogo.proto";
import "cosmos_proto/cosmos.proto";
import "cosmos/base/v1beta1/coin.proto";
import "cosmos/staking/v1beta1/staking.proto";
option go_package = "github.com/cosmos/cosmos-sdk/x/staking/types";
@ -44,7 +46,7 @@ message MsgCreateValidator {
];
string delegator_address = 4 [(gogoproto.moretags) = "yaml:\"delegator_address\""];
string validator_address = 5 [(gogoproto.moretags) = "yaml:\"validator_address\""];
google.protobuf.Any pubkey = 6;
google.protobuf.Any pubkey = 6 [(cosmos_proto.accepts_interface) = "cosmos.crypto.PubKey"];
cosmos.base.v1beta1.Coin value = 7 [(gogoproto.nullable) = false];
}
@ -104,7 +106,7 @@ message MsgBeginRedelegate {
}
// MsgBeginRedelegateResponse defines the Msg/BeginRedelegate response type.
message MsgBeginRedelegateResponse {
message MsgBeginRedelegateResponse {
google.protobuf.Timestamp completion_time = 1 [(gogoproto.nullable) = false, (gogoproto.stdtime) = true];
}
@ -120,6 +122,6 @@ message MsgUndelegate {
}
// MsgUndelegateResponse defines the Msg/Undelegate response type.
message MsgUndelegateResponse {
message MsgUndelegateResponse {
google.protobuf.Timestamp completion_time = 1 [(gogoproto.nullable) = false, (gogoproto.stdtime) = true];
}

View File

@ -1,13 +1,13 @@
package simapp
import (
"github.com/cosmos/cosmos-sdk/simapp/params"
simappparams "github.com/cosmos/cosmos-sdk/simapp/params"
"github.com/cosmos/cosmos-sdk/std"
)
// MakeEncodingConfig creates an EncodingConfig for testing
func MakeEncodingConfig() params.EncodingConfig {
encodingConfig := params.MakeEncodingConfig()
func MakeEncodingConfig() simappparams.EncodingConfig {
encodingConfig := simappparams.MakeEncodingConfig()
std.RegisterLegacyAminoCodec(encodingConfig.Amino)
std.RegisterInterfaces(encodingConfig.InterfaceRegistry)
ModuleBasics.RegisterLegacyAminoCodec(encodingConfig.Amino)

View File

@ -35,13 +35,13 @@ func (app *SimApp) ExportAppStateAndValidators(
return servertypes.ExportedApp{}, err
}
validators := staking.WriteValidators(ctx, app.StakingKeeper)
validators, err := staking.WriteValidators(ctx, app.StakingKeeper)
return servertypes.ExportedApp{
AppState: appState,
Validators: validators,
Height: height,
ConsensusParams: app.BaseApp.GetConsensusParams(ctx),
}, nil
}, err
}
// prepare for fresh start at zero height
@ -174,7 +174,10 @@ func (app *SimApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []
iter.Close()
_ = app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
_, err := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
if err != nil {
log.Fatal(err)
}
/* Handle slashing state. */

View File

@ -8,17 +8,16 @@ import (
"github.com/cosmos/cosmos-sdk/x/auth/tx"
)
// MakeEncodingConfig creates an EncodingConfig for an amino based test configuration.
// MakeEncodingConfig creates an EncodingConfig for a non-amino based test configuration.
func MakeEncodingConfig() EncodingConfig {
amino := codec.NewLegacyAmino()
cdc := codec.NewLegacyAmino()
interfaceRegistry := types.NewInterfaceRegistry()
marshaler := codec.NewProtoCodec(interfaceRegistry)
txCfg := tx.NewTxConfig(marshaler, tx.DefaultSignModes)
return EncodingConfig{
InterfaceRegistry: interfaceRegistry,
Marshaler: marshaler,
TxConfig: txCfg,
Amino: amino,
TxConfig: tx.NewTxConfig(marshaler, tx.DefaultSignModes),
Amino: cdc,
}
}

View File

@ -39,6 +39,7 @@ func BenchmarkFullAppSimulation(b *testing.B) {
SimulationOperations(app, app.AppCodec(), config),
app.ModuleAccountAddrs(),
config,
app.AppCodec(),
)
// export state and simParams before the simulation error is checked
@ -83,6 +84,7 @@ func BenchmarkInvariants(b *testing.B) {
SimulationOperations(app, app.AppCodec(), config),
app.ModuleAccountAddrs(),
config,
app.AppCodec(),
)
// export state and simParams before the simulation error is checked

View File

@ -81,6 +81,7 @@ func TestFullAppSimulation(t *testing.T) {
SimulationOperations(app, app.AppCodec(), config),
app.ModuleAccountAddrs(),
config,
app.AppCodec(),
)
// export state and simParams before the simulation error is checked
@ -118,6 +119,7 @@ func TestAppImportExport(t *testing.T) {
SimulationOperations(app, app.AppCodec(), config),
app.ModuleAccountAddrs(),
config,
app.AppCodec(),
)
// export state and simParams before the simulation error is checked
@ -214,6 +216,7 @@ func TestAppSimulationAfterImport(t *testing.T) {
SimulationOperations(app, app.AppCodec(), config),
app.ModuleAccountAddrs(),
config,
app.AppCodec(),
)
// export state and simParams before the simulation error is checked
@ -261,6 +264,7 @@ func TestAppSimulationAfterImport(t *testing.T) {
SimulationOperations(newApp, newApp.AppCodec(), config),
app.ModuleAccountAddrs(),
config,
app.AppCodec(),
)
require.NoError(t, err)
}
@ -311,6 +315,7 @@ func TestAppStateDeterminism(t *testing.T) {
SimulationOperations(app, app.AppCodec(), config),
app.ModuleAccountAddrs(),
config,
app.AppCodec(),
)
require.NoError(t, err)

View File

@ -13,7 +13,7 @@ import (
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
simapparams "github.com/cosmos/cosmos-sdk/simapp/params"
simappparams "github.com/cosmos/cosmos-sdk/simapp/params"
"github.com/cosmos/cosmos-sdk/types/module"
simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
@ -85,11 +85,11 @@ func AppStateRandomizedFn(
// number of bonded accounts
var initialStake, numInitiallyBonded int64
appParams.GetOrGenerate(
cdc, simapparams.StakePerAccount, &initialStake, r,
cdc, simappparams.StakePerAccount, &initialStake, r,
func(r *rand.Rand) { initialStake = r.Int63n(1e12) },
)
appParams.GetOrGenerate(
cdc, simapparams.InitiallyBondedValidators, &numInitiallyBonded, r,
cdc, simappparams.InitiallyBondedValidators, &numInitiallyBonded, r,
func(r *rand.Rand) { numInitiallyBonded = int64(r.Intn(300)) },
)

View File

@ -19,6 +19,7 @@ import (
bam "github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/client"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/crypto/keys/ed25519"
"github.com/cosmos/cosmos-sdk/simapp/helpers"
sdk "github.com/cosmos/cosmos-sdk/types"
@ -92,9 +93,16 @@ func SetupWithGenesisValSet(t *testing.T, valSet *tmtypes.ValidatorSet, genAccs
bondAmt := sdk.NewInt(1000000)
for _, val := range valSet.Validators {
// Currently validator requires tmcrypto.ed25519 keys, which don't support
// our Marshaling interfaces, so we need to pack them into our version of ed25519.
// There is ongoing work to add secp256k1 keys (https://github.com/cosmos/cosmos-sdk/pull/7604).
pk, err := ed25519.FromTmEd25519(val.PubKey)
require.NoError(t, err)
pkAny, err := codectypes.PackAny(pk)
require.NoError(t, err)
validator := stakingtypes.Validator{
OperatorAddress: sdk.ValAddress(val.Address).String(),
ConsensusPubkey: sdk.MustBech32ifyPubKey(sdk.Bech32PubKeyTypeConsPub, val.PubKey),
ConsensusPubkey: pkAny,
Jailed: false,
Status: stakingtypes.Bonded,
Tokens: bondAmt,

View File

@ -92,11 +92,11 @@ type AppModule struct {
AppModuleBasic
accountKeeper keeper.AccountKeeper
randGenAccountsFn simulation.RandomGenesisAccountsFn
randGenAccountsFn types.RandomGenesisAccountsFn
}
// NewAppModule creates a new AppModule object
func NewAppModule(cdc codec.Marshaler, accountKeeper keeper.AccountKeeper, randGenAccountsFn simulation.RandomGenesisAccountsFn) AppModule {
func NewAppModule(cdc codec.Marshaler, accountKeeper keeper.AccountKeeper, randGenAccountsFn types.RandomGenesisAccountsFn) AppModule {
return AppModule{
AppModuleBasic: AppModuleBasic{},
accountKeeper: accountKeeper,

View File

@ -21,10 +21,6 @@ const (
SigVerifyCostSECP256K1 = "sig_verify_cost_secp256k1"
)
// RandomGenesisAccountsFn defines the function required to generate custom account types
// on the auth module simulation.
type RandomGenesisAccountsFn func(simState *module.SimulationState) types.GenesisAccounts
// RandomGenesisAccounts defines the default RandomGenesisAccountsFn used on the SDK.
// It creates a slice of BaseAccount, ContinuousVestingAccount and DelayedVestingAccount.
func RandomGenesisAccounts(simState *module.SimulationState) types.GenesisAccounts {
@ -92,7 +88,7 @@ func GenSigVerifyCostSECP256K1(r *rand.Rand) uint64 {
}
// RandomizedGenState generates a random GenesisState for auth
func RandomizedGenState(simState *module.SimulationState, randGenAccountsFn RandomGenesisAccountsFn) {
func RandomizedGenState(simState *module.SimulationState, randGenAccountsFn types.RandomGenesisAccountsFn) {
var maxMemoChars uint64
simState.AppParams.GetOrGenerate(
simState.Cdc, MaxMemoChars, &maxMemoChars, simState.Rand,

View File

@ -6,10 +6,9 @@ import (
"fmt"
"math/rand"
"github.com/cosmos/cosmos-sdk/x/simulation"
simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
"github.com/cosmos/cosmos-sdk/x/auth/types"
"github.com/cosmos/cosmos-sdk/x/simulation"
)
const (

View File

@ -9,10 +9,14 @@ import (
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/types/module"
)
var _ types.UnpackInterfacesMessage = GenesisState{}
// RandomGenesisAccountsFn defines the function required to generate custom account types
type RandomGenesisAccountsFn func(simState *module.SimulationState) GenesisAccounts
// NewGenesisState - Create a new genesis state
func NewGenesisState(params Params, accounts GenesisAccounts) *GenesisState {
genAccounts, err := PackAccounts(accounts)

View File

@ -243,13 +243,15 @@ func (suite *SimTestSuite) getTestingValidator0(accounts []simtypes.Account) sta
}
func (suite *SimTestSuite) getTestingValidator(accounts []simtypes.Account, commission stakingtypes.Commission, n int) stakingtypes.Validator {
require := suite.Require()
account := accounts[n]
valPubKey := account.PubKey
valAddr := sdk.ValAddress(account.PubKey.Address().Bytes())
validator := stakingtypes.NewValidator(valAddr, valPubKey, stakingtypes.Description{})
validator, err := validator.SetInitialCommission(commission)
suite.Require().NoError(err)
validator, err := stakingtypes.NewValidator(valAddr, valPubKey, stakingtypes.
Description{})
require.NoError(err)
validator, err = validator.SetInitialCommission(commission)
require.NoError(err)
validator.DelegatorShares = sdk.NewDec(100)
validator.Tokens = sdk.NewInt(1000000)

View File

@ -185,7 +185,7 @@ const _ = grpc.SupportPackageIsVersion4
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type MsgClient interface {
// Send submits an arbitrary Evidence of misbehavior such as equivocation or
// SubmitEvidence submits an arbitrary Evidence of misbehavior such as equivocation or
// counterfactual signing.
SubmitEvidence(ctx context.Context, in *MsgSubmitEvidence, opts ...grpc.CallOption) (*MsgSubmitEvidenceResponse, error)
}
@ -209,7 +209,7 @@ func (c *msgClient) SubmitEvidence(ctx context.Context, in *MsgSubmitEvidence, o
// MsgServer is the server API for Msg service.
type MsgServer interface {
// Send submits an arbitrary Evidence of misbehavior such as equivocation or
// SubmitEvidence submits an arbitrary Evidence of misbehavior such as equivocation or
// counterfactual signing.
SubmitEvidence(context.Context, *MsgSubmitEvidence) (*MsgSubmitEvidenceResponse, error)
}

View File

@ -13,12 +13,9 @@ func InitGenesis(
ctx sdk.Context, stakingKeeper types.StakingKeeper,
deliverTx deliverTxfn, genesisState types.GenesisState,
txEncodingConfig client.TxEncodingConfig,
) []abci.ValidatorUpdate {
var validators []abci.ValidatorUpdate
) (validators []abci.ValidatorUpdate, err error) {
if len(genesisState.GenTxs) > 0 {
validators = DeliverGenTxs(ctx, genesisState.GenTxs, stakingKeeper, deliverTx, txEncodingConfig)
validators, err = DeliverGenTxs(ctx, genesisState.GenTxs, stakingKeeper, deliverTx, txEncodingConfig)
}
return validators
return
}

View File

@ -95,7 +95,7 @@ func DeliverGenTxs(
ctx sdk.Context, genTxs []json.RawMessage,
stakingKeeper types.StakingKeeper, deliverTx deliverTxfn,
txEncodingConfig client.TxEncodingConfig,
) []abci.ValidatorUpdate {
) ([]abci.ValidatorUpdate, error) {
for _, genTx := range genTxs {
tx, err := txEncodingConfig.TxJSONDecoder()(genTx)

View File

@ -98,7 +98,11 @@ func NewAppModule(accountKeeper types.AccountKeeper,
func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, data json.RawMessage) []abci.ValidatorUpdate {
var genesisState types.GenesisState
cdc.MustUnmarshalJSON(data, &genesisState)
return InitGenesis(ctx, am.stakingKeeper, am.deliverTx, genesisState, am.txEncodingConfig)
validators, err := InitGenesis(ctx, am.stakingKeeper, am.deliverTx, genesisState, am.txEncodingConfig)
if err != nil {
panic(err)
}
return validators
}
// ExportGenesis returns the exported genesis state as raw bytes for the genutil

View File

@ -13,7 +13,7 @@ import (
// StakingKeeper defines the expected staking keeper (noalias)
type StakingKeeper interface {
ApplyAndReturnValidatorSetUpdates(sdk.Context) (updates []abci.ValidatorUpdate)
ApplyAndReturnValidatorSetUpdates(sdk.Context) (updates []abci.ValidatorUpdate, err error)
}
// AccountKeeper defines the expected account keeper (noalias)

View File

@ -4,9 +4,6 @@ import (
"context"
"testing"
"github.com/cosmos/cosmos-sdk/simapp"
"github.com/cosmos/cosmos-sdk/x/gov/client/utils"
"github.com/stretchr/testify/require"
"github.com/tendermint/tendermint/rpc/client/mock"
ctypes "github.com/tendermint/tendermint/rpc/core/types"
@ -14,8 +11,10 @@ import (
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/simapp"
sdk "github.com/cosmos/cosmos-sdk/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"github.com/cosmos/cosmos-sdk/x/gov/client/utils"
"github.com/cosmos/cosmos-sdk/x/gov/types"
)

View File

@ -1,19 +1,22 @@
package keeper_test
import (
"testing"
"github.com/cosmos/cosmos-sdk/simapp"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/gov/types"
"github.com/cosmos/cosmos-sdk/x/staking"
stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
"github.com/stretchr/testify/require"
)
var (
TestProposal = types.NewTextProposal("Test", "description")
)
func createValidators(ctx sdk.Context, app *simapp.SimApp, powers []int64) ([]sdk.AccAddress, []sdk.ValAddress) {
func createValidators(t *testing.T, ctx sdk.Context, app *simapp.SimApp, powers []int64) ([]sdk.AccAddress, []sdk.ValAddress) {
addrs := simapp.AddTestAddrsIncremental(app, ctx, 5, sdk.NewInt(30000000))
valAddrs := simapp.ConvertAddrsToValAddrs(addrs)
pks := simapp.CreateTestPubKeys(5)
@ -27,9 +30,12 @@ func createValidators(ctx sdk.Context, app *simapp.SimApp, powers []int64) ([]sd
app.GetSubspace(stakingtypes.ModuleName),
)
val1 := stakingtypes.NewValidator(valAddrs[0], pks[0], stakingtypes.Description{})
val2 := stakingtypes.NewValidator(valAddrs[1], pks[1], stakingtypes.Description{})
val3 := stakingtypes.NewValidator(valAddrs[2], pks[2], stakingtypes.Description{})
val1, err := stakingtypes.NewValidator(valAddrs[0], pks[0], stakingtypes.Description{})
require.NoError(t, err)
val2, err := stakingtypes.NewValidator(valAddrs[1], pks[1], stakingtypes.Description{})
require.NoError(t, err)
val3, err := stakingtypes.NewValidator(valAddrs[2], pks[2], stakingtypes.Description{})
require.NoError(t, err)
app.StakingKeeper.SetValidator(ctx, val1)
app.StakingKeeper.SetValidator(ctx, val2)

View File

@ -713,7 +713,7 @@ func (suite *KeeperTestSuite) TestGRPCQueryDeposits() {
func (suite *KeeperTestSuite) TestGRPCQueryTally() {
app, ctx, queryClient := suite.app, suite.ctx, suite.queryClient
addrs, _ := createValidators(ctx, app, []int64{5, 5, 5})
addrs, _ := createValidators(suite.T(), ctx, app, []int64{5, 5, 5})
var (
req *types.QueryTallyResultRequest

View File

@ -17,7 +17,7 @@ func TestTallyNoOneVotes(t *testing.T) {
app := simapp.Setup(false)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
createValidators(ctx, app, []int64{5, 5, 5})
createValidators(t, ctx, app, []int64{5, 5, 5})
tp := TestProposal
proposal, err := app.GovKeeper.SubmitProposal(ctx, tp)
@ -39,7 +39,7 @@ func TestTallyNoQuorum(t *testing.T) {
app := simapp.Setup(false)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
createValidators(ctx, app, []int64{2, 5, 0})
createValidators(t, ctx, app, []int64{2, 5, 0})
addrs := simapp.AddTestAddrsIncremental(app, ctx, 1, sdk.NewInt(10000000))
@ -64,7 +64,7 @@ func TestTallyOnlyValidatorsAllYes(t *testing.T) {
app := simapp.Setup(false)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
addrs, _ := createValidators(ctx, app, []int64{5, 5, 5})
addrs, _ := createValidators(t, ctx, app, []int64{5, 5, 5})
tp := TestProposal
proposal, err := app.GovKeeper.SubmitProposal(ctx, tp)
@ -90,7 +90,7 @@ func TestTallyOnlyValidators51No(t *testing.T) {
app := simapp.Setup(false)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
valAccAddrs, _ := createValidators(ctx, app, []int64{5, 6, 0})
valAccAddrs, _ := createValidators(t, ctx, app, []int64{5, 6, 0})
tp := TestProposal
proposal, err := app.GovKeeper.SubmitProposal(ctx, tp)
@ -114,7 +114,7 @@ func TestTallyOnlyValidators51Yes(t *testing.T) {
app := simapp.Setup(false)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
valAccAddrs, _ := createValidators(ctx, app, []int64{5, 6, 0})
valAccAddrs, _ := createValidators(t, ctx, app, []int64{5, 6, 0})
tp := TestProposal
proposal, err := app.GovKeeper.SubmitProposal(ctx, tp)
@ -139,7 +139,7 @@ func TestTallyOnlyValidatorsVetoed(t *testing.T) {
app := simapp.Setup(false)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
valAccAddrs, _ := createValidators(ctx, app, []int64{6, 6, 7})
valAccAddrs, _ := createValidators(t, ctx, app, []int64{6, 6, 7})
tp := TestProposal
proposal, err := app.GovKeeper.SubmitProposal(ctx, tp)
@ -165,7 +165,7 @@ func TestTallyOnlyValidatorsAbstainPasses(t *testing.T) {
app := simapp.Setup(false)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
valAccAddrs, _ := createValidators(ctx, app, []int64{6, 6, 7})
valAccAddrs, _ := createValidators(t, ctx, app, []int64{6, 6, 7})
tp := TestProposal
proposal, err := app.GovKeeper.SubmitProposal(ctx, tp)
@ -191,7 +191,7 @@ func TestTallyOnlyValidatorsAbstainFails(t *testing.T) {
app := simapp.Setup(false)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
valAccAddrs, _ := createValidators(ctx, app, []int64{6, 6, 7})
valAccAddrs, _ := createValidators(t, ctx, app, []int64{6, 6, 7})
tp := TestProposal
proposal, err := app.GovKeeper.SubmitProposal(ctx, tp)
@ -217,7 +217,7 @@ func TestTallyOnlyValidatorsNonVoter(t *testing.T) {
app := simapp.Setup(false)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
valAccAddrs, _ := createValidators(ctx, app, []int64{5, 6, 7})
valAccAddrs, _ := createValidators(t, ctx, app, []int64{5, 6, 7})
valAccAddr1, valAccAddr2 := valAccAddrs[0], valAccAddrs[1]
tp := TestProposal
@ -243,7 +243,7 @@ func TestTallyDelgatorOverride(t *testing.T) {
app := simapp.Setup(false)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
addrs, valAddrs := createValidators(ctx, app, []int64{5, 6, 7})
addrs, valAddrs := createValidators(t, ctx, app, []int64{5, 6, 7})
delTokens := sdk.TokensFromConsensusPower(30)
val1, found := app.StakingKeeper.GetValidator(ctx, valAddrs[0])
@ -279,7 +279,7 @@ func TestTallyDelgatorInherit(t *testing.T) {
app := simapp.Setup(false)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
addrs, vals := createValidators(ctx, app, []int64{5, 6, 7})
addrs, vals := createValidators(t, ctx, app, []int64{5, 6, 7})
delTokens := sdk.TokensFromConsensusPower(30)
val3, found := app.StakingKeeper.GetValidator(ctx, vals[2])
@ -314,7 +314,7 @@ func TestTallyDelgatorMultipleOverride(t *testing.T) {
app := simapp.Setup(false)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
addrs, vals := createValidators(ctx, app, []int64{5, 6, 7})
addrs, vals := createValidators(t, ctx, app, []int64{5, 6, 7})
delTokens := sdk.TokensFromConsensusPower(10)
val1, found := app.StakingKeeper.GetValidator(ctx, vals[0])
@ -354,9 +354,9 @@ func TestTallyDelgatorMultipleInherit(t *testing.T) {
app := simapp.Setup(false)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
createValidators(ctx, app, []int64{25, 6, 7})
createValidators(t, ctx, app, []int64{25, 6, 7})
addrs, vals := createValidators(ctx, app, []int64{5, 6, 7})
addrs, vals := createValidators(t, ctx, app, []int64{5, 6, 7})
delTokens := sdk.TokensFromConsensusPower(10)
val2, found := app.StakingKeeper.GetValidator(ctx, vals[1])
@ -395,7 +395,7 @@ func TestTallyJailedValidator(t *testing.T) {
app := simapp.Setup(false)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
addrs, valAddrs := createValidators(ctx, app, []int64{25, 6, 7})
addrs, valAddrs := createValidators(t, ctx, app, []int64{25, 6, 7})
delTokens := sdk.TokensFromConsensusPower(10)
val2, found := app.StakingKeeper.GetValidator(ctx, valAddrs[1])
@ -410,7 +410,9 @@ func TestTallyJailedValidator(t *testing.T) {
_ = staking.EndBlocker(ctx, app.StakingKeeper)
app.StakingKeeper.Jail(ctx, sdk.ConsAddress(val2.GetConsPubKey().Address()))
consKey, err := val2.TmConsPubKey()
require.NoError(t, err)
app.StakingKeeper.Jail(ctx, sdk.ConsAddress(consKey.Address()))
tp := TestProposal
proposal, err := app.GovKeeper.SubmitProposal(ctx, tp)
@ -436,7 +438,7 @@ func TestTallyValidatorMultipleDelegations(t *testing.T) {
app := simapp.Setup(false)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
addrs, valAddrs := createValidators(ctx, app, []int64{10, 10, 10})
addrs, valAddrs := createValidators(t, ctx, app, []int64{10, 10, 10})
delTokens := sdk.TokensFromConsensusPower(10)
val2, found := app.StakingKeeper.GetValidator(ctx, valAddrs[1])

View File

@ -7,10 +7,10 @@ import (
context "context"
fmt "fmt"
types "github.com/cosmos/cosmos-sdk/codec/types"
grpc1 "github.com/gogo/protobuf/grpc"
github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types"
types1 "github.com/cosmos/cosmos-sdk/types"
_ "github.com/gogo/protobuf/gogoproto"
grpc1 "github.com/gogo/protobuf/grpc"
proto "github.com/gogo/protobuf/proto"
_ "github.com/regen-network/cosmos-proto"
grpc "google.golang.org/grpc"

View File

@ -102,12 +102,15 @@ func (suite *KeeperTestSuite) SetupTest() {
privVal := ibctestingmock.NewPV()
pk, err := privVal.GetPubKey()
suite.Require().NoError(err)
val := stakingtypes.NewValidator(sdk.ValAddress(pk.Address()), pk, stakingtypes.Description{})
val, err := stakingtypes.NewValidator(sdk.ValAddress(pk.Address()), pk, stakingtypes.Description{})
suite.Require().NoError(err)
val.Status = stakingtypes.Bonded
val.Tokens = sdk.NewInt(rand.Int63())
validators = append(validators, val)
app.StakingKeeper.SetHistoricalInfo(suite.ctx, int64(i), stakingtypes.NewHistoricalInfo(suite.ctx.BlockHeader(), validators))
hi := stakingtypes.NewHistoricalInfo(suite.ctx.BlockHeader(), validators)
app.StakingKeeper.SetHistoricalInfo(suite.ctx, int64(i), &hi)
}
queryHelper := baseapp.NewQueryServerTestHelper(suite.ctx, app.InterfaceRegistry())

View File

@ -344,7 +344,12 @@ func (chain *TestChain) GetValsAtHeight(height int64) (*tmtypes.ValidatorSet, bo
}
valSet := stakingtypes.Validators(histInfo.Valset)
return tmtypes.NewValidatorSet(valSet.ToTmValidators()), true
tmValidators, err := valSet.ToTmValidators()
if err != nil {
panic(err)
}
return tmtypes.NewValidatorSet(tmValidators), true
}
// GetConnection retrieves an IBC Connection for the provided TestConnection. The

View File

@ -9,7 +9,7 @@ import (
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"github.com/tendermint/tendermint/types"
"github.com/cosmos/cosmos-sdk/simapp/params"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/types/simulation"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
)
@ -153,19 +153,15 @@ func (w WeightedProposalContent) ContentSimulatorFn() simulation.ContentSimulato
//-----------------------------------------------------------------------------
// Param change proposals
// RandomParams returns random simulation consensus parameters, it extracts the Evidence from the Staking genesis state.
func RandomConsensusParams(r *rand.Rand, appState json.RawMessage) *abci.ConsensusParams {
cdc := params.MakeEncodingConfig().Marshaler
// randomConsensusParams returns random simulation consensus parameters, it extracts the Evidence from the Staking genesis state.
func randomConsensusParams(r *rand.Rand, appState json.RawMessage, cdc codec.JSONMarshaler) *abci.ConsensusParams {
var genesisState map[string]json.RawMessage
err := json.Unmarshal(appState, &genesisState)
if err != nil {
panic(err)
}
stakingGenesisState := stakingtypes.GetGenesisStateFromAppState(cdc, genesisState)
consensusParams := &abci.ConsensusParams{
Block: &abci.BlockParams{
MaxBytes: int64(simulation.RandIntBetween(r, 20000000, 30000000)),

View File

@ -14,6 +14,7 @@ import (
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/simulation"
)
@ -23,11 +24,11 @@ const AverageBlockTime = 6 * time.Second
// initialize the chain for the simulation
func initChain(
r *rand.Rand, params Params, accounts []simulation.Account, app *baseapp.BaseApp,
appStateFn simulation.AppStateFn, config simulation.Config,
appStateFn simulation.AppStateFn, config simulation.Config, cdc codec.JSONMarshaler,
) (mockValidators, time.Time, []simulation.Account, string) {
appState, accounts, chainID, genesisTimestamp := appStateFn(r, accounts, config)
consensusParams := RandomConsensusParams(r, appState)
consensusParams := randomConsensusParams(r, appState, cdc)
req := abci.RequestInitChain{
AppStateBytes: appState,
@ -52,6 +53,7 @@ func SimulateFromSeed(
ops WeightedOperations,
blockedAddrs map[string]bool,
config simulation.Config,
cdc codec.JSONMarshaler,
) (stopEarly bool, exportedParams Params, err error) {
// in case we have to end early, don't os.Exit so that we can run cleanup code.
testingMode, _, b := getTestingMode(tb)
@ -67,7 +69,7 @@ func SimulateFromSeed(
// Second variable to keep pending validator set (delayed one block since
// TM 0.24) Initially this is the same as the initial validator set
validators, genesisTimestamp, accs, chainID := initChain(r, params, accs, app, appStateFn, config)
validators, genesisTimestamp, accs, chainID := initChain(r, params, accs, app, appStateFn, config, cdc)
if len(accs) == 0 {
return true, params, fmt.Errorf("must have greater than zero genesis accounts")
}

View File

@ -12,7 +12,11 @@ import (
func InitGenesis(ctx sdk.Context, keeper keeper.Keeper, stakingKeeper types.StakingKeeper, data *types.GenesisState) {
stakingKeeper.IterateValidators(ctx,
func(index int64, validator stakingtypes.ValidatorI) bool {
keeper.AddPubkey(ctx, validator.GetConsPubKey())
consPk, err := validator.TmConsPubKey()
if err != nil {
panic(err)
}
keeper.AddPubkey(ctx, consPk)
return false
},
)

View File

@ -25,13 +25,18 @@ func (k Keeper) AfterValidatorBonded(ctx sdk.Context, address sdk.ConsAddress, _
}
}
// When a validator is created, add the address-pubkey relation.
func (k Keeper) AfterValidatorCreated(ctx sdk.Context, valAddr sdk.ValAddress) {
// AfterValidatorCreated adds the address-pubkey relation when a validator is created.
func (k Keeper) AfterValidatorCreated(ctx sdk.Context, valAddr sdk.ValAddress) error {
validator := k.sk.Validator(ctx, valAddr)
k.AddPubkey(ctx, validator.GetConsPubKey())
consPk, err := validator.TmConsPubKey()
if err != nil {
return err
}
k.AddPubkey(ctx, consPk)
return nil
}
// When a validator is removed, delete the address-pubkey relation.
// AfterValidatorRemoved deletes the address-pubkey relation when a validator is removed,
func (k Keeper) AfterValidatorRemoved(ctx sdk.Context, address sdk.ConsAddress) {
k.deleteAddrPubkeyRelation(ctx, crypto.Address(address))
}

View File

@ -33,8 +33,10 @@ func (k Keeper) Unjail(ctx sdk.Context, validatorAddr sdk.ValAddress) error {
return types.ErrValidatorNotJailed
}
consAddr := sdk.ConsAddress(validator.GetConsPubKey().Address())
consAddr, err := validator.GetConsAddr()
if err != nil {
return err
}
// If the validator has a ValidatorSigningInfo object that signals that the
// validator was bonded and so we must check that the validator is not tombstoned
// and can be unjailed at the current block.

View File

@ -65,7 +65,11 @@ func SimulateMsgUnjail(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Kee
return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgUnjail, "validator is not jailed"), nil, nil
}
consAddr := sdk.ConsAddress(validator.GetConsPubKey().Address())
cons, err := validator.TmConsPubKey()
if err != nil {
return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgUnjail, "unable to get validator consensus key"), nil, err
}
consAddr := sdk.ConsAddress(cons.Address())
info, found := k.GetValidatorSigningInfo(ctx, consAddr)
if !found {
return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgUnjail, "unable to find validator signing info"), nil, nil // skip

View File

@ -67,7 +67,8 @@ func TestSimulateMsgUnjail(t *testing.T) {
// setup validator0 by consensus address
app.StakingKeeper.SetValidatorByConsAddr(ctx, validator0)
val0ConsAddress := sdk.ConsAddress(validator0.GetConsPubKey().Address())
val0ConsAddress, err := validator0.GetConsAddr()
require.NoError(t, err)
info := types.NewValidatorSigningInfo(val0ConsAddress, int64(4), int64(3),
time.Unix(2, 0), false, int64(10))
app.SlashingKeeper.SetValidatorSigningInfo(ctx, val0ConsAddress, info)
@ -136,10 +137,11 @@ func getTestingValidator0(t *testing.T, app *simapp.SimApp, ctx sdk.Context, acc
func getTestingValidator(t *testing.T, app *simapp.SimApp, ctx sdk.Context, accounts []simtypes.Account, commission stakingtypes.Commission, n int) stakingtypes.Validator {
account := accounts[n]
valPubKey := account.PubKey
valPubKey := account.ConsKey.PubKey()
valAddr := sdk.ValAddress(account.PubKey.Address().Bytes())
validator := stakingtypes.NewValidator(valAddr, valPubKey, stakingtypes.Description{})
validator, err := validator.SetInitialCommission(commission)
validator, err := stakingtypes.NewValidator(valAddr, valPubKey, stakingtypes.Description{})
require.NoError(t, err)
validator, err = validator.SetInitialCommission(commission)
require.NoError(t, err)
validator.DelegatorShares = sdk.NewDec(100)

View File

@ -4,7 +4,6 @@ package cli_test
import (
"context"
json "encoding/json"
"fmt"
"strings"
"testing"
@ -277,9 +276,9 @@ func (s *IntegrationTestSuite) TestGetCmdQueryValidators() {
out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args)
s.Require().NoError(err)
var result []types.Validator
s.Require().NoError(json.Unmarshal(out.Bytes(), &result))
s.Require().Equal(len(s.network.Validators), len(result))
var result types.QueryValidatorsResponse
s.Require().NoError(clientCtx.JSONMarshaler.UnmarshalJSON(out.Bytes(), &result))
s.Require().Equal(len(s.network.Validators), len(result.Validators))
})
}
}

View File

@ -113,22 +113,21 @@ $ %s query staking validators
return err
}
resKVs, _, err := clientCtx.QuerySubspace(types.ValidatorsKey, types.StoreKey)
queryClient := types.NewQueryClient(clientCtx)
pageReq, err := client.ReadPageRequest(cmd.Flags())
if err != nil {
return err
}
var validators types.Validators
for _, kv := range resKVs {
validator, err := types.UnmarshalValidator(types.ModuleCdc, kv.Value)
if err != nil {
return err
}
validators = append(validators, validator)
result, err := queryClient.Validators(context.Background(), &types.QueryValidatorsRequest{
// Leaving status empty on purpose to query all validators.
Pagination: pageReq,
})
if err != nil {
return err
}
return clientCtx.PrintOutputLegacy(validators)
return clientCtx.PrintOutput(result)
},
}

View File

@ -2,8 +2,10 @@ package staking
import (
"fmt"
"log"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/crypto"
tmtypes "github.com/tendermint/tendermint/types"
sdk "github.com/cosmos/cosmos-sdk/types"
@ -146,7 +148,11 @@ func InitGenesis(
res = append(res, update)
}
} else {
res = keeper.ApplyAndReturnValidatorSetUpdates(ctx)
var err error
res, err = keeper.ApplyAndReturnValidatorSetUpdates(ctx)
if err != nil {
log.Fatal(err)
}
}
return res
@ -190,11 +196,16 @@ func ExportGenesis(ctx sdk.Context, keeper keeper.Keeper) *types.GenesisState {
}
// WriteValidators returns a slice of bonded genesis validators.
func WriteValidators(ctx sdk.Context, keeper keeper.Keeper) (vals []tmtypes.GenesisValidator) {
func WriteValidators(ctx sdk.Context, keeper keeper.Keeper) (vals []tmtypes.GenesisValidator, err error) {
keeper.IterateLastValidators(ctx, func(_ int64, validator types.ValidatorI) (stop bool) {
var consPk crypto.PubKey
consPk, err = validator.TmConsPubKey()
if err != nil {
return true
}
vals = append(vals, tmtypes.GenesisValidator{
Address: validator.GetConsAddr().Bytes(),
PubKey: validator.GetConsPubKey(),
Address: sdk.ConsAddress(consPk.Address()).Bytes(),
PubKey: consPk,
Power: validator.GetConsensusPower(),
Name: validator.GetMoniker(),
})
@ -215,19 +226,27 @@ func ValidateGenesis(data *types.GenesisState) error {
return data.Params.Validate()
}
func validateGenesisStateValidators(validators []types.Validator) (err error) {
func validateGenesisStateValidators(validators []types.Validator) error {
addrMap := make(map[string]bool, len(validators))
for i := 0; i < len(validators); i++ {
val := validators[i]
strKey := string(val.GetConsPubKey().Bytes())
consPk, err := val.TmConsPubKey()
if err != nil {
return err
}
consAddr, err := val.GetConsAddr()
if err != nil {
return err
}
strKey := string(consPk.Bytes())
if _, ok := addrMap[strKey]; ok {
return fmt.Errorf("duplicate validator in genesis state: moniker %v, address %v", val.Description.Moniker, val.GetConsAddr())
return fmt.Errorf("duplicate validator in genesis state: moniker %v, address %v", val.Description.Moniker, consAddr)
}
if val.Jailed && val.IsBonded() {
return fmt.Errorf("validator is bonded and jailed in genesis state: moniker %v, address %v", val.Description.Moniker, val.GetConsAddr())
return fmt.Errorf("validator is bonded and jailed in genesis state: moniker %v, address %v", val.Description.Moniker, consAddr)
}
if val.DelegatorShares.IsZero() && !val.IsUnbonding() {
@ -237,5 +256,5 @@ func validateGenesisStateValidators(validators []types.Validator) (err error) {
addrMap[strKey] = true
}
return
return nil
}

View File

@ -8,11 +8,13 @@ import (
"github.com/stretchr/testify/require"
abci "github.com/tendermint/tendermint/abci/types"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/crypto/keys/ed25519"
"github.com/cosmos/cosmos-sdk/simapp"
sdk "github.com/cosmos/cosmos-sdk/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/cosmos/cosmos-sdk/x/staking"
"github.com/cosmos/cosmos-sdk/x/staking/teststaking"
"github.com/cosmos/cosmos-sdk/x/staking/types"
)
@ -43,10 +45,10 @@ func TestInitGenesis(t *testing.T) {
validators := make([]types.Validator, 2)
var delegations []types.Delegation
pk0, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeConsPub, PKs[0])
pk0, err := codectypes.PackAny(PKs[0])
require.NoError(t, err)
pk1, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeConsPub, PKs[1])
pk1, err := codectypes.PackAny(PKs[1])
require.NoError(t, err)
// initialize the validators
@ -72,7 +74,9 @@ func TestInitGenesis(t *testing.T) {
require.EqualValues(t, app.StakingKeeper.GetAllValidators(ctx), actualGenesis.Validators)
// Ensure validators have addresses.
for _, val := range staking.WriteValidators(ctx, app.StakingKeeper) {
vals2, err := staking.WriteValidators(ctx, app.StakingKeeper)
require.NoError(t, err)
for _, val := range vals2 {
require.NotEmpty(t, val.Address)
}
@ -102,11 +106,11 @@ func TestInitGenesisLargeValidatorSet(t *testing.T) {
params := app.StakingKeeper.GetParams(ctx)
delegations := []types.Delegation{}
validators := make([]types.Validator, size)
var err error
for i := range validators {
validators[i] = types.NewValidator(sdk.ValAddress(addrs[i]),
validators[i], err = types.NewValidator(sdk.ValAddress(addrs[i]),
PKs[i], types.NewDescription(fmt.Sprintf("#%d", i), "", "", "", ""))
require.NoError(t, err)
validators[i].Status = types.Bonded
tokens := sdk.TokensFromConsensusPower(1)
@ -131,7 +135,7 @@ func TestInitGenesisLargeValidatorSet(t *testing.T) {
func TestValidateGenesis(t *testing.T) {
genValidators1 := make([]types.Validator, 1, 5)
pk := ed25519.GenPrivKey().PubKey()
genValidators1[0] = types.NewValidator(sdk.ValAddress(pk.Address()), pk, types.NewDescription("", "", "", "", ""))
genValidators1[0] = teststaking.NewValidator(t, sdk.ValAddress(pk.Address()), pk)
genValidators1[0].Tokens = sdk.OneInt()
genValidators1[0].DelegatorShares = sdk.OneDec()

View File

@ -52,7 +52,8 @@ func TestValidatorByPowerIndex(t *testing.T) {
initBond := tstaking.CreateValidatorWithValPower(validatorAddr, PKs[0], initPower, true)
// must end-block
updates := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
updates, err := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
require.NoError(t, err)
require.Equal(t, 1, len(updates))
// verify the self-delegation exists
@ -71,7 +72,8 @@ func TestValidatorByPowerIndex(t *testing.T) {
tstaking.CreateValidatorWithValPower(validatorAddr3, PKs[2], initPower, true)
// must end-block
updates = app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
updates, err = app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
require.NoError(t, err)
require.Equal(t, 1, len(updates))
// slash and jail the first validator
@ -104,7 +106,7 @@ func TestValidatorByPowerIndex(t *testing.T) {
res := tstaking.Undelegate(sdk.AccAddress(validatorAddr), validatorAddr, totalBond, true)
var resData types.MsgUndelegateResponse
err := proto.Unmarshal(res.Data, &resData)
err = proto.Unmarshal(res.Data, &resData)
require.NoError(t, err)
ctx = ctx.WithBlockTime(resData.CompletionTime)
@ -130,7 +132,9 @@ func TestDuplicatesMsgCreateValidator(t *testing.T) {
validator := tstaking.CheckValidator(addr1, types.Bonded, false)
assert.Equal(t, addr1.String(), validator.OperatorAddress)
assert.Equal(t, pk1.(cryptotypes.IntoTmPubKey).AsTmPubKey(), validator.GetConsPubKey())
consKey, err := validator.TmConsPubKey()
require.NoError(t, err)
assert.Equal(t, pk1.(cryptotypes.IntoTmPubKey).AsTmPubKey(), consKey)
assert.Equal(t, valTokens, validator.BondedTokens())
assert.Equal(t, valTokens.ToDec(), validator.DelegatorShares)
assert.Equal(t, types.Description{}, validator.Description)
@ -145,12 +149,15 @@ func TestDuplicatesMsgCreateValidator(t *testing.T) {
tstaking.CreateValidator(addr2, pk2, valTokens.Int64(), true)
// must end-block
updates := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
updates, err := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
require.NoError(t, err)
require.Equal(t, 1, len(updates))
validator = tstaking.CheckValidator(addr2, types.Bonded, false)
assert.Equal(t, addr2.String(), validator.OperatorAddress)
assert.Equal(t, pk2.(cryptotypes.IntoTmPubKey).AsTmPubKey(), validator.GetConsPubKey())
consPk, err := validator.TmConsPubKey()
require.NoError(t, err)
assert.Equal(t, pk2.(cryptotypes.IntoTmPubKey).AsTmPubKey(), consPk)
assert.True(sdk.IntEq(t, valTokens, validator.Tokens))
assert.True(sdk.DecEq(t, valTokens.ToDec(), validator.DelegatorShares))
assert.Equal(t, types.Description{}, validator.Description)
@ -182,7 +189,8 @@ func TestLegacyValidatorDelegations(t *testing.T) {
bondAmount := tstaking.CreateValidatorWithValPower(valAddr, valConsPubKey, 10, true)
// must end-block
updates := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
updates, err := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
require.NoError(t, err)
require.Equal(t, 1, len(updates))
// verify the validator exists and has the correct attributes
@ -202,7 +210,7 @@ func TestLegacyValidatorDelegations(t *testing.T) {
res := tstaking.Undelegate(sdk.AccAddress(valAddr), valAddr, bondAmount, true)
var resData types.MsgUndelegateResponse
err := proto.Unmarshal(res.Data, &resData)
err = proto.Unmarshal(res.Data, &resData)
require.NoError(t, err)
ctx = ctx.WithBlockTime(resData.CompletionTime)
@ -320,7 +328,8 @@ func TestEditValidatorDecreaseMinSelfDelegation(t *testing.T) {
tstaking.Handle(msgCreateValidator, true)
// must end-block
updates := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
updates, err := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
require.NoError(t, err)
require.Equal(t, 1, len(updates))
// verify the self-delegation exists
@ -350,7 +359,8 @@ func TestEditValidatorIncreaseMinSelfDelegationBeyondCurrentBond(t *testing.T) {
tstaking.Handle(msgCreateValidator, true)
// must end-block
updates := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
updates, err := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
require.NoError(t, err)
require.Equal(t, 1, len(updates))
// verify the self-delegation exists
@ -1022,7 +1032,8 @@ func TestBondUnbondRedelegateSlashTwice(t *testing.T) {
tstaking.Delegate(del, valA, valTokens.Int64())
// apply Tendermint updates
updates := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
updates, err := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
require.NoError(t, err)
require.Equal(t, 2, len(updates))
// a block passes
@ -1044,7 +1055,8 @@ func TestBondUnbondRedelegateSlashTwice(t *testing.T) {
require.Equal(t, sdk.NewDecFromInt(redAmt.Amount), delegation.Shares)
// must apply validator updates
updates = app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
updates, err = app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
require.NoError(t, err)
require.Equal(t, 2, len(updates))
// slash the validator by half

View File

@ -22,22 +22,19 @@ func createTestInput() (*codec.LegacyAmino, *simapp.SimApp, sdk.Context) {
app := simapp.Setup(false)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
appCodec := app.AppCodec()
app.StakingKeeper = keeper.NewKeeper(
appCodec,
app.AppCodec(),
app.GetKey(types.StoreKey),
app.AccountKeeper,
app.BankKeeper,
app.GetSubspace(types.ModuleName),
)
return codec.NewLegacyAmino(), app, ctx
return app.LegacyAmino(), app, ctx
}
// intended to be used with require/assert: require.True(ValEq(...))
func ValEq(t *testing.T, exp, got types.Validator) (*testing.T, bool, string, types.Validator, types.Validator) {
return t, exp.MinEqual(got), "expected:\n%v\ngot:\n%v", exp, got
return t, exp.MinEqual(&got), "expected:\n%v\ngot:\n%v", exp, got
}
// generateAddresses generates numAddrs of normal AccAddrs and ValAddrs

View File

@ -10,6 +10,7 @@ import (
"github.com/cosmos/cosmos-sdk/simapp"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/staking/keeper"
"github.com/cosmos/cosmos-sdk/x/staking/teststaking"
"github.com/cosmos/cosmos-sdk/x/staking/types"
)
@ -24,7 +25,7 @@ func TestDelegation(t *testing.T) {
amts := []sdk.Int{sdk.NewInt(9), sdk.NewInt(8), sdk.NewInt(7)}
var validators [3]types.Validator
for i, amt := range amts {
validators[i] = types.NewValidator(valAddrs[i], PKs[i], types.Description{})
validators[i] = teststaking.NewValidator(t, valAddrs[i], PKs[i])
validators[i], _ = validators[i].AddTokensFromDel(amt)
}
@ -196,7 +197,7 @@ func TestUnbondDelegation(t *testing.T) {
// create a validator and a delegator to that validator
// note this validator starts not-bonded
validator := types.NewValidator(valAddrs[0], PKs[0], types.Description{})
validator := teststaking.NewValidator(t, valAddrs[0], PKs[0])
validator, issuedShares := validator.AddTokensFromDel(startTokens)
require.Equal(t, startTokens, issuedShares.RoundInt())
@ -237,7 +238,7 @@ func TestUnbondingDelegationsMaxEntries(t *testing.T) {
app.AccountKeeper.SetModuleAccount(ctx, notBondedPool)
// create a validator and a delegator to that validator
validator := types.NewValidator(addrVals[0], PKs[0], types.Description{})
validator := teststaking.NewValidator(t, addrVals[0], PKs[0])
validator, issuedShares := validator.AddTokensFromDel(startTokens)
require.Equal(t, startTokens, issuedShares.RoundInt())
@ -313,7 +314,7 @@ func TestUndelegateSelfDelegationBelowMinSelfDelegation(t *testing.T) {
delCoins := sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), delTokens))
//create a validator with a self-delegation
validator := types.NewValidator(addrVals[0], PKs[0], types.Description{})
validator := teststaking.NewValidator(t, addrVals[0], PKs[0])
validator.MinSelfDelegation = delTokens
validator, issuedShares := validator.AddTokensFromDel(delTokens)
@ -361,8 +362,7 @@ func TestUndelegateSelfDelegationBelowMinSelfDelegation(t *testing.T) {
require.NoError(t, err)
// end block
updates := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
require.Equal(t, 1, len(updates))
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 1)
validator, found := app.StakingKeeper.GetValidator(ctx, addrVals[0])
require.True(t, found)
@ -380,7 +380,7 @@ func TestUndelegateFromUnbondingValidator(t *testing.T) {
addrVals := simapp.ConvertAddrsToValAddrs(addrDels)
//create a validator with a self-delegation
validator := types.NewValidator(addrVals[0], PKs[0], types.Description{})
validator := teststaking.NewValidator(t, addrVals[0], PKs[0])
app.StakingKeeper.SetValidatorByConsAddr(ctx, validator)
validator, issuedShares := validator.AddTokensFromDel(delTokens)
@ -438,8 +438,7 @@ func TestUndelegateFromUnbondingValidator(t *testing.T) {
require.NoError(t, err)
// end block
updates := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
require.Equal(t, 1, len(updates))
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 1)
validator, found := app.StakingKeeper.GetValidator(ctx, addrVals[0])
require.True(t, found)
@ -481,7 +480,7 @@ func TestUndelegateFromUnbondedValidator(t *testing.T) {
app.AccountKeeper.SetModuleAccount(ctx, notBondedPool)
// create a validator with a self-delegation
validator := types.NewValidator(addrVals[0], PKs[0], types.Description{})
validator := teststaking.NewValidator(t, addrVals[0], PKs[0])
app.StakingKeeper.SetValidatorByConsAddr(ctx, validator)
valTokens := sdk.TokensFromConsensusPower(10)
@ -517,8 +516,7 @@ func TestUndelegateFromUnbondedValidator(t *testing.T) {
require.NoError(t, err)
// end block
updates := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
require.Equal(t, 1, len(updates))
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 1)
validator, found := app.StakingKeeper.GetValidator(ctx, addrVals[0])
require.True(t, found)
@ -566,7 +564,7 @@ func TestUnbondingAllDelegationFromValidator(t *testing.T) {
app.AccountKeeper.SetModuleAccount(ctx, notBondedPool)
//create a validator with a self-delegation
validator := types.NewValidator(addrVals[0], PKs[0], types.Description{})
validator := teststaking.NewValidator(t, addrVals[0], PKs[0])
app.StakingKeeper.SetValidatorByConsAddr(ctx, validator)
valTokens := sdk.TokensFromConsensusPower(10)
@ -605,8 +603,7 @@ func TestUnbondingAllDelegationFromValidator(t *testing.T) {
require.NoError(t, err)
// end block
updates := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
require.Equal(t, 1, len(updates))
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 1)
// unbond all the remaining delegation
_, err = app.StakingKeeper.Undelegate(ctx, addrDels[1], addrVals[0], delTokens.ToDec())
@ -734,7 +731,7 @@ func TestRedelegateToSameValidator(t *testing.T) {
app.AccountKeeper.SetModuleAccount(ctx, notBondedPool)
// create a validator with a self-delegation
validator := types.NewValidator(addrVals[0], PKs[0], types.Description{})
validator := teststaking.NewValidator(t, addrVals[0], PKs[0])
validator, issuedShares := validator.AddTokensFromDel(valTokens)
require.Equal(t, valTokens, issuedShares.RoundInt())
validator = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validator, true)
@ -765,7 +762,7 @@ func TestRedelegationMaxEntries(t *testing.T) {
app.AccountKeeper.SetModuleAccount(ctx, notBondedPool)
// create a validator with a self-delegation
validator := types.NewValidator(addrVals[0], PKs[0], types.Description{})
validator := teststaking.NewValidator(t, addrVals[0], PKs[0])
valTokens := sdk.TokensFromConsensusPower(10)
validator, issuedShares := validator.AddTokensFromDel(valTokens)
require.Equal(t, valTokens, issuedShares.RoundInt())
@ -775,7 +772,7 @@ func TestRedelegationMaxEntries(t *testing.T) {
app.StakingKeeper.SetDelegation(ctx, selfDelegation)
// create a second validator
validator2 := types.NewValidator(addrVals[1], PKs[1], types.Description{})
validator2 := teststaking.NewValidator(t, addrVals[1], PKs[1])
validator2, issuedShares = validator2.AddTokensFromDel(valTokens)
require.Equal(t, valTokens, issuedShares.RoundInt())
@ -823,7 +820,7 @@ func TestRedelegateSelfDelegation(t *testing.T) {
app.AccountKeeper.SetModuleAccount(ctx, notBondedPool)
//create a validator with a self-delegation
validator := types.NewValidator(addrVals[0], PKs[0], types.Description{})
validator := teststaking.NewValidator(t, addrVals[0], PKs[0])
app.StakingKeeper.SetValidatorByConsAddr(ctx, validator)
valTokens := sdk.TokensFromConsensusPower(10)
@ -837,7 +834,7 @@ func TestRedelegateSelfDelegation(t *testing.T) {
app.StakingKeeper.SetDelegation(ctx, selfDelegation)
// create a second validator
validator2 := types.NewValidator(addrVals[1], PKs[1], types.Description{})
validator2 := teststaking.NewValidator(t, addrVals[1], PKs[1])
validator2, issuedShares = validator2.AddTokensFromDel(valTokens)
require.Equal(t, valTokens, issuedShares.RoundInt())
validator2 = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validator2, true)
@ -856,8 +853,7 @@ func TestRedelegateSelfDelegation(t *testing.T) {
require.NoError(t, err)
// end block
updates := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
require.Equal(t, 2, len(updates))
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 2)
validator, found := app.StakingKeeper.GetValidator(ctx, addrVals[0])
require.True(t, found)
@ -882,7 +878,7 @@ func TestRedelegateFromUnbondingValidator(t *testing.T) {
app.AccountKeeper.SetModuleAccount(ctx, notBondedPool)
//create a validator with a self-delegation
validator := types.NewValidator(addrVals[0], PKs[0], types.Description{})
validator := teststaking.NewValidator(t, addrVals[0], PKs[0])
app.StakingKeeper.SetValidatorByConsAddr(ctx, validator)
valTokens := sdk.TokensFromConsensusPower(10)
@ -903,7 +899,7 @@ func TestRedelegateFromUnbondingValidator(t *testing.T) {
app.StakingKeeper.SetDelegation(ctx, delegation)
// create a second validator
validator2 := types.NewValidator(addrVals[1], PKs[1], types.Description{})
validator2 := teststaking.NewValidator(t, addrVals[1], PKs[1])
validator2, issuedShares = validator2.AddTokensFromDel(valTokens)
require.Equal(t, valTokens, issuedShares.RoundInt())
validator2 = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validator2, true)
@ -920,8 +916,7 @@ func TestRedelegateFromUnbondingValidator(t *testing.T) {
require.NoError(t, err)
// end block
updates := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
require.Equal(t, 1, len(updates))
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 1)
validator, found := app.StakingKeeper.GetValidator(ctx, addrVals[0])
require.True(t, found)
@ -967,7 +962,7 @@ func TestRedelegateFromUnbondedValidator(t *testing.T) {
app.AccountKeeper.SetModuleAccount(ctx, notBondedPool)
//create a validator with a self-delegation
validator := types.NewValidator(addrVals[0], PKs[0], types.Description{})
validator := teststaking.NewValidator(t, addrVals[0], PKs[0])
app.StakingKeeper.SetValidatorByConsAddr(ctx, validator)
valTokens := sdk.TokensFromConsensusPower(10)
@ -988,7 +983,7 @@ func TestRedelegateFromUnbondedValidator(t *testing.T) {
app.StakingKeeper.SetDelegation(ctx, delegation)
// create a second validator
validator2 := types.NewValidator(addrVals[1], PKs[1], types.Description{})
validator2 := teststaking.NewValidator(t, addrVals[1], PKs[1])
validator2, issuedShares = validator2.AddTokensFromDel(valTokens)
require.Equal(t, valTokens, issuedShares.RoundInt())
validator2 = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validator2, true)
@ -1002,8 +997,7 @@ func TestRedelegateFromUnbondedValidator(t *testing.T) {
require.NoError(t, err)
// end block
updates := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
require.Equal(t, 1, len(updates))
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 1)
validator, found := app.StakingKeeper.GetValidator(ctx, addrVals[0])
require.True(t, found)

View File

@ -3,11 +3,13 @@ package keeper_test
import (
gocontext "context"
"fmt"
"testing"
"github.com/cosmos/cosmos-sdk/simapp"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/query"
"github.com/cosmos/cosmos-sdk/x/staking/keeper"
"github.com/cosmos/cosmos-sdk/x/staking/teststaking"
"github.com/cosmos/cosmos-sdk/x/staking/types"
)
@ -111,7 +113,7 @@ func (suite *KeeperTestSuite) TestGRPCValidator() {
res, err := queryClient.Validator(gocontext.Background(), req)
if tc.expPass {
suite.NoError(err)
suite.Equal(validator, res.Validator)
suite.True(validator.Equal(&res.Validator))
} else {
suite.Error(err)
suite.Nil(res)
@ -573,7 +575,7 @@ func (suite *KeeperTestSuite) TestGRPCQueryHistoricalInfo() {
if tc.expPass {
suite.NoError(err)
suite.NotNil(res)
suite.Equal(&hi, res.Hist)
suite.True(hi.Equal(res.Hist))
} else {
suite.Error(err)
suite.Nil(res)
@ -591,12 +593,12 @@ func (suite *KeeperTestSuite) TestGRPCQueryRedelegation() {
delAmount := sdk.TokensFromConsensusPower(1)
_, err := app.StakingKeeper.Delegate(ctx, addrAcc1, delAmount, types.Unbonded, val1, true)
suite.NoError(err)
_ = app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
applyValidatorSetUpdates(suite.T(), ctx, app.StakingKeeper, -1)
rdAmount := sdk.TokensFromConsensusPower(1)
_, err = app.StakingKeeper.BeginRedelegation(ctx, addrAcc1, val1.GetOperator(), val2.GetOperator(), rdAmount.ToDec())
suite.NoError(err)
app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
applyValidatorSetUpdates(suite.T(), ctx, app.StakingKeeper, -1)
redel, found := app.StakingKeeper.GetRedelegation(ctx, addrAcc1, val1.GetOperator(), val2.GetOperator())
suite.True(found)
@ -683,7 +685,7 @@ func (suite *KeeperTestSuite) TestGRPCQueryValidatorUnbondingDelegations() {
undelAmount := sdk.TokensFromConsensusPower(2)
_, err := app.StakingKeeper.Undelegate(ctx, addrAcc1, val1.GetOperator(), undelAmount.ToDec())
suite.NoError(err)
app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
applyValidatorSetUpdates(suite.T(), ctx, app.StakingKeeper, -1)
var req *types.QueryValidatorUnbondingDelegationsRequest
testCases := []struct {
@ -724,7 +726,7 @@ func (suite *KeeperTestSuite) TestGRPCQueryValidatorUnbondingDelegations() {
}
}
func createValidators(ctx sdk.Context, app *simapp.SimApp, powers []int64) ([]sdk.AccAddress, []sdk.ValAddress, []types.Validator) {
func createValidators(t *testing.T, ctx sdk.Context, app *simapp.SimApp, powers []int64) ([]sdk.AccAddress, []sdk.ValAddress, []types.Validator) {
addrs := simapp.AddTestAddrsIncremental(app, ctx, 5, sdk.NewInt(300000000))
valAddrs := simapp.ConvertAddrsToValAddrs(addrs)
pks := simapp.CreateTestPubKeys(5)
@ -738,8 +740,8 @@ func createValidators(ctx sdk.Context, app *simapp.SimApp, powers []int64) ([]sd
app.GetSubspace(types.ModuleName),
)
val1 := types.NewValidator(valAddrs[0], pks[0], types.Description{})
val2 := types.NewValidator(valAddrs[1], pks[1], types.Description{})
val1 := teststaking.NewValidator(t, valAddrs[0], pks[0])
val2 := teststaking.NewValidator(t, valAddrs[1], pks[1])
vals := []types.Validator{val1, val2}
app.StakingKeeper.SetValidator(ctx, val1)
@ -752,7 +754,7 @@ func createValidators(ctx sdk.Context, app *simapp.SimApp, powers []int64) ([]sd
_, _ = app.StakingKeeper.Delegate(ctx, addrs[0], sdk.TokensFromConsensusPower(powers[0]), types.Unbonded, val1, true)
_, _ = app.StakingKeeper.Delegate(ctx, addrs[1], sdk.TokensFromConsensusPower(powers[1]), types.Unbonded, val2, true)
_, _ = app.StakingKeeper.Delegate(ctx, addrs[0], sdk.TokensFromConsensusPower(powers[2]), types.Unbonded, val2, true)
app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1)
return addrs, valAddrs, vals
}

View File

@ -15,17 +15,14 @@ func (k Keeper) GetHistoricalInfo(ctx sdk.Context, height int64) (types.Historic
return types.HistoricalInfo{}, false
}
hi := types.MustUnmarshalHistoricalInfo(k.cdc, value)
return hi, true
return types.MustUnmarshalHistoricalInfo(k.cdc, value), true
}
// SetHistoricalInfo sets the historical info at a given height
func (k Keeper) SetHistoricalInfo(ctx sdk.Context, height int64, hi types.HistoricalInfo) {
func (k Keeper) SetHistoricalInfo(ctx sdk.Context, height int64, hi *types.HistoricalInfo) {
store := ctx.KVStore(k.storeKey)
key := types.GetHistoricalInfoKey(height)
value := types.MustMarshalHistoricalInfo(k.cdc, hi)
value := k.cdc.MustMarshalBinaryBare(hi)
store.Set(key, value)
}
@ -97,5 +94,5 @@ func (k Keeper) TrackHistoricalInfo(ctx sdk.Context) {
historicalEntry := types.NewHistoricalInfo(ctx.BlockHeader(), lastVals)
// Set latest HistoricalInfo at current height
k.SetHistoricalInfo(ctx, ctx.BlockHeight(), historicalEntry)
k.SetHistoricalInfo(ctx, ctx.BlockHeight(), &historicalEntry)
}

View File

@ -9,6 +9,7 @@ import (
"github.com/cosmos/cosmos-sdk/simapp"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/staking/teststaking"
"github.com/cosmos/cosmos-sdk/x/staking/types"
)
@ -21,12 +22,11 @@ func TestHistoricalInfo(t *testing.T) {
validators := make([]types.Validator, len(addrVals))
for i, valAddr := range addrVals {
validators[i] = types.NewValidator(valAddr, PKs[i], types.Description{})
validators[i] = teststaking.NewValidator(t, valAddr, PKs[i])
}
hi := types.NewHistoricalInfo(ctx.BlockHeader(), validators)
app.StakingKeeper.SetHistoricalInfo(ctx, 2, hi)
app.StakingKeeper.SetHistoricalInfo(ctx, 2, &hi)
recv, found := app.StakingKeeper.GetHistoricalInfo(ctx, 2)
require.True(t, found, "HistoricalInfo not found after set")
@ -62,13 +62,13 @@ func TestTrackHistoricalInfo(t *testing.T) {
Height: 5,
}
valSet := []types.Validator{
types.NewValidator(addrVals[0], PKs[0], types.Description{}),
types.NewValidator(addrVals[1], PKs[1], types.Description{}),
teststaking.NewValidator(t, addrVals[0], PKs[0]),
teststaking.NewValidator(t, addrVals[1], PKs[1]),
}
hi4 := types.NewHistoricalInfo(h4, valSet)
hi5 := types.NewHistoricalInfo(h5, valSet)
app.StakingKeeper.SetHistoricalInfo(ctx, 4, hi4)
app.StakingKeeper.SetHistoricalInfo(ctx, 5, hi5)
app.StakingKeeper.SetHistoricalInfo(ctx, 4, &hi4)
app.StakingKeeper.SetHistoricalInfo(ctx, 5, &hi5)
recv, found := app.StakingKeeper.GetHistoricalInfo(ctx, 4)
require.True(t, found)
require.Equal(t, hi4, recv)
@ -77,10 +77,10 @@ func TestTrackHistoricalInfo(t *testing.T) {
require.Equal(t, hi5, recv)
// Set last validators in keeper
val1 := types.NewValidator(addrVals[2], PKs[2], types.Description{})
val1 := teststaking.NewValidator(t, addrVals[2], PKs[2])
app.StakingKeeper.SetValidator(ctx, val1)
app.StakingKeeper.SetLastValidatorPower(ctx, val1.GetOperator(), 10)
val2 := types.NewValidator(addrVals[3], PKs[3], types.Description{})
val2 := teststaking.NewValidator(t, addrVals[3], PKs[3])
vals := []types.Validator{val1, val2}
sort.Sort(types.Validators(vals))
app.StakingKeeper.SetValidator(ctx, val2)
@ -120,8 +120,8 @@ func TestGetAllHistoricalInfo(t *testing.T) {
addrVals := simapp.ConvertAddrsToValAddrs(addrDels)
valSet := []types.Validator{
types.NewValidator(addrVals[0], PKs[0], types.Description{}),
types.NewValidator(addrVals[1], PKs[1], types.Description{}),
teststaking.NewValidator(t, addrVals[0], PKs[0]),
teststaking.NewValidator(t, addrVals[1], PKs[1]),
}
header1 := tmproto.Header{ChainID: "HelloChain", Height: 10}
@ -135,7 +135,7 @@ func TestGetAllHistoricalInfo(t *testing.T) {
expHistInfos := []types.HistoricalInfo{hist1, hist2, hist3}
for i, hi := range expHistInfos {
app.StakingKeeper.SetHistoricalInfo(ctx, int64(10+i), hi)
app.StakingKeeper.SetHistoricalInfo(ctx, int64(10+i), &hi)
}
infos := app.StakingKeeper.GetAllHistoricalInfo(ctx)

View File

@ -35,14 +35,14 @@ func (suite *KeeperTestSuite) SetupTest() {
types.RegisterQueryServer(queryHelper, querier)
queryClient := types.NewQueryClient(queryHelper)
addrs, _, validators := createValidators(ctx, app, []int64{9, 8, 7})
addrs, _, validators := createValidators(suite.T(), ctx, app, []int64{9, 8, 7})
header := tmproto.Header{
ChainID: "HelloChain",
Height: 5,
}
hi := types.NewHistoricalInfo(header, validators)
app.StakingKeeper.SetHistoricalInfo(ctx, 5, hi)
app.StakingKeeper.SetHistoricalInfo(ctx, 5, &hi)
suite.app, suite.ctx, suite.queryClient, suite.addrs, suite.vals = app, ctx, queryClient, addrs, validators
}

View File

@ -67,7 +67,10 @@ func (k msgServer) CreateValidator(goCtx context.Context, msg *types.MsgCreateVa
}
}
validator := types.NewValidator(valAddr, pk, msg.Description)
validator, err := types.NewValidator(valAddr, pk, msg.Description)
if err != nil {
return nil, err
}
commission := types.NewCommissionWithTime(
msg.Commission.Rate, msg.Commission.MaxRate,
msg.Commission.MaxChangeRate, ctx.BlockHeader().Time,

View File

@ -74,7 +74,7 @@ func queryValidators(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQue
}
validators := k.GetAllValidators(ctx)
filteredVals := make([]types.Validator, 0, len(validators))
filteredVals := make(types.Validators, 0, len(validators))
for _, val := range validators {
if strings.EqualFold(val.GetStatus().String(), params.Status) {

View File

@ -12,6 +12,7 @@ import (
"github.com/cosmos/cosmos-sdk/simapp"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/staking/keeper"
"github.com/cosmos/cosmos-sdk/x/staking/teststaking"
"github.com/cosmos/cosmos-sdk/x/staking/types"
)
@ -26,7 +27,7 @@ func TestNewQuerier(t *testing.T) {
amts := []sdk.Int{sdk.NewInt(9), sdk.NewInt(8)}
var validators [2]types.Validator
for i, amt := range amts {
validators[i] = types.NewValidator(sdk.ValAddress(addrs[i]), PKs[i], types.Description{})
validators[i] = teststaking.NewValidator(t, sdk.ValAddress(addrs[i]), PKs[i])
validators[i], _ = validators[i].AddTokensFromDel(amt)
app.StakingKeeper.SetValidator(ctx, validators[i])
app.StakingKeeper.SetValidatorByPowerIndex(ctx, validators[i])
@ -37,7 +38,7 @@ func TestNewQuerier(t *testing.T) {
Height: 5,
}
hi := types.NewHistoricalInfo(header, validators[:])
app.StakingKeeper.SetHistoricalInfo(ctx, 5, hi)
app.StakingKeeper.SetHistoricalInfo(ctx, 5, &hi)
query := abci.RequestQuery{
Path: "",
@ -146,7 +147,7 @@ func TestQueryValidators(t *testing.T) {
status := []types.BondStatus{types.Bonded, types.Unbonded, types.Unbonding}
var validators [3]types.Validator
for i, amt := range amts {
validators[i] = types.NewValidator(sdk.ValAddress(addrs[i]), PKs[i], types.Description{})
validators[i] = teststaking.NewValidator(t, sdk.ValAddress(addrs[i]), PKs[i])
validators[i], _ = validators[i].AddTokensFromDel(amt)
validators[i] = validators[i].UpdateStatus(status[i])
}
@ -197,7 +198,7 @@ func TestQueryValidators(t *testing.T) {
err = cdc.UnmarshalJSON(res, &queriedValidator)
require.NoError(t, err)
require.Equal(t, validator, queriedValidator)
require.True(t, validator.Equal(&queriedValidator))
}
}
@ -215,11 +216,11 @@ func TestQueryDelegation(t *testing.T) {
pk1, pk2 := pubKeys[0], pubKeys[1]
// Create Validators and Delegation
val1 := types.NewValidator(addrVal1, pk1, types.Description{})
val1 := teststaking.NewValidator(t, addrVal1, pk1)
app.StakingKeeper.SetValidator(ctx, val1)
app.StakingKeeper.SetValidatorByPowerIndex(ctx, val1)
val2 := types.NewValidator(addrVal2, pk2, types.Description{})
val2 := teststaking.NewValidator(t, addrVal2, pk2)
app.StakingKeeper.SetValidator(ctx, val2)
app.StakingKeeper.SetValidatorByPowerIndex(ctx, val2)
@ -228,7 +229,7 @@ func TestQueryDelegation(t *testing.T) {
require.NoError(t, err)
// apply TM updates
app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1)
// Query Delegator bonded validators
queryParams := types.NewQueryDelegatorParams(addrAcc2)
@ -245,7 +246,7 @@ func TestQueryDelegation(t *testing.T) {
res, err := querier(ctx, []string{types.QueryDelegatorValidators}, query)
require.NoError(t, err)
var validatorsResp []types.Validator
var validatorsResp types.Validators
errRes = cdc.UnmarshalJSON(res, &validatorsResp)
require.NoError(t, errRes)
@ -274,8 +275,7 @@ func TestQueryDelegation(t *testing.T) {
var validator types.Validator
errRes = cdc.UnmarshalJSON(res, &validator)
require.NoError(t, errRes)
require.Equal(t, delValidators[0], validator)
require.True(t, validator.Equal(&delValidators[0]))
// error unknown request
query.Data = bz[:len(bz)-1]
@ -461,7 +461,7 @@ func TestQueryValidatorDelegations_Pagination(t *testing.T) {
valAddress := sdk.ValAddress(addrs[0])
val1 := types.NewValidator(valAddress, pubKeys[0], types.Description{})
val1 := teststaking.NewValidator(t, valAddress, pubKeys[0])
app.StakingKeeper.SetValidator(ctx, val1)
app.StakingKeeper.SetValidatorByPowerIndex(ctx, val1)
@ -478,7 +478,7 @@ func TestQueryValidatorDelegations_Pagination(t *testing.T) {
}
// apply TM updates
app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1)
for _, c := range cases {
// Query Delegator bonded validators
@ -512,7 +512,7 @@ func TestQueryValidatorDelegations_Pagination(t *testing.T) {
}
// apply TM updates
app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1)
for _, c := range cases {
// Query Unbonding delegations with pagination.
@ -546,20 +546,20 @@ func TestQueryRedelegations(t *testing.T) {
addrVal1, addrVal2 := sdk.ValAddress(addrAcc1), sdk.ValAddress(addrAcc2)
// Create Validators and Delegation
val1 := types.NewValidator(addrVal1, PKs[0], types.Description{})
val2 := types.NewValidator(addrVal2, PKs[1], types.Description{})
val1 := teststaking.NewValidator(t, addrVal1, PKs[0])
val2 := teststaking.NewValidator(t, addrVal2, PKs[1])
app.StakingKeeper.SetValidator(ctx, val1)
app.StakingKeeper.SetValidator(ctx, val2)
delAmount := sdk.TokensFromConsensusPower(100)
_, err := app.StakingKeeper.Delegate(ctx, addrAcc2, delAmount, types.Unbonded, val1, true)
require.NoError(t, err)
_ = app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1)
rdAmount := sdk.TokensFromConsensusPower(20)
_, err = app.StakingKeeper.BeginRedelegation(ctx, addrAcc2, val1.GetOperator(), val2.GetOperator(), rdAmount.ToDec())
require.NoError(t, err)
app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1)
redel, found := app.StakingKeeper.GetRedelegation(ctx, addrAcc2, val1.GetOperator(), val2.GetOperator())
require.True(t, found)
@ -618,20 +618,20 @@ func TestQueryUnbondingDelegation(t *testing.T) {
addrVal1 := sdk.ValAddress(addrAcc1)
// Create Validators and Delegation
val1 := types.NewValidator(addrVal1, PKs[0], types.Description{})
val1 := teststaking.NewValidator(t, addrVal1, PKs[0])
app.StakingKeeper.SetValidator(ctx, val1)
// delegate
delAmount := sdk.TokensFromConsensusPower(100)
_, err := app.StakingKeeper.Delegate(ctx, addrAcc1, delAmount, types.Unbonded, val1, true)
require.NoError(t, err)
_ = app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1)
// undelegate
undelAmount := sdk.TokensFromConsensusPower(20)
_, err = app.StakingKeeper.Undelegate(ctx, addrAcc1, val1.GetOperator(), undelAmount.ToDec())
require.NoError(t, err)
app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1)
_, found := app.StakingKeeper.GetUnbondingDelegation(ctx, addrAcc1, val1.GetOperator())
require.True(t, found)
@ -706,7 +706,7 @@ func TestQueryUnbondingDelegation(t *testing.T) {
func TestQueryHistoricalInfo(t *testing.T) {
cdc, app, ctx := createTestInput()
legacyQuerierCdc := codec.NewAminoCodec(app.LegacyAmino())
legacyQuerierCdc := codec.NewAminoCodec(cdc)
querier := keeper.NewQuerier(app.StakingKeeper, legacyQuerierCdc.LegacyAmino)
addrs := simapp.AddTestAddrs(app, ctx, 2, sdk.TokensFromConsensusPower(10000))
@ -714,8 +714,8 @@ func TestQueryHistoricalInfo(t *testing.T) {
addrVal1, addrVal2 := sdk.ValAddress(addrAcc1), sdk.ValAddress(addrAcc2)
// Create Validators and Delegation
val1 := types.NewValidator(addrVal1, PKs[0], types.Description{})
val2 := types.NewValidator(addrVal2, PKs[1], types.Description{})
val1 := teststaking.NewValidator(t, addrVal1, PKs[0])
val2 := teststaking.NewValidator(t, addrVal2, PKs[1])
vals := []types.Validator{val1, val2}
app.StakingKeeper.SetValidator(ctx, val1)
app.StakingKeeper.SetValidator(ctx, val2)
@ -725,7 +725,7 @@ func TestQueryHistoricalInfo(t *testing.T) {
Height: 5,
}
hi := types.NewHistoricalInfo(header, vals)
app.StakingKeeper.SetHistoricalInfo(ctx, 5, hi)
app.StakingKeeper.SetHistoricalInfo(ctx, 5, &hi)
queryHistoricalParams := types.QueryHistoricalInfoRequest{Height: 4}
bz, errRes := cdc.MarshalJSON(queryHistoricalParams)

View File

@ -8,7 +8,7 @@ import (
// Return all validators that a delegator is bonded to. If maxRetrieve is supplied, the respective amount will be returned.
func (k Keeper) GetDelegatorValidators(
ctx sdk.Context, delegatorAddr sdk.AccAddress, maxRetrieve uint32,
) []types.Validator {
) types.Validators {
validators := make([]types.Validator, maxRetrieve)
store := ctx.KVStore(k.storeKey)

View File

@ -12,6 +12,7 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/cosmos/cosmos-sdk/x/staking/keeper"
"github.com/cosmos/cosmos-sdk/x/staking/teststaking"
"github.com/cosmos/cosmos-sdk/x/staking/types"
)
@ -41,7 +42,7 @@ func bootstrapSlashTest(t *testing.T, power int64) (*simapp.SimApp, sdk.Context,
app.BankKeeper.SetSupply(ctx, banktypes.NewSupply(totalSupply))
for i := int64(0); i < numVals; i++ {
validator := types.NewValidator(addrVals[i], PKs[i], types.Description{})
validator := teststaking.NewValidator(t, addrVals[i], PKs[i])
validator, _ = validator.AddTokensFromDel(amt)
validator = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validator, true)
app.StakingKeeper.SetValidatorByConsAddr(ctx, validator)
@ -170,8 +171,7 @@ func TestSlashRedelegation(t *testing.T) {
require.Len(t, rd.Entries, 1)
// end block
updates := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
require.Equal(t, 1, len(updates))
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 1)
// initialbalance unchanged
require.Equal(t, sdk.NewInt(10), rd.Entries[0].InitialBalance)
@ -214,8 +214,7 @@ func TestSlashAtNegativeHeight(t *testing.T) {
require.True(t, found)
// end block
updates := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
require.Equal(t, 1, len(updates), "cons addr: %v, updates: %v", []byte(consAddr), updates)
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 1)
validator, found = app.StakingKeeper.GetValidator(ctx, validator.GetOperator())
require.True(t, found)
@ -246,8 +245,7 @@ func TestSlashValidatorAtCurrentHeight(t *testing.T) {
require.True(t, found)
// end block
updates := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
require.Equal(t, 1, len(updates), "cons addr: %v, updates: %v", []byte(consAddr), updates)
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 1)
validator, found = app.StakingKeeper.GetValidator(ctx, validator.GetOperator())
assert.True(t, found)
@ -284,8 +282,7 @@ func TestSlashWithUnbondingDelegation(t *testing.T) {
app.StakingKeeper.Slash(ctx, consAddr, 10, 10, fraction)
// end block
updates := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
require.Equal(t, 1, len(updates))
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 1)
// read updating unbonding delegation
ubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0])
@ -379,7 +376,7 @@ func TestSlashWithUnbondingDelegation(t *testing.T) {
require.Equal(t, sdk.TokensFromConsensusPower(10), diffTokens)
// apply TM updates
app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1)
// read updated validator
// power decreased by 1 again, validator is out of stake
@ -511,7 +508,7 @@ func TestSlashWithRedelegation(t *testing.T) {
require.True(t, found)
require.Len(t, rd.Entries, 1)
// apply TM updates
app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1)
// read updated validator
// validator decreased to zero power, should be in unbonding period
validator, _ = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)

View File

@ -40,21 +40,15 @@ func TestingUpdateValidator(keeper Keeper, ctx sdk.Context, validator types.Vali
keeper.SetValidatorByPowerIndex(ctx, validator)
if apply {
keeper.ApplyAndReturnValidatorSetUpdates(ctx)
validator, found := keeper.GetValidator(ctx, validator.GetOperator())
if !found {
panic("validator expected but not found")
}
return validator
if !apply {
ctx, _ = ctx.CacheContext()
}
_, err := keeper.ApplyAndReturnValidatorSetUpdates(ctx)
if err != nil {
panic(err)
}
cachectx, _ := ctx.CacheContext()
keeper.ApplyAndReturnValidatorSetUpdates(cachectx)
validator, found := keeper.GetValidator(cachectx, validator.GetOperator())
validator, found := keeper.GetValidator(ctx, validator.GetOperator())
if !found {
panic("validator expected but not found")
}

View File

@ -24,7 +24,10 @@ func (k Keeper) BlockValidatorUpdates(ctx sdk.Context) []abci.ValidatorUpdate {
// unbonded after the Endblocker (go from Bonded -> Unbonding during
// ApplyAndReturnValidatorSetUpdates and then Unbonding -> Unbonded during
// UnbondAllMatureValidatorQueue).
validatorUpdates := k.ApplyAndReturnValidatorSetUpdates(ctx)
validatorUpdates, err := k.ApplyAndReturnValidatorSetUpdates(ctx)
if err != nil {
panic(err)
}
// unbond all mature validators from the unbonding queue
k.UnbondAllMatureValidators(ctx)
@ -106,7 +109,7 @@ func (k Keeper) BlockValidatorUpdates(ctx sdk.Context) []abci.ValidatorUpdate {
// CONTRACT: Only validators with non-zero power or zero-power that were bonded
// at the previous block height or were removed from the validator set entirely
// are returned to Tendermint.
func (k Keeper) ApplyAndReturnValidatorSetUpdates(ctx sdk.Context) (updates []abci.ValidatorUpdate) {
func (k Keeper) ApplyAndReturnValidatorSetUpdates(ctx sdk.Context) (updates []abci.ValidatorUpdate, err error) {
maxValidators := k.GetParams(ctx).MaxValidators
totalPower := sdk.ZeroInt()
amtFromBondedToNotBonded, amtFromNotBondedToBonded := sdk.ZeroInt(), sdk.ZeroInt()
@ -139,10 +142,16 @@ func (k Keeper) ApplyAndReturnValidatorSetUpdates(ctx sdk.Context) (updates []ab
// apply the appropriate state change if necessary
switch {
case validator.IsUnbonded():
validator = k.unbondedToBonded(ctx, validator)
validator, err = k.unbondedToBonded(ctx, validator)
if err != nil {
return
}
amtFromNotBondedToBonded = amtFromNotBondedToBonded.Add(validator.GetTokens())
case validator.IsUnbonding():
validator = k.unbondingToBonded(ctx, validator)
validator, err = k.unbondingToBonded(ctx, validator)
if err != nil {
return
}
amtFromNotBondedToBonded = amtFromNotBondedToBonded.Add(validator.GetTokens())
case validator.IsBonded():
// no state change
@ -174,7 +183,10 @@ func (k Keeper) ApplyAndReturnValidatorSetUpdates(ctx sdk.Context) (updates []ab
noLongerBonded := sortNoLongerBonded(last)
for _, valAddrBytes := range noLongerBonded {
validator := k.mustGetValidator(ctx, sdk.ValAddress(valAddrBytes))
validator = k.bondedToUnbonding(ctx, validator)
validator, err = k.bondedToUnbonding(ctx, validator)
if err != nil {
return
}
amtFromBondedToNotBonded = amtFromBondedToNotBonded.Add(validator.GetTokens())
k.DeleteLastValidatorPower(ctx, validator.GetOperator())
updates = append(updates, validator.ABCIValidatorUpdateZero())
@ -200,12 +212,12 @@ func (k Keeper) ApplyAndReturnValidatorSetUpdates(ctx sdk.Context) (updates []ab
k.SetLastTotalPower(ctx, totalPower)
}
return updates
return updates, err
}
// Validator state transitions
func (k Keeper) bondedToUnbonding(ctx sdk.Context, validator types.Validator) types.Validator {
func (k Keeper) bondedToUnbonding(ctx sdk.Context, validator types.Validator) (types.Validator, error) {
if !validator.IsBonded() {
panic(fmt.Sprintf("bad state transition bondedToUnbonding, validator: %v\n", validator))
}
@ -213,7 +225,7 @@ func (k Keeper) bondedToUnbonding(ctx sdk.Context, validator types.Validator) ty
return k.beginUnbondingValidator(ctx, validator)
}
func (k Keeper) unbondingToBonded(ctx sdk.Context, validator types.Validator) types.Validator {
func (k Keeper) unbondingToBonded(ctx sdk.Context, validator types.Validator) (types.Validator, error) {
if !validator.IsUnbonding() {
panic(fmt.Sprintf("bad state transition unbondingToBonded, validator: %v\n", validator))
}
@ -221,7 +233,7 @@ func (k Keeper) unbondingToBonded(ctx sdk.Context, validator types.Validator) ty
return k.bondValidator(ctx, validator)
}
func (k Keeper) unbondedToBonded(ctx sdk.Context, validator types.Validator) types.Validator {
func (k Keeper) unbondedToBonded(ctx sdk.Context, validator types.Validator) (types.Validator, error) {
if !validator.IsUnbonded() {
panic(fmt.Sprintf("bad state transition unbondedToBonded, validator: %v\n", validator))
}
@ -229,7 +241,7 @@ func (k Keeper) unbondedToBonded(ctx sdk.Context, validator types.Validator) typ
return k.bondValidator(ctx, validator)
}
// switches a validator from unbonding state to unbonded state
// UnbondingToUnbonded switches a validator from unbonding state to unbonded state
func (k Keeper) UnbondingToUnbonded(ctx sdk.Context, validator types.Validator) types.Validator {
if !validator.IsUnbonding() {
panic(fmt.Sprintf("bad state transition unbondingToBonded, validator: %v\n", validator))
@ -261,7 +273,7 @@ func (k Keeper) unjailValidator(ctx sdk.Context, validator types.Validator) {
}
// perform all the store operations for when a validator status becomes bonded
func (k Keeper) bondValidator(ctx sdk.Context, validator types.Validator) types.Validator {
func (k Keeper) bondValidator(ctx sdk.Context, validator types.Validator) (types.Validator, error) {
// delete the validator by power index, as the key will change
k.DeleteValidatorByPowerIndex(ctx, validator)
@ -275,13 +287,17 @@ func (k Keeper) bondValidator(ctx sdk.Context, validator types.Validator) types.
k.DeleteValidatorQueue(ctx, validator)
// trigger hook
k.AfterValidatorBonded(ctx, validator.GetConsAddr(), validator.GetOperator())
consAddr, err := validator.GetConsAddr()
if err != nil {
return validator, err
}
k.AfterValidatorBonded(ctx, consAddr, validator.GetOperator())
return validator
return validator, err
}
// perform all the store operations for when a validator begins unbonding
func (k Keeper) beginUnbondingValidator(ctx sdk.Context, validator types.Validator) types.Validator {
func (k Keeper) beginUnbondingValidator(ctx sdk.Context, validator types.Validator) (types.Validator, error) {
params := k.GetParams(ctx)
// delete the validator by power index, as the key will change
@ -306,9 +322,13 @@ func (k Keeper) beginUnbondingValidator(ctx sdk.Context, validator types.Validat
k.InsertUnbondingValidatorQueue(ctx, validator)
// trigger hook
k.AfterValidatorBeginUnbonding(ctx, validator.GetConsAddr(), validator.GetOperator())
consAddr, err := validator.GetConsAddr()
if err != nil {
return validator, err
}
k.AfterValidatorBeginUnbonding(ctx, consAddr, validator.GetOperator())
return validator
return validator, nil
}
// perform all the store operations for when a validator status becomes unbonded

View File

@ -95,14 +95,19 @@ func (k Keeper) mustGetValidatorByConsAddr(ctx sdk.Context, consAddr sdk.ConsAdd
// set the main record holding validator details
func (k Keeper) SetValidator(ctx sdk.Context, validator types.Validator) {
store := ctx.KVStore(k.storeKey)
bz := types.MustMarshalValidator(k.cdc, validator)
bz := types.MustMarshalValidator(k.cdc, &validator)
store.Set(types.GetValidatorKey(validator.GetOperator()), bz)
}
// validator index
func (k Keeper) SetValidatorByConsAddr(ctx sdk.Context, validator types.Validator) {
func (k Keeper) SetValidatorByConsAddr(ctx sdk.Context, validator types.Validator) error {
consPk, err := validator.GetConsAddr()
if err != nil {
return err
}
store := ctx.KVStore(k.storeKey)
store.Set(types.GetValidatorByConsAddrKey(validator.GetConsAddr()), validator.GetOperator())
store.Set(types.GetValidatorByConsAddrKey(consPk), validator.GetOperator())
return nil
}
// validator index
@ -180,6 +185,7 @@ func (k Keeper) UpdateValidatorCommission(ctx sdk.Context,
// remove the validator record and associated indexes
// except for the bonded validator index which is only handled in ApplyAndReturnTendermintUpdates
// TODO, this function panics, and it's not good.
func (k Keeper) RemoveValidator(ctx sdk.Context, address sdk.ValAddress) {
// first retrieve the old validator record
validator, found := k.GetValidator(ctx, address)
@ -195,7 +201,10 @@ func (k Keeper) RemoveValidator(ctx sdk.Context, address sdk.ValAddress) {
panic("attempting to remove a validator which still contains tokens")
}
valConsAddr := validator.GetConsAddr()
valConsAddr, err := validator.GetConsAddr()
if err != nil {
panic(err)
}
// delete the old validator record
store := ctx.KVStore(k.storeKey)

View File

@ -7,15 +7,24 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/crypto"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"github.com/cosmos/cosmos-sdk/simapp"
sdk "github.com/cosmos/cosmos-sdk/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/cosmos/cosmos-sdk/x/staking/keeper"
"github.com/cosmos/cosmos-sdk/x/staking/teststaking"
"github.com/cosmos/cosmos-sdk/x/staking/types"
)
func newMonikerValidator(t *testing.T, operator sdk.ValAddress, pubKey crypto.PubKey, moniker string) types.Validator {
v, err := types.NewValidator(operator, pubKey, types.Description{Moniker: moniker})
require.NoError(t, err)
return v
}
func bootstrapValidatorTest(t *testing.T, power int64, numAddrs int) (*simapp.SimApp, sdk.Context, []sdk.AccAddress, []sdk.ValAddress) {
_, app, ctx := createTestInput()
@ -34,6 +43,18 @@ func bootstrapValidatorTest(t *testing.T, power int64, numAddrs int) (*simapp.Si
return app, ctx, addrDels, addrVals
}
func initValidators(t *testing.T, power int64, numAddrs int, powers []int64) (*simapp.SimApp, sdk.Context, []sdk.AccAddress, []sdk.ValAddress, []types.Validator) {
app, ctx, addrs, valAddrs := bootstrapValidatorTest(t, 1000, 20)
vs := make([]types.Validator, len(powers))
for i, power := range powers {
vs[i] = teststaking.NewValidator(t, sdk.ValAddress(addrs[i]), PKs[i])
tokens := sdk.TokensFromConsensusPower(power)
vs[i], _ = vs[i].AddTokensFromDel(tokens)
}
return app, ctx, addrs, valAddrs, vs
}
func TestSetValidator(t *testing.T) {
app, ctx, _, _ := bootstrapValidatorTest(t, 10, 100)
@ -42,7 +63,7 @@ func TestSetValidator(t *testing.T) {
valTokens := sdk.TokensFromConsensusPower(10)
// test how the validator is set from a purely unbonbed pool
validator := types.NewValidator(valAddr, valPubKey, types.Description{})
validator := teststaking.NewValidator(t, valAddr, valPubKey)
validator, _ = validator.AddTokensFromDel(valTokens)
require.Equal(t, types.Unbonded, validator.Status)
assert.Equal(t, valTokens, validator.Tokens)
@ -51,10 +72,9 @@ func TestSetValidator(t *testing.T) {
app.StakingKeeper.SetValidatorByPowerIndex(ctx, validator)
// ensure update
updates := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
updates := applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 1)
validator, found := app.StakingKeeper.GetValidator(ctx, valAddr)
require.True(t, found)
require.Equal(t, 1, len(updates))
require.Equal(t, validator.ABCIValidatorUpdate(), updates[0])
// after the save the validator should be bonded
@ -104,7 +124,7 @@ func TestUpdateValidatorByPowerIndex(t *testing.T) {
app.AccountKeeper.SetModuleAccount(ctx, notBondedPool)
// add a validator
validator := types.NewValidator(addrVals[0], PKs[0], types.Description{})
validator := teststaking.NewValidator(t, addrVals[0], PKs[0])
validator, delSharesCreated := validator.AddTokensFromDel(sdk.TokensFromConsensusPower(100))
require.Equal(t, types.Unbonded, validator.Status)
require.Equal(t, sdk.TokensFromConsensusPower(100), validator.Tokens)
@ -158,7 +178,7 @@ func TestUpdateBondedValidatorsDecreaseCliff(t *testing.T) {
validators := make([]types.Validator, numVals)
for i := 0; i < len(validators); i++ {
moniker := fmt.Sprintf("val#%d", int64(i))
val := types.NewValidator(valAddrs[i], PKs[i], types.Description{Moniker: moniker})
val := newMonikerValidator(t, valAddrs[i], PKs[i], moniker)
delTokens := sdk.TokensFromConsensusPower(int64((i + 1) * 10))
val, _ = val.AddTokensFromDel(delTokens)
@ -199,7 +219,7 @@ func TestSlashToZeroPowerRemoved(t *testing.T) {
app, ctx, _, addrVals := bootstrapValidatorTest(t, 100, 20)
// add a validator
validator := types.NewValidator(addrVals[0], PKs[0], types.Description{})
validator := teststaking.NewValidator(t, addrVals[0], PKs[0])
valTokens := sdk.TokensFromConsensusPower(100)
bondedPool := app.StakingKeeper.GetBondedPool(ctx)
@ -219,7 +239,7 @@ func TestSlashToZeroPowerRemoved(t *testing.T) {
// slash the validator by 100%
app.StakingKeeper.Slash(ctx, sdk.ConsAddress(PKs[0].Address()), 0, 100, sdk.OneDec())
// apply TM updates
app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1)
// validator should be unbonding
validator, _ = app.StakingKeeper.GetValidator(ctx, addrVals[0])
require.Equal(t, validator.GetStatus(), types.Unbonding)
@ -233,7 +253,7 @@ func TestValidatorBasics(t *testing.T) {
var validators [3]types.Validator
powers := []int64{9, 8, 7}
for i, power := range powers {
validators[i] = types.NewValidator(addrVals[i], PKs[i], types.Description{})
validators[i] = teststaking.NewValidator(t, addrVals[i], PKs[i])
validators[i].Status = types.Unbonded
validators[i].Tokens = sdk.ZeroInt()
tokens := sdk.TokensFromConsensusPower(power)
@ -338,7 +358,7 @@ func TestGetValidatorSortingUnmixed(t *testing.T) {
n := len(amts)
var validators [5]types.Validator
for i, amt := range amts {
validators[i] = types.NewValidator(sdk.ValAddress(addrs[i]), PKs[i], types.Description{})
validators[i] = teststaking.NewValidator(t, sdk.ValAddress(addrs[i]), PKs[i])
validators[i].Status = types.Bonded
validators[i].Tokens = sdk.NewInt(amt)
validators[i].DelegatorShares = sdk.NewDec(amt)
@ -434,7 +454,7 @@ func TestGetValidatorSortingMixed(t *testing.T) {
var validators [5]types.Validator
for i, amt := range amts {
validators[i] = types.NewValidator(sdk.ValAddress(addrs[i]), PKs[i], types.Description{})
validators[i] = teststaking.NewValidator(t, sdk.ValAddress(addrs[i]), PKs[i])
validators[i].DelegatorShares = sdk.NewDec(amt)
validators[i].Status = types.Bonded
validators[i].Tokens = sdk.NewInt(amt)
@ -482,7 +502,7 @@ func TestGetValidatorsEdgeCases(t *testing.T) {
var validators [4]types.Validator
for i, power := range powers {
moniker := fmt.Sprintf("val#%d", int64(i))
validators[i] = types.NewValidator(sdk.ValAddress(addrs[i]), PKs[i], types.Description{Moniker: moniker})
validators[i] = newMonikerValidator(t, sdk.ValAddress(addrs[i]), PKs[i], moniker)
tokens := sdk.TokensFromConsensusPower(power)
validators[i], _ = validators[i].AddTokensFromDel(tokens)
@ -596,9 +616,9 @@ func TestValidatorBondHeight(t *testing.T) {
// initialize some validators into the state
var validators [3]types.Validator
validators[0] = types.NewValidator(sdk.ValAddress(PKs[0].Address().Bytes()), PKs[0], types.Description{})
validators[1] = types.NewValidator(sdk.ValAddress(addrs[1]), PKs[1], types.Description{})
validators[2] = types.NewValidator(sdk.ValAddress(addrs[2]), PKs[2], types.Description{})
validators[0] = teststaking.NewValidator(t, sdk.ValAddress(PKs[0].Address().Bytes()), PKs[0])
validators[1] = teststaking.NewValidator(t, sdk.ValAddress(addrs[1]), PKs[1])
validators[2] = teststaking.NewValidator(t, sdk.ValAddress(addrs[2]), PKs[2])
tokens0 := sdk.TokensFromConsensusPower(200)
tokens1 := sdk.TokensFromConsensusPower(100)
@ -644,7 +664,7 @@ func TestFullValidatorSetPowerChange(t *testing.T) {
powers := []int64{0, 100, 400, 400, 200}
var validators [5]types.Validator
for i, power := range powers {
validators[i] = types.NewValidator(sdk.ValAddress(addrs[i]), PKs[i], types.Description{})
validators[i] = teststaking.NewValidator(t, sdk.ValAddress(addrs[i]), PKs[i])
tokens := sdk.TokensFromConsensusPower(power)
validators[i], _ = validators[i].AddTokensFromDel(tokens)
keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validators[i], true)
@ -684,21 +704,20 @@ func TestApplyAndReturnValidatorSetUpdatesAllNone(t *testing.T) {
valPubKey := PKs[i+1]
valAddr := sdk.ValAddress(valPubKey.Address().Bytes())
validators[i] = types.NewValidator(valAddr, valPubKey, types.Description{})
validators[i] = teststaking.NewValidator(t, valAddr, valPubKey)
tokens := sdk.TokensFromConsensusPower(power)
validators[i], _ = validators[i].AddTokensFromDel(tokens)
}
// test from nothing to something
// tendermintUpdate set: {} -> {c1, c3}
require.Equal(t, 0, len(app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)))
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 0)
app.StakingKeeper.SetValidator(ctx, validators[0])
app.StakingKeeper.SetValidatorByPowerIndex(ctx, validators[0])
app.StakingKeeper.SetValidator(ctx, validators[1])
app.StakingKeeper.SetValidatorByPowerIndex(ctx, validators[1])
updates := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
assert.Equal(t, 2, len(updates))
updates := applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 2)
validators[0], _ = app.StakingKeeper.GetValidator(ctx, validators[0].GetOperator())
validators[1], _ = app.StakingKeeper.GetValidator(ctx, validators[1].GetOperator())
assert.Equal(t, validators[0].ABCIValidatorUpdate(), updates[1])
@ -711,7 +730,7 @@ func TestApplyAndReturnValidatorSetUpdatesIdentical(t *testing.T) {
powers := []int64{10, 20}
var validators [2]types.Validator
for i, power := range powers {
validators[i] = types.NewValidator(sdk.ValAddress(addrs[i]), PKs[i], types.Description{})
validators[i] = teststaking.NewValidator(t, sdk.ValAddress(addrs[i]), PKs[i])
tokens := sdk.TokensFromConsensusPower(power)
validators[i], _ = validators[i].AddTokensFromDel(tokens)
@ -719,13 +738,13 @@ func TestApplyAndReturnValidatorSetUpdatesIdentical(t *testing.T) {
}
validators[0] = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validators[0], false)
validators[1] = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validators[1], false)
require.Equal(t, 2, len(app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)))
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 2)
// test identical,
// tendermintUpdate set: {} -> {}
validators[0] = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validators[0], false)
validators[1] = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validators[1], false)
require.Equal(t, 0, len(app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)))
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 0)
}
func TestApplyAndReturnValidatorSetUpdatesSingleValueChange(t *testing.T) {
@ -734,8 +753,7 @@ func TestApplyAndReturnValidatorSetUpdatesSingleValueChange(t *testing.T) {
powers := []int64{10, 20}
var validators [2]types.Validator
for i, power := range powers {
validators[i] = types.NewValidator(sdk.ValAddress(addrs[i]), PKs[i], types.Description{})
validators[i] = teststaking.NewValidator(t, sdk.ValAddress(addrs[i]), PKs[i])
tokens := sdk.TokensFromConsensusPower(power)
validators[i], _ = validators[i].AddTokensFromDel(tokens)
@ -743,7 +761,7 @@ func TestApplyAndReturnValidatorSetUpdatesSingleValueChange(t *testing.T) {
}
validators[0] = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validators[0], false)
validators[1] = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validators[1], false)
require.Equal(t, 2, len(app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)))
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 2)
// test single value change
// tendermintUpdate set: {} -> {c1'}
@ -751,28 +769,18 @@ func TestApplyAndReturnValidatorSetUpdatesSingleValueChange(t *testing.T) {
validators[0].Tokens = sdk.TokensFromConsensusPower(600)
validators[0] = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validators[0], false)
updates := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
require.Equal(t, 1, len(updates))
updates := applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 1)
require.Equal(t, validators[0].ABCIValidatorUpdate(), updates[0])
}
func TestApplyAndReturnValidatorSetUpdatesMultipleValueChange(t *testing.T) {
app, ctx, addrs, _ := bootstrapValidatorTest(t, 1000, 20)
powers := []int64{10, 20}
var validators [2]types.Validator
for i, power := range powers {
// TODO: use it in other places
app, ctx, _, _, validators := initValidators(t, 1000, 20, powers)
validators[i] = types.NewValidator(sdk.ValAddress(addrs[i]), PKs[i], types.Description{})
tokens := sdk.TokensFromConsensusPower(power)
validators[i], _ = validators[i].AddTokensFromDel(tokens)
}
validators[0] = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validators[0], false)
validators[1] = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validators[1], false)
require.Equal(t, 2, len(app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)))
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 2)
// test multiple value change
// tendermintUpdate set: {c1, c3} -> {c1', c3'}
@ -783,55 +791,41 @@ func TestApplyAndReturnValidatorSetUpdatesMultipleValueChange(t *testing.T) {
validators[0] = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validators[0], false)
validators[1] = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validators[1], false)
updates := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
require.Equal(t, 2, len(updates))
updates := applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 2)
require.Equal(t, validators[0].ABCIValidatorUpdate(), updates[0])
require.Equal(t, validators[1].ABCIValidatorUpdate(), updates[1])
}
func TestApplyAndReturnValidatorSetUpdatesInserted(t *testing.T) {
app, ctx, addrs, _ := bootstrapValidatorTest(t, 1000, 20)
powers := []int64{10, 20, 5, 15, 25}
var validators [5]types.Validator
for i, power := range powers {
validators[i] = types.NewValidator(sdk.ValAddress(addrs[i]), PKs[i], types.Description{})
tokens := sdk.TokensFromConsensusPower(power)
validators[i], _ = validators[i].AddTokensFromDel(tokens)
}
app, ctx, _, _, validators := initValidators(t, 1000, 20, powers)
validators[0] = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validators[0], false)
validators[1] = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validators[1], false)
require.Equal(t, 2, len(app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)))
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 2)
// test validtor added at the beginning
// tendermintUpdate set: {} -> {c0}
app.StakingKeeper.SetValidator(ctx, validators[2])
app.StakingKeeper.SetValidatorByPowerIndex(ctx, validators[2])
updates := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
updates := applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 1)
validators[2], _ = app.StakingKeeper.GetValidator(ctx, validators[2].GetOperator())
require.Equal(t, 1, len(updates))
require.Equal(t, validators[2].ABCIValidatorUpdate(), updates[0])
// test validtor added at the beginning
// tendermintUpdate set: {} -> {c0}
app.StakingKeeper.SetValidator(ctx, validators[3])
app.StakingKeeper.SetValidatorByPowerIndex(ctx, validators[3])
updates = app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
updates = applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 1)
validators[3], _ = app.StakingKeeper.GetValidator(ctx, validators[3].GetOperator())
require.Equal(t, 1, len(updates))
require.Equal(t, validators[3].ABCIValidatorUpdate(), updates[0])
// test validtor added at the end
// tendermintUpdate set: {} -> {c0}
app.StakingKeeper.SetValidator(ctx, validators[4])
app.StakingKeeper.SetValidatorByPowerIndex(ctx, validators[4])
updates = app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
updates = applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 1)
validators[4], _ = app.StakingKeeper.GetValidator(ctx, validators[4].GetOperator())
require.Equal(t, 1, len(updates))
require.Equal(t, validators[4].ABCIValidatorUpdate(), updates[0])
}
@ -844,34 +838,29 @@ func TestApplyAndReturnValidatorSetUpdatesWithCliffValidator(t *testing.T) {
powers := []int64{10, 20, 5}
var validators [5]types.Validator
for i, power := range powers {
validators[i] = types.NewValidator(sdk.ValAddress(addrs[i]), PKs[i], types.Description{})
validators[i] = teststaking.NewValidator(t, sdk.ValAddress(addrs[i]), PKs[i])
tokens := sdk.TokensFromConsensusPower(power)
validators[i], _ = validators[i].AddTokensFromDel(tokens)
}
validators[0] = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validators[0], false)
validators[1] = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validators[1], false)
require.Equal(t, 2, len(app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)))
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 2)
// test validator added at the end but not inserted in the valset
// tendermintUpdate set: {} -> {}
keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validators[2], false)
updates := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
require.Equal(t, 0, len(updates))
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 0)
// test validator change its power and become a gotValidator (pushing out an existing)
// tendermintUpdate set: {} -> {c0, c4}
require.Equal(t, 0, len(app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)))
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 0)
tokens := sdk.TokensFromConsensusPower(10)
validators[2], _ = validators[2].AddTokensFromDel(tokens)
app.StakingKeeper.SetValidator(ctx, validators[2])
app.StakingKeeper.SetValidatorByPowerIndex(ctx, validators[2])
updates = app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
updates := applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 2)
validators[2], _ = app.StakingKeeper.GetValidator(ctx, validators[2].GetOperator())
require.Equal(t, 2, len(updates), "%v", updates)
require.Equal(t, validators[0].ABCIValidatorUpdateZero(), updates[1])
require.Equal(t, validators[2].ABCIValidatorUpdate(), updates[0])
}
@ -882,16 +871,13 @@ func TestApplyAndReturnValidatorSetUpdatesPowerDecrease(t *testing.T) {
powers := []int64{100, 100}
var validators [2]types.Validator
for i, power := range powers {
validators[i] = types.NewValidator(sdk.ValAddress(addrs[i]), PKs[i], types.Description{})
validators[i] = teststaking.NewValidator(t, sdk.ValAddress(addrs[i]), PKs[i])
tokens := sdk.TokensFromConsensusPower(power)
validators[i], _ = validators[i].AddTokensFromDel(tokens)
}
validators[0] = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validators[0], false)
validators[1] = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validators[1], false)
require.Equal(t, 2, len(app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)))
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 2)
// check initial power
require.Equal(t, int64(100), validators[0].GetConsensusPower())
@ -911,8 +897,7 @@ func TestApplyAndReturnValidatorSetUpdatesPowerDecrease(t *testing.T) {
require.Equal(t, int64(70), validators[1].GetConsensusPower())
// Tendermint updates should reflect power change
updates := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
require.Equal(t, 2, len(updates))
updates := applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 2)
require.Equal(t, validators[0].ABCIValidatorUpdate(), updates[0])
require.Equal(t, validators[1].ABCIValidatorUpdate(), updates[1])
}
@ -929,11 +914,10 @@ func TestApplyAndReturnValidatorSetUpdatesNewValidator(t *testing.T) {
// initialize some validators into the state
for i, power := range powers {
valPubKey := PKs[i+1]
valAddr := sdk.ValAddress(valPubKey.Address().Bytes())
validators[i] = types.NewValidator(valAddr, valPubKey, types.Description{})
validators[i] = teststaking.NewValidator(t, valAddr, valPubKey)
tokens := sdk.TokensFromConsensusPower(power)
validators[i], _ = validators[i].AddTokensFromDel(tokens)
@ -942,14 +926,13 @@ func TestApplyAndReturnValidatorSetUpdatesNewValidator(t *testing.T) {
}
// verify initial Tendermint updates are correct
updates := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
require.Equal(t, len(validators), len(updates))
updates := applyValidatorSetUpdates(t, ctx, app.StakingKeeper, len(validators))
validators[0], _ = app.StakingKeeper.GetValidator(ctx, validators[0].GetOperator())
validators[1], _ = app.StakingKeeper.GetValidator(ctx, validators[1].GetOperator())
require.Equal(t, validators[0].ABCIValidatorUpdate(), updates[0])
require.Equal(t, validators[1].ABCIValidatorUpdate(), updates[1])
require.Equal(t, 0, len(app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)))
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 0)
// update initial validator set
for i, power := range powers {
@ -968,7 +951,7 @@ func TestApplyAndReturnValidatorSetUpdatesNewValidator(t *testing.T) {
valAddr := sdk.ValAddress(valPubKey.Address().Bytes())
amt := sdk.NewInt(100)
validator := types.NewValidator(valAddr, valPubKey, types.Description{})
validator := teststaking.NewValidator(t, valAddr, valPubKey)
validator, _ = validator.AddTokensFromDel(amt)
app.StakingKeeper.SetValidator(ctx, validator)
@ -981,18 +964,17 @@ func TestApplyAndReturnValidatorSetUpdatesNewValidator(t *testing.T) {
valPubKey = PKs[len(validators)+2]
valAddr = sdk.ValAddress(valPubKey.Address().Bytes())
validator = types.NewValidator(valAddr, valPubKey, types.Description{})
validator = teststaking.NewValidator(t, valAddr, valPubKey)
tokens := sdk.TokensFromConsensusPower(500)
validator, _ = validator.AddTokensFromDel(tokens)
app.StakingKeeper.SetValidator(ctx, validator)
app.StakingKeeper.SetValidatorByPowerIndex(ctx, validator)
// verify initial Tendermint updates are correct
updates = app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
updates = applyValidatorSetUpdates(t, ctx, app.StakingKeeper, len(validators)+1)
validator, _ = app.StakingKeeper.GetValidator(ctx, validator.GetOperator())
validators[0], _ = app.StakingKeeper.GetValidator(ctx, validators[0].GetOperator())
validators[1], _ = app.StakingKeeper.GetValidator(ctx, validators[1].GetOperator())
require.Equal(t, len(validators)+1, len(updates))
require.Equal(t, validator.ABCIValidatorUpdate(), updates[0])
require.Equal(t, validators[0].ABCIValidatorUpdate(), updates[1])
require.Equal(t, validators[1].ABCIValidatorUpdate(), updates[2])
@ -1014,7 +996,7 @@ func TestApplyAndReturnValidatorSetUpdatesBondTransition(t *testing.T) {
valPubKey := PKs[i+1]
valAddr := sdk.ValAddress(valPubKey.Address().Bytes())
validators[i] = types.NewValidator(valAddr, valPubKey, types.Description{Moniker: moniker})
validators[i] = newMonikerValidator(t, valAddr, valPubKey, moniker)
tokens := sdk.TokensFromConsensusPower(power)
validators[i], _ = validators[i].AddTokensFromDel(tokens)
app.StakingKeeper.SetValidator(ctx, validators[i])
@ -1022,14 +1004,13 @@ func TestApplyAndReturnValidatorSetUpdatesBondTransition(t *testing.T) {
}
// verify initial Tendermint updates are correct
updates := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
require.Equal(t, 2, len(updates))
updates := applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 2)
validators[2], _ = app.StakingKeeper.GetValidator(ctx, validators[2].GetOperator())
validators[1], _ = app.StakingKeeper.GetValidator(ctx, validators[1].GetOperator())
require.Equal(t, validators[2].ABCIValidatorUpdate(), updates[0])
require.Equal(t, validators[1].ABCIValidatorUpdate(), updates[1])
require.Equal(t, 0, len(app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)))
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 0)
// delegate to validator with lowest power but not enough to bond
ctx = ctx.WithBlockHeight(1)
@ -1045,7 +1026,7 @@ func TestApplyAndReturnValidatorSetUpdatesBondTransition(t *testing.T) {
app.StakingKeeper.SetValidatorByPowerIndex(ctx, validators[0])
// verify initial Tendermint updates are correct
require.Equal(t, 0, len(app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)))
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 0)
// create a series of events that will bond and unbond the validator with
// lowest power in a single block context (height)
@ -1058,8 +1039,7 @@ func TestApplyAndReturnValidatorSetUpdatesBondTransition(t *testing.T) {
validators[0], _ = validators[0].RemoveDelShares(validators[0].DelegatorShares)
app.StakingKeeper.SetValidator(ctx, validators[0])
app.StakingKeeper.SetValidatorByPowerIndex(ctx, validators[0])
updates = app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
require.Equal(t, 0, len(updates))
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 0)
app.StakingKeeper.DeleteValidatorByPowerIndex(ctx, validators[1])
tokens = sdk.TokensFromConsensusPower(250)
@ -1068,11 +1048,10 @@ func TestApplyAndReturnValidatorSetUpdatesBondTransition(t *testing.T) {
app.StakingKeeper.SetValidatorByPowerIndex(ctx, validators[1])
// verify initial Tendermint updates are correct
updates = app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)
require.Equal(t, 1, len(updates))
updates = applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 1)
require.Equal(t, validators[1].ABCIValidatorUpdate(), updates[0])
require.Equal(t, 0, len(app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx)))
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 0)
}
func TestUpdateValidatorCommission(t *testing.T) {
@ -1085,8 +1064,8 @@ func TestUpdateValidatorCommission(t *testing.T) {
)
commission2 := types.NewCommission(sdk.NewDecWithPrec(1, 1), sdk.NewDecWithPrec(3, 1), sdk.NewDecWithPrec(1, 1))
val1 := types.NewValidator(addrVals[0], PKs[0], types.Description{})
val2 := types.NewValidator(addrVals[1], PKs[1], types.Description{})
val1 := teststaking.NewValidator(t, addrVals[0], PKs[0])
val2 := teststaking.NewValidator(t, addrVals[1], PKs[1])
val1, _ = val1.SetInitialCommission(commission1)
val2, _ = val2.SetInitialCommission(commission2)
@ -1131,3 +1110,12 @@ func TestUpdateValidatorCommission(t *testing.T) {
}
}
}
func applyValidatorSetUpdates(t *testing.T, ctx sdk.Context, k keeper.Keeper, expectedUpdatesLen int) []abci.ValidatorUpdate {
updates, err := k.ApplyAndReturnValidatorSetUpdates(ctx)
require.NoError(t, err)
if expectedUpdatesLen >= 0 {
require.Equal(t, expectedUpdatesLen, len(updates), "%v", updates)
}
return updates
}

View File

@ -3,7 +3,7 @@ package v040
import (
"fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
v034staking "github.com/cosmos/cosmos-sdk/x/staking/legacy/v034"
v038staking "github.com/cosmos/cosmos-sdk/x/staking/legacy/v038"
v040staking "github.com/cosmos/cosmos-sdk/x/staking/types"
@ -42,9 +42,13 @@ func Migrate(stakingState v038staking.GenesisState) *v040staking.GenesisState {
newValidators := make([]v040staking.Validator, len(stakingState.Validators))
for i, oldValidator := range stakingState.Validators {
pkAny, err := codectypes.PackAny(oldValidator.ConsPubKey)
if err != nil {
panic(fmt.Sprintf("Can't pack validator consensus PK as Any: %s", err))
}
newValidators[i] = v040staking.Validator{
OperatorAddress: oldValidator.OperatorAddress.String(),
ConsensusPubkey: sdk.MustBech32ifyPubKey(sdk.Bech32PubKeyTypeConsPub, oldValidator.ConsPubKey),
ConsensusPubkey: pkAny,
Jailed: oldValidator.Jailed,
Status: migrateBondStatus(oldValidator.Status),
Tokens: oldValidator.Tokens,

View File

@ -43,7 +43,7 @@ func TestMigrate(t *testing.T) {
require.NoError(t, err)
// Make sure about:
// - consensus_pubkey: should be bech32 pubkey
// - consensus_pubkey: should be an any
// - validator's status should be 1 (new unbonded)
expected := `{
"delegations": [],
@ -69,7 +69,10 @@ func TestMigrate(t *testing.T) {
},
"update_time": "0001-01-01T00:00:00Z"
},
"consensus_pubkey": "cosmosvalconspub1zcjduepq9ymett3nlv6fytn7lqxzd3q3ckvd79eqlcf3wkhgamcl4rzghesq83ecpx",
"consensus_pubkey": {
"@type": "/cosmos.crypto.ed25519.PubKey",
"key": "KTeVrjP7NJIufvgMJsQRxZjfFyD+Exda6O7x+oxIvmA="
},
"delegator_shares": "0",
"description": {
"details": "",

View File

@ -37,7 +37,8 @@ func TestDecodeStore(t *testing.T) {
bondTime := time.Now().UTC()
val := types.NewValidator(valAddr1, delPk1, types.NewDescription("test", "test", "test", "test", "test"))
val, err := types.NewValidator(valAddr1, delPk1, types.NewDescription("test", "test", "test", "test", "test"))
require.NoError(t, err)
del := types.NewDelegation(delAddr1, valAddr1, sdk.OneDec())
ubd := types.NewUnbondingDelegation(delAddr1, valAddr1, 15, bondTime, sdk.OneInt())
red := types.NewRedelegation(delAddr1, valAddr1, valAddr1, 12, bondTime, sdk.OneInt(), sdk.OneDec())

View File

@ -84,7 +84,10 @@ func RandomizedGenState(simState *module.SimulationState) {
simulation.RandomDecAmount(simState.Rand, maxCommission),
)
validator := types.NewValidator(valAddr, simState.Accounts[i].ConsKey.PubKey(), types.Description{})
validator, err := types.NewValidator(valAddr, simState.Accounts[i].ConsKey.PubKey(), types.Description{})
if err != nil {
panic(err)
}
validator.Tokens = sdk.NewInt(simState.InitialStake)
validator.DelegatorShares = sdk.NewDec(simState.InitialStake)
validator.Commission = commission
@ -97,7 +100,7 @@ func RandomizedGenState(simState *module.SimulationState) {
stakingGenesis := types.NewGenesisState(params, validators, delegations)
bz, err := json.MarshalIndent(&stakingGenesis, "", " ")
bz, err := json.MarshalIndent(&stakingGenesis.Params, "", " ")
if err != nil {
panic(err)
}

View File

@ -9,6 +9,7 @@ import (
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec"
"github.com/cosmos/cosmos-sdk/types/module"
simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
"github.com/cosmos/cosmos-sdk/x/staking/simulation"
@ -19,6 +20,7 @@ import (
// Abonormal scenarios are not tested here.
func TestRandomizedGenState(t *testing.T) {
interfaceRegistry := codectypes.NewInterfaceRegistry()
cryptocodec.RegisterInterfaces(interfaceRegistry)
cdc := codec.NewProtoCodec(interfaceRegistry)
s := rand.NewSource(1)
@ -53,7 +55,7 @@ func TestRandomizedGenState(t *testing.T) {
require.Equal(t, "1000.000000000000000000", stakingGenesis.Delegations[0].Shares.String())
// check validators
require.Equal(t, "cosmosvaloper1ghekyjucln7y67ntx7cf27m9dpuxxemnsvnaes", stakingGenesis.Validators[2].GetOperator().String())
require.Equal(t, "cosmosvalconspub1zcjduepq280tm686ma80cva9z620dmknd9a858pd2zmq9ackfenfllecjxds0hg9n7", stakingGenesis.Validators[2].ConsensusPubkey)
require.Equal(t, []byte{0xa, 0x20, 0x51, 0xde, 0xbd, 0xe8, 0xfa, 0xdf, 0x4e, 0xfc, 0x33, 0xa5, 0x16, 0x94, 0xf6, 0xee, 0xd3, 0x69, 0x7a, 0x7a, 0x1c, 0x2d, 0x50, 0xb6, 0x2, 0xf7, 0x16, 0x4e, 0x66, 0x9f, 0xff, 0x38, 0x91, 0x9b}, stakingGenesis.Validators[2].ConsensusPubkey.Value)
require.Equal(t, false, stakingGenesis.Validators[2].Jailed)
require.Equal(t, "BOND_STATUS_UNBONDED", stakingGenesis.Validators[2].Status.String())
require.Equal(t, "1000", stakingGenesis.Validators[2].Tokens.String())

View File

@ -16,6 +16,7 @@ import (
distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types"
minttypes "github.com/cosmos/cosmos-sdk/x/mint/types"
"github.com/cosmos/cosmos-sdk/x/staking/simulation"
"github.com/cosmos/cosmos-sdk/x/staking/teststaking"
"github.com/cosmos/cosmos-sdk/x/staking/types"
)
@ -302,7 +303,7 @@ func getTestingValidator(t *testing.T, app *simapp.SimApp, ctx sdk.Context, acco
account := accounts[n]
valPubKey := account.PubKey
valAddr := sdk.ValAddress(account.PubKey.Address().Bytes())
validator := types.NewValidator(valAddr, valPubKey, types.Description{})
validator := teststaking.NewValidator(t, valAddr, valPubKey)
validator, err := validator.SetInitialCommission(commission)
require.NoError(t, err)

View File

@ -0,0 +1,18 @@
package teststaking
import (
"testing"
"github.com/stretchr/testify/require"
"github.com/tendermint/tendermint/crypto"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/staking/types"
)
// NewValidator is a testing helper method to create validators in tests
func NewValidator(t *testing.T, operator sdk.ValAddress, pubKey crypto.PubKey) types.Validator {
v, err := types.NewValidator(operator, pubKey, types.Description{})
require.NoError(t, err)
return v
}

View File

@ -1,14 +1,18 @@
package types
import (
"fmt"
"github.com/tendermint/tendermint/crypto"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/crypto/keys/ed25519"
sdk "github.com/cosmos/cosmos-sdk/types"
)
var (
pk1 = ed25519.GenPrivKey().PubKey()
pk1Any *codectypes.Any
pk2 = ed25519.GenPrivKey().PubKey()
pk3 = ed25519.GenPrivKey().PubKey()
addr1, _ = sdk.Bech32ifyAddressBytes(sdk.Bech32PrefixAccAddr, pk1.Address().Bytes())
@ -21,3 +25,11 @@ var (
emptyAddr sdk.ValAddress
emptyPubkey crypto.PubKey
)
func init() {
var err error
pk1Any, err = codectypes.PackAny(pk1)
if err != nil {
panic(fmt.Sprintf("Can't pack pk1 %t as Any", pk1))
}
}

View File

@ -21,8 +21,8 @@ type ValidatorI interface {
IsUnbonded() bool // check if has status unbonded
IsUnbonding() bool // check if has status unbonding
GetOperator() sdk.ValAddress // operator address to receive/return validators coins
GetConsPubKey() crypto.PubKey // validation consensus pubkey
GetConsAddr() sdk.ConsAddress // validation consensus address
TmConsPubKey() (crypto.PubKey, error) // validation consensus pubkey
GetConsAddr() (sdk.ConsAddress, error) // validation consensus address
GetTokens() sdk.Int // validation tokens
GetBondedTokens() sdk.Int // validator bonded tokens
GetConsensusPower() int64 // validation power in tendermint

View File

@ -4,6 +4,7 @@ import (
"encoding/json"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
)
// NewGenesisState creates a new GenesisState instanc e
@ -33,3 +34,13 @@ func GetGenesisStateFromAppState(cdc codec.JSONMarshaler, appState map[string]js
return &genesisState
}
// UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces
func (g GenesisState) UnpackInterfaces(c codectypes.AnyUnpacker) error {
for i := range g.Validators {
if err := g.Validators[i].UnpackInterfaces(c); err != nil {
return err
}
}
return nil
}

View File

@ -3,9 +3,11 @@ package types
import (
"sort"
"github.com/gogo/protobuf/proto"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
)
@ -20,11 +22,6 @@ func NewHistoricalInfo(header tmproto.Header, valSet Validators) HistoricalInfo
}
}
// MustMarshalHistoricalInfo wll marshal historical info and panic on error
func MustMarshalHistoricalInfo(cdc codec.BinaryMarshaler, hi HistoricalInfo) []byte {
return cdc.MustMarshalBinaryBare(&hi)
}
// MustUnmarshalHistoricalInfo wll unmarshal historical info and panic on error
func MustUnmarshalHistoricalInfo(cdc codec.BinaryMarshaler, value []byte) HistoricalInfo {
hi, err := UnmarshalHistoricalInfo(cdc, value)
@ -38,7 +35,6 @@ func MustUnmarshalHistoricalInfo(cdc codec.BinaryMarshaler, value []byte) Histor
// UnmarshalHistoricalInfo will unmarshal historical info and return any error
func UnmarshalHistoricalInfo(cdc codec.BinaryMarshaler, value []byte) (hi HistoricalInfo, err error) {
err = cdc.UnmarshalBinaryBare(value, &hi)
return hi, err
}
@ -54,3 +50,29 @@ func ValidateBasic(hi HistoricalInfo) error {
return nil
}
// Equal checks if receiver is equal to the parameter
func (hi *HistoricalInfo) Equal(hi2 *HistoricalInfo) bool {
if !proto.Equal(&hi.Header, &hi2.Header) {
return false
}
if len(hi.Valset) != len(hi2.Valset) {
return false
}
for i := range hi.Valset {
if !hi.Valset[i].Equal(&hi2.Valset[i]) {
return false
}
}
return true
}
// UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces
func (hi HistoricalInfo) UnpackInterfaces(c codectypes.AnyUnpacker) error {
for i := range hi.Valset {
if err := hi.Valset[i].UnpackInterfaces(c); err != nil {
return err
}
}
return nil
}

View File

@ -9,36 +9,41 @@ import (
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
)
var (
validators = []Validator{
NewValidator(valAddr1, pk1, Description{}),
NewValidator(valAddr2, pk2, Description{}),
NewValidator(valAddr3, pk3, Description{}),
var header = tmproto.Header{
ChainID: "hello",
Height: 5,
}
func createValidators(t *testing.T) []Validator {
return []Validator{
newValidator(t, valAddr1, pk1),
newValidator(t, valAddr2, pk2),
newValidator(t, valAddr3, pk3),
}
header = tmproto.Header{
ChainID: "hello",
Height: 5,
}
)
}
func TestHistoricalInfo(t *testing.T) {
validators := createValidators(t)
hi := NewHistoricalInfo(header, validators)
require.True(t, sort.IsSorted(Validators(hi.Valset)), "Validators are not sorted")
var value []byte
require.NotPanics(t, func() {
value = MustMarshalHistoricalInfo(ModuleCdc, hi)
value = ModuleCdc.MustMarshalBinaryBare(&hi)
})
require.NotNil(t, value, "Marshalled HistoricalInfo is nil")
recv, err := UnmarshalHistoricalInfo(ModuleCdc, value)
require.Nil(t, err, "Unmarshalling HistoricalInfo failed")
require.Equal(t, hi, recv, "Unmarshalled HistoricalInfo is different from original")
require.Equal(t, hi.Header, recv.Header)
for i := range hi.Valset {
require.True(t, hi.Valset[i].Equal(&recv.Valset[i]))
}
require.True(t, sort.IsSorted(Validators(hi.Valset)), "Validators are not sorted")
}
func TestValidateBasic(t *testing.T) {
validators := createValidators(t)
hi := HistoricalInfo{
Header: header,
}
@ -53,7 +58,6 @@ func TestValidateBasic(t *testing.T) {
validators[j] = it
})
}
hi = HistoricalInfo{
Header: header,
Valset: validators,

View File

@ -24,8 +24,7 @@ var (
func TestGetValidatorPowerRank(t *testing.T) {
valAddr1 := sdk.ValAddress(keysAddr1)
emptyDesc := Description{}
val1 := NewValidator(valAddr1, keysPK1, emptyDesc)
val1 := newValidator(t, valAddr1, keysPK1)
val1.Tokens = sdk.ZeroInt()
val2, val3, val4 := val1, val1, val1
val2.Tokens = sdk.TokensFromConsensusPower(1)

File diff suppressed because it is too large Load Diff

View File

@ -14,6 +14,7 @@ import (
proto "github.com/gogo/protobuf/proto"
github_com_gogo_protobuf_types "github.com/gogo/protobuf/types"
_ "github.com/golang/protobuf/ptypes/timestamp"
_ "github.com/regen-network/cosmos-proto"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
@ -466,59 +467,61 @@ func init() {
func init() { proto.RegisterFile("cosmos/staking/v1beta1/tx.proto", fileDescriptor_0926ef28816b35ab) }
var fileDescriptor_0926ef28816b35ab = []byte{
// 829 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xdc, 0x96, 0xcb, 0x4e, 0xdb, 0x4a,
0x1c, 0xc6, 0xe3, 0x24, 0xe4, 0x70, 0x06, 0x71, 0x33, 0x17, 0x05, 0x0b, 0xc5, 0xc8, 0x9c, 0x0b,
0x3a, 0x07, 0xec, 0x03, 0x47, 0x55, 0x25, 0x36, 0x15, 0x21, 0xad, 0x8a, 0xda, 0x6c, 0x0c, 0xed,
0xa2, 0xaa, 0x14, 0x39, 0xf6, 0xc4, 0xb5, 0x62, 0x7b, 0x82, 0x67, 0x82, 0x88, 0xd4, 0x07, 0xe8,
0x12, 0xa9, 0xbb, 0xae, 0x78, 0x87, 0xbe, 0x04, 0xab, 0x8a, 0x65, 0xd5, 0x45, 0x5a, 0x81, 0x54,
0xb1, 0xce, 0x13, 0x54, 0x1e, 0xdb, 0x13, 0xc7, 0xb9, 0x28, 0x42, 0xcd, 0xa6, 0x2b, 0xc8, 0xf8,
0x37, 0xdf, 0x78, 0xbe, 0xff, 0x37, 0xff, 0x31, 0x10, 0x75, 0x84, 0x1d, 0x84, 0x15, 0x4c, 0xb4,
0xba, 0xe5, 0x9a, 0xca, 0xd9, 0x6e, 0x15, 0x12, 0x6d, 0x57, 0x21, 0xe7, 0x72, 0xc3, 0x43, 0x04,
0xf1, 0xab, 0x01, 0x20, 0x87, 0x80, 0x1c, 0x02, 0xc2, 0xb2, 0x89, 0x4c, 0x44, 0x11, 0xc5, 0xff,
0x2f, 0xa0, 0x85, 0x42, 0x28, 0x57, 0xd5, 0x30, 0x64, 0x5a, 0x3a, 0xb2, 0xdc, 0xf0, 0xb9, 0x68,
0x22, 0x64, 0xda, 0x50, 0xa1, 0xbf, 0xaa, 0xcd, 0x9a, 0x42, 0x2c, 0x07, 0x62, 0xa2, 0x39, 0x8d,
0x10, 0xf8, 0x63, 0xc8, 0xfb, 0x44, 0xcb, 0x07, 0xd4, 0x5a, 0x52, 0x46, 0x73, 0x5b, 0xc1, 0x23,
0xe9, 0x63, 0x16, 0xf0, 0x65, 0x6c, 0x1e, 0x7a, 0x50, 0x23, 0xf0, 0xa5, 0x66, 0x5b, 0x86, 0x46,
0x90, 0xc7, 0x3f, 0x03, 0x33, 0x06, 0xc4, 0xba, 0x67, 0x35, 0x88, 0x85, 0xdc, 0x3c, 0xb7, 0xc1,
0x6d, 0xcd, 0xec, 0x6d, 0xca, 0x83, 0x37, 0x27, 0x97, 0xba, 0x68, 0x31, 0x7b, 0xd5, 0x16, 0x53,
0x6a, 0x7c, 0x36, 0x5f, 0x06, 0x40, 0x47, 0x8e, 0x63, 0x61, 0xec, 0x6b, 0xa5, 0xa9, 0xd6, 0xdf,
0xc3, 0xb4, 0x0e, 0x19, 0xa9, 0x6a, 0x04, 0xe2, 0x50, 0x2f, 0x26, 0xc0, 0xbf, 0x05, 0x4b, 0x8e,
0xe5, 0x56, 0x30, 0xb4, 0x6b, 0x15, 0x03, 0xda, 0xd0, 0xd4, 0xe8, 0x3b, 0x66, 0x36, 0xb8, 0xad,
0xdf, 0x8b, 0xcf, 0x7d, 0xfc, 0x4b, 0x5b, 0xfc, 0xcb, 0xb4, 0xc8, 0x9b, 0x66, 0x55, 0xd6, 0x91,
0xa3, 0x84, 0x1e, 0x05, 0x7f, 0x76, 0xb0, 0x51, 0x57, 0x48, 0xab, 0x01, 0xb1, 0x7c, 0xe4, 0x92,
0x4e, 0x5b, 0x14, 0x5a, 0x9a, 0x63, 0xef, 0x4b, 0x03, 0x24, 0x25, 0x75, 0xd1, 0xb1, 0xdc, 0x63,
0x68, 0xd7, 0x4a, 0x6c, 0x8c, 0x3f, 0x02, 0x8b, 0x21, 0x81, 0xbc, 0x8a, 0x66, 0x18, 0x1e, 0xc4,
0x38, 0x9f, 0xa5, 0x6b, 0xaf, 0x77, 0xda, 0x62, 0x3e, 0x50, 0xeb, 0x43, 0x24, 0x75, 0x81, 0x8d,
0x1d, 0x04, 0x43, 0xbe, 0xd4, 0x59, 0xe4, 0x38, 0x93, 0x9a, 0x4a, 0x4a, 0xf5, 0x21, 0x92, 0xba,
0xc0, 0xc6, 0x22, 0xa9, 0x6d, 0x90, 0x6b, 0x34, 0xab, 0x75, 0xd8, 0xca, 0xe7, 0xa8, 0xbd, 0xcb,
0x72, 0x50, 0x72, 0x39, 0x2a, 0xb9, 0x7c, 0xe0, 0xb6, 0xd4, 0x90, 0xe1, 0x1f, 0x80, 0xa9, 0x33,
0xcd, 0x6e, 0xc2, 0xfc, 0x6f, 0x14, 0x5e, 0x8b, 0x6a, 0xe1, 0xc7, 0x30, 0x56, 0x08, 0x2b, 0xaa,
0x66, 0x40, 0xef, 0x4f, 0xbf, 0xbb, 0x14, 0x53, 0x77, 0x97, 0x62, 0x4a, 0x5a, 0x07, 0x42, 0x7f,
0x68, 0x54, 0x88, 0x1b, 0xc8, 0xc5, 0x50, 0x7a, 0x9f, 0x01, 0x0b, 0x65, 0x6c, 0x3e, 0x36, 0x2c,
0x32, 0xa1, 0x44, 0x3d, 0x1a, 0xe4, 0x5c, 0x9a, 0x3a, 0xc7, 0x77, 0xda, 0xe2, 0x5c, 0xe0, 0xdc,
0x08, 0xbf, 0x1c, 0x30, 0xdf, 0x4d, 0x54, 0xc5, 0xd3, 0x08, 0x0c, 0xf3, 0x53, 0x1a, 0x33, 0x3b,
0x25, 0xa8, 0x77, 0xda, 0xe2, 0x6a, 0xb0, 0x50, 0x42, 0x4a, 0x52, 0xe7, 0xf4, 0x9e, 0x14, 0xf3,
0xe7, 0x83, 0x23, 0x1b, 0xc4, 0xe6, 0xe9, 0x04, 0xe3, 0x1a, 0xab, 0x99, 0x00, 0xf2, 0xc9, 0xa2,
0xb0, 0x8a, 0x7d, 0xe7, 0xc0, 0x4c, 0x19, 0x9b, 0xe1, 0x3c, 0x38, 0x38, 0xe4, 0xdc, 0xcf, 0x0b,
0x79, 0xfa, 0x5e, 0x21, 0x7f, 0x08, 0x72, 0x9a, 0x83, 0x9a, 0x2e, 0xa1, 0xb5, 0x1a, 0x23, 0xb7,
0x21, 0x1e, 0x33, 0x61, 0x05, 0x2c, 0xc5, 0xf6, 0xc9, 0xf6, 0xff, 0x29, 0x4d, 0xbb, 0x60, 0x11,
0x9a, 0x96, 0xab, 0x42, 0x63, 0x02, 0x36, 0x9c, 0x80, 0x95, 0xee, 0x1e, 0xb1, 0xa7, 0x27, 0xac,
0xd8, 0xe8, 0xb4, 0xc5, 0xf5, 0xa4, 0x15, 0x31, 0x4c, 0x52, 0x97, 0xd8, 0xf8, 0xb1, 0xa7, 0x0f,
0x54, 0x35, 0x30, 0x61, 0xaa, 0x99, 0xe1, 0xaa, 0x31, 0x2c, 0xae, 0x5a, 0xc2, 0xa4, 0xdf, 0xe7,
0xec, 0x7d, 0x7d, 0xae, 0xd3, 0x06, 0x91, 0xf0, 0x33, 0xb2, 0x9b, 0x2f, 0xd3, 0xd3, 0xd7, 0xb0,
0xa1, 0x1f, 0xd1, 0x8a, 0x7f, 0xa7, 0x85, 0xfd, 0x40, 0xe8, 0x6b, 0x5b, 0x27, 0xd1, 0x85, 0x57,
0x9c, 0xf6, 0x97, 0xba, 0xf8, 0x2a, 0x72, 0xf4, 0x74, 0x85, 0x93, 0xfd, 0xc7, 0xd2, 0x1d, 0x07,
0x66, 0xcb, 0xd8, 0x7c, 0xe1, 0x1a, 0xbf, 0x7c, 0x7e, 0x6b, 0x60, 0xa5, 0x67, 0xa7, 0x13, 0xb2,
0x74, 0xef, 0x43, 0x16, 0x64, 0xca, 0xd8, 0xe4, 0x4f, 0xc1, 0x7c, 0xf2, 0xd3, 0xe0, 0x9f, 0x61,
0x3d, 0xbb, 0xff, 0x46, 0x10, 0xf6, 0xc6, 0x67, 0xd9, 0x4e, 0xea, 0x60, 0xb6, 0xf7, 0xe6, 0xd8,
0x1a, 0x21, 0xd2, 0x43, 0x0a, 0xff, 0x8d, 0x4b, 0xb2, 0xc5, 0x5e, 0x83, 0x69, 0xd6, 0xf4, 0x36,
0x47, 0xcc, 0x8e, 0x20, 0xe1, 0xdf, 0x31, 0x20, 0xa6, 0x7e, 0x0a, 0xe6, 0x93, 0x2d, 0x65, 0x94,
0x7b, 0x09, 0x76, 0xa4, 0x7b, 0xc3, 0x8e, 0x56, 0x15, 0x80, 0xd8, 0x39, 0xf8, 0x73, 0x84, 0x42,
0x17, 0x13, 0x76, 0xc6, 0xc2, 0xa2, 0x35, 0x8a, 0x4f, 0xae, 0x6e, 0x0a, 0xdc, 0xf5, 0x4d, 0x81,
0xfb, 0x76, 0x53, 0xe0, 0x2e, 0x6e, 0x0b, 0xa9, 0xeb, 0xdb, 0x42, 0xea, 0xf3, 0x6d, 0x21, 0xf5,
0x6a, 0x7b, 0xe4, 0x35, 0x76, 0xce, 0x3e, 0x53, 0xe9, 0x85, 0x56, 0xcd, 0xd1, 0x48, 0xfe, 0xff,
0x23, 0x00, 0x00, 0xff, 0xff, 0x9f, 0x9d, 0x50, 0xee, 0x55, 0x0b, 0x00, 0x00,
// 850 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xdc, 0x96, 0xcb, 0x6e, 0xd3, 0x4c,
0x1c, 0xc5, 0xe3, 0x24, 0xcd, 0xd7, 0x6f, 0xaa, 0xde, 0xdc, 0x8b, 0x52, 0xab, 0x8a, 0x2b, 0x97,
0x4b, 0x05, 0xd4, 0xa1, 0x45, 0x08, 0xd4, 0x0d, 0x6a, 0x1a, 0x10, 0x55, 0x89, 0x84, 0xdc, 0xc2,
0x02, 0x21, 0x45, 0xbe, 0x4c, 0x8c, 0x15, 0xdb, 0x93, 0x7a, 0x26, 0x55, 0x23, 0xf1, 0x00, 0x2c,
0x2b, 0xb1, 0x63, 0xd5, 0x87, 0x60, 0xcf, 0xb6, 0x62, 0x81, 0xba, 0x44, 0x2c, 0x02, 0x6a, 0x25,
0xd4, 0x75, 0x9e, 0x00, 0xd9, 0x1e, 0x3b, 0x8e, 0x73, 0x51, 0x54, 0x91, 0x0d, 0xab, 0x36, 0x33,
0xbf, 0x39, 0x33, 0x73, 0xfe, 0x67, 0x66, 0x0c, 0x78, 0x15, 0x61, 0x0b, 0xe1, 0x3c, 0x26, 0x72,
0xd5, 0xb0, 0xf5, 0xfc, 0xd1, 0x86, 0x02, 0x89, 0xbc, 0x91, 0x27, 0xc7, 0x62, 0xcd, 0x41, 0x04,
0xb1, 0x8b, 0x3e, 0x20, 0x52, 0x40, 0xa4, 0x00, 0x37, 0xaf, 0x23, 0x1d, 0x79, 0x48, 0xde, 0xfd,
0xcf, 0xa7, 0xb9, 0x25, 0x9f, 0x2e, 0xfb, 0x1d, 0x74, 0xa8, 0xdf, 0x95, 0xa3, 0x33, 0x29, 0x32,
0x86, 0xe1, 0x34, 0x2a, 0x32, 0x6c, 0xda, 0xcf, 0xeb, 0x08, 0xe9, 0x26, 0xcc, 0x7b, 0xbf, 0x94,
0x7a, 0x25, 0x4f, 0x0c, 0x0b, 0x62, 0x22, 0x5b, 0x35, 0x0a, 0xdc, 0xe8, 0xb3, 0xd4, 0x60, 0x65,
0x74, 0x05, 0x71, 0x19, 0xd9, 0x6e, 0xf8, 0x5d, 0xc2, 0x97, 0x34, 0x60, 0x4b, 0x58, 0xdf, 0x71,
0xa0, 0x4c, 0xe0, 0x6b, 0xd9, 0x34, 0x34, 0x99, 0x20, 0x87, 0xdd, 0x03, 0x13, 0x1a, 0xc4, 0xaa,
0x63, 0xd4, 0x88, 0x81, 0xec, 0x2c, 0xb3, 0xc2, 0xac, 0x4d, 0x6c, 0xae, 0x8a, 0xbd, 0xf7, 0x2d,
0x16, 0xdb, 0x68, 0x21, 0x7d, 0xd6, 0xe4, 0x13, 0x52, 0x74, 0x34, 0x5b, 0x02, 0x40, 0x45, 0x96,
0x65, 0x60, 0xec, 0x6a, 0x25, 0x3d, 0xad, 0xdb, 0xfd, 0xb4, 0x76, 0x42, 0x52, 0x92, 0x09, 0xc4,
0x54, 0x2f, 0x22, 0xc0, 0xbe, 0x07, 0x73, 0x96, 0x61, 0x97, 0x31, 0x34, 0x2b, 0x65, 0x0d, 0x9a,
0x50, 0x97, 0xbd, 0x35, 0xa6, 0x56, 0x98, 0xb5, 0xff, 0x0b, 0x2f, 0x5c, 0xfc, 0x47, 0x93, 0xbf,
0xa5, 0x1b, 0xe4, 0x5d, 0x5d, 0x11, 0x55, 0x64, 0x51, 0xcb, 0xe9, 0x9f, 0x75, 0xac, 0x55, 0xf3,
0xa4, 0x51, 0x83, 0x58, 0xdc, 0xb5, 0x49, 0xab, 0xc9, 0x73, 0x0d, 0xd9, 0x32, 0xb7, 0x84, 0x1e,
0x92, 0x82, 0x34, 0x6b, 0x19, 0xf6, 0x3e, 0x34, 0x2b, 0xc5, 0xb0, 0x8d, 0xdd, 0x05, 0xb3, 0x94,
0x40, 0x4e, 0x59, 0xd6, 0x34, 0x07, 0x62, 0x9c, 0x4d, 0x7b, 0x73, 0x2f, 0xb7, 0x9a, 0x7c, 0xd6,
0x57, 0xeb, 0x42, 0x04, 0x69, 0x26, 0x6c, 0xdb, 0xf6, 0x9b, 0x5c, 0xa9, 0xa3, 0xc0, 0xf1, 0x50,
0x6a, 0x2c, 0x2e, 0xd5, 0x85, 0x08, 0xd2, 0x4c, 0xd8, 0x16, 0x48, 0x3d, 0x06, 0x99, 0x5a, 0x5d,
0xa9, 0xc2, 0x46, 0x36, 0xe3, 0xd9, 0x3b, 0x2f, 0xfa, 0x25, 0x17, 0x83, 0x92, 0x8b, 0xdb, 0x76,
0xa3, 0x00, 0xbe, 0x7e, 0x5e, 0xcf, 0xbc, 0xac, 0x2b, 0x7b, 0xb0, 0x21, 0x51, 0x9e, 0x7d, 0x08,
0xc6, 0x8e, 0x64, 0xb3, 0x0e, 0xb3, 0xff, 0x79, 0x03, 0x97, 0x82, 0xba, 0xb8, 0x91, 0x8c, 0x14,
0xc5, 0x08, 0x2a, 0xeb, 0xd3, 0x5b, 0xe3, 0x1f, 0x4e, 0xf9, 0xc4, 0xd5, 0x29, 0x9f, 0x10, 0x96,
0x01, 0xd7, 0x1d, 0x20, 0x09, 0xe2, 0x1a, 0xb2, 0x31, 0x14, 0x3e, 0xa6, 0xc0, 0x4c, 0x09, 0xeb,
0x4f, 0x35, 0x83, 0x8c, 0x28, 0x5d, 0x4f, 0x7a, 0xb9, 0x98, 0xf4, 0x5c, 0x64, 0x5b, 0x4d, 0x7e,
0xca, 0x77, 0x71, 0x80, 0x77, 0x16, 0x98, 0x6e, 0xa7, 0xab, 0xec, 0xc8, 0x04, 0xd2, 0x2c, 0x15,
0x87, 0xcc, 0x51, 0x11, 0xaa, 0xad, 0x26, 0xbf, 0xe8, 0x4f, 0x14, 0x93, 0x12, 0xa4, 0x29, 0xb5,
0x23, 0xd1, 0xec, 0x71, 0xef, 0xf8, 0xfa, 0x11, 0x7a, 0x3e, 0xc2, 0xe8, 0x46, 0x6a, 0xc6, 0x81,
0x6c, 0xbc, 0x28, 0x61, 0xc5, 0x7e, 0x33, 0x60, 0xa2, 0x84, 0x75, 0x3a, 0x0e, 0xf6, 0x0e, 0x3c,
0xf3, 0xf7, 0x02, 0x9f, 0xbc, 0x56, 0xe0, 0x1f, 0x81, 0x8c, 0x6c, 0xa1, 0xba, 0x4d, 0xbc, 0x5a,
0x0d, 0x91, 0x5b, 0x8a, 0x47, 0x4c, 0x58, 0x00, 0x73, 0x91, 0x7d, 0x86, 0xfb, 0xff, 0x96, 0xf4,
0x6e, 0xc4, 0x02, 0xd4, 0x0d, 0x5b, 0x82, 0xda, 0x08, 0x6c, 0x38, 0x00, 0x0b, 0xed, 0x3d, 0x62,
0x47, 0x8d, 0x59, 0xb1, 0xd2, 0x6a, 0xf2, 0xcb, 0x71, 0x2b, 0x22, 0x98, 0x20, 0xcd, 0x85, 0xed,
0xfb, 0x8e, 0xda, 0x53, 0x55, 0xc3, 0x24, 0x54, 0x4d, 0xf5, 0x57, 0x8d, 0x60, 0x51, 0xd5, 0x22,
0x26, 0xdd, 0x3e, 0xa7, 0xaf, 0xeb, 0x73, 0xd5, 0xbb, 0x20, 0x62, 0x7e, 0x06, 0x76, 0xb3, 0x25,
0xef, 0xf4, 0xd5, 0x4c, 0xe8, 0x46, 0xb4, 0xec, 0xbe, 0x6f, 0xf4, 0x3e, 0xe0, 0xba, 0xae, 0xb0,
0x83, 0xe0, 0xf1, 0x2b, 0x8c, 0xbb, 0x53, 0x9d, 0xfc, 0xe4, 0x19, 0xef, 0x74, 0xd1, 0xc1, 0x6e,
0xb7, 0x70, 0xc5, 0x80, 0xc9, 0x12, 0xd6, 0x5f, 0xd9, 0xda, 0x3f, 0x9f, 0xdf, 0x0a, 0x58, 0xe8,
0xd8, 0xe9, 0x88, 0x2c, 0xdd, 0xfc, 0x94, 0x06, 0xa9, 0x12, 0xd6, 0xd9, 0x43, 0x30, 0x1d, 0xff,
0x4c, 0xb8, 0xd3, 0xef, 0xce, 0xee, 0x7e, 0x11, 0xb8, 0xcd, 0xe1, 0xd9, 0x70, 0x27, 0x55, 0x30,
0xd9, 0xf9, 0x72, 0xac, 0x0d, 0x10, 0xe9, 0x20, 0xb9, 0xfb, 0xc3, 0x92, 0xe1, 0x64, 0x6f, 0xc1,
0x78, 0x78, 0xe9, 0xad, 0x0e, 0x18, 0x1d, 0x40, 0xdc, 0xdd, 0x21, 0xa0, 0x50, 0xfd, 0x10, 0x4c,
0xc7, 0xaf, 0x94, 0x41, 0xee, 0xc5, 0xd8, 0x81, 0xee, 0xf5, 0x3b, 0x5a, 0x0a, 0x00, 0x91, 0x73,
0x70, 0x73, 0x80, 0x42, 0x1b, 0xe3, 0xd6, 0x87, 0xc2, 0x82, 0x39, 0x0a, 0xcf, 0xce, 0x2e, 0x72,
0xcc, 0xf9, 0x45, 0x8e, 0xf9, 0x75, 0x91, 0x63, 0x4e, 0x2e, 0x73, 0x89, 0xf3, 0xcb, 0x5c, 0xe2,
0xfb, 0x65, 0x2e, 0xf1, 0xe6, 0xde, 0xc0, 0x67, 0xec, 0x38, 0xfc, 0x64, 0xf5, 0x1e, 0x34, 0x25,
0xe3, 0x45, 0xf2, 0xc1, 0x9f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x3e, 0xb3, 0xef, 0xab, 0x7c, 0x0b,
0x00, 0x00,
}
// Reference imports to suppress errors if they are not otherwise used.

View File

@ -14,6 +14,7 @@ import (
"gopkg.in/yaml.v2"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
@ -39,15 +40,15 @@ var _ ValidatorI = Validator{}
// NewValidator constructs a new Validator
//nolint:interfacer
func NewValidator(operator sdk.ValAddress, pubKey crypto.PubKey, description Description) Validator {
var pkStr string
if pubKey != nil {
pkStr = sdk.MustBech32ifyPubKey(sdk.Bech32PubKeyTypeConsPub, pubKey)
func NewValidator(operator sdk.ValAddress, pubKey crypto.PubKey, description Description) (Validator, error) {
pkAny, err := codectypes.PackAny(pubKey)
if err != nil {
return Validator{}, err
}
return Validator{
OperatorAddress: operator.String(),
ConsensusPubkey: pkStr,
ConsensusPubkey: pkAny,
Jailed: false,
Status: Unbonded,
Tokens: sdk.ZeroInt(),
@ -57,7 +58,7 @@ func NewValidator(operator sdk.ValAddress, pubKey crypto.PubKey, description Des
UnbondingTime: time.Unix(0, 0).UTC(),
Commission: NewCommission(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()),
MinSelfDelegation: sdk.OneInt(),
}
}, nil
}
// String implements the Stringer interface for a Validator object.
@ -87,13 +88,17 @@ func (v Validators) ToSDKValidators() (validators []ValidatorI) {
}
// ToTmValidators casts all validators to the corresponding tendermint type.
func (v Validators) ToTmValidators() []*tmtypes.Validator {
func (v Validators) ToTmValidators() ([]*tmtypes.Validator, error) {
validators := make([]*tmtypes.Validator, len(v))
var err error
for i, val := range v {
validators[i] = val.ToTmValidator()
validators[i], err = val.ToTmValidator()
if err != nil {
return nil, err
}
}
return validators
return validators, nil
}
// Sort Validators sorts validator array in ascending operator address order
@ -118,9 +123,19 @@ func (v Validators) Swap(i, j int) {
v[j] = it
}
// UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces
func (v Validators) UnpackInterfaces(c codectypes.AnyUnpacker) error {
for i := range v {
if err := v[i].UnpackInterfaces(c); err != nil {
return err
}
}
return nil
}
// return the redelegation
func MustMarshalValidator(cdc codec.BinaryMarshaler, validator Validator) []byte {
return cdc.MustMarshalBinaryBare(&validator)
func MustMarshalValidator(cdc codec.BinaryMarshaler, validator *Validator) []byte {
return cdc.MustMarshalBinaryBare(validator)
}
// unmarshal a redelegation from a store value
@ -233,7 +248,11 @@ func (d Description) EnsureLength() (Description, error) {
// ABCIValidatorUpdate returns an abci.ValidatorUpdate from a staking validator type
// with the full validator power
func (v Validator) ABCIValidatorUpdate() abci.ValidatorUpdate {
pk, err := encoding.PubKeyToProto(v.GetConsPubKey())
consPk, err := v.TmConsPubKey()
if err != nil {
panic(err)
}
pk, err := encoding.PubKeyToProto(consPk)
if err != nil {
panic(err)
}
@ -247,7 +266,11 @@ func (v Validator) ABCIValidatorUpdate() abci.ValidatorUpdate {
// ABCIValidatorUpdateZero returns an abci.ValidatorUpdate from a staking validator type
// with zero power used for validator updates.
func (v Validator) ABCIValidatorUpdateZero() abci.ValidatorUpdate {
pk, err := encoding.PubKeyToProto(v.GetConsPubKey())
consPk, err := v.TmConsPubKey()
if err != nil {
panic(err)
}
pk, err := encoding.PubKeyToProto(consPk)
if err != nil {
panic(err)
}
@ -259,8 +282,12 @@ func (v Validator) ABCIValidatorUpdateZero() abci.ValidatorUpdate {
}
// ToTmValidator casts an SDK validator to a tendermint type Validator.
func (v Validator) ToTmValidator() *tmtypes.Validator {
return tmtypes.NewValidator(v.GetConsPubKey(), v.ConsensusPower())
func (v Validator) ToTmValidator() (*tmtypes.Validator, error) {
consPk, err := v.TmConsPubKey()
if err != nil {
return nil, err
}
return tmtypes.NewValidator(consPk, v.ConsensusPower()), nil
}
// SetInitialCommission attempts to set a validator's initial commission. An
@ -415,14 +442,24 @@ func (v Validator) RemoveDelShares(delShares sdk.Dec) (Validator, sdk.Int) {
// MinEqual defines a more minimum set of equality conditions when comparing two
// validators.
func (v Validator) MinEqual(other Validator) bool {
return v.ConsensusPubkey == other.ConsensusPubkey &&
(v.OperatorAddress == other.OperatorAddress) &&
func (v *Validator) MinEqual(other *Validator) bool {
return v.OperatorAddress == other.OperatorAddress &&
v.Status == other.Status &&
v.Tokens.Equal(other.Tokens) &&
v.DelegatorShares.Equal(other.DelegatorShares) &&
v.Description == other.Description &&
v.Commission.Equal(other.Commission)
v.Description.Equal(other.Description) &&
v.Commission.Equal(other.Commission) &&
v.Jailed == other.Jailed &&
v.MinSelfDelegation.Equal(other.MinSelfDelegation) &&
v.ConsensusPubkey.Equal(other.ConsensusPubkey)
}
// Equal checks if the receiver equals the parameter
func (v *Validator) Equal(v2 *Validator) bool {
return v.MinEqual(v2) &&
v.UnbondingHeight == v2.UnbondingHeight &&
v.UnbondingTime.Equal(v2.UnbondingTime)
}
func (v Validator) IsJailed() bool { return v.Jailed }
@ -438,24 +475,43 @@ func (v Validator) GetOperator() sdk.ValAddress {
}
return addr
}
func (v Validator) GetConsPubKey() crypto.PubKey {
// TmConsPubKey casts Validator.ConsensusPubkey to crypto.PubKey
func (v Validator) TmConsPubKey() (crypto.PubKey, error) {
pk, ok := v.ConsensusPubkey.GetCachedValue().(cryptotypes.PubKey)
if !ok {
return nil, sdkerrors.Wrapf(sdkerrors.ErrInvalidType, "Expecting crypto.PubKey, got %T", pk)
}
// The way things are refactored now, v.ConsensusPubkey is sometimes a TM
// ed25519 pubkey, sometimes our own ed25519 pubkey. This is very ugly and
// inconsistent.
// Luckily, here we coerce it into a TM ed25519 pubkey always, as this
// pubkey will be passed into TM (eg calling encoding.PubKeyToProto).
pk := sdk.MustGetPubKeyFromBech32(sdk.Bech32PubKeyTypeConsPub, v.ConsensusPubkey)
if intoTmPk, ok := pk.(cryptotypes.IntoTmPubKey); ok {
return intoTmPk.AsTmPubKey()
return intoTmPk.AsTmPubKey(), nil
}
return pk
return nil, sdkerrors.Wrapf(sdkerrors.ErrInvalidPubKey, "Logic error: ConsensusPubkey must be an SDK key and SDK PubKey types must be convertible to tendermint PubKey; got: %T", pk)
}
func (v Validator) GetConsAddr() sdk.ConsAddress { return sdk.ConsAddress(v.GetConsPubKey().Address()) }
// GetConsAddr extracts Consensus key address
func (v Validator) GetConsAddr() (sdk.ConsAddress, error) {
pk, err := v.TmConsPubKey()
if err != nil {
return sdk.ConsAddress{}, err
}
return sdk.ConsAddress(pk.Address()), nil
}
func (v Validator) GetTokens() sdk.Int { return v.Tokens }
func (v Validator) GetBondedTokens() sdk.Int { return v.BondedTokens() }
func (v Validator) GetConsensusPower() int64 { return v.ConsensusPower() }
func (v Validator) GetCommission() sdk.Dec { return v.Commission.Rate }
func (v Validator) GetMinSelfDelegation() sdk.Int { return v.MinSelfDelegation }
func (v Validator) GetDelegatorShares() sdk.Dec { return v.DelegatorShares }
// UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces
func (v Validator) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error {
var pk crypto.PubKey
return unpacker.UnpackAny(v.ConsensusPubkey, &pk)
}

View File

@ -2,12 +2,12 @@ package types
import (
"math/rand"
"reflect"
"sort"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/tendermint/tendermint/crypto"
"github.com/tendermint/tendermint/crypto/encoding"
tmtypes "github.com/tendermint/tendermint/types"
@ -18,16 +18,12 @@ import (
)
func TestValidatorTestEquivalent(t *testing.T) {
val1 := NewValidator(valAddr1, pk1, Description{})
val2 := NewValidator(valAddr1, pk1, Description{})
val1 := newValidator(t, valAddr1, pk1)
val2 := newValidator(t, valAddr1, pk1)
require.Equal(t, val1.String(), val2.String())
ok := val1.String() == val2.String()
require.True(t, ok)
val2 = NewValidator(valAddr2, pk2, Description{})
ok = val1.String() == val2.String()
require.False(t, ok)
val2 = newValidator(t, valAddr2, pk2)
require.NotEqual(t, val1.String(), val2.String())
}
func TestUpdateDescription(t *testing.T) {
@ -60,33 +56,29 @@ func TestUpdateDescription(t *testing.T) {
}
func TestABCIValidatorUpdate(t *testing.T) {
validator := NewValidator(valAddr1, pk1, Description{})
validator := newValidator(t, valAddr1, pk1)
abciVal := validator.ABCIValidatorUpdate()
pk, err := encoding.PubKeyToProto(validator.GetConsPubKey())
consPk, err := validator.TmConsPubKey()
require.NoError(t, err)
pk, err := encoding.PubKeyToProto(consPk)
require.NoError(t, err)
require.Equal(t, pk, abciVal.PubKey)
require.Equal(t, validator.BondedTokens().Int64(), abciVal.Power)
}
func TestABCIValidatorUpdateZero(t *testing.T) {
validator := NewValidator(valAddr1, pk1, Description{})
validator := newValidator(t, valAddr1, pk1)
abciVal := validator.ABCIValidatorUpdateZero()
pk, err := encoding.PubKeyToProto(validator.GetConsPubKey())
consPk, err := validator.TmConsPubKey()
require.NoError(t, err)
pk, err := encoding.PubKeyToProto(consPk)
require.NoError(t, err)
require.Equal(t, pk, abciVal.PubKey)
require.Equal(t, int64(0), abciVal.Power)
}
func TestShareTokens(t *testing.T) {
validator := Validator{
OperatorAddress: valAddr1.String(),
ConsensusPubkey: sdk.MustBech32ifyPubKey(sdk.Bech32PubKeyTypeConsPub, pk1),
Status: Bonded,
Tokens: sdk.NewInt(100),
DelegatorShares: sdk.NewDec(100),
}
validator := mkValidator(100, sdk.NewDec(100))
assert.True(sdk.DecEq(t, sdk.NewDec(50), validator.TokensFromShares(sdk.NewDec(50))))
validator.Tokens = sdk.NewInt(50)
@ -95,16 +87,7 @@ func TestShareTokens(t *testing.T) {
}
func TestRemoveTokens(t *testing.T) {
valPubKey := pk1
valAddr := sdk.ValAddress(valPubKey.Address().Bytes())
validator := Validator{
OperatorAddress: valAddr.String(),
ConsensusPubkey: sdk.MustBech32ifyPubKey(sdk.Bech32PubKeyTypeConsPub, valPubKey),
Status: Bonded,
Tokens: sdk.NewInt(100),
DelegatorShares: sdk.NewDec(100),
}
validator := mkValidator(100, sdk.NewDec(100))
// remove tokens and test check everything
validator = validator.RemoveTokens(sdk.NewInt(10))
@ -120,7 +103,7 @@ func TestRemoveTokens(t *testing.T) {
}
func TestAddTokensValidatorBonded(t *testing.T) {
validator := NewValidator(sdk.ValAddress(pk1.Address().Bytes()), pk1, Description{})
validator := newValidator(t, valAddr1, pk1)
validator = validator.UpdateStatus(Bonded)
validator, delShares := validator.AddTokensFromDel(sdk.NewInt(10))
@ -130,7 +113,7 @@ func TestAddTokensValidatorBonded(t *testing.T) {
}
func TestAddTokensValidatorUnbonding(t *testing.T) {
validator := NewValidator(sdk.ValAddress(pk1.Address().Bytes()), pk1, Description{})
validator := newValidator(t, valAddr1, pk1)
validator = validator.UpdateStatus(Unbonding)
validator, delShares := validator.AddTokensFromDel(sdk.NewInt(10))
@ -142,7 +125,7 @@ func TestAddTokensValidatorUnbonding(t *testing.T) {
func TestAddTokensValidatorUnbonded(t *testing.T) {
validator := NewValidator(sdk.ValAddress(pk1.Address().Bytes()), pk1, Description{})
validator := newValidator(t, valAddr1, pk1)
validator = validator.UpdateStatus(Unbonded)
validator, delShares := validator.AddTokensFromDel(sdk.NewInt(10))
@ -155,8 +138,8 @@ func TestAddTokensValidatorUnbonded(t *testing.T) {
// TODO refactor to make simpler like the AddToken tests above
func TestRemoveDelShares(t *testing.T) {
valA := Validator{
OperatorAddress: sdk.ValAddress(pk1.Address().Bytes()).String(),
ConsensusPubkey: sdk.MustBech32ifyPubKey(sdk.Bech32PubKeyTypeConsPub, pk1),
OperatorAddress: valAddr1.String(),
ConsensusPubkey: pk1Any,
Status: Bonded,
Tokens: sdk.NewInt(100),
DelegatorShares: sdk.NewDec(100),
@ -169,24 +152,14 @@ func TestRemoveDelShares(t *testing.T) {
require.Equal(t, int64(90), valB.BondedTokens().Int64())
// specific case from random tests
poolTokens := sdk.NewInt(5102)
delShares := sdk.NewDec(115)
validator := Validator{
OperatorAddress: sdk.ValAddress(pk1.Address().Bytes()).String(),
ConsensusPubkey: sdk.MustBech32ifyPubKey(sdk.Bech32PubKeyTypeConsPub, pk1),
Status: Bonded,
Tokens: poolTokens,
DelegatorShares: delShares,
}
shares := sdk.NewDec(29)
_, tokens := validator.RemoveDelShares(shares)
validator := mkValidator(5102, sdk.NewDec(115))
_, tokens := validator.RemoveDelShares(sdk.NewDec(29))
require.True(sdk.IntEq(t, sdk.NewInt(1286), tokens))
}
func TestAddTokensFromDel(t *testing.T) {
validator := NewValidator(sdk.ValAddress(pk1.Address().Bytes()), pk1, Description{})
validator := newValidator(t, valAddr1, pk1)
validator, shares := validator.AddTokensFromDel(sdk.NewInt(6))
require.True(sdk.DecEq(t, sdk.NewDec(6), shares))
@ -200,7 +173,7 @@ func TestAddTokensFromDel(t *testing.T) {
}
func TestUpdateStatus(t *testing.T) {
validator := NewValidator(sdk.ValAddress(pk1.Address().Bytes()), pk1, Description{})
validator := newValidator(t, valAddr1, pk1)
validator, _ = validator.AddTokensFromDel(sdk.NewInt(100))
require.Equal(t, Unbonded, validator.Status)
require.Equal(t, int64(100), validator.Tokens.Int64())
@ -220,14 +193,7 @@ func TestUpdateStatus(t *testing.T) {
func TestPossibleOverflow(t *testing.T) {
delShares := sdk.NewDec(391432570689183511).Quo(sdk.NewDec(40113011844664))
validator := Validator{
OperatorAddress: sdk.ValAddress(pk1.Address().Bytes()).String(),
ConsensusPubkey: sdk.MustBech32ifyPubKey(sdk.Bech32PubKeyTypeConsPub, pk1),
Status: Bonded,
Tokens: sdk.NewInt(2159),
DelegatorShares: delShares,
}
validator := mkValidator(2159, delShares)
newValidator, _ := validator.AddTokensFromDel(sdk.NewInt(71))
require.False(t, newValidator.DelegatorShares.IsNegative())
@ -235,19 +201,19 @@ func TestPossibleOverflow(t *testing.T) {
}
func TestValidatorMarshalUnmarshalJSON(t *testing.T) {
validator := NewValidator(valAddr1, pk1, Description{})
validator := newValidator(t, valAddr1, pk1)
js, err := legacy.Cdc.MarshalJSON(validator)
require.NoError(t, err)
require.NotEmpty(t, js)
require.Contains(t, string(js), "\"consensus_pubkey\":\"cosmosvalconspu")
require.Contains(t, string(js), "\"consensus_pubkey\":{\"type\":\"cosmos/PubKeyEd25519\"")
got := &Validator{}
err = legacy.Cdc.UnmarshalJSON(js, got)
assert.NoError(t, err)
assert.Equal(t, validator, *got)
assert.True(t, validator.Equal(got))
}
func TestValidatorSetInitialCommission(t *testing.T) {
val := NewValidator(valAddr1, pk1, Description{})
val := newValidator(t, valAddr1, pk1)
testCases := []struct {
validator Validator
commission Commission
@ -288,7 +254,7 @@ func TestValidatorsSortDeterminism(t *testing.T) {
// Create random validator slice
for i := range vals {
pk := ed25519.GenPrivKey().PubKey()
vals[i] = NewValidator(sdk.ValAddress(pk.Address()), pk, Description{})
vals[i] = newValidator(t, sdk.ValAddress(pk.Address()), pk)
}
// Save sorted copy
@ -304,7 +270,7 @@ func TestValidatorsSortDeterminism(t *testing.T) {
})
Validators(vals).Sort()
require.True(t, reflect.DeepEqual(sortedVals, vals), "Validator sort returned different slices")
require.Equal(t, sortedVals, vals, "Validator sort returned different slices")
}
}
@ -314,14 +280,15 @@ func TestValidatorToTm(t *testing.T) {
for i := range vals {
pk := ed25519.GenPrivKey().PubKey()
val := NewValidator(sdk.ValAddress(pk.Address()), pk, Description{})
val := newValidator(t, sdk.ValAddress(pk.Address()), pk)
val.Status = Bonded
val.Tokens = sdk.NewInt(rand.Int63())
vals[i] = val
expected[i] = tmtypes.NewValidator(pk.(cryptotypes.IntoTmPubKey).AsTmPubKey(), val.ConsensusPower())
}
require.Equal(t, expected, vals.ToTmValidators())
vs, err := vals.ToTmValidators()
require.NoError(t, err)
require.Equal(t, expected, vs)
}
func TestBondStatus(t *testing.T) {
@ -334,3 +301,20 @@ func TestBondStatus(t *testing.T) {
require.Equal(t, BondStatusBonded, Bonded.String())
require.Equal(t, BondStatusUnbonding, Unbonding.String())
}
func mkValidator(tokens int64, shares sdk.Dec) Validator {
return Validator{
OperatorAddress: valAddr1.String(),
ConsensusPubkey: pk1Any,
Status: Bonded,
Tokens: sdk.NewInt(tokens),
DelegatorShares: shares,
}
}
// Creates a new validators and asserts the error check.
func newValidator(t *testing.T, operator sdk.ValAddress, pubKey crypto.PubKey) Validator {
v, err := NewValidator(operator, pubKey, Description{})
require.NoError(t, err)
return v
}

View File

@ -236,17 +236,17 @@ func TestPlanStringer(t *testing.T) {
require.Equal(t, `Upgrade Plan
Name: test
Time: 2020-01-01T00:00:00Z
Info:
Info: .
Upgraded IBC Client: no upgraded client provided`, types.Plan{Name: "test", Time: ti}.String())
require.Equal(t, `Upgrade Plan
Name: test
Height: 100
Info:
Info: .
Upgraded IBC Client: no upgraded client provided`, types.Plan{Name: "test", Height: 100}.String())
require.Equal(t, fmt.Sprintf(`Upgrade Plan
Name: test
Height: 100
Info:
Info: .
Upgraded IBC Client: %s`, clientState), types.Plan{Name: "test", Height: 100, UpgradedClientState: cs}.String())
}

View File

@ -28,7 +28,7 @@ func (p Plan) String() string {
return fmt.Sprintf(`Upgrade Plan
Name: %s
%s
Info: %s
Info: %s.
Upgraded IBC Client: %s`, p.Name, dueUp, p.Info, upgradedClientStr)
}

View File

@ -38,7 +38,7 @@ func TestPlanString(t *testing.T) {
Info: "https://foo.bar",
Time: mustParseTime("2019-07-08T11:33:55Z"),
},
expect: "Upgrade Plan\n Name: due_time\n Time: 2019-07-08T11:33:55Z\n Info: https://foo.bar\n Upgraded IBC Client: no upgraded client provided",
expect: "Upgrade Plan\n Name: due_time\n Time: 2019-07-08T11:33:55Z\n Info: https://foo.bar.\n Upgraded IBC Client: no upgraded client provided",
},
"with height": {
p: Plan{
@ -46,7 +46,7 @@ func TestPlanString(t *testing.T) {
Info: "https://foo.bar/baz",
Height: 7890,
},
expect: "Upgrade Plan\n Name: by height\n Height: 7890\n Info: https://foo.bar/baz\n Upgraded IBC Client: no upgraded client provided",
expect: "Upgrade Plan\n Name: by height\n Height: 7890\n Info: https://foo.bar/baz.\n Upgraded IBC Client: no upgraded client provided",
},
"with IBC client": {
p: Plan{
@ -55,14 +55,14 @@ func TestPlanString(t *testing.T) {
Height: 7890,
UpgradedClientState: cs,
},
expect: fmt.Sprintf("Upgrade Plan\n Name: by height\n Height: 7890\n Info: https://foo.bar/baz\n Upgraded IBC Client: %s", &ibctmtypes.ClientState{}),
expect: fmt.Sprintf("Upgrade Plan\n Name: by height\n Height: 7890\n Info: https://foo.bar/baz.\n Upgraded IBC Client: %s", &ibctmtypes.ClientState{}),
},
"neither": {
p: Plan{
Name: "almost-empty",
},
expect: "Upgrade Plan\n Name: almost-empty\n Height: 0\n Info: \n Upgraded IBC Client: no upgraded client provided",
expect: "Upgrade Plan\n Name: almost-empty\n Height: 0\n Info: .\n Upgraded IBC Client: no upgraded client provided",
},
}