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.

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