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.

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