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.

1329 lines
40 KiB

8 years ago
10 years ago
10 years ago
8 years ago
10 years ago
8 years ago
10 years ago
8 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
8 years ago
10 years ago
10 years ago
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
8 years ago
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
10 years ago
10 years ago
8 years ago
10 years ago
10 years ago
10 years ago
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
10 years ago
8 years ago
10 years ago
10 years ago
8 years ago
9 years ago
10 years ago
10 years ago
8 years ago
10 years ago
10 years ago
8 years ago
8 years ago
8 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
8 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
8 years ago
  1. package consensus
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "reflect"
  7. "sync"
  8. "time"
  9. wire "github.com/tendermint/go-wire"
  10. cmn "github.com/tendermint/tmlibs/common"
  11. "github.com/tendermint/tmlibs/log"
  12. "github.com/tendermint/tendermint/p2p"
  13. sm "github.com/tendermint/tendermint/state"
  14. "github.com/tendermint/tendermint/types"
  15. )
  16. const (
  17. StateChannel = byte(0x20)
  18. DataChannel = byte(0x21)
  19. VoteChannel = byte(0x22)
  20. VoteSetBitsChannel = byte(0x23)
  21. maxConsensusMessageSize = 1048576 // 1MB; NOTE/TODO: keep in sync with types.PartSet sizes.
  22. )
  23. //-----------------------------------------------------------------------------
  24. // ConsensusReactor defines a reactor for the consensus service.
  25. type ConsensusReactor struct {
  26. p2p.BaseReactor // BaseService + p2p.Switch
  27. conS *ConsensusState
  28. fastSync bool
  29. evsw types.EventSwitch
  30. }
  31. // NewConsensusReactor returns a new ConsensusReactor with the given consensusState.
  32. func NewConsensusReactor(consensusState *ConsensusState, fastSync bool) *ConsensusReactor {
  33. conR := &ConsensusReactor{
  34. conS: consensusState,
  35. fastSync: fastSync,
  36. }
  37. conR.BaseReactor = *p2p.NewBaseReactor("ConsensusReactor", conR)
  38. return conR
  39. }
  40. // OnStart implements BaseService.
  41. func (conR *ConsensusReactor) OnStart() error {
  42. conR.Logger.Info("ConsensusReactor ", "fastSync", conR.fastSync)
  43. conR.BaseReactor.OnStart()
  44. // callbacks for broadcasting new steps and votes to peers
  45. // upon their respective events (ie. uses evsw)
  46. conR.registerEventCallbacks()
  47. if !conR.fastSync {
  48. _, err := conR.conS.Start()
  49. if err != nil {
  50. return err
  51. }
  52. }
  53. return nil
  54. }
  55. // OnStop implements BaseService
  56. func (conR *ConsensusReactor) OnStop() {
  57. conR.BaseReactor.OnStop()
  58. conR.conS.Stop()
  59. }
  60. // SwitchToConsensus switches from fast_sync mode to consensus mode.
  61. // It resets the state, turns off fast_sync, and starts the consensus state-machine
  62. func (conR *ConsensusReactor) SwitchToConsensus(state *sm.State) {
  63. conR.Logger.Info("SwitchToConsensus")
  64. conR.conS.reconstructLastCommit(state)
  65. // NOTE: The line below causes broadcastNewRoundStepRoutine() to
  66. // broadcast a NewRoundStepMessage.
  67. conR.conS.updateToState(state)
  68. conR.fastSync = false
  69. conR.conS.Start()
  70. }
  71. // GetChannels implements Reactor
  72. func (conR *ConsensusReactor) GetChannels() []*p2p.ChannelDescriptor {
  73. // TODO optimize
  74. return []*p2p.ChannelDescriptor{
  75. &p2p.ChannelDescriptor{
  76. ID: StateChannel,
  77. Priority: 5,
  78. SendQueueCapacity: 100,
  79. },
  80. &p2p.ChannelDescriptor{
  81. ID: DataChannel, // maybe split between gossiping current block and catchup stuff
  82. Priority: 10, // once we gossip the whole block there's nothing left to send until next height or round
  83. SendQueueCapacity: 100,
  84. RecvBufferCapacity: 50 * 4096,
  85. },
  86. &p2p.ChannelDescriptor{
  87. ID: VoteChannel,
  88. Priority: 5,
  89. SendQueueCapacity: 100,
  90. RecvBufferCapacity: 100 * 100,
  91. },
  92. &p2p.ChannelDescriptor{
  93. ID: VoteSetBitsChannel,
  94. Priority: 1,
  95. SendQueueCapacity: 2,
  96. RecvBufferCapacity: 1024,
  97. },
  98. }
  99. }
  100. // AddPeer implements Reactor
  101. func (conR *ConsensusReactor) AddPeer(peer *p2p.Peer) {
  102. if !conR.IsRunning() {
  103. return
  104. }
  105. // Create peerState for peer
  106. peerState := NewPeerState(peer)
  107. peer.Data.Set(types.PeerStateKey, peerState)
  108. // Begin routines for this peer.
  109. go conR.gossipDataRoutine(peer, peerState)
  110. go conR.gossipVotesRoutine(peer, peerState)
  111. go conR.queryMaj23Routine(peer, peerState)
  112. // Send our state to peer.
  113. // If we're fast_syncing, broadcast a RoundStepMessage later upon SwitchToConsensus().
  114. if !conR.fastSync {
  115. conR.sendNewRoundStepMessages(peer)
  116. }
  117. }
  118. // RemovePeer implements Reactor
  119. func (conR *ConsensusReactor) RemovePeer(peer *p2p.Peer, reason interface{}) {
  120. if !conR.IsRunning() {
  121. return
  122. }
  123. // TODO
  124. //peer.Data.Get(PeerStateKey).(*PeerState).Disconnect()
  125. }
  126. // Receive implements Reactor
  127. // NOTE: We process these messages even when we're fast_syncing.
  128. // Messages affect either a peer state or the consensus state.
  129. // Peer state updates can happen in parallel, but processing of
  130. // proposals, block parts, and votes are ordered by the receiveRoutine
  131. // NOTE: blocks on consensus state for proposals, block parts, and votes
  132. func (conR *ConsensusReactor) Receive(chID byte, src *p2p.Peer, msgBytes []byte) {
  133. if !conR.IsRunning() {
  134. conR.Logger.Debug("Receive", "src", src, "chId", chID, "bytes", msgBytes)
  135. return
  136. }
  137. _, msg, err := DecodeMessage(msgBytes)
  138. if err != nil {
  139. conR.Logger.Error("Error decoding message", "src", src, "chId", chID, "msg", msg, "err", err, "bytes", msgBytes)
  140. // TODO punish peer?
  141. return
  142. }
  143. conR.Logger.Debug("Receive", "src", src, "chId", chID, "msg", msg)
  144. // Get peer states
  145. ps := src.Data.Get(types.PeerStateKey).(*PeerState)
  146. switch chID {
  147. case StateChannel:
  148. switch msg := msg.(type) {
  149. case *NewRoundStepMessage:
  150. ps.ApplyNewRoundStepMessage(msg)
  151. case *CommitStepMessage:
  152. ps.ApplyCommitStepMessage(msg)
  153. case *HasVoteMessage:
  154. ps.ApplyHasVoteMessage(msg)
  155. case *VoteSetMaj23Message:
  156. cs := conR.conS
  157. cs.mtx.Lock()
  158. height, votes := cs.Height, cs.Votes
  159. cs.mtx.Unlock()
  160. if height != msg.Height {
  161. return
  162. }
  163. // Peer claims to have a maj23 for some BlockID at H,R,S,
  164. votes.SetPeerMaj23(msg.Round, msg.Type, ps.Peer.Key, msg.BlockID)
  165. // Respond with a VoteSetBitsMessage showing which votes we have.
  166. // (and consequently shows which we don't have)
  167. var ourVotes *cmn.BitArray
  168. switch msg.Type {
  169. case types.VoteTypePrevote:
  170. ourVotes = votes.Prevotes(msg.Round).BitArrayByBlockID(msg.BlockID)
  171. case types.VoteTypePrecommit:
  172. ourVotes = votes.Precommits(msg.Round).BitArrayByBlockID(msg.BlockID)
  173. default:
  174. conR.Logger.Error("Bad VoteSetBitsMessage field Type")
  175. return
  176. }
  177. src.TrySend(VoteSetBitsChannel, struct{ ConsensusMessage }{&VoteSetBitsMessage{
  178. Height: msg.Height,
  179. Round: msg.Round,
  180. Type: msg.Type,
  181. BlockID: msg.BlockID,
  182. Votes: ourVotes,
  183. }})
  184. default:
  185. conR.Logger.Error(cmn.Fmt("Unknown message type %v", reflect.TypeOf(msg)))
  186. }
  187. case DataChannel:
  188. if conR.fastSync {
  189. conR.Logger.Info("Ignoring message received during fastSync", "msg", msg)
  190. return
  191. }
  192. switch msg := msg.(type) {
  193. case *ProposalMessage:
  194. ps.SetHasProposal(msg.Proposal)
  195. conR.conS.peerMsgQueue <- msgInfo{msg, src.Key}
  196. case *ProposalPOLMessage:
  197. ps.ApplyProposalPOLMessage(msg)
  198. case *BlockPartMessage:
  199. ps.SetHasProposalBlockPart(msg.Height, msg.Round, msg.Part.Index)
  200. conR.conS.peerMsgQueue <- msgInfo{msg, src.Key}
  201. default:
  202. conR.Logger.Error(cmn.Fmt("Unknown message type %v", reflect.TypeOf(msg)))
  203. }
  204. case VoteChannel:
  205. if conR.fastSync {
  206. conR.Logger.Info("Ignoring message received during fastSync", "msg", msg)
  207. return
  208. }
  209. switch msg := msg.(type) {
  210. case *VoteMessage:
  211. cs := conR.conS
  212. cs.mtx.Lock()
  213. height, valSize, lastCommitSize := cs.Height, cs.Validators.Size(), cs.LastCommit.Size()
  214. cs.mtx.Unlock()
  215. ps.EnsureVoteBitArrays(height, valSize)
  216. ps.EnsureVoteBitArrays(height-1, lastCommitSize)
  217. ps.SetHasVote(msg.Vote)
  218. cs.peerMsgQueue <- msgInfo{msg, src.Key}
  219. default:
  220. // don't punish (leave room for soft upgrades)
  221. conR.Logger.Error(cmn.Fmt("Unknown message type %v", reflect.TypeOf(msg)))
  222. }
  223. case VoteSetBitsChannel:
  224. if conR.fastSync {
  225. conR.Logger.Info("Ignoring message received during fastSync", "msg", msg)
  226. return
  227. }
  228. switch msg := msg.(type) {
  229. case *VoteSetBitsMessage:
  230. cs := conR.conS
  231. cs.mtx.Lock()
  232. height, votes := cs.Height, cs.Votes
  233. cs.mtx.Unlock()
  234. if height == msg.Height {
  235. var ourVotes *cmn.BitArray
  236. switch msg.Type {
  237. case types.VoteTypePrevote:
  238. ourVotes = votes.Prevotes(msg.Round).BitArrayByBlockID(msg.BlockID)
  239. case types.VoteTypePrecommit:
  240. ourVotes = votes.Precommits(msg.Round).BitArrayByBlockID(msg.BlockID)
  241. default:
  242. conR.Logger.Error("Bad VoteSetBitsMessage field Type")
  243. return
  244. }
  245. ps.ApplyVoteSetBitsMessage(msg, ourVotes)
  246. } else {
  247. ps.ApplyVoteSetBitsMessage(msg, nil)
  248. }
  249. default:
  250. // don't punish (leave room for soft upgrades)
  251. conR.Logger.Error(cmn.Fmt("Unknown message type %v", reflect.TypeOf(msg)))
  252. }
  253. default:
  254. conR.Logger.Error(cmn.Fmt("Unknown chId %X", chID))
  255. }
  256. if err != nil {
  257. conR.Logger.Error("Error in Receive()", "err", err)
  258. }
  259. }
  260. // SetEventSwitch implements events.Eventable
  261. func (conR *ConsensusReactor) SetEventSwitch(evsw types.EventSwitch) {
  262. conR.evsw = evsw
  263. conR.conS.SetEventSwitch(evsw)
  264. }
  265. //--------------------------------------
  266. // Listens for new steps and votes,
  267. // broadcasting the result to peers
  268. func (conR *ConsensusReactor) registerEventCallbacks() {
  269. types.AddListenerForEvent(conR.evsw, "conR", types.EventStringNewRoundStep(), func(data types.TMEventData) {
  270. rs := data.Unwrap().(types.EventDataRoundState).RoundState.(*RoundState)
  271. conR.broadcastNewRoundStep(rs)
  272. })
  273. types.AddListenerForEvent(conR.evsw, "conR", types.EventStringVote(), func(data types.TMEventData) {
  274. edv := data.Unwrap().(types.EventDataVote)
  275. conR.broadcastHasVoteMessage(edv.Vote)
  276. })
  277. types.AddListenerForEvent(conR.evsw, "conR", types.EventStringProposalHeartbeat(), func(data types.TMEventData) {
  278. heartbeat := data.Unwrap().(types.EventDataProposalHeartbeat)
  279. conR.broadcastProposalHeartbeatMessage(heartbeat)
  280. })
  281. }
  282. func (conR *ConsensusReactor) broadcastProposalHeartbeatMessage(heartbeat types.EventDataProposalHeartbeat) {
  283. msg := &ProposalHeartbeatMessage{heartbeat.Heartbeat}
  284. conR.Switch.Broadcast(StateChannel, struct{ ConsensusMessage }{msg})
  285. }
  286. func (conR *ConsensusReactor) broadcastNewRoundStep(rs *RoundState) {
  287. nrsMsg, csMsg := makeRoundStepMessages(rs)
  288. if nrsMsg != nil {
  289. conR.Switch.Broadcast(StateChannel, struct{ ConsensusMessage }{nrsMsg})
  290. }
  291. if csMsg != nil {
  292. conR.Switch.Broadcast(StateChannel, struct{ ConsensusMessage }{csMsg})
  293. }
  294. }
  295. // Broadcasts HasVoteMessage to peers that care.
  296. func (conR *ConsensusReactor) broadcastHasVoteMessage(vote *types.Vote) {
  297. msg := &HasVoteMessage{
  298. Height: vote.Height,
  299. Round: vote.Round,
  300. Type: vote.Type,
  301. Index: vote.ValidatorIndex,
  302. }
  303. conR.Switch.Broadcast(StateChannel, struct{ ConsensusMessage }{msg})
  304. /*
  305. // TODO: Make this broadcast more selective.
  306. for _, peer := range conR.Switch.Peers().List() {
  307. ps := peer.Data.Get(PeerStateKey).(*PeerState)
  308. prs := ps.GetRoundState()
  309. if prs.Height == vote.Height {
  310. // TODO: Also filter on round?
  311. peer.TrySend(StateChannel, struct{ ConsensusMessage }{msg})
  312. } else {
  313. // Height doesn't match
  314. // TODO: check a field, maybe CatchupCommitRound?
  315. // TODO: But that requires changing the struct field comment.
  316. }
  317. }
  318. */
  319. }
  320. func makeRoundStepMessages(rs *RoundState) (nrsMsg *NewRoundStepMessage, csMsg *CommitStepMessage) {
  321. nrsMsg = &NewRoundStepMessage{
  322. Height: rs.Height,
  323. Round: rs.Round,
  324. Step: rs.Step,
  325. SecondsSinceStartTime: int(time.Since(rs.StartTime).Seconds()),
  326. LastCommitRound: rs.LastCommit.Round(),
  327. }
  328. if rs.Step == RoundStepCommit {
  329. csMsg = &CommitStepMessage{
  330. Height: rs.Height,
  331. BlockPartsHeader: rs.ProposalBlockParts.Header(),
  332. BlockParts: rs.ProposalBlockParts.BitArray(),
  333. }
  334. }
  335. return
  336. }
  337. func (conR *ConsensusReactor) sendNewRoundStepMessages(peer *p2p.Peer) {
  338. rs := conR.conS.GetRoundState()
  339. nrsMsg, csMsg := makeRoundStepMessages(rs)
  340. if nrsMsg != nil {
  341. peer.Send(StateChannel, struct{ ConsensusMessage }{nrsMsg})
  342. }
  343. if csMsg != nil {
  344. peer.Send(StateChannel, struct{ ConsensusMessage }{csMsg})
  345. }
  346. }
  347. func (conR *ConsensusReactor) gossipDataRoutine(peer *p2p.Peer, ps *PeerState) {
  348. logger := conR.Logger.With("peer", peer)
  349. OUTER_LOOP:
  350. for {
  351. // Manage disconnects from self or peer.
  352. if !peer.IsRunning() || !conR.IsRunning() {
  353. logger.Info("Stopping gossipDataRoutine for peer")
  354. return
  355. }
  356. rs := conR.conS.GetRoundState()
  357. prs := ps.GetRoundState()
  358. // Send proposal Block parts?
  359. if rs.ProposalBlockParts.HasHeader(prs.ProposalBlockPartsHeader) {
  360. if index, ok := rs.ProposalBlockParts.BitArray().Sub(prs.ProposalBlockParts.Copy()).PickRandom(); ok {
  361. part := rs.ProposalBlockParts.GetPart(index)
  362. msg := &BlockPartMessage{
  363. Height: rs.Height, // This tells peer that this part applies to us.
  364. Round: rs.Round, // This tells peer that this part applies to us.
  365. Part: part,
  366. }
  367. logger.Debug("Sending block part", "height", prs.Height, "round", prs.Round)
  368. if peer.Send(DataChannel, struct{ ConsensusMessage }{msg}) {
  369. ps.SetHasProposalBlockPart(prs.Height, prs.Round, index)
  370. }
  371. continue OUTER_LOOP
  372. }
  373. }
  374. // If the peer is on a previous height, help catch up.
  375. if (0 < prs.Height) && (prs.Height < rs.Height) {
  376. heightLogger := logger.With("height", prs.Height)
  377. conR.gossipDataForCatchup(heightLogger, rs, prs, ps, peer)
  378. continue OUTER_LOOP
  379. }
  380. // If height and round don't match, sleep.
  381. if (rs.Height != prs.Height) || (rs.Round != prs.Round) {
  382. //logger.Info("Peer Height|Round mismatch, sleeping", "peerHeight", prs.Height, "peerRound", prs.Round, "peer", peer)
  383. time.Sleep(conR.conS.config.PeerGossipSleep())
  384. continue OUTER_LOOP
  385. }
  386. // By here, height and round match.
  387. // Proposal block parts were already matched and sent if any were wanted.
  388. // (These can match on hash so the round doesn't matter)
  389. // Now consider sending other things, like the Proposal itself.
  390. // Send Proposal && ProposalPOL BitArray?
  391. if rs.Proposal != nil && !prs.Proposal {
  392. // Proposal: share the proposal metadata with peer.
  393. {
  394. msg := &ProposalMessage{Proposal: rs.Proposal}
  395. logger.Debug("Sending proposal", "height", prs.Height, "round", prs.Round)
  396. if peer.Send(DataChannel, struct{ ConsensusMessage }{msg}) {
  397. ps.SetHasProposal(rs.Proposal)
  398. }
  399. }
  400. // ProposalPOL: lets peer know which POL votes we have so far.
  401. // Peer must receive ProposalMessage first.
  402. // rs.Proposal was validated, so rs.Proposal.POLRound <= rs.Round,
  403. // so we definitely have rs.Votes.Prevotes(rs.Proposal.POLRound).
  404. if 0 <= rs.Proposal.POLRound {
  405. msg := &ProposalPOLMessage{
  406. Height: rs.Height,
  407. ProposalPOLRound: rs.Proposal.POLRound,
  408. ProposalPOL: rs.Votes.Prevotes(rs.Proposal.POLRound).BitArray(),
  409. }
  410. logger.Debug("Sending POL", "height", prs.Height, "round", prs.Round)
  411. peer.Send(DataChannel, struct{ ConsensusMessage }{msg})
  412. }
  413. continue OUTER_LOOP
  414. }
  415. // Nothing to do. Sleep.
  416. time.Sleep(conR.conS.config.PeerGossipSleep())
  417. continue OUTER_LOOP
  418. }
  419. }
  420. func (conR *ConsensusReactor) gossipDataForCatchup(logger log.Logger, rs *RoundState,
  421. prs *PeerRoundState, ps *PeerState, peer *p2p.Peer) {
  422. if index, ok := prs.ProposalBlockParts.Not().PickRandom(); ok {
  423. // Ensure that the peer's PartSetHeader is correct
  424. blockMeta := conR.conS.blockStore.LoadBlockMeta(prs.Height)
  425. if blockMeta == nil {
  426. logger.Error("Failed to load block meta",
  427. "ourHeight", rs.Height, "blockstoreHeight", conR.conS.blockStore.Height())
  428. time.Sleep(conR.conS.config.PeerGossipSleep())
  429. return
  430. } else if !blockMeta.BlockID.PartsHeader.Equals(prs.ProposalBlockPartsHeader) {
  431. logger.Info("Peer ProposalBlockPartsHeader mismatch, sleeping",
  432. "blockPartsHeader", blockMeta.BlockID.PartsHeader, "peerBlockPartsHeader", prs.ProposalBlockPartsHeader)
  433. time.Sleep(conR.conS.config.PeerGossipSleep())
  434. return
  435. }
  436. // Load the part
  437. part := conR.conS.blockStore.LoadBlockPart(prs.Height, index)
  438. if part == nil {
  439. logger.Error("Could not load part", "index", index,
  440. "blockPartsHeader", blockMeta.BlockID.PartsHeader, "peerBlockPartsHeader", prs.ProposalBlockPartsHeader)
  441. time.Sleep(conR.conS.config.PeerGossipSleep())
  442. return
  443. }
  444. // Send the part
  445. msg := &BlockPartMessage{
  446. Height: prs.Height, // Not our height, so it doesn't matter.
  447. Round: prs.Round, // Not our height, so it doesn't matter.
  448. Part: part,
  449. }
  450. logger.Debug("Sending block part for catchup", "round", prs.Round)
  451. if peer.Send(DataChannel, struct{ ConsensusMessage }{msg}) {
  452. ps.SetHasProposalBlockPart(prs.Height, prs.Round, index)
  453. }
  454. return
  455. } else {
  456. //logger.Info("No parts to send in catch-up, sleeping")
  457. time.Sleep(conR.conS.config.PeerGossipSleep())
  458. return
  459. }
  460. }
  461. func (conR *ConsensusReactor) gossipVotesRoutine(peer *p2p.Peer, ps *PeerState) {
  462. logger := conR.Logger.With("peer", peer)
  463. // Simple hack to throttle logs upon sleep.
  464. var sleeping = 0
  465. OUTER_LOOP:
  466. for {
  467. // Manage disconnects from self or peer.
  468. if !peer.IsRunning() || !conR.IsRunning() {
  469. logger.Info("Stopping gossipVotesRoutine for peer")
  470. return
  471. }
  472. rs := conR.conS.GetRoundState()
  473. prs := ps.GetRoundState()
  474. switch sleeping {
  475. case 1: // First sleep
  476. sleeping = 2
  477. case 2: // No more sleep
  478. sleeping = 0
  479. }
  480. //logger.Debug("gossipVotesRoutine", "rsHeight", rs.Height, "rsRound", rs.Round,
  481. // "prsHeight", prs.Height, "prsRound", prs.Round, "prsStep", prs.Step)
  482. // If height matches, then send LastCommit, Prevotes, Precommits.
  483. if rs.Height == prs.Height {
  484. heightLogger := logger.With("height", prs.Height)
  485. if conR.gossipVotesForHeight(heightLogger, rs, prs, ps) {
  486. continue OUTER_LOOP
  487. }
  488. }
  489. // Special catchup logic.
  490. // If peer is lagging by height 1, send LastCommit.
  491. if prs.Height != 0 && rs.Height == prs.Height+1 {
  492. if ps.PickSendVote(rs.LastCommit) {
  493. logger.Debug("Picked rs.LastCommit to send", "height", prs.Height)
  494. continue OUTER_LOOP
  495. }
  496. }
  497. // Catchup logic
  498. // If peer is lagging by more than 1, send Commit.
  499. if prs.Height != 0 && rs.Height >= prs.Height+2 {
  500. // Load the block commit for prs.Height,
  501. // which contains precommit signatures for prs.Height.
  502. commit := conR.conS.blockStore.LoadBlockCommit(prs.Height)
  503. logger.Info("Loaded BlockCommit for catch-up", "height", prs.Height, "commit", commit)
  504. if ps.PickSendVote(commit) {
  505. logger.Debug("Picked Catchup commit to send", "height", prs.Height)
  506. continue OUTER_LOOP
  507. }
  508. }
  509. if sleeping == 0 {
  510. // We sent nothing. Sleep...
  511. sleeping = 1
  512. logger.Debug("No votes to send, sleeping", "rs.Height", rs.Height, "prs.Height", prs.Height,
  513. "localPV", rs.Votes.Prevotes(rs.Round).BitArray(), "peerPV", prs.Prevotes,
  514. "localPC", rs.Votes.Precommits(rs.Round).BitArray(), "peerPC", prs.Precommits)
  515. } else if sleeping == 2 {
  516. // Continued sleep...
  517. sleeping = 1
  518. }
  519. time.Sleep(conR.conS.config.PeerGossipSleep())
  520. continue OUTER_LOOP
  521. }
  522. }
  523. func (conR *ConsensusReactor) gossipVotesForHeight(logger log.Logger, rs *RoundState, prs *PeerRoundState, ps *PeerState) bool {
  524. // If there are lastCommits to send...
  525. if prs.Step == RoundStepNewHeight {
  526. if ps.PickSendVote(rs.LastCommit) {
  527. logger.Debug("Picked rs.LastCommit to send")
  528. return true
  529. }
  530. }
  531. // If there are prevotes to send...
  532. if prs.Step <= RoundStepPrevote && prs.Round != -1 && prs.Round <= rs.Round {
  533. if ps.PickSendVote(rs.Votes.Prevotes(prs.Round)) {
  534. logger.Debug("Picked rs.Prevotes(prs.Round) to send", "round", prs.Round)
  535. return true
  536. }
  537. }
  538. // If there are precommits to send...
  539. if prs.Step <= RoundStepPrecommit && prs.Round != -1 && prs.Round <= rs.Round {
  540. if ps.PickSendVote(rs.Votes.Precommits(prs.Round)) {
  541. logger.Debug("Picked rs.Precommits(prs.Round) to send", "round", prs.Round)
  542. return true
  543. }
  544. }
  545. // If there are POLPrevotes to send...
  546. if prs.ProposalPOLRound != -1 {
  547. if polPrevotes := rs.Votes.Prevotes(prs.ProposalPOLRound); polPrevotes != nil {
  548. if ps.PickSendVote(polPrevotes) {
  549. logger.Debug("Picked rs.Prevotes(prs.ProposalPOLRound) to send",
  550. "round", prs.ProposalPOLRound)
  551. return true
  552. }
  553. }
  554. }
  555. return false
  556. }
  557. // NOTE: `queryMaj23Routine` has a simple crude design since it only comes
  558. // into play for liveness when there's a signature DDoS attack happening.
  559. func (conR *ConsensusReactor) queryMaj23Routine(peer *p2p.Peer, ps *PeerState) {
  560. logger := conR.Logger.With("peer", peer)
  561. OUTER_LOOP:
  562. for {
  563. // Manage disconnects from self or peer.
  564. if !peer.IsRunning() || !conR.IsRunning() {
  565. logger.Info("Stopping queryMaj23Routine for peer")
  566. return
  567. }
  568. // Maybe send Height/Round/Prevotes
  569. {
  570. rs := conR.conS.GetRoundState()
  571. prs := ps.GetRoundState()
  572. if rs.Height == prs.Height {
  573. if maj23, ok := rs.Votes.Prevotes(prs.Round).TwoThirdsMajority(); ok {
  574. peer.TrySend(StateChannel, struct{ ConsensusMessage }{&VoteSetMaj23Message{
  575. Height: prs.Height,
  576. Round: prs.Round,
  577. Type: types.VoteTypePrevote,
  578. BlockID: maj23,
  579. }})
  580. time.Sleep(conR.conS.config.PeerQueryMaj23Sleep())
  581. }
  582. }
  583. }
  584. // Maybe send Height/Round/Precommits
  585. {
  586. rs := conR.conS.GetRoundState()
  587. prs := ps.GetRoundState()
  588. if rs.Height == prs.Height {
  589. if maj23, ok := rs.Votes.Precommits(prs.Round).TwoThirdsMajority(); ok {
  590. peer.TrySend(StateChannel, struct{ ConsensusMessage }{&VoteSetMaj23Message{
  591. Height: prs.Height,
  592. Round: prs.Round,
  593. Type: types.VoteTypePrecommit,
  594. BlockID: maj23,
  595. }})
  596. time.Sleep(conR.conS.config.PeerQueryMaj23Sleep())
  597. }
  598. }
  599. }
  600. // Maybe send Height/Round/ProposalPOL
  601. {
  602. rs := conR.conS.GetRoundState()
  603. prs := ps.GetRoundState()
  604. if rs.Height == prs.Height && prs.ProposalPOLRound >= 0 {
  605. if maj23, ok := rs.Votes.Prevotes(prs.ProposalPOLRound).TwoThirdsMajority(); ok {
  606. peer.TrySend(StateChannel, struct{ ConsensusMessage }{&VoteSetMaj23Message{
  607. Height: prs.Height,
  608. Round: prs.ProposalPOLRound,
  609. Type: types.VoteTypePrevote,
  610. BlockID: maj23,
  611. }})
  612. time.Sleep(conR.conS.config.PeerQueryMaj23Sleep())
  613. }
  614. }
  615. }
  616. // Little point sending LastCommitRound/LastCommit,
  617. // These are fleeting and non-blocking.
  618. // Maybe send Height/CatchupCommitRound/CatchupCommit.
  619. {
  620. prs := ps.GetRoundState()
  621. if prs.CatchupCommitRound != -1 && 0 < prs.Height && prs.Height <= conR.conS.blockStore.Height() {
  622. commit := conR.conS.LoadCommit(prs.Height)
  623. peer.TrySend(StateChannel, struct{ ConsensusMessage }{&VoteSetMaj23Message{
  624. Height: prs.Height,
  625. Round: commit.Round(),
  626. Type: types.VoteTypePrecommit,
  627. BlockID: commit.BlockID,
  628. }})
  629. time.Sleep(conR.conS.config.PeerQueryMaj23Sleep())
  630. }
  631. }
  632. time.Sleep(conR.conS.config.PeerQueryMaj23Sleep())
  633. continue OUTER_LOOP
  634. }
  635. }
  636. // String returns a string representation of the ConsensusReactor.
  637. // NOTE: For now, it is just a hard-coded string to avoid accessing unprotected shared variables.
  638. // TODO: improve!
  639. func (conR *ConsensusReactor) String() string {
  640. // better not to access shared variables
  641. return "ConsensusReactor" // conR.StringIndented("")
  642. }
  643. // StringIndented returns an indented string representation of the ConsensusReactor
  644. func (conR *ConsensusReactor) StringIndented(indent string) string {
  645. s := "ConsensusReactor{\n"
  646. s += indent + " " + conR.conS.StringIndented(indent+" ") + "\n"
  647. for _, peer := range conR.Switch.Peers().List() {
  648. ps := peer.Data.Get(types.PeerStateKey).(*PeerState)
  649. s += indent + " " + ps.StringIndented(indent+" ") + "\n"
  650. }
  651. s += indent + "}"
  652. return s
  653. }
  654. //-----------------------------------------------------------------------------
  655. // PeerRoundState contains the known state of a peer.
  656. // NOTE: Read-only when returned by PeerState.GetRoundState().
  657. type PeerRoundState struct {
  658. Height int // Height peer is at
  659. Round int // Round peer is at, -1 if unknown.
  660. Step RoundStepType // Step peer is at
  661. StartTime time.Time // Estimated start of round 0 at this height
  662. Proposal bool // True if peer has proposal for this round
  663. ProposalBlockPartsHeader types.PartSetHeader //
  664. ProposalBlockParts *cmn.BitArray //
  665. ProposalPOLRound int // Proposal's POL round. -1 if none.
  666. ProposalPOL *cmn.BitArray // nil until ProposalPOLMessage received.
  667. Prevotes *cmn.BitArray // All votes peer has for this round
  668. Precommits *cmn.BitArray // All precommits peer has for this round
  669. LastCommitRound int // Round of commit for last height. -1 if none.
  670. LastCommit *cmn.BitArray // All commit precommits of commit for last height.
  671. CatchupCommitRound int // Round that we have commit for. Not necessarily unique. -1 if none.
  672. CatchupCommit *cmn.BitArray // All commit precommits peer has for this height & CatchupCommitRound
  673. }
  674. // String returns a string representation of the PeerRoundState
  675. func (prs PeerRoundState) String() string {
  676. return prs.StringIndented("")
  677. }
  678. // StringIndented returns a string representation of the PeerRoundState
  679. func (prs PeerRoundState) StringIndented(indent string) string {
  680. return fmt.Sprintf(`PeerRoundState{
  681. %s %v/%v/%v @%v
  682. %s Proposal %v -> %v
  683. %s POL %v (round %v)
  684. %s Prevotes %v
  685. %s Precommits %v
  686. %s LastCommit %v (round %v)
  687. %s Catchup %v (round %v)
  688. %s}`,
  689. indent, prs.Height, prs.Round, prs.Step, prs.StartTime,
  690. indent, prs.ProposalBlockPartsHeader, prs.ProposalBlockParts,
  691. indent, prs.ProposalPOL, prs.ProposalPOLRound,
  692. indent, prs.Prevotes,
  693. indent, prs.Precommits,
  694. indent, prs.LastCommit, prs.LastCommitRound,
  695. indent, prs.CatchupCommit, prs.CatchupCommitRound,
  696. indent)
  697. }
  698. //-----------------------------------------------------------------------------
  699. var (
  700. ErrPeerStateHeightRegression = errors.New("Error peer state height regression")
  701. ErrPeerStateInvalidStartTime = errors.New("Error peer state invalid startTime")
  702. )
  703. // PeerState contains the known state of a peer, including its connection
  704. // and threadsafe access to its PeerRoundState.
  705. type PeerState struct {
  706. Peer *p2p.Peer
  707. mtx sync.Mutex
  708. PeerRoundState
  709. }
  710. // NewPeerState returns a new PeerState for the given Peer
  711. func NewPeerState(peer *p2p.Peer) *PeerState {
  712. return &PeerState{
  713. Peer: peer,
  714. PeerRoundState: PeerRoundState{
  715. Round: -1,
  716. ProposalPOLRound: -1,
  717. LastCommitRound: -1,
  718. CatchupCommitRound: -1,
  719. },
  720. }
  721. }
  722. // GetRoundState returns an atomic snapshot of the PeerRoundState.
  723. // There's no point in mutating it since it won't change PeerState.
  724. func (ps *PeerState) GetRoundState() *PeerRoundState {
  725. ps.mtx.Lock()
  726. defer ps.mtx.Unlock()
  727. prs := ps.PeerRoundState // copy
  728. return &prs
  729. }
  730. // GetHeight returns an atomic snapshot of the PeerRoundState's height
  731. // used by the mempool to ensure peers are caught up before broadcasting new txs
  732. func (ps *PeerState) GetHeight() int {
  733. ps.mtx.Lock()
  734. defer ps.mtx.Unlock()
  735. return ps.PeerRoundState.Height
  736. }
  737. // SetHasProposal sets the given proposal as known for the peer.
  738. func (ps *PeerState) SetHasProposal(proposal *types.Proposal) {
  739. ps.mtx.Lock()
  740. defer ps.mtx.Unlock()
  741. if ps.Height != proposal.Height || ps.Round != proposal.Round {
  742. return
  743. }
  744. if ps.Proposal {
  745. return
  746. }
  747. ps.Proposal = true
  748. ps.ProposalBlockPartsHeader = proposal.BlockPartsHeader
  749. ps.ProposalBlockParts = cmn.NewBitArray(proposal.BlockPartsHeader.Total)
  750. ps.ProposalPOLRound = proposal.POLRound
  751. ps.ProposalPOL = nil // Nil until ProposalPOLMessage received.
  752. }
  753. // SetHasProposalBlockPart sets the given block part index as known for the peer.
  754. func (ps *PeerState) SetHasProposalBlockPart(height int, round int, index int) {
  755. ps.mtx.Lock()
  756. defer ps.mtx.Unlock()
  757. if ps.Height != height || ps.Round != round {
  758. return
  759. }
  760. ps.ProposalBlockParts.SetIndex(index, true)
  761. }
  762. // PickSendVote picks a vote and sends it to the peer.
  763. // Returns true if vote was sent.
  764. func (ps *PeerState) PickSendVote(votes types.VoteSetReader) bool {
  765. if vote, ok := ps.PickVoteToSend(votes); ok {
  766. msg := &VoteMessage{vote}
  767. return ps.Peer.Send(VoteChannel, struct{ ConsensusMessage }{msg})
  768. }
  769. return false
  770. }
  771. // PickVoteToSend picks a vote to send to the peer.
  772. // Returns true if a vote was picked.
  773. // NOTE: `votes` must be the correct Size() for the Height().
  774. func (ps *PeerState) PickVoteToSend(votes types.VoteSetReader) (vote *types.Vote, ok bool) {
  775. ps.mtx.Lock()
  776. defer ps.mtx.Unlock()
  777. if votes.Size() == 0 {
  778. return nil, false
  779. }
  780. height, round, type_, size := votes.Height(), votes.Round(), votes.Type(), votes.Size()
  781. // Lazily set data using 'votes'.
  782. if votes.IsCommit() {
  783. ps.ensureCatchupCommitRound(height, round, size)
  784. }
  785. ps.ensureVoteBitArrays(height, size)
  786. psVotes := ps.getVoteBitArray(height, round, type_)
  787. if psVotes == nil {
  788. return nil, false // Not something worth sending
  789. }
  790. if index, ok := votes.BitArray().Sub(psVotes).PickRandom(); ok {
  791. ps.setHasVote(height, round, type_, index)
  792. return votes.GetByIndex(index), true
  793. }
  794. return nil, false
  795. }
  796. func (ps *PeerState) getVoteBitArray(height, round int, type_ byte) *cmn.BitArray {
  797. if !types.IsVoteTypeValid(type_) {
  798. cmn.PanicSanity("Invalid vote type")
  799. }
  800. if ps.Height == height {
  801. if ps.Round == round {
  802. switch type_ {
  803. case types.VoteTypePrevote:
  804. return ps.Prevotes
  805. case types.VoteTypePrecommit:
  806. return ps.Precommits
  807. }
  808. }
  809. if ps.CatchupCommitRound == round {
  810. switch type_ {
  811. case types.VoteTypePrevote:
  812. return nil
  813. case types.VoteTypePrecommit:
  814. return ps.CatchupCommit
  815. }
  816. }
  817. if ps.ProposalPOLRound == round {
  818. switch type_ {
  819. case types.VoteTypePrevote:
  820. return ps.ProposalPOL
  821. case types.VoteTypePrecommit:
  822. return nil
  823. }
  824. }
  825. return nil
  826. }
  827. if ps.Height == height+1 {
  828. if ps.LastCommitRound == round {
  829. switch type_ {
  830. case types.VoteTypePrevote:
  831. return nil
  832. case types.VoteTypePrecommit:
  833. return ps.LastCommit
  834. }
  835. }
  836. return nil
  837. }
  838. return nil
  839. }
  840. // 'round': A round for which we have a +2/3 commit.
  841. func (ps *PeerState) ensureCatchupCommitRound(height, round int, numValidators int) {
  842. if ps.Height != height {
  843. return
  844. }
  845. /*
  846. NOTE: This is wrong, 'round' could change.
  847. e.g. if orig round is not the same as block LastCommit round.
  848. if ps.CatchupCommitRound != -1 && ps.CatchupCommitRound != round {
  849. cmn.PanicSanity(cmn.Fmt("Conflicting CatchupCommitRound. Height: %v, Orig: %v, New: %v", height, ps.CatchupCommitRound, round))
  850. }
  851. */
  852. if ps.CatchupCommitRound == round {
  853. return // Nothing to do!
  854. }
  855. ps.CatchupCommitRound = round
  856. if round == ps.Round {
  857. ps.CatchupCommit = ps.Precommits
  858. } else {
  859. ps.CatchupCommit = cmn.NewBitArray(numValidators)
  860. }
  861. }
  862. // EnsureVoteVitArrays ensures the bit-arrays have been allocated for tracking
  863. // what votes this peer has received.
  864. // NOTE: It's important to make sure that numValidators actually matches
  865. // what the node sees as the number of validators for height.
  866. func (ps *PeerState) EnsureVoteBitArrays(height int, numValidators int) {
  867. ps.mtx.Lock()
  868. defer ps.mtx.Unlock()
  869. ps.ensureVoteBitArrays(height, numValidators)
  870. }
  871. func (ps *PeerState) ensureVoteBitArrays(height int, numValidators int) {
  872. if ps.Height == height {
  873. if ps.Prevotes == nil {
  874. ps.Prevotes = cmn.NewBitArray(numValidators)
  875. }
  876. if ps.Precommits == nil {
  877. ps.Precommits = cmn.NewBitArray(numValidators)
  878. }
  879. if ps.CatchupCommit == nil {
  880. ps.CatchupCommit = cmn.NewBitArray(numValidators)
  881. }
  882. if ps.ProposalPOL == nil {
  883. ps.ProposalPOL = cmn.NewBitArray(numValidators)
  884. }
  885. } else if ps.Height == height+1 {
  886. if ps.LastCommit == nil {
  887. ps.LastCommit = cmn.NewBitArray(numValidators)
  888. }
  889. }
  890. }
  891. // SetHasVote sets the given vote as known by the peer
  892. func (ps *PeerState) SetHasVote(vote *types.Vote) {
  893. ps.mtx.Lock()
  894. defer ps.mtx.Unlock()
  895. ps.setHasVote(vote.Height, vote.Round, vote.Type, vote.ValidatorIndex)
  896. }
  897. func (ps *PeerState) setHasVote(height int, round int, type_ byte, index int) {
  898. logger := ps.Peer.Logger.With("peerRound", ps.Round, "height", height, "round", round)
  899. logger.Debug("setHasVote(LastCommit)", "lastCommit", ps.LastCommit, "index", index)
  900. // NOTE: some may be nil BitArrays -> no side effects.
  901. ps.getVoteBitArray(height, round, type_).SetIndex(index, true)
  902. }
  903. // ApplyNewRoundStepMessage updates the peer state for the new round.
  904. func (ps *PeerState) ApplyNewRoundStepMessage(msg *NewRoundStepMessage) {
  905. ps.mtx.Lock()
  906. defer ps.mtx.Unlock()
  907. // Ignore duplicates or decreases
  908. if CompareHRS(msg.Height, msg.Round, msg.Step, ps.Height, ps.Round, ps.Step) <= 0 {
  909. return
  910. }
  911. // Just remember these values.
  912. psHeight := ps.Height
  913. psRound := ps.Round
  914. //psStep := ps.Step
  915. psCatchupCommitRound := ps.CatchupCommitRound
  916. psCatchupCommit := ps.CatchupCommit
  917. startTime := time.Now().Add(-1 * time.Duration(msg.SecondsSinceStartTime) * time.Second)
  918. ps.Height = msg.Height
  919. ps.Round = msg.Round
  920. ps.Step = msg.Step
  921. ps.StartTime = startTime
  922. if psHeight != msg.Height || psRound != msg.Round {
  923. ps.Proposal = false
  924. ps.ProposalBlockPartsHeader = types.PartSetHeader{}
  925. ps.ProposalBlockParts = nil
  926. ps.ProposalPOLRound = -1
  927. ps.ProposalPOL = nil
  928. // We'll update the BitArray capacity later.
  929. ps.Prevotes = nil
  930. ps.Precommits = nil
  931. }
  932. if psHeight == msg.Height && psRound != msg.Round && msg.Round == psCatchupCommitRound {
  933. // Peer caught up to CatchupCommitRound.
  934. // Preserve psCatchupCommit!
  935. // NOTE: We prefer to use prs.Precommits if
  936. // pr.Round matches pr.CatchupCommitRound.
  937. ps.Precommits = psCatchupCommit
  938. }
  939. if psHeight != msg.Height {
  940. // Shift Precommits to LastCommit.
  941. if psHeight+1 == msg.Height && psRound == msg.LastCommitRound {
  942. ps.LastCommitRound = msg.LastCommitRound
  943. ps.LastCommit = ps.Precommits
  944. } else {
  945. ps.LastCommitRound = msg.LastCommitRound
  946. ps.LastCommit = nil
  947. }
  948. // We'll update the BitArray capacity later.
  949. ps.CatchupCommitRound = -1
  950. ps.CatchupCommit = nil
  951. }
  952. }
  953. // ApplyCommitStepMessage updates the peer state for the new commit.
  954. func (ps *PeerState) ApplyCommitStepMessage(msg *CommitStepMessage) {
  955. ps.mtx.Lock()
  956. defer ps.mtx.Unlock()
  957. if ps.Height != msg.Height {
  958. return
  959. }
  960. ps.ProposalBlockPartsHeader = msg.BlockPartsHeader
  961. ps.ProposalBlockParts = msg.BlockParts
  962. }
  963. // ApplyProposalPOLMessage updates the peer state for the new proposal POL.
  964. func (ps *PeerState) ApplyProposalPOLMessage(msg *ProposalPOLMessage) {
  965. ps.mtx.Lock()
  966. defer ps.mtx.Unlock()
  967. if ps.Height != msg.Height {
  968. return
  969. }
  970. if ps.ProposalPOLRound != msg.ProposalPOLRound {
  971. return
  972. }
  973. // TODO: Merge onto existing ps.ProposalPOL?
  974. // We might have sent some prevotes in the meantime.
  975. ps.ProposalPOL = msg.ProposalPOL
  976. }
  977. // ApplyHasVoteMessage updates the peer state for the new vote.
  978. func (ps *PeerState) ApplyHasVoteMessage(msg *HasVoteMessage) {
  979. ps.mtx.Lock()
  980. defer ps.mtx.Unlock()
  981. if ps.Height != msg.Height {
  982. return
  983. }
  984. ps.setHasVote(msg.Height, msg.Round, msg.Type, msg.Index)
  985. }
  986. // ApplyVoteSetBitsMessage updates the peer state for the bit-array of votes
  987. // it claims to have for the corresponding BlockID.
  988. // `ourVotes` is a BitArray of votes we have for msg.BlockID
  989. // NOTE: if ourVotes is nil (e.g. msg.Height < rs.Height),
  990. // we conservatively overwrite ps's votes w/ msg.Votes.
  991. func (ps *PeerState) ApplyVoteSetBitsMessage(msg *VoteSetBitsMessage, ourVotes *cmn.BitArray) {
  992. ps.mtx.Lock()
  993. defer ps.mtx.Unlock()
  994. votes := ps.getVoteBitArray(msg.Height, msg.Round, msg.Type)
  995. if votes != nil {
  996. if ourVotes == nil {
  997. votes.Update(msg.Votes)
  998. } else {
  999. otherVotes := votes.Sub(ourVotes)
  1000. hasVotes := otherVotes.Or(msg.Votes)
  1001. votes.Update(hasVotes)
  1002. }
  1003. }
  1004. }
  1005. // String returns a string representation of the PeerState
  1006. func (ps *PeerState) String() string {
  1007. return ps.StringIndented("")
  1008. }
  1009. // StringIndented returns a string representation of the PeerState
  1010. func (ps *PeerState) StringIndented(indent string) string {
  1011. return fmt.Sprintf(`PeerState{
  1012. %s Key %v
  1013. %s PRS %v
  1014. %s}`,
  1015. indent, ps.Peer.Key,
  1016. indent, ps.PeerRoundState.StringIndented(indent+" "),
  1017. indent)
  1018. }
  1019. //-----------------------------------------------------------------------------
  1020. // Messages
  1021. const (
  1022. msgTypeNewRoundStep = byte(0x01)
  1023. msgTypeCommitStep = byte(0x02)
  1024. msgTypeProposal = byte(0x11)
  1025. msgTypeProposalPOL = byte(0x12)
  1026. msgTypeBlockPart = byte(0x13) // both block & POL
  1027. msgTypeVote = byte(0x14)
  1028. msgTypeHasVote = byte(0x15)
  1029. msgTypeVoteSetMaj23 = byte(0x16)
  1030. msgTypeVoteSetBits = byte(0x17)
  1031. )
  1032. // ConsensusMessage is a message that can be sent and received on the ConsensusReactor
  1033. type ConsensusMessage interface{}
  1034. var _ = wire.RegisterInterface(
  1035. struct{ ConsensusMessage }{},
  1036. wire.ConcreteType{&NewRoundStepMessage{}, msgTypeNewRoundStep},
  1037. wire.ConcreteType{&CommitStepMessage{}, msgTypeCommitStep},
  1038. wire.ConcreteType{&ProposalMessage{}, msgTypeProposal},
  1039. wire.ConcreteType{&ProposalPOLMessage{}, msgTypeProposalPOL},
  1040. wire.ConcreteType{&BlockPartMessage{}, msgTypeBlockPart},
  1041. wire.ConcreteType{&VoteMessage{}, msgTypeVote},
  1042. wire.ConcreteType{&HasVoteMessage{}, msgTypeHasVote},
  1043. wire.ConcreteType{&VoteSetMaj23Message{}, msgTypeVoteSetMaj23},
  1044. wire.ConcreteType{&VoteSetBitsMessage{}, msgTypeVoteSetBits},
  1045. )
  1046. // DecodeMessage decodes the given bytes into a ConsensusMessage.
  1047. // TODO: check for unnecessary extra bytes at the end.
  1048. func DecodeMessage(bz []byte) (msgType byte, msg ConsensusMessage, err error) {
  1049. msgType = bz[0]
  1050. n := new(int)
  1051. r := bytes.NewReader(bz)
  1052. msgI := wire.ReadBinary(struct{ ConsensusMessage }{}, r, maxConsensusMessageSize, n, &err)
  1053. msg = msgI.(struct{ ConsensusMessage }).ConsensusMessage
  1054. return
  1055. }
  1056. //-------------------------------------
  1057. // NewRoundStepMessage is sent for every step taken in the ConsensusState.
  1058. // For every height/round/step transition
  1059. type NewRoundStepMessage struct {
  1060. Height int
  1061. Round int
  1062. Step RoundStepType
  1063. SecondsSinceStartTime int
  1064. LastCommitRound int
  1065. }
  1066. // String returns a string representation.
  1067. func (m *NewRoundStepMessage) String() string {
  1068. return fmt.Sprintf("[NewRoundStep H:%v R:%v S:%v LCR:%v]",
  1069. m.Height, m.Round, m.Step, m.LastCommitRound)
  1070. }
  1071. //-------------------------------------
  1072. // CommitStepMessage is sent when a block is committed.
  1073. type CommitStepMessage struct {
  1074. Height int
  1075. BlockPartsHeader types.PartSetHeader
  1076. BlockParts *cmn.BitArray
  1077. }
  1078. // String returns a string representation.
  1079. func (m *CommitStepMessage) String() string {
  1080. return fmt.Sprintf("[CommitStep H:%v BP:%v BA:%v]", m.Height, m.BlockPartsHeader, m.BlockParts)
  1081. }
  1082. //-------------------------------------
  1083. // ProposalMessage is sent when a new block is proposed.
  1084. type ProposalMessage struct {
  1085. Proposal *types.Proposal
  1086. }
  1087. // String returns a string representation.
  1088. func (m *ProposalMessage) String() string {
  1089. return fmt.Sprintf("[Proposal %v]", m.Proposal)
  1090. }
  1091. //-------------------------------------
  1092. // ProposalPOLMessage is sent when a previous proposal is re-proposed.
  1093. type ProposalPOLMessage struct {
  1094. Height int
  1095. ProposalPOLRound int
  1096. ProposalPOL *cmn.BitArray
  1097. }
  1098. // String returns a string representation.
  1099. func (m *ProposalPOLMessage) String() string {
  1100. return fmt.Sprintf("[ProposalPOL H:%v POLR:%v POL:%v]", m.Height, m.ProposalPOLRound, m.ProposalPOL)
  1101. }
  1102. //-------------------------------------
  1103. // BlockPartMessage is sent when gossipping a piece of the proposed block.
  1104. type BlockPartMessage struct {
  1105. Height int
  1106. Round int
  1107. Part *types.Part
  1108. }
  1109. // String returns a string representation.
  1110. func (m *BlockPartMessage) String() string {
  1111. return fmt.Sprintf("[BlockPart H:%v R:%v P:%v]", m.Height, m.Round, m.Part)
  1112. }
  1113. //-------------------------------------
  1114. // VoteMessage is sent when voting for a proposal (or lack thereof).
  1115. type VoteMessage struct {
  1116. Vote *types.Vote
  1117. }
  1118. // String returns a string representation.
  1119. func (m *VoteMessage) String() string {
  1120. return fmt.Sprintf("[Vote %v]", m.Vote)
  1121. }
  1122. //-------------------------------------
  1123. // HasVoteMessage is sent to indicate that a particular vote has been received.
  1124. type HasVoteMessage struct {
  1125. Height int
  1126. Round int
  1127. Type byte
  1128. Index int
  1129. }
  1130. // String returns a string representation.
  1131. func (m *HasVoteMessage) String() string {
  1132. return fmt.Sprintf("[HasVote VI:%v V:{%v/%02d/%v} VI:%v]", m.Index, m.Height, m.Round, m.Type, m.Index)
  1133. }
  1134. //-------------------------------------
  1135. // VoteSetMaj23Message is sent to indicate that a given BlockID has seen +2/3 votes.
  1136. type VoteSetMaj23Message struct {
  1137. Height int
  1138. Round int
  1139. Type byte
  1140. BlockID types.BlockID
  1141. }
  1142. // String returns a string representation.
  1143. func (m *VoteSetMaj23Message) String() string {
  1144. return fmt.Sprintf("[VSM23 %v/%02d/%v %v]", m.Height, m.Round, m.Type, m.BlockID)
  1145. }
  1146. //-------------------------------------
  1147. // VoteSetBitsMessage is sent to communicate the bit-array of votes seen for the BlockID.
  1148. type VoteSetBitsMessage struct {
  1149. Height int
  1150. Round int
  1151. Type byte
  1152. BlockID types.BlockID
  1153. Votes *cmn.BitArray
  1154. }
  1155. // String returns a string representation.
  1156. func (m *VoteSetBitsMessage) String() string {
  1157. return fmt.Sprintf("[VSB %v/%02d/%v %v %v]", m.Height, m.Round, m.Type, m.BlockID, m.Votes)
  1158. }
  1159. //-------------------------------------
  1160. // ProposalHeartbeatMessage is sent to signal that a node is alive and waiting for transactions for a proposal.
  1161. type ProposalHeartbeatMessage struct {
  1162. Heartbeat *types.Heartbeat
  1163. }
  1164. // String returns a string representation.
  1165. func (m *ProposalHeartbeatMessage) String() string {
  1166. return fmt.Sprintf("[HEARTBEAT %v]", m.Heartbeat)
  1167. }