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.

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