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
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
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
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
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. // XXX 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. polRound, polBlockID := cs.Votes.POLInfo()
  742. proposal := types.NewProposal(height, round, blockParts.Header(), polRound, polBlockID)
  743. err := cs.privValidator.SignProposal(cs.state.ChainID, proposal)
  744. if err == nil {
  745. // Set fields
  746. /* fields set by setProposal and addBlockPart
  747. cs.Proposal = proposal
  748. cs.ProposalBlock = block
  749. cs.ProposalBlockParts = blockParts
  750. */
  751. // send proposal and block parts on internal msg queue
  752. cs.sendInternalMessage(msgInfo{&ProposalMessage{proposal}, ""})
  753. for i := 0; i < blockParts.Total(); i++ {
  754. part := blockParts.GetPart(i)
  755. cs.sendInternalMessage(msgInfo{&BlockPartMessage{cs.Height, cs.Round, part}, ""})
  756. }
  757. log.Info("Signed proposal", "height", height, "round", round, "proposal", proposal)
  758. log.Debug(Fmt("Signed proposal block: %v", block))
  759. } else {
  760. if !cs.replayMode {
  761. log.Warn("enterPropose: Error signing proposal", "height", height, "round", round, "error", err)
  762. }
  763. }
  764. }
  765. // Returns true if the proposal block is complete &&
  766. // (if POLRound was proposed, we have +2/3 prevotes from there).
  767. func (cs *ConsensusState) isProposalComplete() bool {
  768. if cs.Proposal == nil || cs.ProposalBlock == nil {
  769. return false
  770. }
  771. // we have the proposal. if there's a POLRound,
  772. // make sure we have the prevotes from it too
  773. if cs.Proposal.POLRound < 0 {
  774. return true
  775. } else {
  776. // if this is false the proposer is lying or we haven't received the POL yet
  777. return cs.Votes.Prevotes(cs.Proposal.POLRound).HasTwoThirdsMajority()
  778. }
  779. }
  780. // Create the next block to propose and return it.
  781. // Returns nil block upon error.
  782. // NOTE: keep it side-effect free for clarity.
  783. func (cs *ConsensusState) createProposalBlock() (block *types.Block, blockParts *types.PartSet) {
  784. var commit *types.Commit
  785. if cs.Height == 1 {
  786. // We're creating a proposal for the first block.
  787. // The commit is empty, but not nil.
  788. commit = &types.Commit{}
  789. } else if cs.LastCommit.HasTwoThirdsMajority() {
  790. // Make the commit from LastCommit
  791. commit = cs.LastCommit.MakeCommit()
  792. } else {
  793. // This shouldn't happen.
  794. log.Error("enterPropose: Cannot propose anything: No commit for the previous block.")
  795. return
  796. }
  797. // Mempool validated transactions
  798. txs := cs.mempool.Reap(cs.config.GetInt("block_size"))
  799. block = &types.Block{
  800. Header: &types.Header{
  801. ChainID: cs.state.ChainID,
  802. Height: cs.Height,
  803. Time: time.Now(),
  804. NumTxs: len(txs),
  805. LastBlockID: cs.state.LastBlockID,
  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. blockID, 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. polRound, _ := cs.Votes.POLInfo()
  925. if polRound < round {
  926. PanicSanity(Fmt("This POLRound should be %v but got %", round, polRound))
  927. }
  928. // +2/3 prevoted nil. Unlock and precommit nil.
  929. if len(blockID.Hash) == 0 {
  930. if cs.LockedBlock == nil {
  931. log.Notice("enterPrecommit: +2/3 prevoted for nil.")
  932. } else {
  933. log.Notice("enterPrecommit: +2/3 prevoted for nil. Unlocking")
  934. cs.LockedRound = 0
  935. cs.LockedBlock = nil
  936. cs.LockedBlockParts = nil
  937. types.FireEventUnlock(cs.evsw, cs.RoundStateEvent())
  938. }
  939. cs.signAddVote(types.VoteTypePrecommit, nil, types.PartSetHeader{})
  940. return
  941. }
  942. // At this point, +2/3 prevoted for a particular block.
  943. // If we're already locked on that block, precommit it, and update the LockedRound
  944. if cs.LockedBlock.HashesTo(blockID.Hash) {
  945. log.Notice("enterPrecommit: +2/3 prevoted locked block. Relocking")
  946. cs.LockedRound = round
  947. types.FireEventRelock(cs.evsw, cs.RoundStateEvent())
  948. cs.signAddVote(types.VoteTypePrecommit, blockID.Hash, blockID.PartsHeader)
  949. return
  950. }
  951. // If +2/3 prevoted for proposal block, stage and precommit it
  952. if cs.ProposalBlock.HashesTo(blockID.Hash) {
  953. log.Notice("enterPrecommit: +2/3 prevoted proposal block. Locking", "hash", blockID.Hash)
  954. // Validate the block.
  955. if err := cs.state.ValidateBlock(cs.ProposalBlock); err != nil {
  956. PanicConsensus(Fmt("enterPrecommit: +2/3 prevoted for an invalid block: %v", err))
  957. }
  958. cs.LockedRound = round
  959. cs.LockedBlock = cs.ProposalBlock
  960. cs.LockedBlockParts = cs.ProposalBlockParts
  961. types.FireEventLock(cs.evsw, cs.RoundStateEvent())
  962. cs.signAddVote(types.VoteTypePrecommit, blockID.Hash, blockID.PartsHeader)
  963. return
  964. }
  965. // There was a polka in this round for a block we don't have.
  966. // Fetch that block, unlock, and precommit nil.
  967. // The +2/3 prevotes for this round is the POL for our unlock.
  968. // TODO: In the future save the POL prevotes for justification.
  969. cs.LockedRound = 0
  970. cs.LockedBlock = nil
  971. cs.LockedBlockParts = nil
  972. if !cs.ProposalBlockParts.HasHeader(blockID.PartsHeader) {
  973. cs.ProposalBlock = nil
  974. cs.ProposalBlockParts = types.NewPartSetFromHeader(blockID.PartsHeader)
  975. }
  976. types.FireEventUnlock(cs.evsw, cs.RoundStateEvent())
  977. cs.signAddVote(types.VoteTypePrecommit, nil, types.PartSetHeader{})
  978. return
  979. }
  980. // Enter: any +2/3 precommits for next round.
  981. func (cs *ConsensusState) enterPrecommitWait(height int, round int) {
  982. if cs.Height != height || round < cs.Round || (cs.Round == round && RoundStepPrecommitWait <= cs.Step) {
  983. log.Debug(Fmt("enterPrecommitWait(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  984. return
  985. }
  986. if !cs.Votes.Precommits(round).HasTwoThirdsAny() {
  987. PanicSanity(Fmt("enterPrecommitWait(%v/%v), but Precommits does not have any +2/3 votes", height, round))
  988. }
  989. log.Info(Fmt("enterPrecommitWait(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  990. defer func() {
  991. // Done enterPrecommitWait:
  992. cs.updateRoundStep(round, RoundStepPrecommitWait)
  993. cs.newStep()
  994. }()
  995. // Wait for some more precommits; enterNewRound
  996. cs.scheduleTimeout(cs.timeoutParams.Precommit(round), height, round, RoundStepPrecommitWait)
  997. }
  998. // Enter: +2/3 precommits for block
  999. func (cs *ConsensusState) enterCommit(height int, commitRound int) {
  1000. if cs.Height != height || RoundStepCommit <= cs.Step {
  1001. log.Debug(Fmt("enterCommit(%v/%v): Invalid args. Current step: %v/%v/%v", height, commitRound, cs.Height, cs.Round, cs.Step))
  1002. return
  1003. }
  1004. log.Info(Fmt("enterCommit(%v/%v). Current: %v/%v/%v", height, commitRound, cs.Height, cs.Round, cs.Step))
  1005. defer func() {
  1006. // Done enterCommit:
  1007. // keep cs.Round the same, commitRound points to the right Precommits set.
  1008. cs.updateRoundStep(cs.Round, RoundStepCommit)
  1009. cs.CommitRound = commitRound
  1010. cs.newStep()
  1011. // Maybe finalize immediately.
  1012. cs.tryFinalizeCommit(height)
  1013. }()
  1014. blockID, ok := cs.Votes.Precommits(commitRound).TwoThirdsMajority()
  1015. if !ok {
  1016. PanicSanity("RunActionCommit() expects +2/3 precommits")
  1017. }
  1018. // The Locked* fields no longer matter.
  1019. // Move them over to ProposalBlock if they match the commit hash,
  1020. // otherwise they'll be cleared in updateToState.
  1021. if cs.LockedBlock.HashesTo(blockID.Hash) {
  1022. cs.ProposalBlock = cs.LockedBlock
  1023. cs.ProposalBlockParts = cs.LockedBlockParts
  1024. }
  1025. // If we don't have the block being committed, set up to get it.
  1026. if !cs.ProposalBlock.HashesTo(blockID.Hash) {
  1027. if !cs.ProposalBlockParts.HasHeader(blockID.PartsHeader) {
  1028. // We're getting the wrong block.
  1029. // Set up ProposalBlockParts and keep waiting.
  1030. cs.ProposalBlock = nil
  1031. cs.ProposalBlockParts = types.NewPartSetFromHeader(blockID.PartsHeader)
  1032. } else {
  1033. // We just need to keep waiting.
  1034. }
  1035. }
  1036. }
  1037. // If we have the block AND +2/3 commits for it, finalize.
  1038. func (cs *ConsensusState) tryFinalizeCommit(height int) {
  1039. if cs.Height != height {
  1040. PanicSanity(Fmt("tryFinalizeCommit() cs.Height: %v vs height: %v", cs.Height, height))
  1041. }
  1042. blockID, ok := cs.Votes.Precommits(cs.CommitRound).TwoThirdsMajority()
  1043. if !ok || len(blockID.Hash) == 0 {
  1044. log.Warn("Attempt to finalize failed. There was no +2/3 majority, or +2/3 was for <nil>.")
  1045. return
  1046. }
  1047. if !cs.ProposalBlock.HashesTo(blockID.Hash) {
  1048. // TODO: this happens every time if we're not a validator (ugly logs)
  1049. // TODO: ^^ wait, why does it matter that we're a validator?
  1050. log.Warn("Attempt to finalize failed. We don't have the commit block.")
  1051. return
  1052. }
  1053. // go
  1054. cs.finalizeCommit(height)
  1055. }
  1056. // Increment height and goto RoundStepNewHeight
  1057. func (cs *ConsensusState) finalizeCommit(height int) {
  1058. if cs.Height != height || cs.Step != RoundStepCommit {
  1059. log.Debug(Fmt("finalizeCommit(%v): Invalid args. Current step: %v/%v/%v", height, cs.Height, cs.Round, cs.Step))
  1060. return
  1061. }
  1062. blockID, ok := cs.Votes.Precommits(cs.CommitRound).TwoThirdsMajority()
  1063. block, blockParts := cs.ProposalBlock, cs.ProposalBlockParts
  1064. if !ok {
  1065. PanicSanity(Fmt("Cannot finalizeCommit, commit does not have two thirds majority"))
  1066. }
  1067. if !blockParts.HasHeader(blockID.PartsHeader) {
  1068. PanicSanity(Fmt("Expected ProposalBlockParts header to be commit header"))
  1069. }
  1070. if !block.HashesTo(blockID.Hash) {
  1071. PanicSanity(Fmt("Cannot finalizeCommit, ProposalBlock does not hash to commit hash"))
  1072. }
  1073. if err := cs.state.ValidateBlock(block); err != nil {
  1074. PanicConsensus(Fmt("+2/3 committed an invalid block: %v", err))
  1075. }
  1076. log.Notice(Fmt("Finalizing commit of block with %d txs", block.NumTxs), "height", block.Height, "hash", block.Hash())
  1077. log.Info(Fmt("%v", block))
  1078. // Fire off event for new block.
  1079. // TODO: Handle app failure. See #177
  1080. types.FireEventNewBlock(cs.evsw, types.EventDataNewBlock{block})
  1081. types.FireEventNewBlockHeader(cs.evsw, types.EventDataNewBlockHeader{block.Header})
  1082. // Create a copy of the state for staging
  1083. stateCopy := cs.state.Copy()
  1084. // event cache for txs
  1085. eventCache := types.NewEventCache(cs.evsw)
  1086. // Run the block on the State:
  1087. // + update validator sets
  1088. // + run txs on the proxyAppConn
  1089. err := stateCopy.ExecBlock(eventCache, cs.proxyAppConn, block, blockParts.Header())
  1090. if err != nil {
  1091. // TODO: handle this gracefully.
  1092. PanicQ(Fmt("Exec failed for application: %v", err))
  1093. }
  1094. // lock mempool, commit state, update mempoool
  1095. err = cs.commitStateUpdateMempool(stateCopy, block)
  1096. if err != nil {
  1097. // TODO: handle this gracefully.
  1098. PanicQ(Fmt("Commit failed for application: %v", err))
  1099. }
  1100. // txs committed, bad ones removed from mepool; fire events
  1101. // NOTE: the block.AppHash wont reflect these txs until the next block
  1102. eventCache.Flush()
  1103. // Save to blockStore.
  1104. if cs.blockStore.Height() < block.Height {
  1105. precommits := cs.Votes.Precommits(cs.CommitRound)
  1106. seenCommit := precommits.MakeCommit()
  1107. cs.blockStore.SaveBlock(block, blockParts, seenCommit)
  1108. }
  1109. // Save the state.
  1110. stateCopy.Save()
  1111. // NewHeightStep!
  1112. cs.updateToState(stateCopy)
  1113. // cs.StartTime is already set.
  1114. // Schedule Round0 to start soon.
  1115. cs.scheduleRound0(&cs.RoundState)
  1116. // By here,
  1117. // * cs.Height has been increment to height+1
  1118. // * cs.Step is now RoundStepNewHeight
  1119. // * cs.StartTime is set to when we will start round0.
  1120. return
  1121. }
  1122. // mempool must be locked during commit and update
  1123. // because state is typically reset on Commit and old txs must be replayed
  1124. // against committed state before new txs are run in the mempool, lest they be invalid
  1125. func (cs *ConsensusState) commitStateUpdateMempool(s *sm.State, block *types.Block) error {
  1126. cs.mempool.Lock()
  1127. defer cs.mempool.Unlock()
  1128. // Commit block, get hash back
  1129. res := cs.proxyAppConn.CommitSync()
  1130. if res.IsErr() {
  1131. log.Warn("Error in proxyAppConn.CommitSync", "error", res)
  1132. return res
  1133. }
  1134. if res.Log != "" {
  1135. log.Debug("Commit.Log: " + res.Log)
  1136. }
  1137. // Set the state's new AppHash
  1138. s.AppHash = res.Data
  1139. // Update mempool.
  1140. cs.mempool.Update(block.Height, block.Txs)
  1141. return nil
  1142. }
  1143. //-----------------------------------------------------------------------------
  1144. func (cs *ConsensusState) setProposal(proposal *types.Proposal) error {
  1145. // Already have one
  1146. if cs.Proposal != nil {
  1147. return nil
  1148. }
  1149. // Does not apply
  1150. if proposal.Height != cs.Height || proposal.Round != cs.Round {
  1151. return nil
  1152. }
  1153. // We don't care about the proposal if we're already in RoundStepCommit.
  1154. if RoundStepCommit <= cs.Step {
  1155. return nil
  1156. }
  1157. // Verify POLRound, which must be -1 or between 0 and proposal.Round exclusive.
  1158. if proposal.POLRound != -1 &&
  1159. (proposal.POLRound < 0 || proposal.Round <= proposal.POLRound) {
  1160. return ErrInvalidProposalPOLRound
  1161. }
  1162. // Verify signature
  1163. if !cs.Validators.Proposer().PubKey.VerifyBytes(types.SignBytes(cs.state.ChainID, proposal), proposal.Signature) {
  1164. return ErrInvalidProposalSignature
  1165. }
  1166. cs.Proposal = proposal
  1167. cs.ProposalBlockParts = types.NewPartSetFromHeader(proposal.BlockPartsHeader)
  1168. return nil
  1169. }
  1170. // NOTE: block is not necessarily valid.
  1171. // Asynchronously triggers either enterPrevote (before we timeout of propose) or tryFinalizeCommit, once we have the full block.
  1172. func (cs *ConsensusState) addProposalBlockPart(height int, part *types.Part, verify bool) (added bool, err error) {
  1173. // Blocks might be reused, so round mismatch is OK
  1174. if cs.Height != height {
  1175. return false, nil
  1176. }
  1177. // We're not expecting a block part.
  1178. if cs.ProposalBlockParts == nil {
  1179. return false, nil // TODO: bad peer? Return error?
  1180. }
  1181. added, err = cs.ProposalBlockParts.AddPart(part, verify)
  1182. if err != nil {
  1183. return added, err
  1184. }
  1185. if added && cs.ProposalBlockParts.IsComplete() {
  1186. // Added and completed!
  1187. var n int
  1188. var err error
  1189. cs.ProposalBlock = wire.ReadBinary(&types.Block{}, cs.ProposalBlockParts.GetReader(), types.MaxBlockSize, &n, &err).(*types.Block)
  1190. // NOTE: it's possible to receive complete proposal blocks for future rounds without having the proposal
  1191. log.Info("Received complete proposal block", "height", cs.ProposalBlock.Height, "hash", cs.ProposalBlock.Hash())
  1192. if cs.Step == RoundStepPropose && cs.isProposalComplete() {
  1193. // Move onto the next step
  1194. cs.enterPrevote(height, cs.Round)
  1195. } else if cs.Step == RoundStepCommit {
  1196. // If we're waiting on the proposal block...
  1197. cs.tryFinalizeCommit(height)
  1198. }
  1199. return true, err
  1200. }
  1201. return added, nil
  1202. }
  1203. // Attempt to add the vote. if its a duplicate signature, dupeout the validator
  1204. func (cs *ConsensusState) tryAddVote(vote *types.Vote, peerKey string) error {
  1205. _, err := cs.addVote(vote, peerKey)
  1206. if err != nil {
  1207. // If the vote height is off, we'll just ignore it,
  1208. // But if it's a conflicting sig, broadcast evidence tx for slashing.
  1209. // If it's otherwise invalid, punish peer.
  1210. if err == ErrVoteHeightMismatch {
  1211. return err
  1212. } else if _, ok := err.(*types.ErrVoteConflictingVotes); ok {
  1213. if peerKey == "" {
  1214. log.Warn("Found conflicting vote from ourselves. Did you unsafe_reset a validator?", "height", vote.Height, "round", vote.Round, "type", vote.Type)
  1215. return err
  1216. }
  1217. log.Warn("Found conflicting vote. Publish evidence (TODO)")
  1218. /* TODO
  1219. evidenceTx := &types.DupeoutTx{
  1220. Address: address,
  1221. VoteA: *errDupe.VoteA,
  1222. VoteB: *errDupe.VoteB,
  1223. }
  1224. cs.mempool.BroadcastTx(struct{???}{evidenceTx}) // shouldn't need to check returned err
  1225. */
  1226. return err
  1227. } else {
  1228. // Probably an invalid signature. Bad peer.
  1229. log.Warn("Error attempting to add vote", "error", err)
  1230. return ErrAddingVote
  1231. }
  1232. }
  1233. return nil
  1234. }
  1235. //-----------------------------------------------------------------------------
  1236. func (cs *ConsensusState) addVote(vote *types.Vote, peerKey string) (added bool, err error) {
  1237. log.Debug("addVote", "voteHeight", vote.Height, "voteType", vote.Type, "csHeight", cs.Height)
  1238. // A precommit for the previous height?
  1239. if vote.Height+1 == cs.Height {
  1240. if !(cs.Step == RoundStepNewHeight && vote.Type == types.VoteTypePrecommit) {
  1241. // TODO: give the reason ..
  1242. // fmt.Errorf("tryAddVote: Wrong height, not a LastCommit straggler commit.")
  1243. return added, ErrVoteHeightMismatch
  1244. }
  1245. added, err = cs.LastCommit.AddVote(vote)
  1246. if added {
  1247. log.Info(Fmt("Added to lastPrecommits: %v", cs.LastCommit.StringShort()))
  1248. types.FireEventVote(cs.evsw, types.EventDataVote{vote})
  1249. }
  1250. return
  1251. }
  1252. // A prevote/precommit for this height?
  1253. if vote.Height == cs.Height {
  1254. height := cs.Height
  1255. added, err = cs.Votes.AddVote(vote, peerKey)
  1256. if added {
  1257. types.FireEventVote(cs.evsw, types.EventDataVote{vote})
  1258. switch vote.Type {
  1259. case types.VoteTypePrevote:
  1260. prevotes := cs.Votes.Prevotes(vote.Round)
  1261. log.Info("Added to prevote", "vote", vote, "prevotes", prevotes.StringShort())
  1262. // First, unlock if prevotes is a valid POL.
  1263. // >> lockRound < POLRound <= unlockOrChangeLockRound (see spec)
  1264. // NOTE: If (lockRound < POLRound) but !(POLRound <= unlockOrChangeLockRound),
  1265. // we'll still enterNewRound(H,vote.R) and enterPrecommit(H,vote.R) to process it
  1266. // there.
  1267. if (cs.LockedBlock != nil) && (cs.LockedRound < vote.Round) && (vote.Round <= cs.Round) {
  1268. blockID, ok := prevotes.TwoThirdsMajority()
  1269. if ok && !cs.LockedBlock.HashesTo(blockID.Hash) {
  1270. log.Notice("Unlocking because of POL.", "lockedRound", cs.LockedRound, "POLRound", vote.Round)
  1271. cs.LockedRound = 0
  1272. cs.LockedBlock = nil
  1273. cs.LockedBlockParts = nil
  1274. types.FireEventUnlock(cs.evsw, cs.RoundStateEvent())
  1275. }
  1276. }
  1277. if cs.Round <= vote.Round && prevotes.HasTwoThirdsAny() {
  1278. // Round-skip over to PrevoteWait or goto Precommit.
  1279. cs.enterNewRound(height, vote.Round) // if the vote is ahead of us
  1280. if prevotes.HasTwoThirdsMajority() {
  1281. cs.enterPrecommit(height, vote.Round)
  1282. } else {
  1283. cs.enterPrevote(height, vote.Round) // if the vote is ahead of us
  1284. cs.enterPrevoteWait(height, vote.Round)
  1285. }
  1286. } else if cs.Proposal != nil && 0 <= cs.Proposal.POLRound && cs.Proposal.POLRound == vote.Round {
  1287. // If the proposal is now complete, enter prevote of cs.Round.
  1288. if cs.isProposalComplete() {
  1289. cs.enterPrevote(height, cs.Round)
  1290. }
  1291. }
  1292. case types.VoteTypePrecommit:
  1293. precommits := cs.Votes.Precommits(vote.Round)
  1294. log.Info("Added to precommit", "vote", vote, "precommits", precommits.StringShort())
  1295. blockID, ok := precommits.TwoThirdsMajority()
  1296. if ok {
  1297. if len(blockID.Hash) == 0 {
  1298. cs.enterNewRound(height, vote.Round+1)
  1299. } else {
  1300. cs.enterNewRound(height, vote.Round)
  1301. cs.enterPrecommit(height, vote.Round)
  1302. cs.enterCommit(height, vote.Round)
  1303. }
  1304. } else if cs.Round <= vote.Round && precommits.HasTwoThirdsAny() {
  1305. cs.enterNewRound(height, vote.Round)
  1306. cs.enterPrecommit(height, vote.Round)
  1307. cs.enterPrecommitWait(height, vote.Round)
  1308. //}()
  1309. }
  1310. default:
  1311. PanicSanity(Fmt("Unexpected vote type %X", vote.Type)) // Should not happen.
  1312. }
  1313. }
  1314. // Either duplicate, or error upon cs.Votes.AddByIndex()
  1315. return
  1316. } else {
  1317. err = ErrVoteHeightMismatch
  1318. }
  1319. // Height mismatch, bad peer?
  1320. log.Info("Vote ignored and not added", "voteHeight", vote.Height, "csHeight", cs.Height, "err", err)
  1321. return
  1322. }
  1323. func (cs *ConsensusState) signVote(type_ byte, hash []byte, header types.PartSetHeader) (*types.Vote, error) {
  1324. // TODO: store our index in the cs so we don't have to do this every time
  1325. valIndex, _ := cs.Validators.GetByAddress(cs.privValidator.Address)
  1326. vote := &types.Vote{
  1327. ValidatorAddress: cs.privValidator.Address,
  1328. ValidatorIndex: valIndex,
  1329. Height: cs.Height,
  1330. Round: cs.Round,
  1331. Type: type_,
  1332. BlockID: types.BlockID{hash, 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. }