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.3 KiB

8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
7 years ago
  1. package types
  2. import (
  3. "bytes"
  4. "fmt"
  5. "github.com/tendermint/go-crypto"
  6. cmn "github.com/tendermint/tmlibs/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. if bytes.Compare(v.Address, other.Address) < 0 {
  42. return v
  43. } else if bytes.Compare(v.Address, other.Address) > 0 {
  44. return other
  45. } else {
  46. cmn.PanicSanity("Cannot compare identical validators")
  47. return nil
  48. }
  49. }
  50. }
  51. func (v *Validator) String() string {
  52. if v == nil {
  53. return "nil-Validator"
  54. }
  55. return fmt.Sprintf("Validator{%v %v VP:%v A:%v}",
  56. v.Address,
  57. v.PubKey,
  58. v.VotingPower,
  59. v.Accum)
  60. }
  61. // Hash computes the unique ID of a validator with a given voting power.
  62. // It excludes the Accum value, which changes with every round.
  63. func (v *Validator) Hash() []byte {
  64. return tmHash(struct {
  65. Address Address
  66. PubKey crypto.PubKey
  67. VotingPower int64
  68. }{
  69. v.Address,
  70. v.PubKey,
  71. v.VotingPower,
  72. })
  73. }
  74. //--------------------------------------------------------------------------------
  75. // For testing...
  76. // RandValidator returns a randomized validator, useful for testing.
  77. // UNSTABLE
  78. func RandValidator(randPower bool, minPower int64) (*Validator, *PrivValidatorFS) {
  79. _, tempFilePath := cmn.Tempfile("priv_validator_")
  80. privVal := GenPrivValidatorFS(tempFilePath)
  81. votePower := minPower
  82. if randPower {
  83. votePower += int64(cmn.RandUint32())
  84. }
  85. val := NewValidator(privVal.GetPubKey(), votePower)
  86. return val, privVal
  87. }