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.

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