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.

1467 lines
48 KiB

10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
  1. package consensus
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "reflect"
  7. "sync"
  8. "time"
  9. . "github.com/tendermint/go-common"
  10. "github.com/tendermint/go-wire"
  11. bc "github.com/tendermint/tendermint/blockchain"
  12. "github.com/tendermint/tendermint/events"
  13. mempl "github.com/tendermint/tendermint/mempool"
  14. "github.com/tendermint/tendermint/proxy"
  15. sm "github.com/tendermint/tendermint/state"
  16. "github.com/tendermint/tendermint/types"
  17. )
  18. var (
  19. timeoutPropose = 3000 * time.Millisecond // Maximum duration of RoundStepPropose
  20. timeoutPrevote0 = 1000 * time.Millisecond // After any +2/3 prevotes received, wait this long for stragglers.
  21. timeoutPrevoteDelta = 0500 * time.Millisecond // timeoutPrevoteN is timeoutPrevote0 + timeoutPrevoteDelta*N
  22. timeoutPrecommit0 = 1000 * time.Millisecond // After any +2/3 precommits received, wait this long for stragglers.
  23. timeoutPrecommitDelta = 0500 * time.Millisecond // timeoutPrecommitN is timeoutPrecommit0 + timeoutPrecommitDelta*N
  24. timeoutCommit = 2000 * time.Millisecond // After +2/3 commits received for committed block, wait this long for stragglers in the next height's RoundStepNewHeight.
  25. )
  26. var (
  27. ErrInvalidProposalSignature = errors.New("Error invalid proposal signature")
  28. ErrInvalidProposalPOLRound = errors.New("Error invalid proposal POL round")
  29. ErrAddingVote = errors.New("Error adding vote")
  30. ErrVoteHeightMismatch = errors.New("Error vote height mismatch")
  31. )
  32. //-----------------------------------------------------------------------------
  33. // RoundStepType enum type
  34. type RoundStepType uint8 // These must be numeric, ordered.
  35. const (
  36. RoundStepNewHeight = RoundStepType(0x01) // Wait til CommitTime + timeoutCommit
  37. RoundStepNewRound = RoundStepType(0x02) // Setup new round and go to RoundStepPropose
  38. RoundStepPropose = RoundStepType(0x03) // Did propose, gossip proposal
  39. RoundStepPrevote = RoundStepType(0x04) // Did prevote, gossip prevotes
  40. RoundStepPrevoteWait = RoundStepType(0x05) // Did receive any +2/3 prevotes, start timeout
  41. RoundStepPrecommit = RoundStepType(0x06) // Did precommit, gossip precommits
  42. RoundStepPrecommitWait = RoundStepType(0x07) // Did receive any +2/3 precommits, start timeout
  43. RoundStepCommit = RoundStepType(0x08) // Entered commit state machine
  44. // NOTE: RoundStepNewHeight acts as RoundStepCommitWait.
  45. )
  46. func (rs RoundStepType) String() string {
  47. switch rs {
  48. case RoundStepNewHeight:
  49. return "RoundStepNewHeight"
  50. case RoundStepNewRound:
  51. return "RoundStepNewRound"
  52. case RoundStepPropose:
  53. return "RoundStepPropose"
  54. case RoundStepPrevote:
  55. return "RoundStepPrevote"
  56. case RoundStepPrevoteWait:
  57. return "RoundStepPrevoteWait"
  58. case RoundStepPrecommit:
  59. return "RoundStepPrecommit"
  60. case RoundStepPrecommitWait:
  61. return "RoundStepPrecommitWait"
  62. case RoundStepCommit:
  63. return "RoundStepCommit"
  64. default:
  65. return "RoundStepUnknown" // Cannot panic.
  66. }
  67. }
  68. //-----------------------------------------------------------------------------
  69. // Immutable when returned from ConsensusState.GetRoundState()
  70. type RoundState struct {
  71. Height int // Height we are working on
  72. Round int
  73. Step RoundStepType
  74. StartTime time.Time
  75. CommitTime time.Time // Subjective time when +2/3 precommits for Block at Round were found
  76. Validators *types.ValidatorSet
  77. Proposal *types.Proposal
  78. ProposalBlock *types.Block
  79. ProposalBlockParts *types.PartSet
  80. LockedRound int
  81. LockedBlock *types.Block
  82. LockedBlockParts *types.PartSet
  83. Votes *HeightVoteSet
  84. CommitRound int //
  85. LastCommit *types.VoteSet // Last precommits at Height-1
  86. LastValidators *types.ValidatorSet
  87. }
  88. func (rs *RoundState) RoundStateEvent() *types.EventDataRoundState {
  89. edrs := &types.EventDataRoundState{
  90. Height: rs.Height,
  91. Round: rs.Round,
  92. Step: rs.Step.String(),
  93. }
  94. edrs.SetRoundState(rs)
  95. return edrs
  96. }
  97. func (rs *RoundState) String() string {
  98. return rs.StringIndented("")
  99. }
  100. func (rs *RoundState) StringIndented(indent string) string {
  101. return fmt.Sprintf(`RoundState{
  102. %s H:%v R:%v S:%v
  103. %s StartTime: %v
  104. %s CommitTime: %v
  105. %s Validators: %v
  106. %s Proposal: %v
  107. %s ProposalBlock: %v %v
  108. %s LockedRound: %v
  109. %s LockedBlock: %v %v
  110. %s Votes: %v
  111. %s LastCommit: %v
  112. %s LastValidators: %v
  113. %s}`,
  114. indent, rs.Height, rs.Round, rs.Step,
  115. indent, rs.StartTime,
  116. indent, rs.CommitTime,
  117. indent, rs.Validators.StringIndented(indent+" "),
  118. indent, rs.Proposal,
  119. indent, rs.ProposalBlockParts.StringShort(), rs.ProposalBlock.StringShort(),
  120. indent, rs.LockedRound,
  121. indent, rs.LockedBlockParts.StringShort(), rs.LockedBlock.StringShort(),
  122. indent, rs.Votes.StringIndented(indent+" "),
  123. indent, rs.LastCommit.StringShort(),
  124. indent, rs.LastValidators.StringIndented(indent+" "),
  125. indent)
  126. }
  127. func (rs *RoundState) StringShort() string {
  128. return fmt.Sprintf(`RoundState{H:%v R:%v S:%v ST:%v}`,
  129. rs.Height, rs.Round, rs.Step, rs.StartTime)
  130. }
  131. //-----------------------------------------------------------------------------
  132. var (
  133. msgQueueSize = 1000
  134. tickTockBufferSize = 10
  135. )
  136. // msgs from the reactor which may update the state
  137. type msgInfo struct {
  138. msg ConsensusMessage
  139. peerKey string
  140. }
  141. // internally generated messages which may update the state
  142. type timeoutInfo struct {
  143. duration time.Duration
  144. height int
  145. round int
  146. step RoundStepType
  147. }
  148. func (ti *timeoutInfo) String() string {
  149. return fmt.Sprintf("%v ; %d/%d %v", ti.duration, ti.height, ti.round, ti.step)
  150. }
  151. // Tracks consensus state across block heights and rounds.
  152. type ConsensusState struct {
  153. QuitService
  154. proxyAppCtx proxy.AppContext
  155. blockStore *bc.BlockStore
  156. mempool *mempl.Mempool
  157. privValidator *types.PrivValidator
  158. mtx sync.Mutex
  159. RoundState
  160. state *sm.State // State until height-1.
  161. stagedBlock *types.Block // Cache last staged block.
  162. stagedState *sm.State // Cache result of staged block.
  163. peerMsgQueue chan msgInfo // serializes msgs affecting state (proposals, block parts, votes)
  164. internalMsgQueue chan msgInfo // like peerMsgQueue but for our own proposals, parts, votes
  165. timeoutTicker *time.Ticker // ticker for timeouts
  166. tickChan chan timeoutInfo // start the timeoutTicker in the timeoutRoutine
  167. tockChan chan timeoutInfo // timeouts are relayed on tockChan to the receiveRoutine
  168. evsw *events.EventSwitch
  169. evc *events.EventCache // set in stageBlock and passed into state
  170. nSteps int // used for testing to limit the number of transitions the state makes
  171. }
  172. func NewConsensusState(state *sm.State, proxyAppCtx proxy.AppContext, blockStore *bc.BlockStore, mempool *mempl.Mempool) *ConsensusState {
  173. cs := &ConsensusState{
  174. proxyAppCtx: proxyAppCtx,
  175. blockStore: blockStore,
  176. mempool: mempool,
  177. peerMsgQueue: make(chan msgInfo, msgQueueSize),
  178. internalMsgQueue: make(chan msgInfo, msgQueueSize),
  179. timeoutTicker: new(time.Ticker),
  180. tickChan: make(chan timeoutInfo, tickTockBufferSize),
  181. tockChan: make(chan timeoutInfo, tickTockBufferSize),
  182. }
  183. cs.updateToState(state)
  184. // Don't call scheduleRound0 yet.
  185. // We do that upon Start().
  186. cs.reconstructLastCommit(state)
  187. cs.QuitService = *NewQuitService(log, "ConsensusState", cs)
  188. return cs
  189. }
  190. //----------------------------------------
  191. // Public interface
  192. // implements events.Eventable
  193. func (cs *ConsensusState) SetEventSwitch(evsw *events.EventSwitch) {
  194. cs.evsw = evsw
  195. }
  196. func (cs *ConsensusState) String() string {
  197. return Fmt("ConsensusState(H:%v R:%v S:%v", cs.Height, cs.Round, cs.Step)
  198. }
  199. func (cs *ConsensusState) GetState() *sm.State {
  200. cs.mtx.Lock()
  201. defer cs.mtx.Unlock()
  202. return cs.state.Copy()
  203. }
  204. func (cs *ConsensusState) GetRoundState() *RoundState {
  205. cs.mtx.Lock()
  206. defer cs.mtx.Unlock()
  207. return cs.getRoundState()
  208. }
  209. func (cs *ConsensusState) getRoundState() *RoundState {
  210. rs := cs.RoundState // copy
  211. return &rs
  212. }
  213. func (cs *ConsensusState) SetPrivValidator(priv *types.PrivValidator) {
  214. cs.mtx.Lock()
  215. defer cs.mtx.Unlock()
  216. cs.privValidator = priv
  217. }
  218. func (cs *ConsensusState) OnStart() error {
  219. cs.BaseService.OnStart()
  220. // first we schedule the round (no go routines)
  221. // then we start the timeout and receive routines.
  222. // tickChan is buffered so scheduleRound0 will finish.
  223. // Then all further access to the RoundState is through the receiveRoutine
  224. cs.scheduleRound0(cs.Height)
  225. cs.startRoutines(0)
  226. return nil
  227. }
  228. // timeoutRoutine: receive requests for timeouts on tickChan and fire timeouts on tockChan
  229. // receiveRoutine: serializes processing of proposoals, block parts, votes; coordinates state transitions
  230. func (cs *ConsensusState) startRoutines(maxSteps int) {
  231. go cs.timeoutRoutine()
  232. go cs.receiveRoutine(maxSteps)
  233. }
  234. func (cs *ConsensusState) OnStop() {
  235. cs.QuitService.OnStop()
  236. }
  237. //------------------------------------------------------------
  238. // Public interface for passing messages into the consensus state,
  239. // possibly causing a state transition
  240. // TODO: should these return anything or let callers just use events?
  241. // May block on send if queue is full.
  242. func (cs *ConsensusState) AddVote(valIndex int, vote *types.Vote, peerKey string) (added bool, address []byte, err error) {
  243. if peerKey == "" {
  244. cs.internalMsgQueue <- msgInfo{&VoteMessage{valIndex, vote}, ""}
  245. } else {
  246. cs.peerMsgQueue <- msgInfo{&VoteMessage{valIndex, vote}, peerKey}
  247. }
  248. // TODO: wait for event?!
  249. return false, nil, nil
  250. }
  251. // May block on send if queue is full.
  252. func (cs *ConsensusState) SetProposal(proposal *types.Proposal, peerKey string) error {
  253. if peerKey == "" {
  254. cs.internalMsgQueue <- msgInfo{&ProposalMessage{proposal}, ""}
  255. } else {
  256. cs.peerMsgQueue <- msgInfo{&ProposalMessage{proposal}, peerKey}
  257. }
  258. // TODO: wait for event?!
  259. return nil
  260. }
  261. // May block on send if queue is full.
  262. func (cs *ConsensusState) AddProposalBlockPart(height, round int, part *types.Part, peerKey string) error {
  263. if peerKey == "" {
  264. cs.internalMsgQueue <- msgInfo{&BlockPartMessage{height, round, part}, ""}
  265. } else {
  266. cs.peerMsgQueue <- msgInfo{&BlockPartMessage{height, round, part}, peerKey}
  267. }
  268. // TODO: wait for event?!
  269. return nil
  270. }
  271. func (cs *ConsensusState) SetProposalAndBlock(proposal *types.Proposal, block *types.Block, parts *types.PartSet, peerKey string) error {
  272. cs.SetProposal(proposal, peerKey)
  273. for i := 0; i < parts.Total(); i++ {
  274. part := parts.GetPart(i)
  275. cs.AddProposalBlockPart(proposal.Height, proposal.Round, part, peerKey)
  276. }
  277. return nil // TODO errors
  278. }
  279. //------------------------------------------------------------
  280. // internal functions for managing the state
  281. func (cs *ConsensusState) updateHeight(height int) {
  282. cs.Height = height
  283. }
  284. func (cs *ConsensusState) updateRoundStep(round int, step RoundStepType) {
  285. cs.Round = round
  286. cs.Step = step
  287. }
  288. // enterNewRound(height, 0) at cs.StartTime.
  289. func (cs *ConsensusState) scheduleRound0(height int) {
  290. //log.Info("scheduleRound0", "now", time.Now(), "startTime", cs.StartTime)
  291. sleepDuration := cs.StartTime.Sub(time.Now())
  292. cs.scheduleTimeout(sleepDuration, height, 0, RoundStepNewHeight)
  293. }
  294. // Attempt to schedule a timeout by sending timeoutInfo on the tickChan.
  295. // The timeoutRoutine is alwaya available to read from tickChan (it won't block).
  296. // The scheduling may fail if the timeoutRoutine has already scheduled a timeout for a later height/round/step.
  297. func (cs *ConsensusState) scheduleTimeout(duration time.Duration, height, round int, step RoundStepType) {
  298. cs.tickChan <- timeoutInfo{duration, height, round, step}
  299. }
  300. // send a msg into the receiveRoutine regarding our own proposal, block part, or vote
  301. func (cs *ConsensusState) sendInternalMessage(mi msgInfo) {
  302. select {
  303. case cs.internalMsgQueue <- mi:
  304. default:
  305. // NOTE: using the go-routine means our votes can
  306. // be processed out of order.
  307. // TODO: use CList here for strict determinism and
  308. // attempt push to internalMsgQueue in receiveRoutine
  309. log.Debug("Internal msg queue is full. Using a go-routine")
  310. go func() { cs.internalMsgQueue <- mi }()
  311. }
  312. }
  313. // Reconstruct LastCommit from SeenValidation, which we saved along with the block,
  314. // (which happens even before saving the state)
  315. func (cs *ConsensusState) reconstructLastCommit(state *sm.State) {
  316. if state.LastBlockHeight == 0 {
  317. return
  318. }
  319. lastPrecommits := types.NewVoteSet(state.LastBlockHeight, 0, types.VoteTypePrecommit, state.LastValidators)
  320. seenValidation := cs.blockStore.LoadSeenValidation(state.LastBlockHeight)
  321. for idx, precommit := range seenValidation.Precommits {
  322. if precommit == nil {
  323. continue
  324. }
  325. added, _, err := lastPrecommits.AddByIndex(idx, precommit)
  326. if !added || err != nil {
  327. PanicCrisis(Fmt("Failed to reconstruct LastCommit: %v", err))
  328. }
  329. }
  330. if !lastPrecommits.HasTwoThirdsMajority() {
  331. PanicSanity("Failed to reconstruct LastCommit: Does not have +2/3 maj")
  332. }
  333. cs.LastCommit = lastPrecommits
  334. }
  335. // Updates ConsensusState and increments height to match that of state.
  336. // The round becomes 0 and cs.Step becomes RoundStepNewHeight.
  337. func (cs *ConsensusState) updateToState(state *sm.State) {
  338. if cs.CommitRound > -1 && 0 < cs.Height && cs.Height != state.LastBlockHeight {
  339. PanicSanity(Fmt("updateToState() expected state height of %v but found %v",
  340. cs.Height, state.LastBlockHeight))
  341. }
  342. if cs.state != nil && cs.state.LastBlockHeight+1 != cs.Height {
  343. // This might happen when someone else is mutating cs.state.
  344. // Someone forgot to pass in state.Copy() somewhere?!
  345. PanicSanity(Fmt("Inconsistent cs.state.LastBlockHeight+1 %v vs cs.Height %v",
  346. cs.state.LastBlockHeight+1, cs.Height))
  347. }
  348. // If state isn't further out than cs.state, just ignore.
  349. // This happens when SwitchToConsensus() is called in the reactor.
  350. // We don't want to reset e.g. the Votes.
  351. if cs.state != nil && (state.LastBlockHeight <= cs.state.LastBlockHeight) {
  352. log.Notice("Ignoring updateToState()", "newHeight", state.LastBlockHeight+1, "oldHeight", cs.state.LastBlockHeight+1)
  353. return
  354. }
  355. // Reset fields based on state.
  356. validators := state.Validators
  357. height := state.LastBlockHeight + 1 // next desired block height
  358. lastPrecommits := (*types.VoteSet)(nil)
  359. if cs.CommitRound > -1 && cs.Votes != nil {
  360. if !cs.Votes.Precommits(cs.CommitRound).HasTwoThirdsMajority() {
  361. PanicSanity("updateToState(state) called but last Precommit round didn't have +2/3")
  362. }
  363. lastPrecommits = cs.Votes.Precommits(cs.CommitRound)
  364. }
  365. // RoundState fields
  366. cs.updateHeight(height)
  367. cs.updateRoundStep(0, RoundStepNewHeight)
  368. if cs.CommitTime.IsZero() {
  369. // "Now" makes it easier to sync up dev nodes.
  370. // We add timeoutCommit to allow transactions
  371. // to be gathered for the first block.
  372. // And alternative solution that relies on clocks:
  373. // cs.StartTime = state.LastBlockTime.Add(timeoutCommit)
  374. cs.StartTime = time.Now().Add(timeoutCommit)
  375. } else {
  376. cs.StartTime = cs.CommitTime.Add(timeoutCommit)
  377. }
  378. cs.CommitTime = time.Time{}
  379. cs.Validators = validators
  380. cs.Proposal = nil
  381. cs.ProposalBlock = nil
  382. cs.ProposalBlockParts = nil
  383. cs.LockedRound = 0
  384. cs.LockedBlock = nil
  385. cs.LockedBlockParts = nil
  386. cs.Votes = NewHeightVoteSet(height, validators)
  387. cs.CommitRound = -1
  388. cs.LastCommit = lastPrecommits
  389. cs.LastValidators = state.LastValidators
  390. cs.state = state
  391. cs.stagedBlock = nil
  392. cs.stagedState = nil
  393. // Finally, broadcast RoundState
  394. cs.newStep()
  395. }
  396. func (cs *ConsensusState) newStep() {
  397. cs.nSteps += 1
  398. // newStep is called by updateToStep in NewConsensusState before the evsw is set!
  399. if cs.evsw != nil {
  400. cs.evsw.FireEvent(types.EventStringNewRoundStep(), cs.RoundStateEvent())
  401. }
  402. }
  403. //-----------------------------------------
  404. // the main go routines
  405. // the state machine sends on tickChan to start a new timer.
  406. // timers are interupted and replaced by new ticks from later steps
  407. // timeouts of 0 on the tickChan will be immediately relayed to the tockChan
  408. func (cs *ConsensusState) timeoutRoutine() {
  409. log.Debug("Starting timeout routine")
  410. var ti timeoutInfo
  411. for {
  412. select {
  413. case newti := <-cs.tickChan:
  414. log.Debug("Received tick", "old_ti", ti, "new_ti", newti)
  415. // ignore tickers for old height/round/step
  416. if newti.height < ti.height {
  417. continue
  418. } else if newti.height == ti.height {
  419. if newti.round < ti.round {
  420. continue
  421. } else if newti.round == ti.round {
  422. if ti.step > 0 && newti.step <= ti.step {
  423. continue
  424. }
  425. }
  426. }
  427. ti = newti
  428. // if the newti has duration == 0, we relay to the tockChan immediately (no timeout)
  429. if ti.duration == time.Duration(0) {
  430. go func(t timeoutInfo) { cs.tockChan <- t }(ti)
  431. continue
  432. }
  433. log.Info("Scheduling timeout", "dur", ti.duration, "height", ti.height, "round", ti.round, "step", ti.step)
  434. cs.timeoutTicker.Stop()
  435. cs.timeoutTicker = time.NewTicker(ti.duration)
  436. case <-cs.timeoutTicker.C:
  437. log.Info("Timed out", "dur", ti.duration, "height", ti.height, "round", ti.round, "step", ti.step)
  438. cs.timeoutTicker.Stop()
  439. // go routine here gaurantees timeoutRoutine doesn't block.
  440. // Determinism comes from playback in the receiveRoutine.
  441. // We can eliminate it by merging the timeoutRoutine into receiveRoutine
  442. // and managing the timeouts ourselves with a millisecond ticker
  443. go func(t timeoutInfo) { cs.tockChan <- t }(ti)
  444. case <-cs.Quit:
  445. return
  446. }
  447. }
  448. }
  449. // a nice idea but probably more trouble than its worth
  450. func (cs *ConsensusState) stopTimer() {
  451. cs.timeoutTicker.Stop()
  452. }
  453. // receiveRoutine handles messages which may cause state transitions.
  454. // it's argument (n) is the number of messages to process before exiting - use 0 to run forever
  455. // It keeps the RoundState and is the only thing that updates it.
  456. // Updates (state transitions) happen on timeouts, complete proposals, and 2/3 majorities
  457. func (cs *ConsensusState) receiveRoutine(maxSteps int) {
  458. for {
  459. if maxSteps > 0 {
  460. if cs.nSteps >= maxSteps {
  461. log.Warn("reached max steps. exiting receive routine")
  462. cs.nSteps = 0
  463. return
  464. }
  465. }
  466. rs := cs.RoundState
  467. var mi msgInfo
  468. select {
  469. case mi = <-cs.peerMsgQueue:
  470. // handles proposals, block parts, votes
  471. // may generate internal events (votes, complete proposals, 2/3 majorities)
  472. cs.handleMsg(mi, rs)
  473. case mi = <-cs.internalMsgQueue:
  474. // handles proposals, block parts, votes
  475. cs.handleMsg(mi, rs)
  476. case ti := <-cs.tockChan:
  477. // if the timeout is relevant to the rs
  478. // go to the next step
  479. cs.handleTimeout(ti, rs)
  480. case <-cs.Quit:
  481. return
  482. }
  483. }
  484. }
  485. // state transitions on complete-proposal, 2/3-any, 2/3-one
  486. func (cs *ConsensusState) handleMsg(mi msgInfo, rs RoundState) {
  487. cs.mtx.Lock()
  488. defer cs.mtx.Unlock()
  489. var err error
  490. msg, peerKey := mi.msg, mi.peerKey
  491. switch msg := msg.(type) {
  492. case *ProposalMessage:
  493. // will not cause transition.
  494. // once proposal is set, we can receive block parts
  495. err = cs.setProposal(msg.Proposal)
  496. case *BlockPartMessage:
  497. // if the proposal is complete, we'll enterPrevote or tryFinalizeCommit
  498. // if we're the only validator, the enterPrevote may take us through to the next round
  499. _, err = cs.addProposalBlockPart(msg.Height, msg.Part)
  500. case *VoteMessage:
  501. // attempt to add the vote and dupeout the validator if its a duplicate signature
  502. // if the vote gives us a 2/3-any or 2/3-one, we transition
  503. err := cs.tryAddVote(msg.ValidatorIndex, msg.Vote, peerKey)
  504. if err == ErrAddingVote {
  505. // TODO: punish peer
  506. }
  507. // NOTE: the vote is broadcast to peers by the reactor listening
  508. // for vote events
  509. // TODO: If rs.Height == vote.Height && rs.Round < vote.Round,
  510. // the peer is sending us CatchupCommit precommits.
  511. // We could make note of this and help filter in broadcastHasVoteMessage().
  512. default:
  513. log.Warn("Unknown msg type", reflect.TypeOf(msg))
  514. }
  515. if err != nil {
  516. log.Error("error with msg", "error", err)
  517. }
  518. }
  519. func (cs *ConsensusState) handleTimeout(ti timeoutInfo, rs RoundState) {
  520. log.Debug("Received tock", "timeout", ti.duration, "height", ti.height, "round", ti.round, "step", ti.step)
  521. // timeouts must be for current height, round, step
  522. if ti.height != rs.Height || ti.round < rs.Round || (ti.round == rs.Round && ti.step < rs.Step) {
  523. log.Debug("Ignoring tock because we're ahead", "height", rs.Height, "round", rs.Round, "step", rs.Step)
  524. return
  525. }
  526. // the timeout will now cause a state transition
  527. cs.mtx.Lock()
  528. defer cs.mtx.Unlock()
  529. switch ti.step {
  530. case RoundStepNewHeight:
  531. // NewRound event fired from enterNewRound.
  532. // Do we want a timeout event too?
  533. cs.enterNewRound(ti.height, 0)
  534. case RoundStepPropose:
  535. cs.evsw.FireEvent(types.EventStringTimeoutPropose(), cs.RoundStateEvent())
  536. cs.enterPrevote(ti.height, ti.round)
  537. case RoundStepPrevoteWait:
  538. cs.evsw.FireEvent(types.EventStringTimeoutWait(), cs.RoundStateEvent())
  539. cs.enterPrecommit(ti.height, ti.round)
  540. case RoundStepPrecommitWait:
  541. cs.evsw.FireEvent(types.EventStringTimeoutWait(), cs.RoundStateEvent())
  542. cs.enterNewRound(ti.height, ti.round+1)
  543. default:
  544. panic(Fmt("Invalid timeout step: %v", ti.step))
  545. }
  546. }
  547. //-----------------------------------------------------------------------------
  548. // State functions
  549. // Used internally by handleTimeout and handleMsg to make state transitions
  550. // Enter: +2/3 precommits for nil at (height,round-1)
  551. // Enter: `timeoutPrecommits` after any +2/3 precommits from (height,round-1)
  552. // Enter: `startTime = commitTime+timeoutCommit` from NewHeight(height)
  553. // NOTE: cs.StartTime was already set for height.
  554. func (cs *ConsensusState) enterNewRound(height int, round int) {
  555. if cs.Height != height || round < cs.Round || (cs.Round == round && cs.Step != RoundStepNewHeight) {
  556. log.Debug(Fmt("enterNewRound(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  557. return
  558. }
  559. if now := time.Now(); cs.StartTime.After(now) {
  560. log.Warn("Need to set a buffer and log.Warn() here for sanity.", "startTime", cs.StartTime, "now", now)
  561. }
  562. // cs.stopTimer()
  563. log.Notice(Fmt("enterNewRound(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  564. // Increment validators if necessary
  565. validators := cs.Validators
  566. if cs.Round < round {
  567. validators = validators.Copy()
  568. validators.IncrementAccum(round - cs.Round)
  569. }
  570. // Setup new round
  571. // we don't fire newStep for this step,
  572. // but we fire an event, so update the round step first
  573. cs.updateRoundStep(round, RoundStepNewRound)
  574. cs.Validators = validators
  575. if round == 0 {
  576. // We've already reset these upon new height,
  577. // and meanwhile we might have received a proposal
  578. // for round 0.
  579. } else {
  580. cs.Proposal = nil
  581. cs.ProposalBlock = nil
  582. cs.ProposalBlockParts = nil
  583. }
  584. cs.Votes.SetRound(round + 1) // also track next round (round+1) to allow round-skipping
  585. cs.evsw.FireEvent(types.EventStringNewRound(), cs.RoundStateEvent())
  586. // Immediately go to enterPropose.
  587. cs.enterPropose(height, round)
  588. }
  589. // Enter: from NewRound(height,round).
  590. func (cs *ConsensusState) enterPropose(height int, round int) {
  591. // cs.mtx.Lock()
  592. // cs.mtx.Unlock()
  593. if cs.Height != height || round < cs.Round || (cs.Round == round && RoundStepPropose <= cs.Step) {
  594. log.Debug(Fmt("enterPropose(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  595. return
  596. }
  597. log.Info(Fmt("enterPropose(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  598. defer func() {
  599. // Done enterPropose:
  600. cs.updateRoundStep(round, RoundStepPropose)
  601. cs.newStep()
  602. // If we have the whole proposal + POL, then goto Prevote now.
  603. // else, we'll enterPrevote when the rest of the proposal is received (in AddProposalBlockPart),
  604. // or else after timeoutPropose
  605. if cs.isProposalComplete() {
  606. cs.enterPrevote(height, cs.Round)
  607. }
  608. }()
  609. // This step times out after `timeoutPropose`
  610. cs.scheduleTimeout(timeoutPropose, height, round, RoundStepPropose)
  611. // Nothing more to do if we're not a validator
  612. if cs.privValidator == nil {
  613. return
  614. }
  615. if !bytes.Equal(cs.Validators.Proposer().Address, cs.privValidator.Address) {
  616. log.Info("enterPropose: Not our turn to propose", "proposer", cs.Validators.Proposer().Address, "privValidator", cs.privValidator)
  617. } else {
  618. log.Info("enterPropose: Our turn to propose", "proposer", cs.Validators.Proposer().Address, "privValidator", cs.privValidator)
  619. cs.decideProposal(height, round)
  620. }
  621. }
  622. func (cs *ConsensusState) decideProposal(height, round int) {
  623. var block *types.Block
  624. var blockParts *types.PartSet
  625. // Decide on block
  626. if cs.LockedBlock != nil {
  627. // If we're locked onto a block, just choose that.
  628. block, blockParts = cs.LockedBlock, cs.LockedBlockParts
  629. } else {
  630. // Create a new proposal block from state/txs from the mempool.
  631. block, blockParts = cs.createProposalBlock()
  632. if block == nil { // on error
  633. return
  634. }
  635. }
  636. // Make proposal
  637. proposal := types.NewProposal(height, round, blockParts.Header(), cs.Votes.POLRound())
  638. err := cs.privValidator.SignProposal(cs.state.ChainID, proposal)
  639. if err == nil {
  640. // Set fields
  641. /* fields set by setProposal and addBlockPart
  642. cs.Proposal = proposal
  643. cs.ProposalBlock = block
  644. cs.ProposalBlockParts = blockParts
  645. */
  646. // send proposal and block parts on internal msg queue
  647. cs.sendInternalMessage(msgInfo{&ProposalMessage{proposal}, ""})
  648. for i := 0; i < blockParts.Total(); i++ {
  649. part := blockParts.GetPart(i)
  650. cs.sendInternalMessage(msgInfo{&BlockPartMessage{cs.Height, cs.Round, part}, ""})
  651. }
  652. log.Notice("Signed and sent proposal", "height", height, "round", round, "proposal", proposal)
  653. log.Debug(Fmt("Signed and sent proposal block: %v", block))
  654. } else {
  655. log.Warn("enterPropose: Error signing proposal", "height", height, "round", round, "error", err)
  656. }
  657. }
  658. // Returns true if the proposal block is complete &&
  659. // (if POLRound was proposed, we have +2/3 prevotes from there).
  660. func (cs *ConsensusState) isProposalComplete() bool {
  661. if cs.Proposal == nil || cs.ProposalBlock == nil {
  662. return false
  663. }
  664. // we have the proposal. if there's a POLRound,
  665. // make sure we have the prevotes from it too
  666. if cs.Proposal.POLRound < 0 {
  667. return true
  668. } else {
  669. // if this is false the proposer is lying or we haven't received the POL yet
  670. return cs.Votes.Prevotes(cs.Proposal.POLRound).HasTwoThirdsMajority()
  671. }
  672. }
  673. // Create the next block to propose and return it.
  674. // Returns nil block upon error.
  675. // NOTE: keep it side-effect free for clarity.
  676. func (cs *ConsensusState) createProposalBlock() (block *types.Block, blockParts *types.PartSet) {
  677. var validation *types.Validation
  678. if cs.Height == 1 {
  679. // We're creating a proposal for the first block.
  680. // The validation is empty, but not nil.
  681. validation = &types.Validation{}
  682. } else if cs.LastCommit.HasTwoThirdsMajority() {
  683. // Make the validation from LastCommit
  684. validation = cs.LastCommit.MakeValidation()
  685. } else {
  686. // This shouldn't happen.
  687. log.Error("enterPropose: Cannot propose anything: No validation for the previous block.")
  688. return
  689. }
  690. // Mempool run transactions and the resulting hash
  691. txs, hash, err := cs.mempool.Reap()
  692. if err != nil {
  693. log.Warn("createProposalBlock: Error getting proposal txs", "error", err)
  694. return nil, nil
  695. }
  696. block = &types.Block{
  697. Header: &types.Header{
  698. ChainID: cs.state.ChainID,
  699. Height: cs.Height,
  700. Time: time.Now(),
  701. Fees: 0, // TODO fees
  702. NumTxs: len(txs),
  703. LastBlockHash: cs.state.LastBlockHash,
  704. LastBlockParts: cs.state.LastBlockParts,
  705. ValidatorsHash: cs.state.Validators.Hash(),
  706. AppHash: hash,
  707. },
  708. LastValidation: validation,
  709. Data: &types.Data{
  710. Txs: txs,
  711. },
  712. }
  713. block.FillHeader()
  714. blockParts = block.MakePartSet()
  715. return block, blockParts
  716. }
  717. // Enter: `timeoutPropose` after entering Propose.
  718. // Enter: proposal block and POL is ready.
  719. // Enter: any +2/3 prevotes for future round.
  720. // Prevote for LockedBlock if we're locked, or ProposalBlock if valid.
  721. // Otherwise vote nil.
  722. func (cs *ConsensusState) enterPrevote(height int, round int) {
  723. //cs.mtx.Lock()
  724. //defer cs.mtx.Unlock()
  725. if cs.Height != height || round < cs.Round || (cs.Round == round && RoundStepPrevote <= cs.Step) {
  726. log.Debug(Fmt("enterPrevote(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  727. return
  728. }
  729. defer func() {
  730. // Done enterPrevote:
  731. cs.updateRoundStep(round, RoundStepPrevote)
  732. cs.newStep()
  733. }()
  734. // fire event for how we got here
  735. if cs.isProposalComplete() {
  736. cs.evsw.FireEvent(types.EventStringCompleteProposal(), cs.RoundStateEvent())
  737. } else {
  738. // we received +2/3 prevotes for a future round
  739. // TODO: catchup event?
  740. }
  741. // cs.stopTimer()
  742. log.Info(Fmt("enterPrevote(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  743. // Sign and broadcast vote as necessary
  744. cs.doPrevote(height, round)
  745. // Once `addVote` hits any +2/3 prevotes, we will go to PrevoteWait
  746. // (so we have more time to try and collect +2/3 prevotes for a single block)
  747. }
  748. func (cs *ConsensusState) doPrevote(height int, round int) {
  749. // If a block is locked, prevote that.
  750. if cs.LockedBlock != nil {
  751. log.Info("enterPrevote: Block was locked")
  752. cs.signAddVote(types.VoteTypePrevote, cs.LockedBlock.Hash(), cs.LockedBlockParts.Header())
  753. return
  754. }
  755. // If ProposalBlock is nil, prevote nil.
  756. if cs.ProposalBlock == nil {
  757. log.Warn("enterPrevote: ProposalBlock is nil")
  758. cs.signAddVote(types.VoteTypePrevote, nil, types.PartSetHeader{})
  759. return
  760. }
  761. // Try staging cs.ProposalBlock
  762. err := cs.stageBlock(cs.ProposalBlock, cs.ProposalBlockParts)
  763. if err != nil {
  764. // ProposalBlock is invalid, prevote nil.
  765. log.Warn("enterPrevote: ProposalBlock is invalid", "error", err)
  766. cs.signAddVote(types.VoteTypePrevote, nil, types.PartSetHeader{})
  767. return
  768. }
  769. // Prevote cs.ProposalBlock
  770. // NOTE: the proposal signature is validated when it is received,
  771. // and the proposal block parts are validated as they are received (against the merkle hash in the proposal)
  772. cs.signAddVote(types.VoteTypePrevote, cs.ProposalBlock.Hash(), cs.ProposalBlockParts.Header())
  773. return
  774. }
  775. // Enter: any +2/3 prevotes at next round.
  776. func (cs *ConsensusState) enterPrevoteWait(height int, round int) {
  777. //cs.mtx.Lock()
  778. //defer cs.mtx.Unlock()
  779. if cs.Height != height || round < cs.Round || (cs.Round == round && RoundStepPrevoteWait <= cs.Step) {
  780. log.Debug(Fmt("enterPrevoteWait(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  781. return
  782. }
  783. if !cs.Votes.Prevotes(round).HasTwoThirdsAny() {
  784. PanicSanity(Fmt("enterPrevoteWait(%v/%v), but Prevotes does not have any +2/3 votes", height, round))
  785. }
  786. log.Info(Fmt("enterPrevoteWait(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  787. defer func() {
  788. // Done enterPrevoteWait:
  789. cs.updateRoundStep(round, RoundStepPrevoteWait)
  790. cs.newStep()
  791. }()
  792. // After `timeoutPrevote0+timeoutPrevoteDelta*round`, enterPrecommit()
  793. cs.scheduleTimeout(timeoutPrevote0+timeoutPrevoteDelta*time.Duration(round), height, round, RoundStepPrevoteWait)
  794. }
  795. // Enter: +2/3 precomits for block or nil.
  796. // Enter: `timeoutPrevote` after any +2/3 prevotes.
  797. // Enter: any +2/3 precommits for next round.
  798. // Lock & precommit the ProposalBlock if we have enough prevotes for it (a POL in this round)
  799. // else, unlock an existing lock and precommit nil if +2/3 of prevotes were nil,
  800. // else, precommit nil otherwise.
  801. func (cs *ConsensusState) enterPrecommit(height int, round int) {
  802. //cs.mtx.Lock()
  803. // defer cs.mtx.Unlock()
  804. if cs.Height != height || round < cs.Round || (cs.Round == round && RoundStepPrecommit <= cs.Step) {
  805. log.Debug(Fmt("enterPrecommit(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  806. return
  807. }
  808. // cs.stopTimer()
  809. log.Info(Fmt("enterPrecommit(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  810. defer func() {
  811. // Done enterPrecommit:
  812. cs.updateRoundStep(round, RoundStepPrecommit)
  813. cs.newStep()
  814. }()
  815. hash, partsHeader, ok := cs.Votes.Prevotes(round).TwoThirdsMajority()
  816. // If we don't have a polka, we must precommit nil
  817. if !ok {
  818. if cs.LockedBlock != nil {
  819. log.Info("enterPrecommit: No +2/3 prevotes during enterPrecommit while we're locked. Precommitting nil")
  820. } else {
  821. log.Info("enterPrecommit: No +2/3 prevotes during enterPrecommit. Precommitting nil.")
  822. }
  823. cs.signAddVote(types.VoteTypePrecommit, nil, types.PartSetHeader{})
  824. return
  825. }
  826. // At this point +2/3 prevoted for a particular block or nil
  827. cs.evsw.FireEvent(types.EventStringPolka(), cs.RoundStateEvent())
  828. // the latest POLRound should be this round
  829. if cs.Votes.POLRound() < round {
  830. PanicSanity(Fmt("This POLRound should be %v but got %", round, cs.Votes.POLRound()))
  831. }
  832. // +2/3 prevoted nil. Unlock and precommit nil.
  833. if len(hash) == 0 {
  834. if cs.LockedBlock == nil {
  835. log.Info("enterPrecommit: +2/3 prevoted for nil.")
  836. } else {
  837. log.Info("enterPrecommit: +2/3 prevoted for nil. Unlocking")
  838. cs.LockedRound = 0
  839. cs.LockedBlock = nil
  840. cs.LockedBlockParts = nil
  841. cs.evsw.FireEvent(types.EventStringUnlock(), cs.RoundStateEvent())
  842. }
  843. cs.signAddVote(types.VoteTypePrecommit, nil, types.PartSetHeader{})
  844. return
  845. }
  846. // At this point, +2/3 prevoted for a particular block.
  847. // If we're already locked on that block, precommit it, and update the LockedRound
  848. if cs.LockedBlock.HashesTo(hash) {
  849. log.Info("enterPrecommit: +2/3 prevoted locked block. Relocking")
  850. cs.LockedRound = round
  851. cs.evsw.FireEvent(types.EventStringRelock(), cs.RoundStateEvent())
  852. cs.signAddVote(types.VoteTypePrecommit, hash, partsHeader)
  853. return
  854. }
  855. // If +2/3 prevoted for proposal block, stage and precommit it
  856. if cs.ProposalBlock.HashesTo(hash) {
  857. log.Info("enterPrecommit: +2/3 prevoted proposal block. Locking", "hash", hash)
  858. // Validate the block.
  859. if err := cs.stageBlock(cs.ProposalBlock, cs.ProposalBlockParts); err != nil {
  860. PanicConsensus(Fmt("enterPrecommit: +2/3 prevoted for an invalid block: %v", err))
  861. }
  862. cs.LockedRound = round
  863. cs.LockedBlock = cs.ProposalBlock
  864. cs.LockedBlockParts = cs.ProposalBlockParts
  865. cs.evsw.FireEvent(types.EventStringLock(), cs.RoundStateEvent())
  866. cs.signAddVote(types.VoteTypePrecommit, hash, partsHeader)
  867. return
  868. }
  869. // There was a polka in this round for a block we don't have.
  870. // Fetch that block, unlock, and precommit nil.
  871. // The +2/3 prevotes for this round is the POL for our unlock.
  872. // TODO: In the future save the POL prevotes for justification.
  873. cs.LockedRound = 0
  874. cs.LockedBlock = nil
  875. cs.LockedBlockParts = nil
  876. if !cs.ProposalBlockParts.HasHeader(partsHeader) {
  877. cs.ProposalBlock = nil
  878. cs.ProposalBlockParts = types.NewPartSetFromHeader(partsHeader)
  879. }
  880. cs.evsw.FireEvent(types.EventStringUnlock(), cs.RoundStateEvent())
  881. cs.signAddVote(types.VoteTypePrecommit, nil, types.PartSetHeader{})
  882. return
  883. }
  884. // Enter: any +2/3 precommits for next round.
  885. func (cs *ConsensusState) enterPrecommitWait(height int, round int) {
  886. //cs.mtx.Lock()
  887. //defer cs.mtx.Unlock()
  888. if cs.Height != height || round < cs.Round || (cs.Round == round && RoundStepPrecommitWait <= cs.Step) {
  889. log.Debug(Fmt("enterPrecommitWait(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  890. return
  891. }
  892. if !cs.Votes.Precommits(round).HasTwoThirdsAny() {
  893. PanicSanity(Fmt("enterPrecommitWait(%v/%v), but Precommits does not have any +2/3 votes", height, round))
  894. }
  895. log.Info(Fmt("enterPrecommitWait(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  896. defer func() {
  897. // Done enterPrecommitWait:
  898. cs.updateRoundStep(round, RoundStepPrecommitWait)
  899. cs.newStep()
  900. }()
  901. // After `timeoutPrecommit0+timeoutPrecommitDelta*round`, enterNewRound()
  902. cs.scheduleTimeout(timeoutPrecommit0+timeoutPrecommitDelta*time.Duration(round), height, round, RoundStepPrecommitWait)
  903. }
  904. // Enter: +2/3 precommits for block
  905. func (cs *ConsensusState) enterCommit(height int, commitRound int) {
  906. //cs.mtx.Lock()
  907. //defer cs.mtx.Unlock()
  908. if cs.Height != height || RoundStepCommit <= cs.Step {
  909. log.Debug(Fmt("enterCommit(%v/%v): Invalid args. Current step: %v/%v/%v", height, commitRound, cs.Height, cs.Round, cs.Step))
  910. return
  911. }
  912. log.Info(Fmt("enterCommit(%v/%v). Current: %v/%v/%v", height, commitRound, cs.Height, cs.Round, cs.Step))
  913. defer func() {
  914. // Done enterCommit:
  915. // keep ca.Round the same, it points to the right Precommits set.
  916. cs.updateRoundStep(cs.Round, RoundStepCommit)
  917. cs.CommitRound = commitRound
  918. cs.newStep()
  919. // Maybe finalize immediately.
  920. cs.tryFinalizeCommit(height)
  921. }()
  922. hash, partsHeader, ok := cs.Votes.Precommits(commitRound).TwoThirdsMajority()
  923. if !ok {
  924. PanicSanity("RunActionCommit() expects +2/3 precommits")
  925. }
  926. // The Locked* fields no longer matter.
  927. // Move them over to ProposalBlock if they match the commit hash,
  928. // otherwise they'll be cleared in updateToState.
  929. if cs.LockedBlock.HashesTo(hash) {
  930. cs.ProposalBlock = cs.LockedBlock
  931. cs.ProposalBlockParts = cs.LockedBlockParts
  932. }
  933. // If we don't have the block being committed, set up to get it.
  934. if !cs.ProposalBlock.HashesTo(hash) {
  935. if !cs.ProposalBlockParts.HasHeader(partsHeader) {
  936. // We're getting the wrong block.
  937. // Set up ProposalBlockParts and keep waiting.
  938. cs.ProposalBlock = nil
  939. cs.ProposalBlockParts = types.NewPartSetFromHeader(partsHeader)
  940. } else {
  941. // We just need to keep waiting.
  942. }
  943. }
  944. }
  945. // If we have the block AND +2/3 commits for it, finalize.
  946. func (cs *ConsensusState) tryFinalizeCommit(height int) {
  947. if cs.Height != height {
  948. PanicSanity(Fmt("tryFinalizeCommit() cs.Height: %v vs height: %v", cs.Height, height))
  949. }
  950. hash, _, ok := cs.Votes.Precommits(cs.CommitRound).TwoThirdsMajority()
  951. if !ok || len(hash) == 0 {
  952. log.Warn("Attempt to finalize failed. There was no +2/3 majority, or +2/3 was for <nil>.")
  953. return
  954. }
  955. if !cs.ProposalBlock.HashesTo(hash) {
  956. log.Warn("Attempt to finalize failed. We don't have the commit block.")
  957. return
  958. }
  959. // go
  960. cs.finalizeCommit(height)
  961. }
  962. // Increment height and goto RoundStepNewHeight
  963. func (cs *ConsensusState) finalizeCommit(height int) {
  964. //cs.mtx.Lock()
  965. //defer cs.mtx.Unlock()
  966. if cs.Height != height || cs.Step != RoundStepCommit {
  967. log.Debug(Fmt("finalizeCommit(%v): Invalid args. Current step: %v/%v/%v", height, cs.Height, cs.Round, cs.Step))
  968. return
  969. }
  970. hash, header, ok := cs.Votes.Precommits(cs.CommitRound).TwoThirdsMajority()
  971. if !ok {
  972. PanicSanity(Fmt("Cannot finalizeCommit, commit does not have two thirds majority"))
  973. }
  974. if !cs.ProposalBlockParts.HasHeader(header) {
  975. PanicSanity(Fmt("Expected ProposalBlockParts header to be commit header"))
  976. }
  977. if !cs.ProposalBlock.HashesTo(hash) {
  978. PanicSanity(Fmt("Cannot finalizeCommit, ProposalBlock does not hash to commit hash"))
  979. }
  980. if err := cs.stageBlock(cs.ProposalBlock, cs.ProposalBlockParts); err != nil {
  981. PanicConsensus(Fmt("+2/3 committed an invalid block: %v", err))
  982. }
  983. log.Info(Fmt("Finalizing commit of block: %v", cs.ProposalBlock))
  984. // We have the block, so stage/save/commit-vote.
  985. cs.saveBlock(cs.ProposalBlock, cs.ProposalBlockParts, cs.Votes.Precommits(cs.CommitRound))
  986. // NewHeightStep!
  987. cs.updateToState(cs.stagedState)
  988. // cs.StartTime is already set.
  989. // Schedule Round0 to start soon.
  990. cs.scheduleRound0(height + 1)
  991. // By here,
  992. // * cs.Height has been increment to height+1
  993. // * cs.Step is now RoundStepNewHeight
  994. // * cs.StartTime is set to when we will start round0.
  995. return
  996. }
  997. //-----------------------------------------------------------------------------
  998. func (cs *ConsensusState) setProposal(proposal *types.Proposal) error {
  999. //cs.mtx.Lock()
  1000. //defer cs.mtx.Unlock()
  1001. // Already have one
  1002. if cs.Proposal != nil {
  1003. return nil
  1004. }
  1005. // Does not apply
  1006. if proposal.Height != cs.Height || proposal.Round != cs.Round {
  1007. return nil
  1008. }
  1009. // We don't care about the proposal if we're already in RoundStepCommit.
  1010. if RoundStepCommit <= cs.Step {
  1011. return nil
  1012. }
  1013. // Verify POLRound, which must be -1 or between 0 and proposal.Round exclusive.
  1014. if proposal.POLRound != -1 &&
  1015. (proposal.POLRound < 0 || proposal.Round <= proposal.POLRound) {
  1016. return ErrInvalidProposalPOLRound
  1017. }
  1018. // Verify signature
  1019. if !cs.Validators.Proposer().PubKey.VerifyBytes(types.SignBytes(cs.state.ChainID, proposal), proposal.Signature) {
  1020. return ErrInvalidProposalSignature
  1021. }
  1022. cs.Proposal = proposal
  1023. cs.ProposalBlockParts = types.NewPartSetFromHeader(proposal.BlockPartsHeader)
  1024. return nil
  1025. }
  1026. // NOTE: block is not necessarily valid.
  1027. // This can trigger us to go into enterPrevote asynchronously (before we timeout of propose) or to attempt to commit
  1028. func (cs *ConsensusState) addProposalBlockPart(height int, part *types.Part) (added bool, err error) {
  1029. //cs.mtx.Lock()
  1030. //defer cs.mtx.Unlock()
  1031. // Blocks might be reused, so round mismatch is OK
  1032. if cs.Height != height {
  1033. return false, nil
  1034. }
  1035. // We're not expecting a block part.
  1036. if cs.ProposalBlockParts == nil {
  1037. return false, nil // TODO: bad peer? Return error?
  1038. }
  1039. added, err = cs.ProposalBlockParts.AddPart(part)
  1040. if err != nil {
  1041. return added, err
  1042. }
  1043. if added && cs.ProposalBlockParts.IsComplete() {
  1044. // Added and completed!
  1045. var n int
  1046. var err error
  1047. cs.ProposalBlock = wire.ReadBinary(&types.Block{}, cs.ProposalBlockParts.GetReader(), types.MaxBlockSize, &n, &err).(*types.Block)
  1048. log.Info("Received complete proposal", "hash", cs.ProposalBlock.Hash(), "round", cs.Proposal.Round)
  1049. if cs.Step == RoundStepPropose && cs.isProposalComplete() {
  1050. // Move onto the next step
  1051. cs.enterPrevote(height, cs.Round)
  1052. } else if cs.Step == RoundStepCommit {
  1053. // If we're waiting on the proposal block...
  1054. cs.tryFinalizeCommit(height)
  1055. }
  1056. return true, err
  1057. }
  1058. return added, nil
  1059. }
  1060. // Attempt to add the vote. if its a duplicate signature, dupeout the validator
  1061. func (cs *ConsensusState) tryAddVote(valIndex int, vote *types.Vote, peerKey string) error {
  1062. _, _, err := cs.addVote(valIndex, vote, peerKey)
  1063. if err != nil {
  1064. // If the vote height is off, we'll just ignore it,
  1065. // But if it's a conflicting sig, broadcast evidence tx for slashing.
  1066. // If it's otherwise invalid, punish peer.
  1067. if err == ErrVoteHeightMismatch {
  1068. return err
  1069. } else if _, ok := err.(*types.ErrVoteConflictingSignature); ok {
  1070. log.Warn("Found conflicting vote. Publish evidence")
  1071. /* TODO
  1072. evidenceTx := &types.DupeoutTx{
  1073. Address: address,
  1074. VoteA: *errDupe.VoteA,
  1075. VoteB: *errDupe.VoteB,
  1076. }
  1077. cs.mempool.BroadcastTx(evidenceTx) // shouldn't need to check returned err
  1078. */
  1079. return err
  1080. } else {
  1081. // Probably an invalid signature. Bad peer.
  1082. log.Warn("Error attempting to add vote", "error", err)
  1083. return ErrAddingVote
  1084. }
  1085. }
  1086. return nil
  1087. }
  1088. //-----------------------------------------------------------------------------
  1089. func (cs *ConsensusState) addVote(valIndex int, vote *types.Vote, peerKey string) (added bool, address []byte, err error) {
  1090. log.Debug("addVote", "voteHeight", vote.Height, "voteType", vote.Type, "csHeight", cs.Height)
  1091. // A precommit for the previous height?
  1092. if vote.Height+1 == cs.Height {
  1093. if !(cs.Step == RoundStepNewHeight && vote.Type == types.VoteTypePrecommit) {
  1094. // TODO: give the reason ..
  1095. // fmt.Errorf("tryAddVote: Wrong height, not a LastCommit straggler commit.")
  1096. return added, nil, ErrVoteHeightMismatch
  1097. }
  1098. added, address, err = cs.LastCommit.AddByIndex(valIndex, vote)
  1099. if added {
  1100. log.Info(Fmt("Added to lastPrecommits: %v", cs.LastCommit.StringShort()))
  1101. cs.evsw.FireEvent(types.EventStringVote(), &types.EventDataVote{valIndex, address, vote})
  1102. }
  1103. return
  1104. }
  1105. // A prevote/precommit for this height?
  1106. if vote.Height == cs.Height {
  1107. height := cs.Height
  1108. added, address, err = cs.Votes.AddByIndex(valIndex, vote, peerKey)
  1109. if added {
  1110. cs.evsw.FireEvent(types.EventStringVote(), &types.EventDataVote{valIndex, address, vote})
  1111. switch vote.Type {
  1112. case types.VoteTypePrevote:
  1113. prevotes := cs.Votes.Prevotes(vote.Round)
  1114. log.Info("Added to prevote", "vote", vote, "prevotes", prevotes.StringShort())
  1115. // First, unlock if prevotes is a valid POL.
  1116. // >> lockRound < POLRound <= unlockOrChangeLockRound (see spec)
  1117. // NOTE: If (lockRound < POLRound) but !(POLRound <= unlockOrChangeLockRound),
  1118. // we'll still enterNewRound(H,vote.R) and enterPrecommit(H,vote.R) to process it
  1119. // there.
  1120. if (cs.LockedBlock != nil) && (cs.LockedRound < vote.Round) && (vote.Round <= cs.Round) {
  1121. hash, _, ok := prevotes.TwoThirdsMajority()
  1122. if ok && !cs.LockedBlock.HashesTo(hash) {
  1123. log.Notice("Unlocking because of POL.", "lockedRound", cs.LockedRound, "POLRound", vote.Round)
  1124. cs.LockedRound = 0
  1125. cs.LockedBlock = nil
  1126. cs.LockedBlockParts = nil
  1127. cs.evsw.FireEvent(types.EventStringUnlock(), cs.RoundStateEvent())
  1128. }
  1129. }
  1130. if cs.Round <= vote.Round && prevotes.HasTwoThirdsAny() {
  1131. // Round-skip over to PrevoteWait or goto Precommit.
  1132. cs.enterNewRound(height, vote.Round) // if the vote is ahead of us
  1133. if prevotes.HasTwoThirdsMajority() {
  1134. cs.enterPrecommit(height, vote.Round)
  1135. } else {
  1136. cs.enterPrevote(height, vote.Round) // if the vote is ahead of us
  1137. cs.enterPrevoteWait(height, vote.Round)
  1138. }
  1139. } else if cs.Proposal != nil && 0 <= cs.Proposal.POLRound && cs.Proposal.POLRound == vote.Round {
  1140. // If the proposal is now complete, enter prevote of cs.Round.
  1141. if cs.isProposalComplete() {
  1142. cs.enterPrevote(height, cs.Round)
  1143. }
  1144. }
  1145. case types.VoteTypePrecommit:
  1146. precommits := cs.Votes.Precommits(vote.Round)
  1147. log.Info("Added to precommit", "vote", vote, "precommits", precommits.StringShort())
  1148. hash, _, ok := precommits.TwoThirdsMajority()
  1149. if ok {
  1150. if len(hash) == 0 {
  1151. cs.enterNewRound(height, vote.Round+1)
  1152. } else {
  1153. cs.enterNewRound(height, vote.Round)
  1154. cs.enterPrecommit(height, vote.Round)
  1155. cs.enterCommit(height, vote.Round)
  1156. }
  1157. } else if cs.Round <= vote.Round && precommits.HasTwoThirdsAny() {
  1158. cs.enterNewRound(height, vote.Round)
  1159. cs.enterPrecommit(height, vote.Round)
  1160. cs.enterPrecommitWait(height, vote.Round)
  1161. //}()
  1162. }
  1163. default:
  1164. PanicSanity(Fmt("Unexpected vote type %X", vote.Type)) // Should not happen.
  1165. }
  1166. }
  1167. // Either duplicate, or error upon cs.Votes.AddByIndex()
  1168. return
  1169. } else {
  1170. err = ErrVoteHeightMismatch
  1171. }
  1172. // Height mismatch, bad peer?
  1173. log.Info("Vote ignored and not added", "voteHeight", vote.Height, "csHeight", cs.Height)
  1174. return
  1175. }
  1176. func (cs *ConsensusState) stageBlock(block *types.Block, blockParts *types.PartSet) error {
  1177. if block == nil {
  1178. PanicSanity("Cannot stage nil block")
  1179. }
  1180. // Already staged?
  1181. blockHash := block.Hash()
  1182. if cs.stagedBlock != nil && len(blockHash) != 0 && bytes.Equal(cs.stagedBlock.Hash(), blockHash) {
  1183. return nil
  1184. }
  1185. // Create a new event cache to cache all events.
  1186. cs.evc = events.NewEventCache(cs.evsw)
  1187. // Create a copy of the state for staging
  1188. stateCopy := cs.state.Copy()
  1189. stateCopy.SetEventCache(cs.evc)
  1190. // Run the block on the State:
  1191. // + update validator sets
  1192. // + first rolls back proxyAppCtx
  1193. // + run txs on the proxyAppCtx or rollback
  1194. err := stateCopy.ExecBlock(cs.proxyAppCtx, block, blockParts.Header())
  1195. if err != nil {
  1196. return err
  1197. }
  1198. // Everything looks good!
  1199. cs.stagedBlock = block
  1200. cs.stagedState = stateCopy
  1201. return nil
  1202. }
  1203. func (cs *ConsensusState) signVote(type_ byte, hash []byte, header types.PartSetHeader) (*types.Vote, error) {
  1204. vote := &types.Vote{
  1205. Height: cs.Height,
  1206. Round: cs.Round,
  1207. Type: type_,
  1208. BlockHash: hash,
  1209. BlockPartsHeader: header,
  1210. }
  1211. err := cs.privValidator.SignVote(cs.state.ChainID, vote)
  1212. return vote, err
  1213. }
  1214. // signs the vote, publishes on internalMsgQueue
  1215. func (cs *ConsensusState) signAddVote(type_ byte, hash []byte, header types.PartSetHeader) *types.Vote {
  1216. if cs.privValidator == nil || !cs.Validators.HasAddress(cs.privValidator.Address) {
  1217. return nil
  1218. }
  1219. vote, err := cs.signVote(type_, hash, header)
  1220. if err == nil {
  1221. // TODO: store our index in the cs so we don't have to do this every time
  1222. valIndex, _ := cs.Validators.GetByAddress(cs.privValidator.Address)
  1223. cs.sendInternalMessage(msgInfo{&VoteMessage{valIndex, vote}, ""})
  1224. log.Notice("Signed and pushed vote", "height", cs.Height, "round", cs.Round, "vote", vote, "error", err)
  1225. return vote
  1226. } else {
  1227. log.Warn("Error signing vote", "height", cs.Height, "round", cs.Round, "vote", vote, "error", err)
  1228. return nil
  1229. }
  1230. }
  1231. // Save Block, save the +2/3 Commits we've seen
  1232. func (cs *ConsensusState) saveBlock(block *types.Block, blockParts *types.PartSet, commits *types.VoteSet) {
  1233. // The proposal must be valid.
  1234. if err := cs.stageBlock(block, blockParts); err != nil {
  1235. PanicSanity(Fmt("saveBlock() an invalid block: %v", err))
  1236. }
  1237. // Save to blockStore.
  1238. if cs.blockStore.Height() < block.Height {
  1239. seenValidation := commits.MakeValidation()
  1240. cs.blockStore.SaveBlock(block, blockParts, seenValidation)
  1241. }
  1242. // Commit to proxyAppCtx
  1243. err := cs.stagedState.Commit(cs.proxyAppCtx)
  1244. if err != nil {
  1245. // TODO: handle this gracefully.
  1246. PanicQ(Fmt("Commit failed for applicaiton"))
  1247. }
  1248. // Save the state.
  1249. cs.stagedState.Save()
  1250. // Update mempool.
  1251. cs.mempool.Update(block)
  1252. // Fire off event
  1253. if cs.evsw != nil && cs.evc != nil {
  1254. cs.evsw.FireEvent(types.EventStringNewBlock(), types.EventDataNewBlock{block})
  1255. go cs.evc.Flush()
  1256. }
  1257. }
  1258. //---------------------------------------------------------
  1259. func CompareHRS(h1, r1 int, s1 RoundStepType, h2, r2 int, s2 RoundStepType) int {
  1260. if h1 < h2 {
  1261. return -1
  1262. } else if h1 > h2 {
  1263. return 1
  1264. }
  1265. if r1 < r2 {
  1266. return -1
  1267. } else if r1 > r2 {
  1268. return 1
  1269. }
  1270. if s1 < s2 {
  1271. return -1
  1272. } else if s1 > s2 {
  1273. return 1
  1274. }
  1275. return 0
  1276. }