tendermint/state/validator_set.go

303 lines
8.8 KiB
Go
Raw Normal View History

2014-10-11 21:27:58 -07:00
package state
import (
"bytes"
2014-10-18 01:42:33 -07:00
"fmt"
"sort"
2014-10-18 01:42:33 -07:00
"strings"
2014-10-11 21:27:58 -07:00
2015-04-01 17:30:16 -07:00
"github.com/tendermint/tendermint/account"
. "github.com/tendermint/tendermint/common"
"github.com/tendermint/tendermint/merkle"
"github.com/tendermint/tendermint/types"
2014-10-11 21:27:58 -07:00
)
// ValidatorSet represent a set of *Validator at a given height.
// The validators can be fetched by address or index.
2014-12-23 23:20:49 -08:00
// The index is in order of .Address, so the indices are fixed
// for all rounds of a given blockchain height.
// On the other hand, the .AccumPower of each validator and
// the designated .Proposer() of a set changes every round,
// upon calling .IncrementAccum().
// NOTE: Not goroutine-safe.
// NOTE: All get/set to validators should copy the value for safety.
// TODO: consider validator Accum overflow
// TODO: replace validators []*Validator with github.com/jaekwon/go-ibbs?
2014-10-11 21:27:58 -07:00
type ValidatorSet struct {
2014-12-17 01:37:13 -08:00
Validators []*Validator // NOTE: persisted via reflect, must be exported.
2014-12-17 01:37:13 -08:00
// cached (unexported)
proposer *Validator
2014-10-11 21:27:58 -07:00
totalVotingPower uint64
}
func NewValidatorSet(vals []*Validator) *ValidatorSet {
validators := make([]*Validator, len(vals))
for i, val := range vals {
validators[i] = val.Copy()
2014-10-11 21:27:58 -07:00
}
sort.Sort(ValidatorsByAddress(validators))
2014-10-11 21:27:58 -07:00
return &ValidatorSet{
2014-12-17 01:37:13 -08:00
Validators: validators,
2014-10-11 21:27:58 -07:00
}
}
// TODO: mind the overflow when times and votingPower shares too large.
func (valSet *ValidatorSet) IncrementAccum(times uint) {
// Add VotingPower * times to each validator and order into heap.
validatorsHeap := NewHeap()
2014-12-17 01:37:13 -08:00
for _, val := range valSet.Validators {
val.Accum += int64(val.VotingPower) * int64(times) // TODO: mind overflow
validatorsHeap.Push(val, accumComparable(val.Accum))
}
// Decrement the validator with most accum, times times.
for i := uint(0); i < times; i++ {
mostest := validatorsHeap.Peek().(*Validator)
if i == times-1 {
valSet.proposer = mostest
}
mostest.Accum -= int64(valSet.TotalVotingPower())
validatorsHeap.Update(mostest, accumComparable(mostest.Accum))
}
2014-10-11 21:27:58 -07:00
}
func (valSet *ValidatorSet) Copy() *ValidatorSet {
2014-12-17 01:37:13 -08:00
validators := make([]*Validator, len(valSet.Validators))
for i, val := range valSet.Validators {
// NOTE: must copy, since IncrementAccum updates in place.
validators[i] = val.Copy()
}
2014-10-11 21:27:58 -07:00
return &ValidatorSet{
2014-12-17 01:37:13 -08:00
Validators: validators,
proposer: valSet.proposer,
totalVotingPower: valSet.totalVotingPower,
2014-10-11 21:27:58 -07:00
}
}
func (valSet *ValidatorSet) HasAddress(address []byte) bool {
2014-12-17 01:37:13 -08:00
idx := sort.Search(len(valSet.Validators), func(i int) bool {
return bytes.Compare(address, valSet.Validators[i].Address) <= 0
})
2014-12-17 01:37:13 -08:00
return idx != len(valSet.Validators) && bytes.Compare(valSet.Validators[idx].Address, address) == 0
2014-10-11 21:27:58 -07:00
}
func (valSet *ValidatorSet) GetByAddress(address []byte) (index uint, val *Validator) {
2014-12-17 01:37:13 -08:00
idx := sort.Search(len(valSet.Validators), func(i int) bool {
return bytes.Compare(address, valSet.Validators[i].Address) <= 0
})
2014-12-17 01:37:13 -08:00
if idx != len(valSet.Validators) && bytes.Compare(valSet.Validators[idx].Address, address) == 0 {
return uint(idx), valSet.Validators[idx].Copy()
} else {
return 0, nil
}
}
func (valSet *ValidatorSet) GetByIndex(index uint) (address []byte, val *Validator) {
2014-12-17 01:37:13 -08:00
val = valSet.Validators[index]
return val.Address, val.Copy()
2014-10-11 21:27:58 -07:00
}
func (valSet *ValidatorSet) Size() uint {
2014-12-17 01:37:13 -08:00
return uint(len(valSet.Validators))
2014-10-11 21:27:58 -07:00
}
func (valSet *ValidatorSet) TotalVotingPower() uint64 {
if valSet.totalVotingPower == 0 {
2014-12-17 01:37:13 -08:00
for _, val := range valSet.Validators {
valSet.totalVotingPower += val.VotingPower
}
}
return valSet.totalVotingPower
2014-10-11 21:27:58 -07:00
}
func (valSet *ValidatorSet) Proposer() (proposer *Validator) {
if valSet.proposer == nil {
2014-12-17 01:37:13 -08:00
for _, val := range valSet.Validators {
valSet.proposer = valSet.proposer.CompareAccum(val)
}
}
return valSet.proposer.Copy()
2014-10-11 21:27:58 -07:00
}
func (valSet *ValidatorSet) Hash() []byte {
2014-12-17 01:37:13 -08:00
if len(valSet.Validators) == 0 {
return nil
}
2014-12-17 01:37:13 -08:00
hashables := make([]merkle.Hashable, len(valSet.Validators))
for i, val := range valSet.Validators {
hashables[i] = val
}
2015-06-18 20:19:39 -07:00
return merkle.SimpleHashFromHashables(hashables)
2014-10-11 21:27:58 -07:00
}
func (valSet *ValidatorSet) Add(val *Validator) (added bool) {
val = val.Copy()
2014-12-17 01:37:13 -08:00
idx := sort.Search(len(valSet.Validators), func(i int) bool {
return bytes.Compare(val.Address, valSet.Validators[i].Address) <= 0
})
2014-12-17 01:37:13 -08:00
if idx == len(valSet.Validators) {
valSet.Validators = append(valSet.Validators, val)
// Invalidate cache
valSet.proposer = nil
valSet.totalVotingPower = 0
return true
2014-12-17 01:37:13 -08:00
} else if bytes.Compare(valSet.Validators[idx].Address, val.Address) == 0 {
2014-10-11 21:27:58 -07:00
return false
} else {
2015-01-16 01:06:15 -08:00
newValidators := make([]*Validator, len(valSet.Validators)+1)
copy(newValidators[:idx], valSet.Validators[:idx])
newValidators[idx] = val
copy(newValidators[idx+1:], valSet.Validators[idx:])
2014-12-17 01:37:13 -08:00
valSet.Validators = newValidators
// Invalidate cache
valSet.proposer = nil
valSet.totalVotingPower = 0
return true
2014-10-11 21:27:58 -07:00
}
2014-10-12 21:14:10 -07:00
}
func (valSet *ValidatorSet) Update(val *Validator) (updated bool) {
index, sameVal := valSet.GetByAddress(val.Address)
if sameVal == nil {
2014-10-12 21:14:10 -07:00
return false
} else {
2014-12-17 01:37:13 -08:00
valSet.Validators[index] = val.Copy()
// Invalidate cache
valSet.proposer = nil
valSet.totalVotingPower = 0
return true
2014-10-12 21:14:10 -07:00
}
2014-10-11 21:27:58 -07:00
}
func (valSet *ValidatorSet) Remove(address []byte) (val *Validator, removed bool) {
2014-12-17 01:37:13 -08:00
idx := sort.Search(len(valSet.Validators), func(i int) bool {
return bytes.Compare(address, valSet.Validators[i].Address) <= 0
})
2014-12-17 01:37:13 -08:00
if idx == len(valSet.Validators) || bytes.Compare(valSet.Validators[idx].Address, address) != 0 {
return nil, false
} else {
2014-12-17 01:37:13 -08:00
removedVal := valSet.Validators[idx]
newValidators := valSet.Validators[:idx]
if idx+1 < len(valSet.Validators) {
newValidators = append(newValidators, valSet.Validators[idx+1:]...)
}
2014-12-17 01:37:13 -08:00
valSet.Validators = newValidators
// Invalidate cache
valSet.proposer = nil
valSet.totalVotingPower = 0
return removedVal, true
}
2014-10-12 21:14:10 -07:00
}
func (valSet *ValidatorSet) Iterate(fn func(index uint, val *Validator) bool) {
2014-12-17 01:37:13 -08:00
for i, val := range valSet.Validators {
stop := fn(uint(i), val.Copy())
if stop {
break
}
}
2014-10-11 21:27:58 -07:00
}
2014-10-18 01:42:33 -07:00
// Verify that +2/3 of the set had signed the given signBytes
2015-06-21 19:11:21 -07:00
func (valSet *ValidatorSet) VerifyValidation(chainID string,
hash []byte, parts types.PartSetHeader, height uint, v *types.Validation) error {
2015-06-05 14:15:40 -07:00
if valSet.Size() != uint(len(v.Precommits)) {
2015-06-21 19:11:21 -07:00
return fmt.Errorf("Invalid validation -- wrong set size: %v vs %v", valSet.Size(), len(v.Precommits))
}
if height != v.Height() {
return fmt.Errorf("Invalid validation -- wrong height: %v vs %v", height, v.Height())
}
talliedVotingPower := uint64(0)
2015-06-21 19:11:21 -07:00
round := v.Round()
2015-06-05 14:15:40 -07:00
for idx, precommit := range v.Precommits {
2015-06-21 19:11:21 -07:00
// may be nil if validator skipped.
if precommit == nil {
continue
}
2015-06-21 19:11:21 -07:00
if precommit.Height != height {
return fmt.Errorf("Invalid validation -- wrong height: %v vs %v", height, precommit.Height)
}
2015-06-21 19:11:21 -07:00
if precommit.Round != round {
return fmt.Errorf("Invalid validation -- wrong round: %v vs %v", round, precommit.Round)
}
if precommit.Type != types.VoteTypePrecommit {
return fmt.Errorf("Invalid validation -- not precommit @ index %v", idx)
}
_, val := valSet.GetByIndex(uint(idx))
// Validate signature
precommitSignBytes := account.SignBytes(chainID, precommit)
2015-06-05 14:15:40 -07:00
if !val.PubKey.VerifyBytes(precommitSignBytes, precommit.Signature) {
2015-06-21 19:11:21 -07:00
return fmt.Errorf("Invalid validation -- invalid signature: %v", precommit)
}
2015-06-21 19:11:21 -07:00
if !bytes.Equal(precommit.BlockHash, hash) {
continue // Not an error, but doesn't count
}
if !parts.Equals(precommit.BlockParts) {
continue // Not an error, but doesn't count
}
// Good precommit!
talliedVotingPower += val.VotingPower
}
if talliedVotingPower > valSet.TotalVotingPower()*2/3 {
return nil
} else {
2015-06-21 19:11:21 -07:00
return fmt.Errorf("Invalid validation -- insufficient voting power: got %v, needed %v",
talliedVotingPower, (valSet.TotalVotingPower()*2/3 + 1))
}
}
func (valSet *ValidatorSet) String() string {
2014-12-23 01:35:54 -08:00
return valSet.StringIndented("")
2014-10-21 01:18:46 -07:00
}
2014-12-23 01:35:54 -08:00
func (valSet *ValidatorSet) StringIndented(indent string) string {
2014-10-18 01:42:33 -07:00
valStrings := []string{}
valSet.Iterate(func(index uint, val *Validator) bool {
2014-10-18 01:42:33 -07:00
valStrings = append(valStrings, val.String())
return false
})
return fmt.Sprintf(`ValidatorSet{
%s Proposer: %v
%s Validators:
%s %v
%s}`,
indent, valSet.Proposer().String(),
2014-10-18 01:42:33 -07:00
indent,
indent, strings.Join(valStrings, "\n"+indent+" "),
indent)
}
//-------------------------------------
// Implements sort for sorting validators by address.
type ValidatorsByAddress []*Validator
func (vs ValidatorsByAddress) Len() int {
return len(vs)
}
func (vs ValidatorsByAddress) Less(i, j int) bool {
return bytes.Compare(vs[i].Address, vs[j].Address) == -1
}
func (vs ValidatorsByAddress) Swap(i, j int) {
it := vs[i]
vs[i] = vs[j]
vs[j] = it
}
//-------------------------------------
// Use with Heap for sorting validators by accum
type accumComparable uint64
// We want to find the validator with the greatest accum.
func (ac accumComparable) Less(o interface{}) bool {
return uint64(ac) < uint64(o.(accumComparable))
}