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.

1238 lines
44 KiB

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