You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

98 lines
2.2 KiB

  1. package types
  2. import (
  3. "bytes"
  4. "fmt"
  5. "github.com/tendermint/tendermint/crypto"
  6. cmn "github.com/tendermint/tendermint/libs/common"
  7. )
  8. // Volatile state for each Validator
  9. // NOTE: The Accum is not included in Validator.Hash();
  10. // make sure to update that method if changes are made here
  11. type Validator struct {
  12. Address Address `json:"address"`
  13. PubKey crypto.PubKey `json:"pub_key"`
  14. VotingPower int64 `json:"voting_power"`
  15. Accum int64 `json:"accum"`
  16. }
  17. func NewValidator(pubKey crypto.PubKey, votingPower int64) *Validator {
  18. return &Validator{
  19. Address: pubKey.Address(),
  20. PubKey: pubKey,
  21. VotingPower: votingPower,
  22. Accum: 0,
  23. }
  24. }
  25. // Creates a new copy of the validator so we can mutate accum.
  26. // Panics if the validator is nil.
  27. func (v *Validator) Copy() *Validator {
  28. vCopy := *v
  29. return &vCopy
  30. }
  31. // Returns the one with higher Accum.
  32. func (v *Validator) CompareAccum(other *Validator) *Validator {
  33. if v == nil {
  34. return other
  35. }
  36. if v.Accum > other.Accum {
  37. return v
  38. } else if v.Accum < other.Accum {
  39. return other
  40. } else {
  41. result := bytes.Compare(v.Address, other.Address)
  42. if result < 0 {
  43. return v
  44. } else if result > 0 {
  45. return other
  46. } else {
  47. cmn.PanicSanity("Cannot compare identical validators")
  48. return nil
  49. }
  50. }
  51. }
  52. func (v *Validator) String() string {
  53. if v == nil {
  54. return "nil-Validator"
  55. }
  56. return fmt.Sprintf("Validator{%v %v VP:%v A:%v}",
  57. v.Address,
  58. v.PubKey,
  59. v.VotingPower,
  60. v.Accum)
  61. }
  62. // Hash computes the unique ID of a validator with a given voting power.
  63. // It excludes the Accum value, which changes with every round.
  64. func (v *Validator) Hash() []byte {
  65. return aminoHash(struct {
  66. Address Address
  67. PubKey crypto.PubKey
  68. VotingPower int64
  69. }{
  70. v.Address,
  71. v.PubKey,
  72. v.VotingPower,
  73. })
  74. }
  75. //----------------------------------------
  76. // RandValidator
  77. // RandValidator returns a randomized validator, useful for testing.
  78. // UNSTABLE
  79. func RandValidator(randPower bool, minPower int64) (*Validator, PrivValidator) {
  80. privVal := NewMockPV()
  81. votePower := minPower
  82. if randPower {
  83. votePower += int64(cmn.RandUint32())
  84. }
  85. val := NewValidator(privVal.GetPubKey(), votePower)
  86. return val, privVal
  87. }