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.

302 lines
8.0 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
9 years ago
  1. package types
  2. import (
  3. "bytes"
  4. "fmt"
  5. "strings"
  6. "sync"
  7. . "github.com/tendermint/go-common"
  8. "github.com/tendermint/go-wire"
  9. )
  10. // VoteSet helps collect signatures from validators at each height+round
  11. // for a predefined vote type.
  12. // Note that there three kinds of votes: prevotes, precommits, and commits.
  13. // A commit of prior rounds can be added added in lieu of votes/precommits.
  14. // NOTE: Assumes that the sum total of voting power does not exceed MaxUInt64.
  15. type VoteSet struct {
  16. height int
  17. round int
  18. type_ byte
  19. mtx sync.Mutex
  20. valSet *ValidatorSet
  21. votes []*Vote // validator index -> vote
  22. votesBitArray *BitArray // validator index -> has vote?
  23. votesByBlock map[string]int64 // string(blockHash)+string(blockParts) -> vote sum.
  24. totalVotes int64
  25. maj23Hash []byte
  26. maj23PartsHeader PartSetHeader
  27. maj23Exists bool
  28. }
  29. // Constructs a new VoteSet struct used to accumulate votes for given height/round.
  30. func NewVoteSet(height int, round int, type_ byte, valSet *ValidatorSet) *VoteSet {
  31. if height == 0 {
  32. PanicSanity("Cannot make VoteSet for height == 0, doesn't make sense.")
  33. }
  34. return &VoteSet{
  35. height: height,
  36. round: round,
  37. type_: type_,
  38. valSet: valSet,
  39. votes: make([]*Vote, valSet.Size()),
  40. votesBitArray: NewBitArray(valSet.Size()),
  41. votesByBlock: make(map[string]int64),
  42. totalVotes: 0,
  43. }
  44. }
  45. func (voteSet *VoteSet) Height() int {
  46. if voteSet == nil {
  47. return 0
  48. } else {
  49. return voteSet.height
  50. }
  51. }
  52. func (voteSet *VoteSet) Round() int {
  53. if voteSet == nil {
  54. return -1
  55. } else {
  56. return voteSet.round
  57. }
  58. }
  59. func (voteSet *VoteSet) Type() byte {
  60. if voteSet == nil {
  61. return 0x00
  62. } else {
  63. return voteSet.type_
  64. }
  65. }
  66. func (voteSet *VoteSet) Size() int {
  67. if voteSet == nil {
  68. return 0
  69. } else {
  70. return voteSet.valSet.Size()
  71. }
  72. }
  73. // Returns added=true, index if vote was added
  74. // Otherwise returns err=ErrVote[UnexpectedStep|InvalidAccount|InvalidSignature|InvalidBlockHash|ConflictingSignature]
  75. // Duplicate votes return added=false, err=nil.
  76. // NOTE: vote should not be mutated after adding.
  77. func (voteSet *VoteSet) AddByIndex(valIndex int, vote *Vote) (added bool, address []byte, err error) {
  78. voteSet.mtx.Lock()
  79. defer voteSet.mtx.Unlock()
  80. return voteSet.addByIndex(valIndex, vote)
  81. }
  82. // Returns added=true, index if vote was added
  83. // Otherwise returns err=ErrVote[UnexpectedStep|InvalidAccount|InvalidSignature|InvalidBlockHash|ConflictingSignature]
  84. // Duplicate votes return added=false, err=nil.
  85. // NOTE: vote should not be mutated after adding.
  86. func (voteSet *VoteSet) AddByAddress(address []byte, vote *Vote) (added bool, index int, err error) {
  87. voteSet.mtx.Lock()
  88. defer voteSet.mtx.Unlock()
  89. // Ensure that signer is a validator.
  90. valIndex, val := voteSet.valSet.GetByAddress(address)
  91. if val == nil {
  92. return false, 0, ErrVoteInvalidAccount
  93. }
  94. return voteSet.addVote(val, valIndex, vote)
  95. }
  96. func (voteSet *VoteSet) addByIndex(valIndex int, vote *Vote) (added bool, address []byte, err error) {
  97. // Ensure that signer is a validator.
  98. address, val := voteSet.valSet.GetByIndex(valIndex)
  99. if val == nil {
  100. return false, nil, ErrVoteInvalidAccount
  101. }
  102. added, _, err = voteSet.addVote(val, valIndex, vote)
  103. return
  104. }
  105. func (voteSet *VoteSet) addVote(val *Validator, valIndex int, vote *Vote) (bool, int, error) {
  106. // Make sure the step matches. (or that vote is commit && round < voteSet.round)
  107. if (vote.Height != voteSet.height) ||
  108. (vote.Round != voteSet.round) ||
  109. (vote.Type != voteSet.type_) {
  110. return false, 0, ErrVoteUnexpectedStep
  111. }
  112. // Check signature.
  113. if !val.PubKey.VerifyBytes(SignBytes(config.GetString("chain_id"), vote), vote.Signature) {
  114. // Bad signature.
  115. return false, 0, ErrVoteInvalidSignature
  116. }
  117. // If vote already exists, return false.
  118. if existingVote := voteSet.votes[valIndex]; existingVote != nil {
  119. if bytes.Equal(existingVote.BlockHash, vote.BlockHash) {
  120. return false, valIndex, nil
  121. } else {
  122. return false, valIndex, &ErrVoteConflictingSignature{
  123. VoteA: existingVote,
  124. VoteB: vote,
  125. }
  126. }
  127. }
  128. // Add vote.
  129. voteSet.votes[valIndex] = vote
  130. voteSet.votesBitArray.SetIndex(valIndex, true)
  131. blockKey := string(vote.BlockHash) + string(wire.BinaryBytes(vote.BlockPartsHeader))
  132. totalBlockHashVotes := voteSet.votesByBlock[blockKey] + val.VotingPower
  133. voteSet.votesByBlock[blockKey] = totalBlockHashVotes
  134. voteSet.totalVotes += val.VotingPower
  135. // If we just nudged it up to two thirds majority, add it.
  136. if totalBlockHashVotes > voteSet.valSet.TotalVotingPower()*2/3 &&
  137. (totalBlockHashVotes-val.VotingPower) <= voteSet.valSet.TotalVotingPower()*2/3 {
  138. voteSet.maj23Hash = vote.BlockHash
  139. voteSet.maj23PartsHeader = vote.BlockPartsHeader
  140. voteSet.maj23Exists = true
  141. }
  142. return true, valIndex, nil
  143. }
  144. func (voteSet *VoteSet) BitArray() *BitArray {
  145. if voteSet == nil {
  146. return nil
  147. }
  148. voteSet.mtx.Lock()
  149. defer voteSet.mtx.Unlock()
  150. return voteSet.votesBitArray.Copy()
  151. }
  152. func (voteSet *VoteSet) GetByIndex(valIndex int) *Vote {
  153. voteSet.mtx.Lock()
  154. defer voteSet.mtx.Unlock()
  155. return voteSet.votes[valIndex]
  156. }
  157. func (voteSet *VoteSet) GetByAddress(address []byte) *Vote {
  158. voteSet.mtx.Lock()
  159. defer voteSet.mtx.Unlock()
  160. valIndex, val := voteSet.valSet.GetByAddress(address)
  161. if val == nil {
  162. PanicSanity("GetByAddress(address) returned nil")
  163. }
  164. return voteSet.votes[valIndex]
  165. }
  166. func (voteSet *VoteSet) HasTwoThirdsMajority() bool {
  167. if voteSet == nil {
  168. return false
  169. }
  170. voteSet.mtx.Lock()
  171. defer voteSet.mtx.Unlock()
  172. return voteSet.maj23Exists
  173. }
  174. func (voteSet *VoteSet) IsCommit() bool {
  175. if voteSet == nil {
  176. return false
  177. }
  178. if voteSet.type_ != VoteTypePrecommit {
  179. return false
  180. }
  181. voteSet.mtx.Lock()
  182. defer voteSet.mtx.Unlock()
  183. return len(voteSet.maj23Hash) > 0
  184. }
  185. func (voteSet *VoteSet) HasTwoThirdsAny() bool {
  186. if voteSet == nil {
  187. return false
  188. }
  189. voteSet.mtx.Lock()
  190. defer voteSet.mtx.Unlock()
  191. return voteSet.totalVotes > voteSet.valSet.TotalVotingPower()*2/3
  192. }
  193. // Returns either a blockhash (or nil) that received +2/3 majority.
  194. // If there exists no such majority, returns (nil, false).
  195. func (voteSet *VoteSet) TwoThirdsMajority() (hash []byte, parts PartSetHeader, ok bool) {
  196. voteSet.mtx.Lock()
  197. defer voteSet.mtx.Unlock()
  198. if voteSet.maj23Exists {
  199. return voteSet.maj23Hash, voteSet.maj23PartsHeader, true
  200. } else {
  201. return nil, PartSetHeader{}, false
  202. }
  203. }
  204. func (voteSet *VoteSet) String() string {
  205. if voteSet == nil {
  206. return "nil-VoteSet"
  207. }
  208. return voteSet.StringIndented("")
  209. }
  210. func (voteSet *VoteSet) StringIndented(indent string) string {
  211. voteStrings := make([]string, len(voteSet.votes))
  212. for i, vote := range voteSet.votes {
  213. if vote == nil {
  214. voteStrings[i] = "nil-Vote"
  215. } else {
  216. voteStrings[i] = vote.String()
  217. }
  218. }
  219. return fmt.Sprintf(`VoteSet{
  220. %s H:%v R:%v T:%v
  221. %s %v
  222. %s %v
  223. %s}`,
  224. indent, voteSet.height, voteSet.round, voteSet.type_,
  225. indent, strings.Join(voteStrings, "\n"+indent+" "),
  226. indent, voteSet.votesBitArray,
  227. indent)
  228. }
  229. func (voteSet *VoteSet) StringShort() string {
  230. if voteSet == nil {
  231. return "nil-VoteSet"
  232. }
  233. voteSet.mtx.Lock()
  234. defer voteSet.mtx.Unlock()
  235. return fmt.Sprintf(`VoteSet{H:%v R:%v T:%v +2/3:%v %v}`,
  236. voteSet.height, voteSet.round, voteSet.type_, voteSet.maj23Exists, voteSet.votesBitArray)
  237. }
  238. //--------------------------------------------------------------------------------
  239. // Validation
  240. func (voteSet *VoteSet) MakeValidation() *Validation {
  241. if voteSet.type_ != VoteTypePrecommit {
  242. PanicSanity("Cannot MakeValidation() unless VoteSet.Type is VoteTypePrecommit")
  243. }
  244. voteSet.mtx.Lock()
  245. defer voteSet.mtx.Unlock()
  246. if len(voteSet.maj23Hash) == 0 {
  247. PanicSanity("Cannot MakeValidation() unless a blockhash has +2/3")
  248. }
  249. precommits := make([]*Vote, voteSet.valSet.Size())
  250. voteSet.valSet.Iterate(func(valIndex int, val *Validator) bool {
  251. vote := voteSet.votes[valIndex]
  252. if vote == nil {
  253. return false
  254. }
  255. if !bytes.Equal(vote.BlockHash, voteSet.maj23Hash) {
  256. return false
  257. }
  258. if !vote.BlockPartsHeader.Equals(voteSet.maj23PartsHeader) {
  259. return false
  260. }
  261. precommits[valIndex] = vote
  262. return false
  263. })
  264. return &Validation{
  265. Precommits: precommits,
  266. }
  267. }