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.

862 lines
24 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
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
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. "errors"
  5. "fmt"
  6. "reflect"
  7. "sync"
  8. "sync/atomic"
  9. "time"
  10. "github.com/tendermint/tendermint/binary"
  11. bc "github.com/tendermint/tendermint/blockchain"
  12. . "github.com/tendermint/tendermint/common"
  13. . "github.com/tendermint/tendermint/consensus/types"
  14. "github.com/tendermint/tendermint/events"
  15. "github.com/tendermint/tendermint/p2p"
  16. sm "github.com/tendermint/tendermint/state"
  17. "github.com/tendermint/tendermint/types"
  18. )
  19. const (
  20. StateChannel = byte(0x20)
  21. DataChannel = byte(0x21)
  22. VoteChannel = byte(0x22)
  23. peerStateKey = "ConsensusReactor.peerState"
  24. peerGossipSleepDuration = 100 * time.Millisecond // Time to sleep if there's nothing to send.
  25. )
  26. //-----------------------------------------------------------------------------
  27. // The reactor's underlying ConsensusState may change state at any time.
  28. // We atomically copy the RoundState struct before using it.
  29. type ConsensusReactor struct {
  30. sw *p2p.Switch
  31. running uint32
  32. quit chan struct{}
  33. blockStore *bc.BlockStore
  34. conS *ConsensusState
  35. evsw *events.EventSwitch
  36. }
  37. func NewConsensusReactor(consensusState *ConsensusState, blockStore *bc.BlockStore) *ConsensusReactor {
  38. conR := &ConsensusReactor{
  39. blockStore: blockStore,
  40. quit: make(chan struct{}),
  41. conS: consensusState,
  42. }
  43. return conR
  44. }
  45. // Implements Reactor
  46. func (conR *ConsensusReactor) Start(sw *p2p.Switch) {
  47. if atomic.CompareAndSwapUint32(&conR.running, 0, 1) {
  48. log.Info("Starting ConsensusReactor")
  49. conR.sw = sw
  50. conR.conS.Start()
  51. go conR.broadcastNewRoundStepRoutine()
  52. }
  53. }
  54. // Implements Reactor
  55. func (conR *ConsensusReactor) Stop() {
  56. if atomic.CompareAndSwapUint32(&conR.running, 1, 0) {
  57. log.Info("Stopping ConsensusReactor")
  58. conR.conS.Stop()
  59. close(conR.quit)
  60. }
  61. }
  62. func (conR *ConsensusReactor) IsRunning() bool {
  63. return atomic.LoadUint32(&conR.running) == 1
  64. }
  65. // Implements Reactor
  66. func (conR *ConsensusReactor) GetChannels() []*p2p.ChannelDescriptor {
  67. // TODO optimize
  68. return []*p2p.ChannelDescriptor{
  69. &p2p.ChannelDescriptor{
  70. Id: StateChannel,
  71. Priority: 5,
  72. },
  73. &p2p.ChannelDescriptor{
  74. Id: DataChannel,
  75. Priority: 5,
  76. },
  77. &p2p.ChannelDescriptor{
  78. Id: VoteChannel,
  79. Priority: 5,
  80. },
  81. }
  82. }
  83. // Implements Reactor
  84. func (conR *ConsensusReactor) AddPeer(peer *p2p.Peer) {
  85. if !conR.IsRunning() {
  86. return
  87. }
  88. // Create peerState for peer
  89. peerState := NewPeerState(peer)
  90. peer.Data.Set(peerStateKey, peerState)
  91. // Begin gossip routines for this peer.
  92. go conR.gossipDataRoutine(peer, peerState)
  93. go conR.gossipVotesRoutine(peer, peerState)
  94. // Send our state to peer.
  95. conR.sendNewRoundStepRoutine(peer)
  96. }
  97. // Implements Reactor
  98. func (conR *ConsensusReactor) RemovePeer(peer *p2p.Peer, reason interface{}) {
  99. if !conR.IsRunning() {
  100. return
  101. }
  102. //peer.Data.Get(peerStateKey).(*PeerState).Disconnect()
  103. }
  104. // Implements Reactor
  105. func (conR *ConsensusReactor) Receive(chId byte, peer *p2p.Peer, msgBytes []byte) {
  106. if !conR.IsRunning() {
  107. return
  108. }
  109. // Get round state
  110. rs := conR.conS.GetRoundState()
  111. ps := peer.Data.Get(peerStateKey).(*PeerState)
  112. _, msg_, err := DecodeMessage(msgBytes)
  113. if err != nil {
  114. log.Warn("Error decoding message", "channel", chId, "peer", peer, "msg", msg_, "error", err, "bytes", msgBytes)
  115. return
  116. }
  117. log.Debug("Receive", "channel", chId, "peer", peer, "msg", msg_, "bytes", msgBytes)
  118. switch chId {
  119. case StateChannel:
  120. switch msg := msg_.(type) {
  121. case *NewRoundStepMessage:
  122. ps.ApplyNewRoundStepMessage(msg, rs)
  123. case *CommitStepMessage:
  124. ps.ApplyCommitStepMessage(msg)
  125. case *HasVoteMessage:
  126. ps.ApplyHasVoteMessage(msg)
  127. default:
  128. log.Warn(Fmt("Unknown message type %v", reflect.TypeOf(msg)))
  129. }
  130. case DataChannel:
  131. switch msg := msg_.(type) {
  132. case *ProposalMessage:
  133. ps.SetHasProposal(msg.Proposal)
  134. err = conR.conS.SetProposal(msg.Proposal)
  135. case *PartMessage:
  136. if msg.Type == partTypeProposalBlock {
  137. ps.SetHasProposalBlockPart(msg.Height, msg.Round, msg.Part.Index)
  138. _, err = conR.conS.AddProposalBlockPart(msg.Height, msg.Round, msg.Part)
  139. } else if msg.Type == partTypeProposalPOL {
  140. ps.SetHasProposalPOLPart(msg.Height, msg.Round, msg.Part.Index)
  141. _, err = conR.conS.AddProposalPOLPart(msg.Height, msg.Round, msg.Part)
  142. } else {
  143. log.Warn(Fmt("Unknown part type %v", msg.Type))
  144. }
  145. default:
  146. log.Warn(Fmt("Unknown message type %v", reflect.TypeOf(msg)))
  147. }
  148. case VoteChannel:
  149. switch msg := msg_.(type) {
  150. case *VoteMessage:
  151. vote := msg.Vote
  152. if rs.Height != vote.Height {
  153. return // Wrong height. Not necessarily a bad peer.
  154. }
  155. validatorIndex := msg.ValidatorIndex
  156. address, _ := rs.Validators.GetByIndex(validatorIndex)
  157. added, index, err := conR.conS.AddVote(address, vote)
  158. if err != nil {
  159. // If conflicting sig, broadcast evidence tx for slashing. Else punish peer.
  160. if errDupe, ok := err.(*types.ErrVoteConflictingSignature); ok {
  161. log.Warn("Found conflicting vote. Publish evidence")
  162. evidenceTx := &types.DupeoutTx{
  163. Address: address,
  164. VoteA: *errDupe.VoteA,
  165. VoteB: *errDupe.VoteB,
  166. }
  167. conR.conS.mempoolReactor.BroadcastTx(evidenceTx) // shouldn't need to check returned err
  168. } else {
  169. // Probably an invalid signature. Bad peer.
  170. log.Warn("Error attempting to add vote", "error", err)
  171. // TODO: punish peer
  172. }
  173. }
  174. // Initialize Prevotes/Precommits/Commits if needed
  175. ps.EnsureVoteBitArrays(rs.Height, rs.Validators.Size())
  176. ps.SetHasVote(vote, index)
  177. if added {
  178. msg := &HasVoteMessage{
  179. Height: vote.Height,
  180. Round: vote.Round,
  181. Type: vote.Type,
  182. Index: index,
  183. }
  184. conR.sw.Broadcast(StateChannel, msg)
  185. }
  186. default:
  187. log.Warn(Fmt("Unknown message type %v", reflect.TypeOf(msg)))
  188. }
  189. default:
  190. log.Warn(Fmt("Unknown channel %X", chId))
  191. }
  192. if err != nil {
  193. log.Warn("Error in Receive()", "error", err)
  194. }
  195. }
  196. // Sets our private validator account for signing votes.
  197. func (conR *ConsensusReactor) SetPrivValidator(priv *sm.PrivValidator) {
  198. conR.conS.SetPrivValidator(priv)
  199. }
  200. // Reset to some state.
  201. func (conR *ConsensusReactor) ResetToState(state *sm.State) {
  202. conR.conS.updateToState(state, false)
  203. }
  204. // implements events.Eventable
  205. func (conR *ConsensusReactor) SetEventSwitch(evsw *events.EventSwitch) {
  206. conR.evsw = evsw
  207. }
  208. //--------------------------------------
  209. func makeRoundStepMessages(rs *RoundState) (nrsMsg *NewRoundStepMessage, csMsg *CommitStepMessage) {
  210. // Get seconds since beginning of height.
  211. timeElapsed := time.Now().Sub(rs.StartTime)
  212. // Broadcast NewRoundStepMessage
  213. nrsMsg = &NewRoundStepMessage{
  214. Height: rs.Height,
  215. Round: rs.Round,
  216. Step: rs.Step,
  217. SecondsSinceStartTime: uint(timeElapsed.Seconds()),
  218. }
  219. // If the step is commit, then also broadcast a CommitStepMessage.
  220. if rs.Step == RoundStepCommit {
  221. csMsg = &CommitStepMessage{
  222. Height: rs.Height,
  223. BlockParts: rs.ProposalBlockParts.Header(),
  224. BlockBitArray: rs.ProposalBlockParts.BitArray(),
  225. }
  226. }
  227. return
  228. }
  229. // Listens for changes to the ConsensusState.Step by pulling
  230. // on conR.conS.NewStepCh().
  231. func (conR *ConsensusReactor) broadcastNewRoundStepRoutine() {
  232. for {
  233. // Get RoundState with new Step or quit.
  234. var rs *RoundState
  235. select {
  236. case rs = <-conR.conS.NewStepCh():
  237. case <-conR.quit:
  238. return
  239. }
  240. nrsMsg, csMsg := makeRoundStepMessages(rs)
  241. if nrsMsg != nil {
  242. conR.sw.Broadcast(StateChannel, nrsMsg)
  243. }
  244. if csMsg != nil {
  245. conR.sw.Broadcast(StateChannel, csMsg)
  246. }
  247. }
  248. }
  249. func (conR *ConsensusReactor) sendNewRoundStepRoutine(peer *p2p.Peer) {
  250. rs := conR.conS.GetRoundState()
  251. nrsMsg, csMsg := makeRoundStepMessages(rs)
  252. if nrsMsg != nil {
  253. peer.Send(StateChannel, nrsMsg)
  254. }
  255. if csMsg != nil {
  256. peer.Send(StateChannel, nrsMsg)
  257. }
  258. }
  259. func (conR *ConsensusReactor) gossipDataRoutine(peer *p2p.Peer, ps *PeerState) {
  260. OUTER_LOOP:
  261. for {
  262. // Manage disconnects from self or peer.
  263. if !peer.IsRunning() || !conR.IsRunning() {
  264. log.Info(Fmt("Stopping gossipDataRoutine for %v.", peer))
  265. return
  266. }
  267. rs := conR.conS.GetRoundState()
  268. prs := ps.GetRoundState()
  269. // Send proposal Block parts?
  270. // NOTE: if we or peer is at RoundStepCommit*, the round
  271. // won't necessarily match, but that's OK.
  272. if rs.ProposalBlockParts.HasHeader(prs.ProposalBlockParts) {
  273. //log.Debug("ProposalBlockParts matched", "blockParts", prs.ProposalBlockParts)
  274. if index, ok := rs.ProposalBlockParts.BitArray().Sub(prs.ProposalBlockBitArray.Copy()).PickRandom(); ok {
  275. part := rs.ProposalBlockParts.GetPart(index)
  276. msg := &PartMessage{
  277. Height: rs.Height,
  278. Round: rs.Round,
  279. Type: partTypeProposalBlock,
  280. Part: part,
  281. }
  282. peer.Send(DataChannel, msg)
  283. ps.SetHasProposalBlockPart(rs.Height, rs.Round, index)
  284. continue OUTER_LOOP
  285. }
  286. }
  287. // If the peer is on a previous height, help catch up.
  288. if 0 < prs.Height && prs.Height < rs.Height {
  289. //log.Debug("Data catchup", "height", rs.Height, "peerHeight", prs.Height, "peerProposalBlockBitArray", prs.ProposalBlockBitArray)
  290. if index, ok := prs.ProposalBlockBitArray.Not().PickRandom(); ok {
  291. // Ensure that the peer's PartSetHeader is correct
  292. blockMeta := conR.blockStore.LoadBlockMeta(prs.Height)
  293. if !blockMeta.Parts.Equals(prs.ProposalBlockParts) {
  294. log.Debug("Peer ProposalBlockParts mismatch, sleeping",
  295. "peerHeight", prs.Height, "blockParts", blockMeta.Parts, "peerBlockParts", prs.ProposalBlockParts)
  296. time.Sleep(peerGossipSleepDuration)
  297. continue OUTER_LOOP
  298. }
  299. // Load the part
  300. part := conR.blockStore.LoadBlockPart(prs.Height, index)
  301. if part == nil {
  302. log.Warn("Could not load part", "index", index,
  303. "peerHeight", prs.Height, "blockParts", blockMeta.Parts, "peerBlockParts", prs.ProposalBlockParts)
  304. time.Sleep(peerGossipSleepDuration)
  305. continue OUTER_LOOP
  306. }
  307. // Send the part
  308. msg := &PartMessage{
  309. Height: prs.Height,
  310. Round: prs.Round,
  311. Type: partTypeProposalBlock,
  312. Part: part,
  313. }
  314. peer.Send(DataChannel, msg)
  315. ps.SetHasProposalBlockPart(prs.Height, prs.Round, index)
  316. continue OUTER_LOOP
  317. } else {
  318. //log.Debug("No parts to send in catch-up, sleeping")
  319. time.Sleep(peerGossipSleepDuration)
  320. continue OUTER_LOOP
  321. }
  322. }
  323. // If height and round don't match, sleep.
  324. if rs.Height != prs.Height || rs.Round != prs.Round {
  325. //log.Debug("Peer Height|Round mismatch, sleeping", "peerHeight", prs.Height, "peerRound", prs.Round, "peer", peer)
  326. time.Sleep(peerGossipSleepDuration)
  327. continue OUTER_LOOP
  328. }
  329. // Send proposal?
  330. if rs.Proposal != nil && !prs.Proposal {
  331. msg := &ProposalMessage{Proposal: rs.Proposal}
  332. peer.Send(DataChannel, msg)
  333. ps.SetHasProposal(rs.Proposal)
  334. continue OUTER_LOOP
  335. }
  336. // Send proposal POL parts?
  337. if rs.ProposalPOLParts.HasHeader(prs.ProposalPOLParts) {
  338. if index, ok := rs.ProposalPOLParts.BitArray().Sub(prs.ProposalPOLBitArray.Copy()).PickRandom(); ok {
  339. msg := &PartMessage{
  340. Height: rs.Height,
  341. Round: rs.Round,
  342. Type: partTypeProposalPOL,
  343. Part: rs.ProposalPOLParts.GetPart(index),
  344. }
  345. peer.Send(DataChannel, msg)
  346. ps.SetHasProposalPOLPart(rs.Height, rs.Round, index)
  347. continue OUTER_LOOP
  348. }
  349. }
  350. // Nothing to do. Sleep.
  351. time.Sleep(peerGossipSleepDuration)
  352. continue OUTER_LOOP
  353. }
  354. }
  355. func (conR *ConsensusReactor) gossipVotesRoutine(peer *p2p.Peer, ps *PeerState) {
  356. OUTER_LOOP:
  357. for {
  358. // Manage disconnects from self or peer.
  359. if !peer.IsRunning() || !conR.IsRunning() {
  360. log.Info(Fmt("Stopping gossipVotesRoutine for %v.", peer))
  361. return
  362. }
  363. rs := conR.conS.GetRoundState()
  364. prs := ps.GetRoundState()
  365. trySendVote := func(voteSet *VoteSet, peerVoteSet BitArray) (sent bool) {
  366. if prs.Height == voteSet.Height() {
  367. // Initialize Prevotes/Precommits/Commits if needed
  368. ps.EnsureVoteBitArrays(prs.Height, voteSet.Size())
  369. }
  370. // TODO: give priority to our vote.
  371. if index, ok := voteSet.BitArray().Sub(peerVoteSet.Copy()).PickRandom(); ok {
  372. vote := voteSet.GetByIndex(index)
  373. // NOTE: vote may be a commit.
  374. msg := &VoteMessage{index, vote}
  375. peer.Send(VoteChannel, msg)
  376. ps.SetHasVote(vote, index)
  377. return true
  378. }
  379. return false
  380. }
  381. trySendCommitFromValidation := func(blockMeta *types.BlockMeta, validation *types.Validation, peerVoteSet BitArray) (sent bool) {
  382. // Initialize Commits if needed
  383. ps.EnsureVoteBitArrays(prs.Height, uint(len(validation.Commits)))
  384. if index, ok := validation.BitArray().Sub(prs.Commits.Copy()).PickRandom(); ok {
  385. commit := validation.Commits[index]
  386. log.Debug("Picked commit to send", "index", index, "commit", commit)
  387. // Reconstruct vote.
  388. vote := &types.Vote{
  389. Height: prs.Height,
  390. Round: commit.Round,
  391. Type: types.VoteTypeCommit,
  392. BlockHash: blockMeta.Hash,
  393. BlockParts: blockMeta.Parts,
  394. Signature: commit.Signature,
  395. }
  396. msg := &VoteMessage{index, vote}
  397. peer.Send(VoteChannel, msg)
  398. ps.SetHasVote(vote, index)
  399. return true
  400. }
  401. return false
  402. }
  403. // If height matches, then send LastCommits, Prevotes, Precommits, or Commits.
  404. if rs.Height == prs.Height {
  405. // If there are lastcommits to send...
  406. if prs.Round == 0 && prs.Step == RoundStepNewHeight {
  407. if prs.LastCommits.Size() == rs.LastCommits.Size() {
  408. if trySendVote(rs.LastCommits, prs.LastCommits) {
  409. continue OUTER_LOOP
  410. }
  411. }
  412. }
  413. // If there are prevotes to send...
  414. if rs.Round == prs.Round && prs.Step <= RoundStepPrevote {
  415. if trySendVote(rs.Prevotes, prs.Prevotes) {
  416. continue OUTER_LOOP
  417. }
  418. }
  419. // If there are precommits to send...
  420. if rs.Round == prs.Round && prs.Step <= RoundStepPrecommit {
  421. if trySendVote(rs.Precommits, prs.Precommits) {
  422. continue OUTER_LOOP
  423. }
  424. }
  425. // If there are any commits to send...
  426. if trySendVote(rs.Commits, prs.Commits) {
  427. continue OUTER_LOOP
  428. }
  429. }
  430. // Catchup logic
  431. if prs.Height != 0 && !prs.HasAllCatchupCommits {
  432. // If peer is lagging by height 1, match our LastCommits or SeenValidation to peer's Commits.
  433. if rs.Height == prs.Height+1 && rs.LastCommits.Size() > 0 {
  434. // If there are lastcommits to send...
  435. if trySendVote(rs.LastCommits, prs.Commits) {
  436. continue OUTER_LOOP
  437. } else {
  438. ps.SetHasAllCatchupCommits(prs.Height)
  439. }
  440. }
  441. // Or, if peer is lagging by 1 and we don't have LastCommits, send SeenValidation.
  442. if rs.Height == prs.Height+1 && rs.LastCommits.Size() == 0 {
  443. // Load the blockMeta for block at prs.Height
  444. blockMeta := conR.blockStore.LoadBlockMeta(prs.Height)
  445. // Load the seen validation for prs.Height
  446. validation := conR.blockStore.LoadSeenValidation(prs.Height)
  447. log.Debug("Loaded SeenValidation for catch-up", "height", prs.Height, "blockMeta", blockMeta, "validation", validation)
  448. if trySendCommitFromValidation(blockMeta, validation, prs.Commits) {
  449. continue OUTER_LOOP
  450. } else {
  451. ps.SetHasAllCatchupCommits(prs.Height)
  452. }
  453. }
  454. // If peer is lagging by more than 1, send Validation.
  455. if rs.Height >= prs.Height+2 {
  456. // Load the blockMeta for block at prs.Height
  457. blockMeta := conR.blockStore.LoadBlockMeta(prs.Height)
  458. // Load the block validation for prs.Height+1,
  459. // which contains commit signatures for prs.Height.
  460. validation := conR.blockStore.LoadBlockValidation(prs.Height + 1)
  461. log.Debug("Loaded BlockValidation for catch-up", "height", prs.Height+1, "blockMeta", blockMeta, "validation", validation)
  462. if trySendCommitFromValidation(blockMeta, validation, prs.Commits) {
  463. continue OUTER_LOOP
  464. } else {
  465. ps.SetHasAllCatchupCommits(prs.Height)
  466. }
  467. }
  468. }
  469. // We sent nothing. Sleep...
  470. time.Sleep(peerGossipSleepDuration)
  471. continue OUTER_LOOP
  472. }
  473. }
  474. //-----------------------------------------------------------------------------
  475. // Read only when returned by PeerState.GetRoundState().
  476. type PeerRoundState struct {
  477. Height uint // Height peer is at
  478. Round uint // Round peer is at
  479. Step RoundStep // Step peer is at
  480. StartTime time.Time // Estimated start of round 0 at this height
  481. Proposal bool // True if peer has proposal for this round
  482. ProposalBlockParts types.PartSetHeader //
  483. ProposalBlockBitArray BitArray // True bit -> has part
  484. ProposalPOLParts types.PartSetHeader //
  485. ProposalPOLBitArray BitArray // True bit -> has part
  486. Prevotes BitArray // All votes peer has for this round
  487. Precommits BitArray // All precommits peer has for this round
  488. Commits BitArray // All commits peer has for this height
  489. LastCommits BitArray // All commits peer has for last height
  490. HasAllCatchupCommits bool // Used for catch-up
  491. }
  492. //-----------------------------------------------------------------------------
  493. var (
  494. ErrPeerStateHeightRegression = errors.New("Error peer state height regression")
  495. ErrPeerStateInvalidStartTime = errors.New("Error peer state invalid startTime")
  496. )
  497. type PeerState struct {
  498. mtx sync.Mutex
  499. PeerRoundState
  500. }
  501. func NewPeerState(peer *p2p.Peer) *PeerState {
  502. return &PeerState{}
  503. }
  504. // Returns an atomic snapshot of the PeerRoundState.
  505. // There's no point in mutating it since it won't change PeerState.
  506. func (ps *PeerState) GetRoundState() *PeerRoundState {
  507. ps.mtx.Lock()
  508. defer ps.mtx.Unlock()
  509. prs := ps.PeerRoundState // copy
  510. return &prs
  511. }
  512. func (ps *PeerState) SetHasProposal(proposal *Proposal) {
  513. ps.mtx.Lock()
  514. defer ps.mtx.Unlock()
  515. if ps.Height != proposal.Height || ps.Round != proposal.Round {
  516. return
  517. }
  518. if ps.Proposal {
  519. return
  520. }
  521. ps.Proposal = true
  522. ps.ProposalBlockParts = proposal.BlockParts
  523. ps.ProposalBlockBitArray = NewBitArray(uint(proposal.BlockParts.Total))
  524. ps.ProposalPOLParts = proposal.POLParts
  525. ps.ProposalPOLBitArray = NewBitArray(uint(proposal.POLParts.Total))
  526. }
  527. func (ps *PeerState) SetHasProposalBlockPart(height uint, round uint, index uint) {
  528. ps.mtx.Lock()
  529. defer ps.mtx.Unlock()
  530. if ps.Height != height || ps.Round != round {
  531. return
  532. }
  533. ps.ProposalBlockBitArray.SetIndex(uint(index), true)
  534. }
  535. func (ps *PeerState) SetHasProposalPOLPart(height uint, round uint, index uint) {
  536. ps.mtx.Lock()
  537. defer ps.mtx.Unlock()
  538. if ps.Height != height || ps.Round != round {
  539. return
  540. }
  541. ps.ProposalPOLBitArray.SetIndex(uint(index), true)
  542. }
  543. func (ps *PeerState) EnsureVoteBitArrays(height uint, numValidators uint) {
  544. ps.mtx.Lock()
  545. defer ps.mtx.Unlock()
  546. if ps.Height != height {
  547. return
  548. }
  549. if ps.Prevotes.IsZero() {
  550. ps.Prevotes = NewBitArray(numValidators)
  551. }
  552. if ps.Precommits.IsZero() {
  553. ps.Precommits = NewBitArray(numValidators)
  554. }
  555. if ps.Commits.IsZero() {
  556. ps.Commits = NewBitArray(numValidators)
  557. }
  558. }
  559. func (ps *PeerState) SetHasVote(vote *types.Vote, index uint) {
  560. ps.mtx.Lock()
  561. defer ps.mtx.Unlock()
  562. ps.setHasVote(vote.Height, vote.Round, vote.Type, index)
  563. }
  564. func (ps *PeerState) setHasVote(height uint, round uint, type_ byte, index uint) {
  565. if ps.Height == height+1 && type_ == types.VoteTypeCommit {
  566. // Special case for LastCommits.
  567. ps.LastCommits.SetIndex(index, true)
  568. return
  569. } else if ps.Height != height {
  570. // Does not apply.
  571. return
  572. }
  573. switch type_ {
  574. case types.VoteTypePrevote:
  575. ps.Prevotes.SetIndex(index, true)
  576. case types.VoteTypePrecommit:
  577. ps.Precommits.SetIndex(index, true)
  578. case types.VoteTypeCommit:
  579. if round < ps.Round {
  580. ps.Prevotes.SetIndex(index, true)
  581. ps.Precommits.SetIndex(index, true)
  582. }
  583. ps.Commits.SetIndex(index, true)
  584. default:
  585. panic("Invalid vote type")
  586. }
  587. }
  588. // When catching up, this helps keep track of whether
  589. // we should send more commit votes from the block (validation) store
  590. func (ps *PeerState) SetHasAllCatchupCommits(height uint) {
  591. ps.mtx.Lock()
  592. defer ps.mtx.Unlock()
  593. if ps.Height == height {
  594. ps.HasAllCatchupCommits = true
  595. }
  596. }
  597. func (ps *PeerState) ApplyNewRoundStepMessage(msg *NewRoundStepMessage, rs *RoundState) {
  598. ps.mtx.Lock()
  599. defer ps.mtx.Unlock()
  600. // Just remember these values.
  601. psHeight := ps.Height
  602. psRound := ps.Round
  603. //psStep := ps.Step
  604. startTime := time.Now().Add(-1 * time.Duration(msg.SecondsSinceStartTime) * time.Second)
  605. ps.Height = msg.Height
  606. ps.Round = msg.Round
  607. ps.Step = msg.Step
  608. ps.StartTime = startTime
  609. if psHeight != msg.Height || psRound != msg.Round {
  610. ps.Proposal = false
  611. ps.ProposalBlockParts = types.PartSetHeader{}
  612. ps.ProposalBlockBitArray = BitArray{}
  613. ps.ProposalPOLParts = types.PartSetHeader{}
  614. ps.ProposalPOLBitArray = BitArray{}
  615. // We'll update the BitArray capacity later.
  616. ps.Prevotes = BitArray{}
  617. ps.Precommits = BitArray{}
  618. }
  619. if psHeight != msg.Height {
  620. // Shift Commits to LastCommits
  621. if psHeight+1 == msg.Height {
  622. ps.LastCommits = ps.Commits
  623. } else {
  624. ps.LastCommits = BitArray{}
  625. }
  626. // We'll update the BitArray capacity later.
  627. ps.Commits = BitArray{}
  628. ps.HasAllCatchupCommits = false
  629. }
  630. }
  631. func (ps *PeerState) ApplyCommitStepMessage(msg *CommitStepMessage) {
  632. ps.mtx.Lock()
  633. defer ps.mtx.Unlock()
  634. if ps.Height != msg.Height {
  635. return
  636. }
  637. ps.ProposalBlockParts = msg.BlockParts
  638. ps.ProposalBlockBitArray = msg.BlockBitArray
  639. }
  640. func (ps *PeerState) ApplyHasVoteMessage(msg *HasVoteMessage) {
  641. ps.mtx.Lock()
  642. defer ps.mtx.Unlock()
  643. // Special case for LastCommits
  644. if ps.Height == msg.Height+1 && msg.Type == types.VoteTypeCommit {
  645. ps.LastCommits.SetIndex(msg.Index, true)
  646. return
  647. } else if ps.Height != msg.Height {
  648. return
  649. }
  650. ps.setHasVote(msg.Height, msg.Round, msg.Type, msg.Index)
  651. }
  652. //-----------------------------------------------------------------------------
  653. // Messages
  654. const (
  655. msgTypeNewRoundStep = byte(0x01)
  656. msgTypeCommitStep = byte(0x02)
  657. msgTypeProposal = byte(0x11)
  658. msgTypePart = byte(0x12) // both block & POL
  659. msgTypeVote = byte(0x13)
  660. msgTypeHasVote = byte(0x14)
  661. )
  662. type ConsensusMessage interface{}
  663. var _ = binary.RegisterInterface(
  664. struct{ ConsensusMessage }{},
  665. binary.ConcreteType{&NewRoundStepMessage{}, msgTypeNewRoundStep},
  666. binary.ConcreteType{&CommitStepMessage{}, msgTypeCommitStep},
  667. binary.ConcreteType{&ProposalMessage{}, msgTypeProposal},
  668. binary.ConcreteType{&PartMessage{}, msgTypePart},
  669. binary.ConcreteType{&VoteMessage{}, msgTypeVote},
  670. binary.ConcreteType{&HasVoteMessage{}, msgTypeHasVote},
  671. )
  672. // TODO: check for unnecessary extra bytes at the end.
  673. func DecodeMessage(bz []byte) (msgType byte, msg ConsensusMessage, err error) {
  674. msgType = bz[0]
  675. n := new(int64)
  676. r := bytes.NewReader(bz)
  677. msg = binary.ReadBinary(struct{ ConsensusMessage }{}, r, n, &err).(struct{ ConsensusMessage }).ConsensusMessage
  678. return
  679. }
  680. //-------------------------------------
  681. type NewRoundStepMessage struct {
  682. Height uint
  683. Round uint
  684. Step RoundStep
  685. SecondsSinceStartTime uint
  686. }
  687. func (m *NewRoundStepMessage) String() string {
  688. return fmt.Sprintf("[NewRoundStep H:%v R:%v S:%v]", m.Height, m.Round, m.Step)
  689. }
  690. //-------------------------------------
  691. type CommitStepMessage struct {
  692. Height uint
  693. BlockParts types.PartSetHeader
  694. BlockBitArray BitArray
  695. }
  696. func (m *CommitStepMessage) String() string {
  697. return fmt.Sprintf("[CommitStep H:%v BP:%v BA:%v]", m.Height, m.BlockParts, m.BlockBitArray)
  698. }
  699. //-------------------------------------
  700. type ProposalMessage struct {
  701. Proposal *Proposal
  702. }
  703. func (m *ProposalMessage) String() string {
  704. return fmt.Sprintf("[Proposal %v]", m.Proposal)
  705. }
  706. //-------------------------------------
  707. const (
  708. partTypeProposalBlock = byte(0x01)
  709. partTypeProposalPOL = byte(0x02)
  710. )
  711. type PartMessage struct {
  712. Height uint
  713. Round uint
  714. Type byte
  715. Part *types.Part
  716. }
  717. func (m *PartMessage) String() string {
  718. return fmt.Sprintf("[Part H:%v R:%v T:%X P:%v]", m.Height, m.Round, m.Type, m.Part)
  719. }
  720. //-------------------------------------
  721. type VoteMessage struct {
  722. ValidatorIndex uint
  723. Vote *types.Vote
  724. }
  725. func (m *VoteMessage) String() string {
  726. return fmt.Sprintf("[Vote VI:%v V:%v]", m.ValidatorIndex, m.Vote)
  727. }
  728. //-------------------------------------
  729. type HasVoteMessage struct {
  730. Height uint
  731. Round uint
  732. Type byte
  733. Index uint
  734. }
  735. func (m *HasVoteMessage) String() string {
  736. return fmt.Sprintf("[HasVote %v/%v T:%X]", m.Height, m.Round, m.Type)
  737. }