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.

266 lines
7.6 KiB

9 years ago
7 years ago
  1. package types
  2. import (
  3. "errors"
  4. "fmt"
  5. "strings"
  6. "sync"
  7. tmjson "github.com/tendermint/tendermint/libs/json"
  8. tmmath "github.com/tendermint/tendermint/libs/math"
  9. tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
  10. "github.com/tendermint/tendermint/types"
  11. )
  12. type RoundVoteSet struct {
  13. Prevotes *types.VoteSet
  14. Precommits *types.VoteSet
  15. }
  16. var (
  17. ErrGotVoteFromUnwantedRound = errors.New(
  18. "peer has sent a vote that does not match our round for more than one round",
  19. )
  20. )
  21. /*
  22. Keeps track of all VoteSets from round 0 to round 'round'.
  23. Also keeps track of up to one RoundVoteSet greater than
  24. 'round' from each peer, to facilitate catchup syncing of commits.
  25. A commit is +2/3 precommits for a block at a round,
  26. but which round is not known in advance, so when a peer
  27. provides a precommit for a round greater than mtx.round,
  28. we create a new entry in roundVoteSets but also remember the
  29. peer to prevent abuse.
  30. We let each peer provide us with up to 2 unexpected "catchup" rounds.
  31. One for their LastCommit round, and another for the official commit round.
  32. */
  33. type HeightVoteSet struct {
  34. chainID string
  35. height int64
  36. valSet *types.ValidatorSet
  37. mtx sync.Mutex
  38. round int32 // max tracked round
  39. roundVoteSets map[int32]RoundVoteSet // keys: [0...round]
  40. peerCatchupRounds map[types.NodeID][]int32 // keys: peer.ID; values: at most 2 rounds
  41. }
  42. func NewHeightVoteSet(chainID string, height int64, valSet *types.ValidatorSet) *HeightVoteSet {
  43. hvs := &HeightVoteSet{
  44. chainID: chainID,
  45. }
  46. hvs.Reset(height, valSet)
  47. return hvs
  48. }
  49. func (hvs *HeightVoteSet) Reset(height int64, valSet *types.ValidatorSet) {
  50. hvs.mtx.Lock()
  51. defer hvs.mtx.Unlock()
  52. hvs.height = height
  53. hvs.valSet = valSet
  54. hvs.roundVoteSets = make(map[int32]RoundVoteSet)
  55. hvs.peerCatchupRounds = make(map[types.NodeID][]int32)
  56. hvs.addRound(0)
  57. hvs.round = 0
  58. }
  59. func (hvs *HeightVoteSet) Height() int64 {
  60. hvs.mtx.Lock()
  61. defer hvs.mtx.Unlock()
  62. return hvs.height
  63. }
  64. func (hvs *HeightVoteSet) Round() int32 {
  65. hvs.mtx.Lock()
  66. defer hvs.mtx.Unlock()
  67. return hvs.round
  68. }
  69. // Create more RoundVoteSets up to round.
  70. func (hvs *HeightVoteSet) SetRound(round int32) {
  71. hvs.mtx.Lock()
  72. defer hvs.mtx.Unlock()
  73. newRound := tmmath.SafeSubInt32(hvs.round, 1)
  74. if hvs.round != 0 && (round < newRound) {
  75. panic("SetRound() must increment hvs.round")
  76. }
  77. for r := newRound; r <= round; r++ {
  78. if _, ok := hvs.roundVoteSets[r]; ok {
  79. continue // Already exists because peerCatchupRounds.
  80. }
  81. hvs.addRound(r)
  82. }
  83. hvs.round = round
  84. }
  85. func (hvs *HeightVoteSet) addRound(round int32) {
  86. if _, ok := hvs.roundVoteSets[round]; ok {
  87. panic("addRound() for an existing round")
  88. }
  89. // log.Debug("addRound(round)", "round", round)
  90. prevotes := types.NewVoteSet(hvs.chainID, hvs.height, round, tmproto.PrevoteType, hvs.valSet)
  91. precommits := types.NewVoteSet(hvs.chainID, hvs.height, round, tmproto.PrecommitType, hvs.valSet)
  92. hvs.roundVoteSets[round] = RoundVoteSet{
  93. Prevotes: prevotes,
  94. Precommits: precommits,
  95. }
  96. }
  97. // Duplicate votes return added=false, err=nil.
  98. // By convention, peerID is "" if origin is self.
  99. func (hvs *HeightVoteSet) AddVote(vote *types.Vote, peerID types.NodeID) (added bool, err error) {
  100. hvs.mtx.Lock()
  101. defer hvs.mtx.Unlock()
  102. if !types.IsVoteTypeValid(vote.Type) {
  103. return
  104. }
  105. voteSet := hvs.getVoteSet(vote.Round, vote.Type)
  106. if voteSet == nil {
  107. if rndz := hvs.peerCatchupRounds[peerID]; len(rndz) < 2 {
  108. hvs.addRound(vote.Round)
  109. voteSet = hvs.getVoteSet(vote.Round, vote.Type)
  110. hvs.peerCatchupRounds[peerID] = append(rndz, vote.Round)
  111. } else {
  112. // punish peer
  113. err = ErrGotVoteFromUnwantedRound
  114. return
  115. }
  116. }
  117. added, err = voteSet.AddVote(vote)
  118. return
  119. }
  120. func (hvs *HeightVoteSet) Prevotes(round int32) *types.VoteSet {
  121. hvs.mtx.Lock()
  122. defer hvs.mtx.Unlock()
  123. return hvs.getVoteSet(round, tmproto.PrevoteType)
  124. }
  125. func (hvs *HeightVoteSet) Precommits(round int32) *types.VoteSet {
  126. hvs.mtx.Lock()
  127. defer hvs.mtx.Unlock()
  128. return hvs.getVoteSet(round, tmproto.PrecommitType)
  129. }
  130. // Last round and blockID that has +2/3 prevotes for a particular block or nil.
  131. // Returns -1 if no such round exists.
  132. func (hvs *HeightVoteSet) POLInfo() (polRound int32, polBlockID types.BlockID) {
  133. hvs.mtx.Lock()
  134. defer hvs.mtx.Unlock()
  135. for r := hvs.round; r >= 0; r-- {
  136. rvs := hvs.getVoteSet(r, tmproto.PrevoteType)
  137. polBlockID, ok := rvs.TwoThirdsMajority()
  138. if ok {
  139. return r, polBlockID
  140. }
  141. }
  142. return -1, types.BlockID{}
  143. }
  144. func (hvs *HeightVoteSet) getVoteSet(round int32, voteType tmproto.SignedMsgType) *types.VoteSet {
  145. rvs, ok := hvs.roundVoteSets[round]
  146. if !ok {
  147. return nil
  148. }
  149. switch voteType {
  150. case tmproto.PrevoteType:
  151. return rvs.Prevotes
  152. case tmproto.PrecommitType:
  153. return rvs.Precommits
  154. default:
  155. panic(fmt.Sprintf("Unexpected vote type %X", voteType))
  156. }
  157. }
  158. // If a peer claims that it has 2/3 majority for given blockKey, call this.
  159. // NOTE: if there are too many peers, or too much peer churn,
  160. // this can cause memory issues.
  161. // TODO: implement ability to remove peers too
  162. func (hvs *HeightVoteSet) SetPeerMaj23(
  163. round int32,
  164. voteType tmproto.SignedMsgType,
  165. peerID types.NodeID,
  166. blockID types.BlockID) error {
  167. hvs.mtx.Lock()
  168. defer hvs.mtx.Unlock()
  169. if !types.IsVoteTypeValid(voteType) {
  170. return fmt.Errorf("setPeerMaj23: Invalid vote type %X", voteType)
  171. }
  172. voteSet := hvs.getVoteSet(round, voteType)
  173. if voteSet == nil {
  174. return nil // something we don't know about yet
  175. }
  176. return voteSet.SetPeerMaj23(types.P2PID(peerID), blockID)
  177. }
  178. //---------------------------------------------------------
  179. // string and json
  180. func (hvs *HeightVoteSet) String() string {
  181. return hvs.StringIndented("")
  182. }
  183. func (hvs *HeightVoteSet) StringIndented(indent string) string {
  184. hvs.mtx.Lock()
  185. defer hvs.mtx.Unlock()
  186. vsStrings := make([]string, 0, (len(hvs.roundVoteSets)+1)*2)
  187. // rounds 0 ~ hvs.round inclusive
  188. for round := int32(0); round <= hvs.round; round++ {
  189. voteSetString := hvs.roundVoteSets[round].Prevotes.StringShort()
  190. vsStrings = append(vsStrings, voteSetString)
  191. voteSetString = hvs.roundVoteSets[round].Precommits.StringShort()
  192. vsStrings = append(vsStrings, voteSetString)
  193. }
  194. // all other peer catchup rounds
  195. for round, roundVoteSet := range hvs.roundVoteSets {
  196. if round <= hvs.round {
  197. continue
  198. }
  199. voteSetString := roundVoteSet.Prevotes.StringShort()
  200. vsStrings = append(vsStrings, voteSetString)
  201. voteSetString = roundVoteSet.Precommits.StringShort()
  202. vsStrings = append(vsStrings, voteSetString)
  203. }
  204. return fmt.Sprintf(`HeightVoteSet{H:%v R:0~%v
  205. %s %v
  206. %s}`,
  207. hvs.height, hvs.round,
  208. indent, strings.Join(vsStrings, "\n"+indent+" "),
  209. indent)
  210. }
  211. func (hvs *HeightVoteSet) MarshalJSON() ([]byte, error) {
  212. hvs.mtx.Lock()
  213. defer hvs.mtx.Unlock()
  214. return tmjson.Marshal(hvs.toAllRoundVotes())
  215. }
  216. func (hvs *HeightVoteSet) toAllRoundVotes() []roundVotes {
  217. totalRounds := hvs.round + 1
  218. allVotes := make([]roundVotes, totalRounds)
  219. // rounds 0 ~ hvs.round inclusive
  220. for round := int32(0); round < totalRounds; round++ {
  221. allVotes[round] = roundVotes{
  222. Round: round,
  223. Prevotes: hvs.roundVoteSets[round].Prevotes.VoteStrings(),
  224. PrevotesBitArray: hvs.roundVoteSets[round].Prevotes.BitArrayString(),
  225. Precommits: hvs.roundVoteSets[round].Precommits.VoteStrings(),
  226. PrecommitsBitArray: hvs.roundVoteSets[round].Precommits.BitArrayString(),
  227. }
  228. }
  229. // TODO: all other peer catchup rounds
  230. return allVotes
  231. }
  232. type roundVotes struct {
  233. Round int32 `json:"round"`
  234. Prevotes []string `json:"prevotes"`
  235. PrevotesBitArray string `json:"prevotes_bit_array"`
  236. Precommits []string `json:"precommits"`
  237. PrecommitsBitArray string `json:"precommits_bit_array"`
  238. }