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.

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