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.

332 lines
8.8 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
  1. package types
  2. import (
  3. "bytes"
  4. "fmt"
  5. "strings"
  6. "sync"
  7. acm "github.com/tendermint/tendermint/account"
  8. . "github.com/tendermint/tendermint/common"
  9. "github.com/tendermint/tendermint/wire"
  10. )
  11. // VoteSet helps collect signatures from validators at each height+round
  12. // for a predefined vote type.
  13. // Note that there three kinds of votes: prevotes, precommits, and commits.
  14. // A commit of prior rounds can be added added in lieu of votes/precommits.
  15. // NOTE: Assumes that the sum total of voting power does not exceed MaxUInt64.
  16. type VoteSet struct {
  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(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. height: height,
  37. round: round,
  38. type_: type_,
  39. valSet: valSet,
  40. votes: make([]*Vote, valSet.Size()),
  41. votesBitArray: NewBitArray(valSet.Size()),
  42. votesByBlock: make(map[string]int64),
  43. totalVotes: 0,
  44. }
  45. }
  46. func (voteSet *VoteSet) Height() int {
  47. if voteSet == nil {
  48. return 0
  49. } else {
  50. return voteSet.height
  51. }
  52. }
  53. func (voteSet *VoteSet) Round() int {
  54. if voteSet == nil {
  55. return 0
  56. } else {
  57. return voteSet.round
  58. }
  59. }
  60. func (voteSet *VoteSet) Type() byte {
  61. if voteSet == nil {
  62. return 0x00
  63. } else {
  64. return voteSet.type_
  65. }
  66. }
  67. func (voteSet *VoteSet) Size() int {
  68. if voteSet == nil {
  69. return 0
  70. } else {
  71. return voteSet.valSet.Size()
  72. }
  73. }
  74. // Returns added=true, index if vote was added
  75. // Otherwise returns err=ErrVote[UnexpectedStep|InvalidAccount|InvalidSignature|InvalidBlockHash|ConflictingSignature]
  76. // Duplicate votes return added=false, err=nil.
  77. // NOTE: vote should not be mutated after adding.
  78. func (voteSet *VoteSet) AddByIndex(valIndex int, vote *Vote) (added bool, index int, err error) {
  79. voteSet.mtx.Lock()
  80. defer voteSet.mtx.Unlock()
  81. return voteSet.addByIndex(valIndex, vote)
  82. }
  83. // Returns added=true, index if vote was added
  84. // Otherwise returns err=ErrVote[UnexpectedStep|InvalidAccount|InvalidSignature|InvalidBlockHash|ConflictingSignature]
  85. // Duplicate votes return added=false, err=nil.
  86. // NOTE: vote should not be mutated after adding.
  87. func (voteSet *VoteSet) AddByAddress(address []byte, vote *Vote) (added bool, index int, err error) {
  88. voteSet.mtx.Lock()
  89. defer voteSet.mtx.Unlock()
  90. // Ensure that signer is a validator.
  91. valIndex, val := voteSet.valSet.GetByAddress(address)
  92. if val == nil {
  93. return false, 0, ErrVoteInvalidAccount
  94. }
  95. return voteSet.addVote(val, valIndex, vote)
  96. }
  97. func (voteSet *VoteSet) addByIndex(valIndex int, vote *Vote) (bool, int, error) {
  98. // Ensure that signer is a validator.
  99. _, val := voteSet.valSet.GetByIndex(valIndex)
  100. if val == nil {
  101. return false, 0, ErrVoteInvalidAccount
  102. }
  103. return voteSet.addVote(val, valIndex, vote)
  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(acm.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. voteSet.mtx.Lock()
  179. defer voteSet.mtx.Unlock()
  180. return len(voteSet.maj23Hash) > 0
  181. }
  182. func (voteSet *VoteSet) HasTwoThirdsAny() bool {
  183. if voteSet == nil {
  184. return false
  185. }
  186. voteSet.mtx.Lock()
  187. defer voteSet.mtx.Unlock()
  188. return voteSet.totalVotes > voteSet.valSet.TotalVotingPower()*2/3
  189. }
  190. // Returns either a blockhash (or nil) that received +2/3 majority.
  191. // If there exists no such majority, returns (nil, false).
  192. func (voteSet *VoteSet) TwoThirdsMajority() (hash []byte, parts PartSetHeader, ok bool) {
  193. voteSet.mtx.Lock()
  194. defer voteSet.mtx.Unlock()
  195. if voteSet.maj23Exists {
  196. return voteSet.maj23Hash, voteSet.maj23PartsHeader, true
  197. } else {
  198. return nil, PartSetHeader{}, false
  199. }
  200. }
  201. func (voteSet *VoteSet) String() string {
  202. if voteSet == nil {
  203. return "nil-VoteSet"
  204. }
  205. return voteSet.StringIndented("")
  206. }
  207. func (voteSet *VoteSet) StringIndented(indent string) string {
  208. voteStrings := make([]string, len(voteSet.votes))
  209. for i, vote := range voteSet.votes {
  210. if vote == nil {
  211. voteStrings[i] = "nil-Vote"
  212. } else {
  213. voteStrings[i] = vote.String()
  214. }
  215. }
  216. return fmt.Sprintf(`VoteSet{
  217. %s H:%v R:%v T:%v
  218. %s %v
  219. %s %v
  220. %s}`,
  221. indent, voteSet.height, voteSet.round, voteSet.type_,
  222. indent, strings.Join(voteStrings, "\n"+indent+" "),
  223. indent, voteSet.votesBitArray,
  224. indent)
  225. }
  226. func (voteSet *VoteSet) StringShort() string {
  227. if voteSet == nil {
  228. return "nil-VoteSet"
  229. }
  230. voteSet.mtx.Lock()
  231. defer voteSet.mtx.Unlock()
  232. return fmt.Sprintf(`VoteSet{H:%v R:%v T:%v +2/3:%v %v}`,
  233. voteSet.height, voteSet.round, voteSet.type_, voteSet.maj23Exists, voteSet.votesBitArray)
  234. }
  235. //--------------------------------------------------------------------------------
  236. // Validation
  237. func (voteSet *VoteSet) MakeValidation() *Validation {
  238. if voteSet.type_ != VoteTypePrecommit {
  239. PanicSanity("Cannot MakeValidation() unless VoteSet.Type is VoteTypePrecommit")
  240. }
  241. voteSet.mtx.Lock()
  242. defer voteSet.mtx.Unlock()
  243. if len(voteSet.maj23Hash) == 0 {
  244. PanicSanity("Cannot MakeValidation() unless a blockhash has +2/3")
  245. }
  246. precommits := make([]*Vote, voteSet.valSet.Size())
  247. voteSet.valSet.Iterate(func(valIndex int, val *Validator) bool {
  248. vote := voteSet.votes[valIndex]
  249. if vote == nil {
  250. return false
  251. }
  252. if !bytes.Equal(vote.BlockHash, voteSet.maj23Hash) {
  253. return false
  254. }
  255. if !vote.BlockPartsHeader.Equals(voteSet.maj23PartsHeader) {
  256. return false
  257. }
  258. precommits[valIndex] = vote
  259. return false
  260. })
  261. return &Validation{
  262. Precommits: precommits,
  263. }
  264. }
  265. //--------------------------------------------------------------------------------
  266. // For testing...
  267. func RandValidator(randBonded bool, minBonded int64) (*ValidatorInfo, *Validator, *PrivValidator) {
  268. privVal := GenPrivValidator()
  269. _, tempFilePath := Tempfile("priv_validator_")
  270. privVal.SetFile(tempFilePath)
  271. bonded := minBonded
  272. if randBonded {
  273. bonded += int64(RandUint32())
  274. }
  275. valInfo := &ValidatorInfo{
  276. Address: privVal.Address,
  277. PubKey: privVal.PubKey,
  278. UnbondTo: []*TxOutput{&TxOutput{
  279. Amount: bonded,
  280. Address: privVal.Address,
  281. }},
  282. FirstBondHeight: 0,
  283. FirstBondAmount: bonded,
  284. }
  285. val := &Validator{
  286. Address: valInfo.Address,
  287. PubKey: valInfo.PubKey,
  288. BondHeight: 0,
  289. UnbondHeight: 0,
  290. LastCommitHeight: 0,
  291. VotingPower: valInfo.FirstBondAmount,
  292. Accum: 0,
  293. }
  294. return valInfo, val, privVal
  295. }