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.

1228 lines
44 KiB

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