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.

1557 lines
51 KiB

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