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.

1620 lines
55 KiB

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