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.

1527 lines
51 KiB

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