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.

1550 lines
51 KiB

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