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.

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