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.

1225 lines
44 KiB

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