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.

1505 lines
50 KiB

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