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.

1560 lines
52 KiB

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