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.

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