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.

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