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.

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