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.

1553 lines
51 KiB

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