You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1560 lines
52 KiB

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