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.

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