tendermint/types/validator.go

98 lines
2.2 KiB
Go
Raw Normal View History

package types
import (
"bytes"
2014-10-18 01:42:33 -07:00
"fmt"
2015-11-01 11:34:08 -08:00
"github.com/tendermint/go-crypto"
2017-04-27 16:01:18 -07:00
cmn "github.com/tendermint/tmlibs/common"
)
// Volatile state for each Validator
2017-05-16 12:31:19 -07:00
// NOTE: The Accum is not included in Validator.Hash();
// make sure to update that method if changes are made here
type Validator struct {
Address Address `json:"address"`
PubKey crypto.PubKey `json:"pub_key"`
VotingPower int64 `json:"voting_power"`
2017-05-16 12:31:19 -07:00
Accum int64 `json:"accum"`
}
2016-11-19 16:32:35 -08:00
func NewValidator(pubKey crypto.PubKey, votingPower int64) *Validator {
return &Validator{
Address: pubKey.Address(),
PubKey: pubKey,
VotingPower: votingPower,
Accum: 0,
}
}
// Creates a new copy of the validator so we can mutate accum.
// Panics if the validator is nil.
func (v *Validator) Copy() *Validator {
vCopy := *v
return &vCopy
}
2014-10-11 21:27:58 -07:00
// Returns the one with higher Accum.
func (v *Validator) CompareAccum(other *Validator) *Validator {
if v == nil {
return other
2014-09-14 15:37:32 -07:00
}
2014-10-11 21:27:58 -07:00
if v.Accum > other.Accum {
return v
} else if v.Accum < other.Accum {
return other
} else {
if bytes.Compare(v.Address, other.Address) < 0 {
2014-10-11 21:27:58 -07:00
return v
} else if bytes.Compare(v.Address, other.Address) > 0 {
2014-10-11 21:27:58 -07:00
return other
} else {
2017-04-27 16:01:18 -07:00
cmn.PanicSanity("Cannot compare identical validators")
2015-07-19 16:42:52 -07:00
return nil
}
}
}
2014-10-18 01:42:33 -07:00
func (v *Validator) String() string {
if v == nil {
return "nil-Validator"
}
return fmt.Sprintf("Validator{%v %v VP:%v A:%v}",
v.Address,
v.PubKey,
v.VotingPower,
v.Accum)
}
2017-05-16 12:31:19 -07:00
// Hash computes the unique ID of a validator with a given voting power.
2017-09-05 13:52:25 -07:00
// It excludes the Accum value, which changes with every round.
func (v *Validator) Hash() []byte {
return aminoHash(struct {
Address Address
2017-05-16 12:31:19 -07:00
PubKey crypto.PubKey
VotingPower int64
}{
v.Address,
v.PubKey,
v.VotingPower,
})
2014-10-18 01:42:33 -07:00
}
//----------------------------------------
// RandValidator
2017-09-22 09:00:37 -07:00
// RandValidator returns a randomized validator, useful for testing.
// UNSTABLE
func RandValidator(randPower bool, minPower int64) (*Validator, PrivValidator) {
privVal := NewMockPV()
votePower := minPower
if randPower {
2017-04-27 16:01:18 -07:00
votePower += int64(cmn.RandUint32())
}
val := NewValidator(privVal.GetPubKey(), votePower)
return val, privVal
}