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.

899 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. } else if sleeping == 2 {
  499. // Continued sleep...
  500. sleeping = 1
  501. }
  502. time.Sleep(peerGossipSleepDuration)
  503. continue OUTER_LOOP
  504. }
  505. }
  506. //-----------------------------------------------------------------------------
  507. // Read only when returned by PeerState.GetRoundState().
  508. type PeerRoundState struct {
  509. Height uint // Height peer is at
  510. Round uint // Round peer is at
  511. Step RoundStepType // Step peer is at
  512. StartTime time.Time // Estimated start of round 0 at this height
  513. Proposal bool // True if peer has proposal for this round
  514. ProposalBlockParts types.PartSetHeader //
  515. ProposalBlockBitArray BitArray // True bit -> has part
  516. ProposalPOLParts types.PartSetHeader //
  517. ProposalPOLBitArray BitArray // True bit -> has part
  518. Prevotes BitArray // All votes peer has for this round
  519. Precommits BitArray // All precommits peer has for this round
  520. Commits BitArray // All commits peer has for this height
  521. LastCommits BitArray // All commits peer has for last height
  522. HasAllCatchupCommits bool // Used for catch-up
  523. }
  524. //-----------------------------------------------------------------------------
  525. var (
  526. ErrPeerStateHeightRegression = errors.New("Error peer state height regression")
  527. ErrPeerStateInvalidStartTime = errors.New("Error peer state invalid startTime")
  528. )
  529. type PeerState struct {
  530. mtx sync.Mutex
  531. PeerRoundState
  532. }
  533. func NewPeerState(peer *p2p.Peer) *PeerState {
  534. return &PeerState{}
  535. }
  536. // Returns an atomic snapshot of the PeerRoundState.
  537. // There's no point in mutating it since it won't change PeerState.
  538. func (ps *PeerState) GetRoundState() *PeerRoundState {
  539. ps.mtx.Lock()
  540. defer ps.mtx.Unlock()
  541. prs := ps.PeerRoundState // copy
  542. return &prs
  543. }
  544. func (ps *PeerState) SetHasProposal(proposal *Proposal) {
  545. ps.mtx.Lock()
  546. defer ps.mtx.Unlock()
  547. if ps.Height != proposal.Height || ps.Round != proposal.Round {
  548. return
  549. }
  550. if ps.Proposal {
  551. return
  552. }
  553. ps.Proposal = true
  554. ps.ProposalBlockParts = proposal.BlockParts
  555. ps.ProposalBlockBitArray = NewBitArray(uint(proposal.BlockParts.Total))
  556. ps.ProposalPOLParts = proposal.POLParts
  557. ps.ProposalPOLBitArray = NewBitArray(uint(proposal.POLParts.Total))
  558. }
  559. func (ps *PeerState) SetHasProposalBlockPart(height uint, round uint, index uint) {
  560. ps.mtx.Lock()
  561. defer ps.mtx.Unlock()
  562. if ps.Height != height || ps.Round != round {
  563. return
  564. }
  565. ps.ProposalBlockBitArray.SetIndex(uint(index), true)
  566. }
  567. func (ps *PeerState) SetHasProposalPOLPart(height uint, round uint, index uint) {
  568. ps.mtx.Lock()
  569. defer ps.mtx.Unlock()
  570. if ps.Height != height || ps.Round != round {
  571. return
  572. }
  573. ps.ProposalPOLBitArray.SetIndex(uint(index), true)
  574. }
  575. func (ps *PeerState) EnsureVoteBitArrays(height uint, numValidators uint) {
  576. ps.mtx.Lock()
  577. defer ps.mtx.Unlock()
  578. if ps.Height != height {
  579. return
  580. }
  581. if ps.Prevotes.IsZero() {
  582. ps.Prevotes = NewBitArray(numValidators)
  583. }
  584. if ps.Precommits.IsZero() {
  585. ps.Precommits = NewBitArray(numValidators)
  586. }
  587. if ps.Commits.IsZero() {
  588. ps.Commits = NewBitArray(numValidators)
  589. }
  590. }
  591. func (ps *PeerState) SetHasVote(vote *types.Vote, index uint) {
  592. ps.mtx.Lock()
  593. defer ps.mtx.Unlock()
  594. ps.setHasVote(vote.Height, vote.Round, vote.Type, index)
  595. }
  596. func (ps *PeerState) setHasVote(height uint, round uint, type_ byte, index uint) {
  597. if ps.Height == height+1 && type_ == types.VoteTypeCommit {
  598. // Special case for LastCommits.
  599. ps.LastCommits.SetIndex(index, true)
  600. return
  601. } else if ps.Height != height {
  602. // Does not apply.
  603. return
  604. }
  605. switch type_ {
  606. case types.VoteTypePrevote:
  607. ps.Prevotes.SetIndex(index, true)
  608. case types.VoteTypePrecommit:
  609. ps.Precommits.SetIndex(index, true)
  610. case types.VoteTypeCommit:
  611. if round < ps.Round {
  612. ps.Prevotes.SetIndex(index, true)
  613. ps.Precommits.SetIndex(index, true)
  614. }
  615. ps.Commits.SetIndex(index, true)
  616. default:
  617. panic("Invalid vote type")
  618. }
  619. }
  620. // When catching up, this helps keep track of whether
  621. // we should send more commit votes from the block (validation) store
  622. func (ps *PeerState) SetHasAllCatchupCommits(height uint) {
  623. ps.mtx.Lock()
  624. defer ps.mtx.Unlock()
  625. if ps.Height == height {
  626. ps.HasAllCatchupCommits = true
  627. }
  628. }
  629. func (ps *PeerState) ApplyNewRoundStepMessage(msg *NewRoundStepMessage, rs *RoundState) {
  630. ps.mtx.Lock()
  631. defer ps.mtx.Unlock()
  632. // Just remember these values.
  633. psHeight := ps.Height
  634. psRound := ps.Round
  635. //psStep := ps.Step
  636. startTime := time.Now().Add(-1 * time.Duration(msg.SecondsSinceStartTime) * time.Second)
  637. ps.Height = msg.Height
  638. ps.Round = msg.Round
  639. ps.Step = msg.Step
  640. ps.StartTime = startTime
  641. if psHeight != msg.Height || psRound != msg.Round {
  642. ps.Proposal = false
  643. ps.ProposalBlockParts = types.PartSetHeader{}
  644. ps.ProposalBlockBitArray = BitArray{}
  645. ps.ProposalPOLParts = types.PartSetHeader{}
  646. ps.ProposalPOLBitArray = BitArray{}
  647. // We'll update the BitArray capacity later.
  648. ps.Prevotes = BitArray{}
  649. ps.Precommits = BitArray{}
  650. }
  651. if psHeight != msg.Height {
  652. // Shift Commits to LastCommits
  653. if psHeight+1 == msg.Height {
  654. ps.LastCommits = ps.Commits
  655. } else {
  656. ps.LastCommits = BitArray{}
  657. }
  658. // We'll update the BitArray capacity later.
  659. ps.Commits = BitArray{}
  660. ps.HasAllCatchupCommits = false
  661. }
  662. }
  663. func (ps *PeerState) ApplyCommitStepMessage(msg *CommitStepMessage) {
  664. ps.mtx.Lock()
  665. defer ps.mtx.Unlock()
  666. if ps.Height != msg.Height {
  667. return
  668. }
  669. ps.ProposalBlockParts = msg.BlockParts
  670. ps.ProposalBlockBitArray = msg.BlockBitArray
  671. }
  672. func (ps *PeerState) ApplyHasVoteMessage(msg *HasVoteMessage) {
  673. ps.mtx.Lock()
  674. defer ps.mtx.Unlock()
  675. // Special case for LastCommits
  676. if ps.Height == msg.Height+1 && msg.Type == types.VoteTypeCommit {
  677. ps.LastCommits.SetIndex(msg.Index, true)
  678. return
  679. } else if ps.Height != msg.Height {
  680. return
  681. }
  682. ps.setHasVote(msg.Height, msg.Round, msg.Type, msg.Index)
  683. }
  684. //-----------------------------------------------------------------------------
  685. // Messages
  686. const (
  687. msgTypeNewRoundStep = byte(0x01)
  688. msgTypeCommitStep = byte(0x02)
  689. msgTypeProposal = byte(0x11)
  690. msgTypePart = byte(0x12) // both block & POL
  691. msgTypeVote = byte(0x13)
  692. msgTypeHasVote = byte(0x14)
  693. )
  694. type ConsensusMessage interface{}
  695. var _ = binary.RegisterInterface(
  696. struct{ ConsensusMessage }{},
  697. binary.ConcreteType{&NewRoundStepMessage{}, msgTypeNewRoundStep},
  698. binary.ConcreteType{&CommitStepMessage{}, msgTypeCommitStep},
  699. binary.ConcreteType{&ProposalMessage{}, msgTypeProposal},
  700. binary.ConcreteType{&PartMessage{}, msgTypePart},
  701. binary.ConcreteType{&VoteMessage{}, msgTypeVote},
  702. binary.ConcreteType{&HasVoteMessage{}, msgTypeHasVote},
  703. )
  704. // TODO: check for unnecessary extra bytes at the end.
  705. func DecodeMessage(bz []byte) (msgType byte, msg ConsensusMessage, err error) {
  706. msgType = bz[0]
  707. n := new(int64)
  708. r := bytes.NewReader(bz)
  709. msg = binary.ReadBinary(struct{ ConsensusMessage }{}, r, n, &err).(struct{ ConsensusMessage }).ConsensusMessage
  710. return
  711. }
  712. //-------------------------------------
  713. type NewRoundStepMessage struct {
  714. Height uint
  715. Round uint
  716. Step RoundStepType
  717. SecondsSinceStartTime uint
  718. }
  719. func (m *NewRoundStepMessage) String() string {
  720. return fmt.Sprintf("[NewRoundStep H:%v R:%v S:%v]", m.Height, m.Round, m.Step)
  721. }
  722. //-------------------------------------
  723. type CommitStepMessage struct {
  724. Height uint
  725. BlockParts types.PartSetHeader
  726. BlockBitArray BitArray
  727. }
  728. func (m *CommitStepMessage) String() string {
  729. return fmt.Sprintf("[CommitStep H:%v BP:%v BA:%v]", m.Height, m.BlockParts, m.BlockBitArray)
  730. }
  731. //-------------------------------------
  732. type ProposalMessage struct {
  733. Proposal *Proposal
  734. }
  735. func (m *ProposalMessage) String() string {
  736. return fmt.Sprintf("[Proposal %v]", m.Proposal)
  737. }
  738. //-------------------------------------
  739. const (
  740. partTypeProposalBlock = byte(0x01)
  741. partTypeProposalPOL = byte(0x02)
  742. )
  743. type PartMessage struct {
  744. Height uint
  745. Round uint
  746. Type byte
  747. Part *types.Part
  748. }
  749. func (m *PartMessage) String() string {
  750. return fmt.Sprintf("[Part H:%v R:%v T:%X P:%v]", m.Height, m.Round, m.Type, m.Part)
  751. }
  752. //-------------------------------------
  753. type VoteMessage struct {
  754. ValidatorIndex uint
  755. Vote *types.Vote
  756. }
  757. func (m *VoteMessage) String() string {
  758. return fmt.Sprintf("[Vote VI:%v V:%v]", m.ValidatorIndex, m.Vote)
  759. }
  760. //-------------------------------------
  761. type HasVoteMessage struct {
  762. Height uint
  763. Round uint
  764. Type byte
  765. Index uint
  766. }
  767. func (m *HasVoteMessage) String() string {
  768. return fmt.Sprintf("[HasVote VI:%v V:Vote{%v/%02d/%v}]", m.Index, m.Height, m.Round, m.Type)
  769. }