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.

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