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.

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