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.

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