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.

1178 lines
40 KiB

10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
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
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
9 years ago
10 years ago
10 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
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
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
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
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
9 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
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
9 years ago
10 years ago
  1. /*
  2. Consensus State Machine Overview:
  3. NewHeight, NewRound, Propose, Prevote, Precommit represent state machine steps. (aka RoundStep).
  4. To "prevote/precommit" something means to broadcast a prevote/precommit vote for something.
  5. During NewHeight/NewRound/Propose/Prevote/Precommit:
  6. * Nodes gossip the proposal block proposed by the designated proposer at round.
  7. * Nodes gossip prevotes/precommits at rounds [0...currentRound+1] (currentRound+1 to allow round-skipping)
  8. * Nodes gossip prevotes for the proposal's POL (proof-of-lock) round if proposed.
  9. * Nodes gossip to late nodes (lagging in height) with precommits of the commit round (aka catchup)
  10. Upon each state transition, the height/round/step is broadcast to neighboring peers.
  11. The set of +2/3 of precommits at the same round for the same block is called a Commit, or Validation.
  12. A block contains the last block's Validation, which includes the Commit precommits.
  13. While all the precommits in the Validation are from the same height & round (ordered by validator index),
  14. some precommits may be <nil> (if the validator's precommit vote didn't reach the proposer in time),
  15. or some precommits may be for different blockhashes for the last block hash (which is fine).
  16. Each unlock/change-of-lock should be justifiable by an POL where +2/3 prevoted for
  17. some block or <nil> at some round.
  18. POL = Proof-of-Lock = +2/3 prevotes for block B (or +2/3 prevotes for <nil>) at (H,R)
  19. lockRound < POLRound <= unlockOrChangeLockRound
  20. Without the POLRound <= unlockOrChangeLockRound condition, an unlock would be possible from a
  21. future condition that hasn't happened yet, so it destroys deterministic accountability.
  22. With lockRound < POLRound <= unlockOrChangeLockRound, blame can be shifted to lower rounds.
  23. * NewRound(height:H,round:R):
  24. * Set up new round. --> goto Propose(H,R)
  25. * NOTE: Not much happens in this step. It exists for clarity.
  26. * Propose(height:H,round:R):
  27. * Upon entering Propose:
  28. * The designated proposer proposes a block at (H,R).
  29. * The Propose step ends:
  30. * After `timeoutPropose` after entering Propose. --> goto Prevote(H,R)
  31. * After receiving proposal block and all POL prevotes. --> goto Prevote(H,R)
  32. * After any +2/3 prevotes received at (H,R+1). --> goto Prevote(H,R+1)
  33. * After any +2/3 precommits received at (H,R+1). --> goto Precommit(H,R+1)
  34. * After +2/3 precommits received for a particular block. --> goto Commit(H)
  35. * Prevote(height:H,round:R):
  36. * Upon entering Prevote, each validator broadcasts its prevote vote.
  37. * If the validator is locked on a block, it prevotes that.
  38. * Else, if the proposed block from Propose(H,R) is good, it prevotes that.
  39. * Else, if the proposal is invalid or wasn't received on time, it prevotes <nil>.
  40. * The Prevote step ends:
  41. * After +2/3 prevotes for a particular block or <nil>. --> goto Precommit(H,R)
  42. * After `timeoutPrevote` after receiving any +2/3 prevotes. --> goto Precommit(H,R)
  43. * After any +2/3 prevotes received at (H,R+1). --> goto Prevote(H,R+1)
  44. * After any +2/3 precommits received at (H,R+1). --> goto Precommit(H,R+1)
  45. * After +2/3 precommits received for a particular block. --> goto Commit(H)
  46. * Precommit(height:H,round:R):
  47. * Upon entering Precommit, each validator broadcasts its precommit vote.
  48. * If the validator had seen +2/3 of prevotes for a particular block from Prevote(H,R),
  49. it locks (changes lock to) that block and precommits that block.
  50. * Else, if the validator had seen +2/3 of prevotes for <nil>, it unlocks and precommits <nil>.
  51. * Else, if +2/3 of prevotes for a particular block or <nil> is not received on time,
  52. it precommits what it's locked on, or <nil>.
  53. * The Precommit step ends:
  54. * After +2/3 precommits for a particular block. --> goto Commit(H)
  55. * After +2/3 precommits for <nil>. --> goto NewRound(H,R+1)
  56. * After `timeoutPrecommit` after receiving any +2/3 precommits. --> goto NewRound(H,R+1)
  57. * After any +2/3 prevotes received at (H,R+1). --> goto Prevote(H,R+1)
  58. * After any +2/3 precommits received at (H,R+1). --> goto Precommit(H,R+1)
  59. * Commit(height:H):
  60. * Set CommitTime = now
  61. * Wait until block is received. --> goto NewHeight(H+1)
  62. * NewHeight(height:H):
  63. * Move Precommits to LastCommit and increment height.
  64. * Set StartTime = CommitTime+timeoutCommit
  65. * Wait until `StartTime` to receive straggler commits. --> goto NewRound(H,0)
  66. * Proof of Safety:
  67. If a good validator commits at round R, it's because it saw +2/3 of precommits at round R.
  68. This implies that (assuming tolerance bounds) +1/3 of honest nodes are still locked at round R+1.
  69. These locked validators will remain locked until they see +2/3 prevote for something
  70. else, but this won't happen because +1/3 are locked and honest.
  71. * Proof of Liveness:
  72. Lemma 1: If +1/3 good nodes are locked on two different blocks, the proposers' POLRound will
  73. eventually cause nodes locked from the earlier round to unlock.
  74. -> `timeoutProposalR` increments with round R, while the block.size && POL prevote size
  75. are fixed, so eventually we'll be able to "fully gossip" the block & POL.
  76. TODO: cap the block.size at something reasonable.
  77. Lemma 2: If a good node is at round R, neighboring good nodes will soon catch up to round R.
  78. Lemma 3: If a node at (H,R) receives +2/3 prevotes for a block (or +2/3 for <nil>) at (H,R+1),
  79. it will enter NewRound(H,R+1).
  80. Lemma 4: Terminal conditions imply the existence of deterministic accountability, for
  81. a synchronous (fixed-duration) protocol extension (judgement).
  82. TODO: define terminal conditions (fork and non-decision).
  83. TODO: define new assumptions for the synchronous judgement period.
  84. +-------------------------------------+
  85. v |(Wait til `CommmitTime+timeoutCommit`)
  86. +-----------+ +-----+-----+
  87. +----------> | Propose +--------------+ | NewHeight |
  88. | +-----------+ | +-----------+
  89. | | ^
  90. |(Else, after timeoutPrecommit) v |
  91. +-----+-----+ +-----------+ |
  92. | Precommit | <------------------------+ Prevote | |
  93. +-----+-----+ +-----------+ |
  94. |(When +2/3 Precommits for block found) |
  95. v |
  96. +--------------------------------------------------------------------+
  97. | Commit |
  98. | |
  99. | * Set CommitTime = now; |
  100. | * Wait for block, then stage/save/commit block; |
  101. +--------------------------------------------------------------------+
  102. */
  103. package consensus
  104. import (
  105. "bytes"
  106. "errors"
  107. "fmt"
  108. "sync"
  109. "sync/atomic"
  110. "time"
  111. "github.com/tendermint/tendermint/account"
  112. "github.com/tendermint/tendermint/binary"
  113. bc "github.com/tendermint/tendermint/blockchain"
  114. . "github.com/tendermint/tendermint/common"
  115. . "github.com/tendermint/tendermint/consensus/types"
  116. "github.com/tendermint/tendermint/events"
  117. mempl "github.com/tendermint/tendermint/mempool"
  118. sm "github.com/tendermint/tendermint/state"
  119. "github.com/tendermint/tendermint/types"
  120. )
  121. var (
  122. timeoutPropose = 3000 * time.Millisecond // Maximum duration of RoundStepPropose
  123. timeoutPrevote0 = 1000 * time.Millisecond // After any +2/3 prevotes received, wait this long for stragglers.
  124. timeoutPrevoteDelta = 0500 * time.Millisecond // timeoutPrevoteN is timeoutPrevote0 + timeoutPrevoteDelta*N
  125. timeoutPrecommit0 = 1000 * time.Millisecond // After any +2/3 precommits received, wait this long for stragglers.
  126. timeoutPrecommitDelta = 0500 * time.Millisecond // timeoutPrecommitN is timeoutPrecommit0 + timeoutPrecommitDelta*N
  127. timeoutCommit = 2000 * time.Millisecond // After +2/3 commits received for committed block, wait this long for stragglers in the next height's RoundStepNewHeight.
  128. )
  129. var (
  130. ErrInvalidProposalSignature = errors.New("Error invalid proposal signature")
  131. ErrInvalidProposalPOLRound = errors.New("Error invalid proposal POL round")
  132. )
  133. //-----------------------------------------------------------------------------
  134. // RoundStepType enum type
  135. type RoundStepType uint8 // These must be numeric, ordered.
  136. const (
  137. RoundStepNewHeight = RoundStepType(0x01) // Wait til CommitTime + timeoutCommit
  138. RoundStepNewRound = RoundStepType(0x02) // Setup new round and go to RoundStepPropose
  139. RoundStepPropose = RoundStepType(0x03) // Did propose, gossip proposal
  140. RoundStepPrevote = RoundStepType(0x04) // Did prevote, gossip prevotes
  141. RoundStepPrevoteWait = RoundStepType(0x05) // Did receive any +2/3 prevotes, start timeout
  142. RoundStepPrecommit = RoundStepType(0x06) // Did precommit, gossip precommits
  143. RoundStepPrecommitWait = RoundStepType(0x07) // Did receive any +2/3 precommits, start timeout
  144. RoundStepCommit = RoundStepType(0x08) // Entered commit state machine
  145. // NOTE: RoundStepNewHeight acts as RoundStepCommitWait.
  146. )
  147. func (rs RoundStepType) String() string {
  148. switch rs {
  149. case RoundStepNewHeight:
  150. return "RoundStepNewHeight"
  151. case RoundStepNewRound:
  152. return "RoundStepNewRound"
  153. case RoundStepPropose:
  154. return "RoundStepPropose"
  155. case RoundStepPrevote:
  156. return "RoundStepPrevote"
  157. case RoundStepPrevoteWait:
  158. return "RoundStepPrevoteWait"
  159. case RoundStepPrecommit:
  160. return "RoundStepPrecommit"
  161. case RoundStepPrecommitWait:
  162. return "RoundStepPrecommitWait"
  163. case RoundStepCommit:
  164. return "RoundStepCommit"
  165. default:
  166. panic(Fmt("Unknown RoundStep %X", rs))
  167. }
  168. }
  169. //-----------------------------------------------------------------------------
  170. // Immutable when returned from ConsensusState.GetRoundState()
  171. type RoundState struct {
  172. Height int // Height we are working on
  173. Round int
  174. Step RoundStepType
  175. StartTime time.Time
  176. CommitTime time.Time // Subjective time when +2/3 precommits for Block at Round were found
  177. Validators *sm.ValidatorSet
  178. Proposal *Proposal
  179. ProposalBlock *types.Block
  180. ProposalBlockParts *types.PartSet
  181. LockedRound int
  182. LockedBlock *types.Block
  183. LockedBlockParts *types.PartSet
  184. Votes *HeightVoteSet
  185. LastCommit *VoteSet // Last precommits at Height-1
  186. }
  187. func (rs *RoundState) String() string {
  188. return rs.StringIndented("")
  189. }
  190. func (rs *RoundState) StringIndented(indent string) string {
  191. return fmt.Sprintf(`RoundState{
  192. %s H:%v R:%v S:%v
  193. %s StartTime: %v
  194. %s CommitTime: %v
  195. %s Validators: %v
  196. %s Proposal: %v
  197. %s ProposalBlock: %v %v
  198. %s LockedRound: %v
  199. %s LockedBlock: %v %v
  200. %s Votes: %v
  201. %s LastCommit: %v
  202. %s}`,
  203. indent, rs.Height, rs.Round, rs.Step,
  204. indent, rs.StartTime,
  205. indent, rs.CommitTime,
  206. indent, rs.Validators.StringIndented(indent+" "),
  207. indent, rs.Proposal,
  208. indent, rs.ProposalBlockParts.StringShort(), rs.ProposalBlock.StringShort(),
  209. indent, rs.LockedRound,
  210. indent, rs.LockedBlockParts.StringShort(), rs.LockedBlock.StringShort(),
  211. indent, rs.Votes.StringIndented(indent+" "),
  212. indent, rs.LastCommit.StringShort(),
  213. indent)
  214. }
  215. func (rs *RoundState) StringShort() string {
  216. return fmt.Sprintf(`RoundState{H:%v R:%v S:%v ST:%v}`,
  217. rs.Height, rs.Round, rs.Step, rs.StartTime)
  218. }
  219. //-----------------------------------------------------------------------------
  220. // Tracks consensus state across block heights and rounds.
  221. type ConsensusState struct {
  222. started uint32
  223. stopped uint32
  224. quit chan struct{}
  225. blockStore *bc.BlockStore
  226. mempoolReactor *mempl.MempoolReactor
  227. privValidator *sm.PrivValidator
  228. newStepCh chan *RoundState
  229. mtx sync.Mutex
  230. RoundState
  231. state *sm.State // State until height-1.
  232. stagedBlock *types.Block // Cache last staged block.
  233. stagedState *sm.State // Cache result of staged block.
  234. evsw events.Fireable
  235. evc *events.EventCache // set in stageBlock and passed into state
  236. }
  237. func NewConsensusState(state *sm.State, blockStore *bc.BlockStore, mempoolReactor *mempl.MempoolReactor) *ConsensusState {
  238. cs := &ConsensusState{
  239. quit: make(chan struct{}),
  240. blockStore: blockStore,
  241. mempoolReactor: mempoolReactor,
  242. newStepCh: make(chan *RoundState, 10),
  243. }
  244. cs.updateToState(state, true)
  245. // Don't call scheduleRound0 yet.
  246. // We do that upon Start().
  247. cs.maybeRebond()
  248. cs.reconstructLastCommit(state)
  249. return cs
  250. }
  251. // Reconstruct LastCommit from SeenValidation, which we saved along with the block,
  252. // (which happens even before saving the state)
  253. func (cs *ConsensusState) reconstructLastCommit(state *sm.State) {
  254. if state.LastBlockHeight == 0 {
  255. return
  256. }
  257. lastPrecommits := NewVoteSet(state.LastBlockHeight, 0, types.VoteTypePrecommit, state.LastBondedValidators)
  258. seenValidation := cs.blockStore.LoadSeenValidation(state.LastBlockHeight)
  259. for idx, precommit := range seenValidation.Precommits {
  260. added, _, err := lastPrecommits.AddByIndex(idx, precommit)
  261. if !added || err != nil {
  262. panic(Fmt("Failed to reconstruct LastCommit: %v", err))
  263. }
  264. }
  265. if !lastPrecommits.HasTwoThirdsMajority() {
  266. panic("Failed to reconstruct LastCommit: Does not have +2/3 maj")
  267. }
  268. cs.LastCommit = lastPrecommits
  269. }
  270. func (cs *ConsensusState) GetState() *sm.State {
  271. cs.mtx.Lock()
  272. defer cs.mtx.Unlock()
  273. return cs.state.Copy()
  274. }
  275. func (cs *ConsensusState) GetRoundState() *RoundState {
  276. cs.mtx.Lock()
  277. defer cs.mtx.Unlock()
  278. return cs.getRoundState()
  279. }
  280. func (cs *ConsensusState) getRoundState() *RoundState {
  281. rs := cs.RoundState // copy
  282. return &rs
  283. }
  284. func (cs *ConsensusState) NewStepCh() chan *RoundState {
  285. return cs.newStepCh
  286. }
  287. func (cs *ConsensusState) Start() {
  288. if atomic.CompareAndSwapUint32(&cs.started, 0, 1) {
  289. log.Info("Starting ConsensusState")
  290. cs.scheduleRound0(cs.Height)
  291. }
  292. }
  293. // EnterNewRound(height, 0) at cs.StartTime.
  294. func (cs *ConsensusState) scheduleRound0(height int) {
  295. //log.Debug("scheduleRound0", "now", time.Now(), "startTime", cs.StartTime)
  296. sleepDuration := cs.StartTime.Sub(time.Now())
  297. go func() {
  298. if 0 < sleepDuration {
  299. time.Sleep(sleepDuration)
  300. }
  301. cs.EnterNewRound(height, 0)
  302. }()
  303. }
  304. func (cs *ConsensusState) Stop() {
  305. if atomic.CompareAndSwapUint32(&cs.stopped, 0, 1) {
  306. log.Info("Stopping ConsensusState")
  307. close(cs.quit)
  308. }
  309. }
  310. func (cs *ConsensusState) IsStopped() bool {
  311. return atomic.LoadUint32(&cs.stopped) == 1
  312. }
  313. // Updates ConsensusState and increments height to match that of state.
  314. // The round becomes 0 and cs.Step becomes RoundStepNewHeight.
  315. func (cs *ConsensusState) updateToState(state *sm.State, contiguous bool) {
  316. // SANITY CHECK
  317. if contiguous && 0 < cs.Height && cs.Height != state.LastBlockHeight {
  318. panic(Fmt("updateToState() expected state height of %v but found %v",
  319. cs.Height, state.LastBlockHeight))
  320. }
  321. // END SANITY CHECK
  322. // Reset fields based on state.
  323. validators := state.BondedValidators
  324. height := state.LastBlockHeight + 1 // next desired block height
  325. lastPrecommits := (*VoteSet)(nil)
  326. if contiguous && cs.Votes != nil {
  327. if !cs.Votes.Precommits(cs.Round).HasTwoThirdsMajority() {
  328. panic("updateToState(state, true) called but last Precommit round didn't have +2/3")
  329. }
  330. lastPrecommits = cs.Votes.Precommits(cs.Round)
  331. }
  332. // RoundState fields
  333. cs.Height = height
  334. cs.Round = 0
  335. cs.Step = RoundStepNewHeight
  336. if cs.CommitTime.IsZero() {
  337. // "Now" makes it easier to sync up dev nodes.
  338. // We add timeoutCommit to allow transactions
  339. // to be gathered for the first block.
  340. // And alternative solution that relies on clocks:
  341. // cs.StartTime = state.LastBlockTime.Add(timeoutCommit)
  342. cs.StartTime = time.Now().Add(timeoutCommit)
  343. } else {
  344. cs.StartTime = cs.CommitTime.Add(timeoutCommit)
  345. }
  346. cs.CommitTime = time.Time{}
  347. cs.Validators = validators
  348. cs.Proposal = nil
  349. cs.ProposalBlock = nil
  350. cs.ProposalBlockParts = nil
  351. cs.LockedRound = 0
  352. cs.LockedBlock = nil
  353. cs.LockedBlockParts = nil
  354. cs.Votes = NewHeightVoteSet(height, validators)
  355. cs.LastCommit = lastPrecommits
  356. cs.state = state
  357. cs.stagedBlock = nil
  358. cs.stagedState = nil
  359. // Finally, broadcast RoundState
  360. cs.newStepCh <- cs.getRoundState()
  361. }
  362. // If we're unbonded, broadcast RebondTx.
  363. func (cs *ConsensusState) maybeRebond() {
  364. if cs.privValidator == nil || !cs.state.UnbondingValidators.HasAddress(cs.privValidator.Address) {
  365. return
  366. }
  367. rebondTx := &types.RebondTx{
  368. Address: cs.privValidator.Address,
  369. Height: cs.Height,
  370. }
  371. err := cs.privValidator.SignRebondTx(cs.state.ChainID, rebondTx)
  372. if err == nil {
  373. err := cs.mempoolReactor.BroadcastTx(rebondTx)
  374. if err != nil {
  375. log.Error("Failed to broadcast RebondTx",
  376. "height", cs.Height, "round", cs.Round, "tx", rebondTx, "error", err)
  377. } else {
  378. log.Info("Signed and broadcast RebondTx",
  379. "height", cs.Height, "round", cs.Round, "tx", rebondTx)
  380. }
  381. } else {
  382. log.Warn("Error signing RebondTx", "height", cs.Height, "round", cs.Round, "tx", rebondTx, "error", err)
  383. }
  384. }
  385. func (cs *ConsensusState) SetPrivValidator(priv *sm.PrivValidator) {
  386. cs.mtx.Lock()
  387. defer cs.mtx.Unlock()
  388. cs.privValidator = priv
  389. }
  390. //-----------------------------------------------------------------------------
  391. // Enter: +2/3 precommits for nil at (height,round-1)
  392. // Enter: `timeoutPrecommits` after any +2/3 precommits from (height,round-1)
  393. // Enter: `startTime = commitTime+timeoutCommit` from NewHeight(height)
  394. // NOTE: cs.StartTime was already set for height.
  395. func (cs *ConsensusState) EnterNewRound(height int, round int) {
  396. cs.mtx.Lock()
  397. defer cs.mtx.Unlock()
  398. if cs.Height != height || round < cs.Round || (cs.Round == round && cs.Step != RoundStepNewHeight) {
  399. log.Debug(Fmt("EnterNewRound(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  400. return
  401. }
  402. if now := time.Now(); cs.StartTime.After(now) {
  403. log.Warn("Need to set a buffer and log.Warn() here for sanity.", "startTime", cs.StartTime, "now", now)
  404. }
  405. // Increment validators if necessary
  406. validators := cs.Validators
  407. if cs.Round < round {
  408. validators = validators.Copy()
  409. validators.IncrementAccum(round - cs.Round)
  410. }
  411. // Setup new round
  412. cs.Round = round
  413. cs.Step = RoundStepNewRound
  414. cs.Validators = validators
  415. cs.Proposal = nil
  416. cs.ProposalBlock = nil
  417. cs.ProposalBlockParts = nil
  418. cs.Votes.SetRound(round + 1) // also track next round (round+1) to allow round-skipping
  419. // Immediately go to EnterPropose.
  420. go cs.EnterPropose(height, round)
  421. }
  422. // Enter: from NewRound(height,round).
  423. func (cs *ConsensusState) EnterPropose(height int, round int) {
  424. cs.mtx.Lock()
  425. defer cs.mtx.Unlock()
  426. if cs.Height != height || round < cs.Round || (cs.Round == round && RoundStepPropose <= cs.Step) {
  427. log.Debug(Fmt("EnterPropose(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  428. return
  429. }
  430. defer func() {
  431. // Done EnterPropose:
  432. cs.Round = round
  433. cs.Step = RoundStepPropose
  434. cs.newStepCh <- cs.getRoundState()
  435. // If we already have the proposal + POL, then goto Prevote
  436. if cs.isProposalComplete() {
  437. go cs.EnterPrevote(height, cs.Round)
  438. }
  439. }()
  440. // This step times out after `timeoutPropose`
  441. go func() {
  442. time.Sleep(timeoutPropose)
  443. cs.EnterPrevote(height, round)
  444. }()
  445. // Nothing more to do if we're not a validator
  446. if cs.privValidator == nil {
  447. return
  448. }
  449. if !bytes.Equal(cs.Validators.Proposer().Address, cs.privValidator.Address) {
  450. log.Debug("EnterPropose: Not our turn to propose", "proposer", cs.Validators.Proposer().Address, "privValidator", cs.privValidator)
  451. } else {
  452. log.Debug("EnterPropose: Our turn to propose", "proposer", cs.Validators.Proposer().Address, "privValidator", cs.privValidator)
  453. cs.decideProposal(height, round)
  454. }
  455. }
  456. // Decides on the next proposal and sets them onto cs.Proposal*
  457. func (cs *ConsensusState) decideProposal(height int, round int) {
  458. var block *types.Block
  459. var blockParts *types.PartSet
  460. // Decide on block
  461. if cs.LockedBlock != nil {
  462. // If we're locked onto a block, just choose that.
  463. block, blockParts = cs.LockedBlock, cs.LockedBlockParts
  464. } else {
  465. // Create a new proposal block from state/txs from the mempool.
  466. block, blockParts = cs.createProposalBlock()
  467. }
  468. // Make proposal
  469. proposal := NewProposal(height, round, blockParts.Header(), cs.Votes.POLRound())
  470. err := cs.privValidator.SignProposal(cs.state.ChainID, proposal)
  471. if err == nil {
  472. log.Info("Signed and set proposal", "height", height, "round", round, "proposal", proposal)
  473. log.Debug(Fmt("Signed and set proposal block: %v", block))
  474. // Set fields
  475. cs.Proposal = proposal
  476. cs.ProposalBlock = block
  477. cs.ProposalBlockParts = blockParts
  478. } else {
  479. log.Warn("EnterPropose: Error signing proposal", "height", height, "round", round, "error", err)
  480. }
  481. }
  482. // Returns true if the proposal block is complete &&
  483. // (if POLRound was proposed, we have +2/3 prevotes from there).
  484. func (cs *ConsensusState) isProposalComplete() bool {
  485. if cs.Proposal == nil || cs.ProposalBlock == nil {
  486. return false
  487. }
  488. if cs.Proposal.POLRound < 0 {
  489. return true
  490. } else {
  491. return cs.Votes.Prevotes(cs.Proposal.POLRound).HasTwoThirdsMajority()
  492. }
  493. }
  494. // Create the next block to propose and return it.
  495. // NOTE: make it side-effect free for clarity.
  496. func (cs *ConsensusState) createProposalBlock() (block *types.Block, blockParts *types.PartSet) {
  497. var validation *types.Validation
  498. if cs.Height == 1 {
  499. // We're creating a proposal for the first block.
  500. // The validation is empty, but not nil.
  501. validation = &types.Validation{}
  502. } else if cs.LastCommit.HasTwoThirdsMajority() {
  503. // Make the validation from LastCommit
  504. validation = cs.LastCommit.MakeValidation()
  505. } else {
  506. // This shouldn't happen.
  507. log.Error("EnterPropose: Cannot propose anything: No validation for the previous block.")
  508. return
  509. }
  510. txs := cs.mempoolReactor.Mempool.GetProposalTxs()
  511. block = &types.Block{
  512. Header: &types.Header{
  513. ChainID: cs.state.ChainID,
  514. Height: cs.Height,
  515. Time: time.Now(),
  516. Fees: 0, // TODO fees
  517. NumTxs: len(txs),
  518. LastBlockHash: cs.state.LastBlockHash,
  519. LastBlockParts: cs.state.LastBlockParts,
  520. StateHash: nil, // Will set afterwards.
  521. },
  522. LastValidation: validation,
  523. Data: &types.Data{
  524. Txs: txs,
  525. },
  526. }
  527. // Set the block.Header.StateHash.
  528. err := cs.state.ComputeBlockStateHash(block)
  529. if err != nil {
  530. log.Error("EnterPropose: Error setting state hash", "error", err)
  531. return
  532. }
  533. blockParts = block.MakePartSet()
  534. return block, blockParts
  535. }
  536. // Enter: `timeoutPropose` after entering Propose.
  537. // Enter: proposal block and POL is ready.
  538. // Enter: any +2/3 prevotes for future round.
  539. // Prevote for LockedBlock if we're locked, or ProposalBlock if valid.
  540. // Otherwise vote nil.
  541. func (cs *ConsensusState) EnterPrevote(height int, round int) {
  542. cs.mtx.Lock()
  543. defer cs.mtx.Unlock()
  544. if cs.Height != height || round < cs.Round || (cs.Round == round && RoundStepPrevote <= cs.Step) {
  545. log.Debug(Fmt("EnterPrevote(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  546. return
  547. }
  548. // Sign and broadcast vote as necessary
  549. cs.doPrevote(height, round)
  550. // Done EnterPrevote:
  551. cs.Round = round
  552. cs.Step = RoundStepPrevote
  553. cs.newStepCh <- cs.getRoundState()
  554. /* This isn't necessary because addVote() does it for us.
  555. if cs.Votes.Prevotes(round).HasTwoThirdsAny() {
  556. go cs.EnterPrevoteWait(height, round)
  557. }*/
  558. }
  559. func (cs *ConsensusState) doPrevote(height int, round int) {
  560. // If a block is locked, prevote that.
  561. if cs.LockedBlock != nil {
  562. log.Debug("EnterPrevote: Block was locked")
  563. cs.signAddVote(types.VoteTypePrevote, cs.LockedBlock.Hash(), cs.LockedBlockParts.Header())
  564. return
  565. }
  566. // If ProposalBlock is nil, prevote nil.
  567. if cs.ProposalBlock == nil {
  568. log.Warn("EnterPrevote: ProposalBlock is nil")
  569. cs.signAddVote(types.VoteTypePrevote, nil, types.PartSetHeader{})
  570. return
  571. }
  572. // Try staging cs.ProposalBlock
  573. err := cs.stageBlock(cs.ProposalBlock, cs.ProposalBlockParts)
  574. if err != nil {
  575. // ProposalBlock is invalid, prevote nil.
  576. log.Warn("EnterPrevote: ProposalBlock is invalid", "error", err)
  577. cs.signAddVote(types.VoteTypePrevote, nil, types.PartSetHeader{})
  578. return
  579. }
  580. // Prevote cs.ProposalBlock
  581. cs.signAddVote(types.VoteTypePrevote, cs.ProposalBlock.Hash(), cs.ProposalBlockParts.Header())
  582. return
  583. }
  584. // Enter: any +2/3 prevotes at next round.
  585. func (cs *ConsensusState) EnterPrevoteWait(height int, round int) {
  586. cs.mtx.Lock()
  587. defer cs.mtx.Unlock()
  588. if cs.Height != height || round < cs.Round || (cs.Round == round && RoundStepPrevoteWait <= cs.Step) {
  589. log.Debug(Fmt("EnterPrevoteWait(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  590. return
  591. }
  592. if !cs.Votes.Prevotes(round).HasTwoThirdsAny() {
  593. panic(Fmt("EnterPrevoteWait(%v/%v), but Prevotes does not have any +2/3 votes", height, round))
  594. }
  595. // Done EnterPrevoteWait:
  596. cs.Round = round
  597. cs.Step = RoundStepPrevoteWait
  598. cs.newStepCh <- cs.getRoundState()
  599. // After `timeoutPrevote0+timeoutPrevoteDelta*round`, EnterPrecommit()
  600. go func() {
  601. time.Sleep(timeoutPrevote0 + timeoutPrevote0*time.Duration(round))
  602. cs.EnterPrecommit(height, round)
  603. }()
  604. }
  605. // Enter: +2/3 precomits for block or nil.
  606. // Enter: `timeoutPrevote` after any +2/3 prevotes.
  607. // Enter: any +2/3 precommits for next round.
  608. // Lock & precommit the ProposalBlock if we have enough prevotes for it,
  609. // else, unlock an existing lock and precommit nil if +2/3 of prevotes were nil,
  610. // else, precommit locked block or nil otherwise.
  611. func (cs *ConsensusState) EnterPrecommit(height int, round int) {
  612. cs.mtx.Lock()
  613. defer cs.mtx.Unlock()
  614. if cs.Height != height || round < cs.Round || (cs.Round == round && RoundStepPrecommit <= cs.Step) {
  615. log.Debug(Fmt("EnterPrecommit(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  616. return
  617. }
  618. defer func() {
  619. // Done EnterPrecommit:
  620. cs.Round = round
  621. cs.Step = RoundStepPrecommit
  622. cs.newStepCh <- cs.getRoundState()
  623. /* This isn't necessary because addVote() does it for us.
  624. if cs.Votes.Precommits(round).HasTwoThirdsAny() {
  625. go cs.EnterPrecommitWait(height, round)
  626. }*/
  627. }()
  628. hash, partsHeader, ok := cs.Votes.Prevotes(round).TwoThirdsMajority()
  629. // If we don't have two thirds of prevotes, just precommit locked block or nil
  630. if !ok {
  631. if cs.LockedBlock != nil {
  632. log.Info("EnterPrecommit: No +2/3 prevotes during EnterPrecommit. Precommitting lock.")
  633. cs.signAddVote(types.VoteTypePrecommit, cs.LockedBlock.Hash(), cs.LockedBlockParts.Header())
  634. } else {
  635. log.Info("EnterPrecommit: No +2/3 prevotes during EnterPrecommit. Precommitting nil.")
  636. cs.signAddVote(types.VoteTypePrecommit, nil, types.PartSetHeader{})
  637. }
  638. return
  639. }
  640. // +2/3 prevoted nil. Unlock and precommit nil.
  641. if len(hash) == 0 {
  642. if cs.LockedBlock == nil {
  643. log.Info("EnterPrecommit: +2/3 prevoted for nil.")
  644. } else {
  645. log.Info("EnterPrecommit: +2/3 prevoted for nil. Unlocking")
  646. cs.LockedRound = 0
  647. cs.LockedBlock = nil
  648. cs.LockedBlockParts = nil
  649. }
  650. cs.signAddVote(types.VoteTypePrecommit, nil, types.PartSetHeader{})
  651. return
  652. }
  653. // At this point, +2/3 prevoted for a particular block.
  654. // If +2/3 prevoted for already locked block, precommit it.
  655. if cs.LockedBlock.HashesTo(hash) {
  656. log.Info("EnterPrecommit: +2/3 prevoted locked block.")
  657. cs.signAddVote(types.VoteTypePrecommit, hash, partsHeader)
  658. return
  659. }
  660. // If +2/3 prevoted for proposal block, stage and precommit it
  661. if cs.ProposalBlock.HashesTo(hash) {
  662. log.Info("EnterPrecommit: +2/3 prevoted proposal block.")
  663. // Validate the block.
  664. if err := cs.stageBlock(cs.ProposalBlock, cs.ProposalBlockParts); err != nil {
  665. panic(Fmt("EnterPrecommit: +2/3 prevoted for an invalid block: %v", err))
  666. }
  667. cs.LockedRound = round
  668. cs.LockedBlock = cs.ProposalBlock
  669. cs.LockedBlockParts = cs.ProposalBlockParts
  670. cs.signAddVote(types.VoteTypePrecommit, hash, partsHeader)
  671. return
  672. }
  673. // Otherwise, we need to fetch the +2/3 prevoted block.
  674. // Unlock and precommit nil.
  675. // The +2/3 prevotes for this round is the POL for our unlock.
  676. if cs.Votes.POLRound() < round {
  677. panic(Fmt("This POLRound shold be %v but got %", round, cs.Votes.POLRound()))
  678. }
  679. cs.LockedRound = 0
  680. cs.LockedBlock = nil
  681. cs.LockedBlockParts = nil
  682. if !cs.ProposalBlockParts.HasHeader(partsHeader) {
  683. cs.ProposalBlock = nil
  684. cs.ProposalBlockParts = types.NewPartSetFromHeader(partsHeader)
  685. }
  686. cs.signAddVote(types.VoteTypePrecommit, nil, types.PartSetHeader{})
  687. return
  688. }
  689. // Enter: any +2/3 precommits for next round.
  690. func (cs *ConsensusState) EnterPrecommitWait(height int, round int) {
  691. cs.mtx.Lock()
  692. defer cs.mtx.Unlock()
  693. if cs.Height != height || round < cs.Round || (cs.Round == round && RoundStepPrecommitWait <= cs.Step) {
  694. log.Debug(Fmt("EnterPrecommitWait(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  695. return
  696. }
  697. if !cs.Votes.Precommits(round).HasTwoThirdsAny() {
  698. panic(Fmt("EnterPrecommitWait(%v/%v), but Precommits does not have any +2/3 votes", height, round))
  699. }
  700. // Done EnterPrecommitWait:
  701. cs.Round = round
  702. cs.Step = RoundStepPrecommitWait
  703. cs.newStepCh <- cs.getRoundState()
  704. // After `timeoutPrecommit0+timeoutPrecommitDelta*round`, EnterNewRound()
  705. go func() {
  706. time.Sleep(timeoutPrecommit0 + timeoutPrecommitDelta*time.Duration(round))
  707. // If we have +2/3 of precommits for a particular block (or nil),
  708. // we already entered commit (or the next round).
  709. // So just try to transition to the next round,
  710. // which is what we'd do otherwise.
  711. cs.EnterNewRound(height, round+1)
  712. }()
  713. }
  714. // Enter: +2/3 precommits for block
  715. func (cs *ConsensusState) EnterCommit(height int) {
  716. cs.mtx.Lock()
  717. defer cs.mtx.Unlock()
  718. if cs.Height != height || RoundStepCommit <= cs.Step {
  719. log.Debug(Fmt("EnterCommit(%v): Invalid args. Current step: %v/%v/%v", height, cs.Height, cs.Round, cs.Step))
  720. return
  721. }
  722. defer func() {
  723. // Done Entercommit:
  724. // keep ca.Round the same, it points to the right Precommits set.
  725. cs.Step = RoundStepCommit
  726. cs.newStepCh <- cs.getRoundState()
  727. // Maybe finalize immediately.
  728. cs.tryFinalizeCommit(height)
  729. }()
  730. // SANITY CHECK
  731. hash, partsHeader, ok := cs.Votes.Precommits(cs.Round).TwoThirdsMajority()
  732. if !ok {
  733. panic("RunActionCommit() expects +2/3 precommits")
  734. }
  735. // END SANITY CHECK
  736. // The Locked* fields no longer matter.
  737. // Move them over to ProposalBlock if they match the commit hash,
  738. // otherwise they can now be cleared.
  739. if cs.LockedBlock.HashesTo(hash) {
  740. cs.ProposalBlock = cs.LockedBlock
  741. cs.ProposalBlockParts = cs.LockedBlockParts
  742. cs.LockedRound = 0
  743. cs.LockedBlock = nil
  744. cs.LockedBlockParts = nil
  745. } else {
  746. cs.LockedRound = 0
  747. cs.LockedBlock = nil
  748. cs.LockedBlockParts = nil
  749. }
  750. // If we don't have the block being committed, set up to get it.
  751. if !cs.ProposalBlock.HashesTo(hash) {
  752. if !cs.ProposalBlockParts.HasHeader(partsHeader) {
  753. // We're getting the wrong block.
  754. // Set up ProposalBlockParts and keep waiting.
  755. cs.ProposalBlock = nil
  756. cs.ProposalBlockParts = types.NewPartSetFromHeader(partsHeader)
  757. } else {
  758. // We just need to keep waiting.
  759. }
  760. }
  761. }
  762. // If we have the block AND +2/3 commits for it, finalize.
  763. func (cs *ConsensusState) tryFinalizeCommit(height int) {
  764. // SANITY CHECK
  765. if cs.Height != height {
  766. panic(Fmt("tryFinalizeCommit() cs.Height: %v vs height: %v", cs.Height, height))
  767. }
  768. // END SANITY CHECK
  769. hash, _, ok := cs.Votes.Precommits(cs.Round).TwoThirdsMajority()
  770. if !ok || len(hash) == 0 {
  771. return // There was no +2/3 majority, or +2/3 was for <nil>.
  772. }
  773. if !cs.ProposalBlock.HashesTo(hash) {
  774. return // We don't have the commit block.
  775. }
  776. go cs.FinalizeCommit(height)
  777. }
  778. // Increment height and goto RoundStepNewHeight
  779. func (cs *ConsensusState) FinalizeCommit(height int) {
  780. cs.mtx.Lock()
  781. defer cs.mtx.Unlock()
  782. if cs.Height != height || cs.Step != RoundStepCommit {
  783. log.Debug(Fmt("FinalizeCommit(%v): Invalid args. Current step: %v/%v/%v", height, cs.Height, cs.Round, cs.Step))
  784. return
  785. }
  786. hash, header, ok := cs.Votes.Precommits(cs.Round).TwoThirdsMajority()
  787. // SANITY CHECK
  788. if !ok {
  789. panic(Fmt("Cannot FinalizeCommit, commit does not have two thirds majority"))
  790. }
  791. if !cs.ProposalBlockParts.HasHeader(header) {
  792. panic(Fmt("Expected ProposalBlockParts header to be commit header"))
  793. }
  794. if !cs.ProposalBlock.HashesTo(hash) {
  795. panic(Fmt("Cannot FinalizeCommit, ProposalBlock does not hash to commit hash"))
  796. }
  797. if err := cs.stageBlock(cs.ProposalBlock, cs.ProposalBlockParts); err != nil {
  798. panic(Fmt("+2/3 committed an invalid block: %v", err))
  799. }
  800. // END SANITY CHECK
  801. log.Debug(Fmt("Finalizing commit of block: %v", cs.ProposalBlock))
  802. // We have the block, so stage/save/commit-vote.
  803. cs.saveBlock(cs.ProposalBlock, cs.ProposalBlockParts, cs.Votes.Precommits(cs.Round))
  804. // Increment height.
  805. cs.updateToState(cs.stagedState, true)
  806. // cs.StartTime is already set.
  807. // Schedule Round0 to start soon.
  808. go cs.scheduleRound0(height + 1)
  809. // If we're unbonded, broadcast RebondTx.
  810. cs.maybeRebond()
  811. // By here,
  812. // * cs.Height has been increment to height+1
  813. // * cs.Step is now RoundStepNewHeight
  814. // * cs.StartTime is set to when we will start round0.
  815. return
  816. }
  817. //-----------------------------------------------------------------------------
  818. func (cs *ConsensusState) SetProposal(proposal *Proposal) error {
  819. cs.mtx.Lock()
  820. defer cs.mtx.Unlock()
  821. // Already have one
  822. if cs.Proposal != nil {
  823. return nil
  824. }
  825. // Does not apply
  826. if proposal.Height != cs.Height || proposal.Round != cs.Round {
  827. return nil
  828. }
  829. // We don't care about the proposal if we're already in RoundStepCommit.
  830. if RoundStepCommit <= cs.Step {
  831. return nil
  832. }
  833. // Verify POLRound, which must be -1 or between 0 and proposal.Round exclusive.
  834. if proposal.POLRound != -1 &&
  835. (proposal.POLRound < 0 || proposal.Round <= proposal.POLRound) {
  836. return ErrInvalidProposalPOLRound
  837. }
  838. // Verify signature
  839. if !cs.Validators.Proposer().PubKey.VerifyBytes(account.SignBytes(cs.state.ChainID, proposal), proposal.Signature) {
  840. return ErrInvalidProposalSignature
  841. }
  842. cs.Proposal = proposal
  843. cs.ProposalBlockParts = types.NewPartSetFromHeader(proposal.BlockPartsHeader)
  844. return nil
  845. }
  846. // NOTE: block is not necessarily valid.
  847. func (cs *ConsensusState) AddProposalBlockPart(height int, part *types.Part) (added bool, err error) {
  848. cs.mtx.Lock()
  849. defer cs.mtx.Unlock()
  850. // Blocks might be reused, so round mismatch is OK
  851. if cs.Height != height {
  852. return false, nil
  853. }
  854. // We're not expecting a block part.
  855. if cs.ProposalBlockParts == nil {
  856. return false, nil // TODO: bad peer? Return error?
  857. }
  858. added, err = cs.ProposalBlockParts.AddPart(part)
  859. if err != nil {
  860. return added, err
  861. }
  862. if added && cs.ProposalBlockParts.IsComplete() {
  863. // Added and completed!
  864. var n int64
  865. var err error
  866. cs.ProposalBlock = binary.ReadBinary(&types.Block{}, cs.ProposalBlockParts.GetReader(), &n, &err).(*types.Block)
  867. log.Debug("Received complete proposal", "hash", cs.ProposalBlock.Hash())
  868. if cs.Step == RoundStepPropose && cs.isProposalComplete() {
  869. // Move onto the next step
  870. go cs.EnterPrevote(height, cs.Round)
  871. } else if cs.Step == RoundStepCommit {
  872. // If we're waiting on the proposal block...
  873. cs.tryFinalizeCommit(height)
  874. }
  875. return true, err
  876. }
  877. return added, nil
  878. }
  879. func (cs *ConsensusState) AddVote(address []byte, vote *types.Vote, peerKey string) (added bool, index int, err error) {
  880. cs.mtx.Lock()
  881. defer cs.mtx.Unlock()
  882. return cs.addVote(address, vote, peerKey)
  883. }
  884. //-----------------------------------------------------------------------------
  885. func (cs *ConsensusState) addVote(address []byte, vote *types.Vote, peerKey string) (added bool, index int, err error) {
  886. // A precommit for the previous height?
  887. if vote.Height+1 == cs.Height && vote.Type == types.VoteTypePrecommit {
  888. added, index, err = cs.LastCommit.AddByAddress(address, vote)
  889. if added {
  890. log.Debug(Fmt("Added to lastPrecommits: %v", cs.LastCommit.StringShort()))
  891. }
  892. return
  893. }
  894. // A prevote/precommit for this height?
  895. if vote.Height == cs.Height {
  896. height := cs.Height
  897. added, index, err = cs.Votes.AddByAddress(address, vote, peerKey)
  898. if added {
  899. switch vote.Type {
  900. case types.VoteTypePrevote:
  901. prevotes := cs.Votes.Prevotes(vote.Round)
  902. log.Debug(Fmt("Added to prevotes: %v", prevotes.StringShort()))
  903. // First, unlock if prevotes is a valid POL.
  904. // >> lockRound < POLRound <= unlockOrChangeLockRound (see spec)
  905. // NOTE: If (lockRound < POLRound) but !(POLRound <= unlockOrChangeLockRound),
  906. // we'll still EnterNewRound(H,vote.R) and EnterPrecommit(H,vote.R) to process it
  907. // there.
  908. if (cs.LockedBlock != nil) && (cs.LockedRound < vote.Round) && (vote.Round <= cs.Round) {
  909. hash, _, ok := prevotes.TwoThirdsMajority()
  910. if ok && !cs.LockedBlock.HashesTo(hash) {
  911. log.Info("Unlocking because of POL.", "lockedRound", cs.LockedRound, "POLRound", vote.Round)
  912. cs.LockedRound = 0
  913. cs.LockedBlock = nil
  914. cs.LockedBlockParts = nil
  915. }
  916. }
  917. if cs.Round <= vote.Round && prevotes.HasTwoThirdsAny() {
  918. // Round-skip over to PrevoteWait or goto Precommit.
  919. go func() {
  920. if cs.Round < vote.Round {
  921. cs.EnterNewRound(height, vote.Round)
  922. }
  923. if prevotes.HasTwoThirdsMajority() {
  924. cs.EnterPrecommit(height, vote.Round)
  925. } else {
  926. cs.EnterPrevote(height, vote.Round)
  927. cs.EnterPrevoteWait(height, vote.Round)
  928. }
  929. }()
  930. } else if cs.Proposal != nil && 0 <= cs.Proposal.POLRound && cs.Proposal.POLRound == vote.Round {
  931. // If the proposal is now complete, enter prevote of cs.Round.
  932. if cs.isProposalComplete() {
  933. go cs.EnterPrevote(height, cs.Round)
  934. }
  935. }
  936. case types.VoteTypePrecommit:
  937. precommits := cs.Votes.Precommits(vote.Round)
  938. log.Debug(Fmt("Added to precommit: %v", precommits.StringShort()))
  939. if cs.Round <= vote.Round && precommits.HasTwoThirdsAny() {
  940. go func() {
  941. hash, _, ok := precommits.TwoThirdsMajority()
  942. if ok && len(hash) == 0 {
  943. cs.EnterNewRound(height, vote.Round+1)
  944. return
  945. } else if cs.Round < vote.Round {
  946. cs.EnterNewRound(height, vote.Round)
  947. }
  948. if ok {
  949. cs.EnterCommit(height)
  950. } else {
  951. cs.EnterPrecommit(height, vote.Round)
  952. cs.EnterPrecommitWait(height, vote.Round)
  953. }
  954. }()
  955. }
  956. default:
  957. panic(Fmt("Unexpected vote type %X", vote.Type)) // Should not happen.
  958. }
  959. }
  960. return
  961. }
  962. // Height mismatch, bad peer? TODO
  963. return
  964. }
  965. func (cs *ConsensusState) stageBlock(block *types.Block, blockParts *types.PartSet) error {
  966. if block == nil {
  967. panic("Cannot stage nil block")
  968. }
  969. // Already staged?
  970. blockHash := block.Hash()
  971. if cs.stagedBlock != nil && len(blockHash) != 0 && bytes.Equal(cs.stagedBlock.Hash(), blockHash) {
  972. return nil
  973. }
  974. // Create a copy of the state for staging
  975. stateCopy := cs.state.Copy()
  976. // reset the event cache and pass it into the state
  977. cs.evc = events.NewEventCache(cs.evsw)
  978. stateCopy.SetFireable(cs.evc)
  979. // Commit block onto the copied state.
  980. // NOTE: Basic validation is done in state.AppendBlock().
  981. err := sm.ExecBlock(stateCopy, block, blockParts.Header())
  982. if err != nil {
  983. return err
  984. } else {
  985. cs.stagedBlock = block
  986. cs.stagedState = stateCopy
  987. return nil
  988. }
  989. }
  990. func (cs *ConsensusState) signAddVote(type_ byte, hash []byte, header types.PartSetHeader) *types.Vote {
  991. if cs.privValidator == nil || !cs.Validators.HasAddress(cs.privValidator.Address) {
  992. return nil
  993. }
  994. vote := &types.Vote{
  995. Height: cs.Height,
  996. Round: cs.Round,
  997. Type: type_,
  998. BlockHash: hash,
  999. BlockParts: header,
  1000. }
  1001. err := cs.privValidator.SignVote(cs.state.ChainID, vote)
  1002. if err == nil {
  1003. _, _, err := cs.addVote(cs.privValidator.Address, vote, "")
  1004. log.Info("Signed and added vote", "height", cs.Height, "round", cs.Round, "vote", vote, "error", err)
  1005. return vote
  1006. } else {
  1007. log.Warn("Error signing vote", "height", cs.Height, "round", cs.Round, "vote", vote, "error", err)
  1008. return nil
  1009. }
  1010. }
  1011. // Save Block, save the +2/3 Commits we've seen
  1012. func (cs *ConsensusState) saveBlock(block *types.Block, blockParts *types.PartSet, commits *VoteSet) {
  1013. // The proposal must be valid.
  1014. if err := cs.stageBlock(block, blockParts); err != nil {
  1015. panic(Fmt("saveBlock() an invalid block: %v", err))
  1016. }
  1017. // Save to blockStore.
  1018. if cs.blockStore.Height() < block.Height {
  1019. seenValidation := commits.MakeValidation()
  1020. cs.blockStore.SaveBlock(block, blockParts, seenValidation)
  1021. }
  1022. // Save the state.
  1023. cs.stagedState.Save()
  1024. // Update mempool.
  1025. cs.mempoolReactor.Mempool.ResetForBlockAndState(block, cs.stagedState)
  1026. // Fire off event
  1027. go func(block *types.Block) {
  1028. cs.evsw.FireEvent(types.EventStringNewBlock(), block)
  1029. cs.evc.Flush()
  1030. }(block)
  1031. }
  1032. // implements events.Eventable
  1033. func (cs *ConsensusState) SetFireable(evsw events.Fireable) {
  1034. cs.evsw = evsw
  1035. }