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.

1437 lines
48 KiB

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