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.

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