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.

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