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.

1174 lines
37 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
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
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. Consensus State Machine Overview:
  3. * Propose, Prevote, Precommit represent state machine stages. (aka RoundStep, or step).
  4. Each take a predetermined amount of time depending on the round number.
  5. * The Commit step can be entered by two means:
  6. 1. After the Precommit step, +2/3 Precommits were found
  7. 2. At any time, +2/3 Commits were found
  8. * Once in the Commit stage, two conditions must both be satisfied
  9. before proceeding to the next height NewHeight.
  10. * The Propose step of the next height does not begin until
  11. at least Delta duration *after* +2/3 Commits were found.
  12. The step stays at NewHeight until this timeout occurs before
  13. proceeding to Propose.
  14. +-------------------------------------+
  15. | |
  16. v |(Wait til CommitTime + Delta)
  17. +-----------+ +-----+-----+
  18. +----------> | Propose +--------------+ | NewHeight |
  19. | +-----------+ | +-----------+
  20. | | ^
  21. | | |
  22. | | |
  23. |(Else) v |
  24. +-----+-----+ +-----------+ |
  25. | Precommit | <------------------------+ Prevote | |
  26. +-----+-----+ +-----------+ |
  27. |(If +2/3 Precommits found) |
  28. | |
  29. | + (When +2/3 Commits found) |
  30. | | |
  31. v v |
  32. +------------------------------------------------------------------------------+
  33. | Commit | |
  34. | | |
  35. | +----------------+ * Save Block | |
  36. | |Get Block Parts |---> * Stage Block +--+ + |
  37. | +----------------+ * Broadcast Commit | * Setup New Height |
  38. | | * Move Commits set to |
  39. | +--> LastCommits to continue |
  40. | | collecting commits |
  41. | +-----------------+ | * Broadcast New State |
  42. | |Get +2/3 Commits |--> * Set CommitTime +--+ |
  43. | +-----------------+ |
  44. | |
  45. +------------------------------------------------------------------------------+
  46. */
  47. package consensus
  48. import (
  49. "bytes"
  50. "errors"
  51. "fmt"
  52. "math"
  53. "sync"
  54. "sync/atomic"
  55. "time"
  56. "github.com/tendermint/tendermint/account"
  57. "github.com/tendermint/tendermint/binary"
  58. bc "github.com/tendermint/tendermint/blockchain"
  59. . "github.com/tendermint/tendermint/common"
  60. "github.com/tendermint/tendermint/config"
  61. . "github.com/tendermint/tendermint/consensus/types"
  62. "github.com/tendermint/tendermint/events"
  63. mempl "github.com/tendermint/tendermint/mempool"
  64. sm "github.com/tendermint/tendermint/state"
  65. "github.com/tendermint/tendermint/types"
  66. )
  67. const (
  68. roundDeadlinePrevote = float64(1.0 / 3.0) // When the prevote is due.
  69. roundDeadlinePrecommit = float64(2.0 / 3.0) // When the precommit vote is due.
  70. )
  71. var (
  72. RoundDuration0 = 10 * time.Second // The first round is 60 seconds long.
  73. RoundDurationDelta = 3 * time.Second // Each successive round lasts 15 seconds longer.
  74. newHeightDelta = RoundDuration0 / 3 // The time to wait between commitTime and startTime of next consensus rounds.
  75. )
  76. var (
  77. ErrInvalidProposalSignature = errors.New("Error invalid proposal signature")
  78. )
  79. //-----------------------------------------------------------------------------
  80. // RoundStep enum type
  81. type RoundStep uint8
  82. const (
  83. RoundStepNewHeight = RoundStep(0x00) // Round0 for new height started, wait til CommitTime + Delta
  84. RoundStepNewRound = RoundStep(0x01) // Pseudostep, immediately goes to RoundStepPropose
  85. RoundStepPropose = RoundStep(0x10) // Did propose, gossip proposal
  86. RoundStepPrevote = RoundStep(0x11) // Did prevote, gossip prevotes
  87. RoundStepPrecommit = RoundStep(0x12) // Did precommit, gossip precommits
  88. RoundStepCommit = RoundStep(0x20) // Entered commit state machine
  89. )
  90. func (rs RoundStep) String() string {
  91. switch rs {
  92. case RoundStepNewHeight:
  93. return "RoundStepNewHeight"
  94. case RoundStepNewRound:
  95. return "RoundStepNewRound"
  96. case RoundStepPropose:
  97. return "RoundStepPropose"
  98. case RoundStepPrevote:
  99. return "RoundStepPrevote"
  100. case RoundStepPrecommit:
  101. return "RoundStepPrecommit"
  102. case RoundStepCommit:
  103. return "RoundStepCommit"
  104. default:
  105. panic(Fmt("Unknown RoundStep %X", rs))
  106. }
  107. }
  108. //-----------------------------------------------------------------------------
  109. // RoundAction enum type
  110. type RoundActionType uint8
  111. const (
  112. RoundActionPropose = RoundActionType(0xA0) // Propose and goto RoundStepPropose
  113. RoundActionPrevote = RoundActionType(0xA1) // Prevote and goto RoundStepPrevote
  114. RoundActionPrecommit = RoundActionType(0xA2) // Precommit and goto RoundStepPrecommit
  115. RoundActionTryCommit = RoundActionType(0xC0) // Goto RoundStepCommit, or RoundStepPropose for next round.
  116. RoundActionCommit = RoundActionType(0xC1) // Goto RoundStepCommit upon +2/3 commits
  117. RoundActionTryFinalize = RoundActionType(0xC2) // Maybe goto RoundStepPropose for next round.
  118. )
  119. func (rat RoundActionType) String() string {
  120. switch rat {
  121. case RoundActionPropose:
  122. return "RoundActionPropose"
  123. case RoundActionPrevote:
  124. return "RoundActionPrevote"
  125. case RoundActionPrecommit:
  126. return "RoundActionPrecommit"
  127. case RoundActionTryCommit:
  128. return "RoundActionTryCommit"
  129. case RoundActionCommit:
  130. return "RoundActionCommit"
  131. case RoundActionTryFinalize:
  132. return "RoundActionTryFinalize"
  133. default:
  134. panic(Fmt("Unknown RoundAction %X", rat))
  135. }
  136. }
  137. //-----------------------------------------------------------------------------
  138. type RoundAction struct {
  139. Height uint // The block height for which consensus is reaching for.
  140. Round uint // The round number at given height.
  141. Action RoundActionType // Action to perform.
  142. }
  143. func (ra RoundAction) String() string {
  144. return Fmt("RoundAction{H:%v R:%v A:%v}", ra.Height, ra.Round, ra.Action)
  145. }
  146. //-----------------------------------------------------------------------------
  147. // Immutable when returned from ConsensusState.GetRoundState()
  148. type RoundState struct {
  149. Height uint // Height we are working on
  150. Round uint
  151. Step RoundStep
  152. StartTime time.Time
  153. CommitTime time.Time // Time when +2/3 commits were found
  154. Validators *sm.ValidatorSet
  155. Proposal *Proposal
  156. ProposalBlock *types.Block
  157. ProposalBlockParts *types.PartSet
  158. ProposalPOL *POL
  159. ProposalPOLParts *types.PartSet
  160. LockedBlock *types.Block
  161. LockedBlockParts *types.PartSet
  162. LockedPOL *POL // Rarely needed, so no LockedPOLParts.
  163. Prevotes *VoteSet
  164. Precommits *VoteSet
  165. Commits *VoteSet
  166. LastCommits *VoteSet
  167. PrivValidator *sm.PrivValidator
  168. }
  169. func (rs *RoundState) String() string {
  170. return rs.StringIndented("")
  171. }
  172. func (rs *RoundState) StringIndented(indent string) string {
  173. return fmt.Sprintf(`RoundState{
  174. %s H:%v R:%v S:%v
  175. %s StartTime: %v
  176. %s CommitTime: %v
  177. %s Validators: %v
  178. %s Proposal: %v
  179. %s ProposalBlock: %v %v
  180. %s ProposalPOL: %v %v
  181. %s LockedBlock: %v %v
  182. %s LockedPOL: %v
  183. %s Prevotes: %v
  184. %s Precommits: %v
  185. %s Commits: %v
  186. %s LastCommits: %v
  187. %s}`,
  188. indent, rs.Height, rs.Round, rs.Step,
  189. indent, rs.StartTime,
  190. indent, rs.CommitTime,
  191. indent, rs.Validators.StringIndented(indent+" "),
  192. indent, rs.Proposal,
  193. indent, rs.ProposalBlockParts.StringShort(), rs.ProposalBlock.StringShort(),
  194. indent, rs.ProposalPOLParts.StringShort(), rs.ProposalPOL.StringShort(),
  195. indent, rs.LockedBlockParts.StringShort(), rs.LockedBlock.StringShort(),
  196. indent, rs.LockedPOL.StringShort(),
  197. indent, rs.Prevotes.StringIndented(indent+" "),
  198. indent, rs.Precommits.StringIndented(indent+" "),
  199. indent, rs.Commits.StringIndented(indent+" "),
  200. indent, rs.LastCommits.StringShort(),
  201. indent)
  202. }
  203. func (rs *RoundState) StringShort() string {
  204. return fmt.Sprintf(`RoundState{H:%v R:%v S:%v ST:%v}`,
  205. rs.Height, rs.Round, rs.Step, rs.StartTime)
  206. }
  207. //-----------------------------------------------------------------------------
  208. // Tracks consensus state across block heights and rounds.
  209. type ConsensusState struct {
  210. started uint32
  211. stopped uint32
  212. quit chan struct{}
  213. blockStore *bc.BlockStore
  214. mempoolReactor *mempl.MempoolReactor
  215. runActionCh chan RoundAction
  216. newStepCh chan *RoundState
  217. mtx sync.Mutex
  218. RoundState
  219. state *sm.State // State until height-1.
  220. stagedBlock *types.Block // Cache last staged block.
  221. stagedState *sm.State // Cache result of staged block.
  222. lastCommitVoteHeight uint // Last called commitVoteBlock() or saveCommitVoteBlock() on.
  223. evsw *events.EventSwitch
  224. }
  225. func NewConsensusState(state *sm.State, blockStore *bc.BlockStore, mempoolReactor *mempl.MempoolReactor) *ConsensusState {
  226. cs := &ConsensusState{
  227. quit: make(chan struct{}),
  228. blockStore: blockStore,
  229. mempoolReactor: mempoolReactor,
  230. runActionCh: make(chan RoundAction, 1),
  231. newStepCh: make(chan *RoundState, 1),
  232. }
  233. cs.updateToState(state, true)
  234. return cs
  235. }
  236. func (cs *ConsensusState) GetState() *sm.State {
  237. cs.mtx.Lock()
  238. defer cs.mtx.Unlock()
  239. return cs.state.Copy()
  240. }
  241. func (cs *ConsensusState) GetRoundState() *RoundState {
  242. cs.mtx.Lock()
  243. defer cs.mtx.Unlock()
  244. return cs.getRoundState()
  245. }
  246. func (cs *ConsensusState) getRoundState() *RoundState {
  247. rs := cs.RoundState // copy
  248. return &rs
  249. }
  250. func (cs *ConsensusState) NewStepCh() chan *RoundState {
  251. return cs.newStepCh
  252. }
  253. func (cs *ConsensusState) Start() {
  254. if atomic.CompareAndSwapUint32(&cs.started, 0, 1) {
  255. log.Info("Starting ConsensusState")
  256. go cs.stepTransitionRoutine()
  257. }
  258. }
  259. func (cs *ConsensusState) Stop() {
  260. if atomic.CompareAndSwapUint32(&cs.stopped, 0, 1) {
  261. log.Info("Stopping ConsensusState")
  262. close(cs.quit)
  263. }
  264. }
  265. func (cs *ConsensusState) IsStopped() bool {
  266. return atomic.LoadUint32(&cs.stopped) == 1
  267. }
  268. func (cs *ConsensusState) queueAction(ra RoundAction) {
  269. go func() {
  270. cs.runActionCh <- ra
  271. }()
  272. }
  273. // Source of all round state transitions (and votes).
  274. func (cs *ConsensusState) stepTransitionRoutine() {
  275. // For clarity, all state transitions that happen after some timeout are here.
  276. // Schedule the next action by pushing a RoundAction{} to cs.runActionCh.
  277. scheduleNextAction := func() {
  278. go func() {
  279. // NOTE: We can push directly to runActionCh because
  280. // we're running in a separate goroutine, which avoids deadlocks.
  281. rs := cs.getRoundState()
  282. round, roundStartTime, RoundDuration, _, elapsedRatio := calcRoundInfo(rs.StartTime)
  283. log.Debug("Scheduling next action", "height", rs.Height, "round", round, "step", rs.Step, "roundStartTime", roundStartTime, "elapsedRatio", elapsedRatio)
  284. switch rs.Step {
  285. case RoundStepNewHeight:
  286. // We should run RoundActionPropose when rs.StartTime passes.
  287. if elapsedRatio < 0 {
  288. // startTime is in the future.
  289. time.Sleep(time.Duration((-1.0 * elapsedRatio) * float64(RoundDuration)))
  290. }
  291. cs.runActionCh <- RoundAction{rs.Height, rs.Round, RoundActionPropose}
  292. case RoundStepNewRound:
  293. // Pseudostep: Immediately goto propose.
  294. cs.runActionCh <- RoundAction{rs.Height, rs.Round, RoundActionPropose}
  295. case RoundStepPropose:
  296. // Wake up when it's time to vote.
  297. time.Sleep(time.Duration((roundDeadlinePrevote - elapsedRatio) * float64(RoundDuration)))
  298. cs.runActionCh <- RoundAction{rs.Height, rs.Round, RoundActionPrevote}
  299. case RoundStepPrevote:
  300. // Wake up when it's time to precommit.
  301. time.Sleep(time.Duration((roundDeadlinePrecommit - elapsedRatio) * float64(RoundDuration)))
  302. cs.runActionCh <- RoundAction{rs.Height, rs.Round, RoundActionPrecommit}
  303. case RoundStepPrecommit:
  304. // Wake up when the round is over.
  305. time.Sleep(time.Duration((1.0 - elapsedRatio) * float64(RoundDuration)))
  306. cs.runActionCh <- RoundAction{rs.Height, rs.Round, RoundActionTryCommit}
  307. case RoundStepCommit:
  308. // There's nothing to scheudle, we're waiting for
  309. // ProposalBlockParts.IsComplete() &&
  310. // Commits.HasTwoThirdsMajority()
  311. panic("The next action from RoundStepCommit is not scheduled by time")
  312. default:
  313. panic("Should not happen")
  314. }
  315. }()
  316. }
  317. scheduleNextAction()
  318. // NOTE: All ConsensusState.RunAction*() calls come from here.
  319. // Since only one routine calls them, it is safe to assume that
  320. // the RoundState Height/Round/Step won't change concurrently.
  321. // However, other fields like Proposal could change concurrent
  322. // due to gossip routines.
  323. ACTION_LOOP:
  324. for {
  325. var roundAction RoundAction
  326. select {
  327. case roundAction = <-cs.runActionCh:
  328. case <-cs.quit:
  329. return
  330. }
  331. height, round, action := roundAction.Height, roundAction.Round, roundAction.Action
  332. rs := cs.GetRoundState()
  333. // Continue if action is not relevant
  334. if height != rs.Height {
  335. log.Debug("Discarding round action: Height mismatch", "height", rs.Height, "roundAction", roundAction)
  336. continue
  337. }
  338. // If action <= RoundActionPrecommit, the round must match too.
  339. if action <= RoundActionPrecommit && round != rs.Round {
  340. log.Debug("Discarding round action: Round mismatch", "round", rs.Round, "roundAction", roundAction)
  341. continue
  342. }
  343. log.Info("Running round action", "height", rs.Height, "round", rs.Round, "step", rs.Step, "roundAction", roundAction, "startTime", rs.StartTime)
  344. // Run action
  345. switch action {
  346. case RoundActionPropose:
  347. if rs.Step != RoundStepNewHeight && rs.Step != RoundStepNewRound {
  348. continue ACTION_LOOP
  349. }
  350. cs.RunActionPropose(rs.Height, rs.Round)
  351. scheduleNextAction()
  352. continue ACTION_LOOP
  353. case RoundActionPrevote:
  354. if rs.Step >= RoundStepPrevote {
  355. continue ACTION_LOOP
  356. }
  357. cs.RunActionPrevote(rs.Height, rs.Round)
  358. scheduleNextAction()
  359. continue ACTION_LOOP
  360. case RoundActionPrecommit:
  361. if rs.Step >= RoundStepPrecommit {
  362. continue ACTION_LOOP
  363. }
  364. cs.RunActionPrecommit(rs.Height, rs.Round)
  365. scheduleNextAction()
  366. continue ACTION_LOOP
  367. case RoundActionTryCommit:
  368. if rs.Step >= RoundStepCommit {
  369. continue ACTION_LOOP
  370. }
  371. if rs.Precommits.HasTwoThirdsMajority() {
  372. // Enter RoundStepCommit and commit.
  373. cs.RunActionCommit(rs.Height)
  374. continue ACTION_LOOP
  375. } else {
  376. // Could not commit, move onto next round.
  377. cs.SetupNewRound(rs.Height, rs.Round+1)
  378. // cs.Step is now at RoundStepNewRound
  379. scheduleNextAction()
  380. continue ACTION_LOOP
  381. }
  382. case RoundActionCommit:
  383. if rs.Step >= RoundStepCommit {
  384. continue ACTION_LOOP
  385. }
  386. // Enter RoundStepCommit and commit.
  387. cs.RunActionCommit(rs.Height)
  388. continue ACTION_LOOP
  389. case RoundActionTryFinalize:
  390. if cs.TryFinalizeCommit(rs.Height) {
  391. // Now at new height
  392. // cs.Step is at RoundStepNewHeight or RoundStepNewRound.
  393. newBlock := cs.blockStore.LoadBlock(cs.state.LastBlockHeight)
  394. cs.evsw.FireEvent(types.EventStringNewBlock(), newBlock)
  395. scheduleNextAction()
  396. continue ACTION_LOOP
  397. } else {
  398. // do not schedule next action.
  399. continue ACTION_LOOP
  400. }
  401. default:
  402. panic("Unknown action")
  403. }
  404. // For clarity, ensure that all switch cases call "continue"
  405. panic("Should not happen.")
  406. }
  407. }
  408. // Updates ConsensusState and increments height to match that of state.
  409. // If calculated round is greater than 0 (based on BlockTime or calculated StartTime)
  410. // then also sets up the appropriate round, and cs.Step becomes RoundStepNewRound.
  411. // Otherwise the round is 0 and cs.Step becomes RoundStepNewHeight.
  412. func (cs *ConsensusState) updateToState(state *sm.State, contiguous bool) {
  413. // Sanity check state.
  414. if contiguous && cs.Height > 0 && cs.Height != state.LastBlockHeight {
  415. panic(Fmt("updateToState() expected state height of %v but found %v",
  416. cs.Height, state.LastBlockHeight))
  417. }
  418. // Reset fields based on state.
  419. validators := state.BondedValidators
  420. height := state.LastBlockHeight + 1 // next desired block height
  421. // RoundState fields
  422. cs.Height = height
  423. cs.Round = 0
  424. cs.Step = RoundStepNewHeight
  425. if cs.CommitTime.IsZero() {
  426. cs.StartTime = state.LastBlockTime.Add(newHeightDelta)
  427. } else {
  428. cs.StartTime = cs.CommitTime.Add(newHeightDelta)
  429. }
  430. cs.CommitTime = time.Time{}
  431. cs.Validators = validators
  432. cs.Proposal = nil
  433. cs.ProposalBlock = nil
  434. cs.ProposalBlockParts = nil
  435. cs.ProposalPOL = nil
  436. cs.ProposalPOLParts = nil
  437. cs.LockedBlock = nil
  438. cs.LockedBlockParts = nil
  439. cs.LockedPOL = nil
  440. cs.Prevotes = NewVoteSet(height, 0, types.VoteTypePrevote, validators)
  441. cs.Precommits = NewVoteSet(height, 0, types.VoteTypePrecommit, validators)
  442. cs.LastCommits = cs.Commits
  443. cs.Commits = NewVoteSet(height, 0, types.VoteTypeCommit, validators)
  444. cs.state = state
  445. cs.stagedBlock = nil
  446. cs.stagedState = nil
  447. // Update the round if we need to.
  448. round := calcRound(cs.StartTime)
  449. if round > 0 {
  450. cs.setupNewRound(round)
  451. }
  452. // If we've timed out, then send rebond tx.
  453. if cs.PrivValidator != nil && cs.state.UnbondingValidators.HasAddress(cs.PrivValidator.Address) {
  454. rebondTx := &types.RebondTx{
  455. Address: cs.PrivValidator.Address,
  456. Height: cs.Height + 1,
  457. }
  458. err := cs.PrivValidator.SignRebondTx(rebondTx)
  459. if err == nil {
  460. log.Info("Signed and broadcast RebondTx", "height", cs.Height, "round", cs.Round, "tx", rebondTx)
  461. cs.mempoolReactor.BroadcastTx(rebondTx)
  462. } else {
  463. log.Warn("Error signing RebondTx", "height", cs.Height, "round", cs.Round, "tx", rebondTx, "error", err)
  464. }
  465. }
  466. }
  467. // After the call cs.Step becomes RoundStepNewRound.
  468. func (cs *ConsensusState) setupNewRound(round uint) {
  469. // Sanity check
  470. if round == 0 {
  471. panic("setupNewRound() should never be called for round 0")
  472. }
  473. // Increment all the way to round.
  474. validators := cs.Validators.Copy()
  475. validators.IncrementAccum(round - cs.Round)
  476. cs.Round = round
  477. cs.Step = RoundStepNewRound
  478. cs.Validators = validators
  479. cs.Proposal = nil
  480. cs.ProposalBlock = nil
  481. cs.ProposalBlockParts = nil
  482. cs.ProposalPOL = nil
  483. cs.ProposalPOLParts = nil
  484. cs.Prevotes = NewVoteSet(cs.Height, round, types.VoteTypePrevote, validators)
  485. cs.Prevotes.AddFromCommits(cs.Commits)
  486. cs.Precommits = NewVoteSet(cs.Height, round, types.VoteTypePrecommit, validators)
  487. cs.Precommits.AddFromCommits(cs.Commits)
  488. }
  489. func (cs *ConsensusState) SetPrivValidator(priv *sm.PrivValidator) {
  490. cs.mtx.Lock()
  491. defer cs.mtx.Unlock()
  492. cs.PrivValidator = priv
  493. }
  494. //-----------------------------------------------------------------------------
  495. // Set up the round to desired round and set step to RoundStepNewRound
  496. func (cs *ConsensusState) SetupNewRound(height uint, desiredRound uint) bool {
  497. cs.mtx.Lock()
  498. defer cs.mtx.Unlock()
  499. if cs.Height != height {
  500. return false
  501. }
  502. if desiredRound <= cs.Round {
  503. return false
  504. }
  505. cs.setupNewRound(desiredRound)
  506. // c.Step is now RoundStepNewRound
  507. cs.newStepCh <- cs.getRoundState()
  508. return true
  509. }
  510. func (cs *ConsensusState) RunActionPropose(height uint, round uint) {
  511. cs.mtx.Lock()
  512. defer cs.mtx.Unlock()
  513. if cs.Height != height || cs.Round != round {
  514. return
  515. }
  516. defer func() {
  517. cs.Step = RoundStepPropose
  518. cs.newStepCh <- cs.getRoundState()
  519. }()
  520. // Nothing to do if it's not our turn.
  521. if cs.PrivValidator == nil {
  522. return
  523. }
  524. if !bytes.Equal(cs.Validators.Proposer().Address, cs.PrivValidator.Address) {
  525. log.Debug("Not our turn to propose", "proposer", cs.Validators.Proposer().Address, "privValidator", cs.PrivValidator)
  526. return
  527. } else {
  528. log.Debug("Our turn to propose", "proposer", cs.Validators.Proposer().Address, "privValidator", cs.PrivValidator)
  529. }
  530. var block *types.Block
  531. var blockParts *types.PartSet
  532. var pol *POL
  533. var polParts *types.PartSet
  534. // Decide on block and POL
  535. if cs.LockedBlock != nil {
  536. // If we're locked onto a block, just choose that.
  537. block = cs.LockedBlock
  538. blockParts = cs.LockedBlockParts
  539. pol = cs.LockedPOL
  540. } else {
  541. // Otherwise we should create a new proposal.
  542. var validation *types.Validation
  543. if cs.Height == 1 {
  544. // We're creating a proposal for the first block.
  545. // The validation is empty.
  546. validation = &types.Validation{}
  547. } else if cs.LastCommits.HasTwoThirdsMajority() {
  548. // Make the validation from LastCommits
  549. validation = cs.LastCommits.MakeValidation()
  550. } else {
  551. // Upon reboot, we may have to use SeenValidation
  552. validation = cs.blockStore.LoadSeenValidation(height - 1)
  553. if validation == nil {
  554. // We just don't have any validation for the previous block
  555. log.Debug("Cannot propose anything: No validation for the previous block.")
  556. return
  557. }
  558. }
  559. txs := cs.mempoolReactor.Mempool.GetProposalTxs()
  560. block = &types.Block{
  561. Header: &types.Header{
  562. Network: config.App().GetString("Network"),
  563. Height: cs.Height,
  564. Time: time.Now(),
  565. Fees: 0, // TODO fees
  566. NumTxs: uint(len(txs)),
  567. LastBlockHash: cs.state.LastBlockHash,
  568. LastBlockParts: cs.state.LastBlockParts,
  569. StateHash: nil, // Will set afterwards.
  570. },
  571. Validation: validation,
  572. Data: &types.Data{
  573. Txs: txs,
  574. },
  575. }
  576. // Set the types.Header.StateHash.
  577. err := cs.state.SetBlockStateHash(block)
  578. if err != nil {
  579. log.Error("Error setting state hash", "error", err)
  580. return
  581. }
  582. blockParts = block.MakePartSet()
  583. pol = cs.LockedPOL // If exists, is a PoUnlock.
  584. }
  585. if pol != nil {
  586. polParts = pol.MakePartSet()
  587. }
  588. // Make proposal
  589. proposal := NewProposal(cs.Height, cs.Round, blockParts.Header(), polParts.Header())
  590. err := cs.PrivValidator.SignProposal(proposal)
  591. if err == nil {
  592. log.Info("Signed and set proposal", "height", cs.Height, "round", cs.Round, "proposal", proposal)
  593. log.Debug(Fmt("Signed and set proposal block: %v", block))
  594. // Set fields
  595. cs.Proposal = proposal
  596. cs.ProposalBlock = block
  597. cs.ProposalBlockParts = blockParts
  598. cs.ProposalPOL = pol
  599. cs.ProposalPOLParts = polParts
  600. } else {
  601. log.Warn("Error signing proposal", "height", cs.Height, "round", cs.Round, "error", err)
  602. }
  603. }
  604. // Prevote for LockedBlock if we're locked, or ProposealBlock if valid.
  605. // Otherwise vote nil.
  606. func (cs *ConsensusState) RunActionPrevote(height uint, round uint) {
  607. cs.mtx.Lock()
  608. defer cs.mtx.Unlock()
  609. if cs.Height != height || cs.Round != round {
  610. panic(Fmt("RunActionPrevote(%v/%v), expected %v/%v", height, round, cs.Height, cs.Round))
  611. }
  612. defer func() {
  613. cs.Step = RoundStepPrevote
  614. cs.newStepCh <- cs.getRoundState()
  615. }()
  616. // If a block is locked, prevote that.
  617. if cs.LockedBlock != nil {
  618. cs.signAddVote(types.VoteTypePrevote, cs.LockedBlock.Hash(), cs.LockedBlockParts.Header())
  619. return
  620. }
  621. // If ProposalBlock is nil, prevote nil.
  622. if cs.ProposalBlock == nil {
  623. log.Warn("ProposalBlock is nil")
  624. cs.signAddVote(types.VoteTypePrevote, nil, types.PartSetHeader{})
  625. return
  626. }
  627. // Try staging cs.ProposalBlock
  628. err := cs.stageBlock(cs.ProposalBlock, cs.ProposalBlockParts)
  629. if err != nil {
  630. // ProposalBlock is invalid, prevote nil.
  631. log.Warn("ProposalBlock is invalid", "error", err)
  632. cs.signAddVote(types.VoteTypePrevote, nil, types.PartSetHeader{})
  633. return
  634. }
  635. // Prevote cs.ProposalBlock
  636. cs.signAddVote(types.VoteTypePrevote, cs.ProposalBlock.Hash(), cs.ProposalBlockParts.Header())
  637. return
  638. }
  639. // Lock & Precommit the ProposalBlock if we have enough prevotes for it,
  640. // or unlock an existing lock if +2/3 of prevotes were nil.
  641. func (cs *ConsensusState) RunActionPrecommit(height uint, round uint) {
  642. cs.mtx.Lock()
  643. defer cs.mtx.Unlock()
  644. if cs.Height != height || cs.Round != round {
  645. panic(Fmt("RunActionPrecommit(%v/%v), expected %v/%v", height, round, cs.Height, cs.Round))
  646. }
  647. defer func() {
  648. cs.Step = RoundStepPrecommit
  649. cs.newStepCh <- cs.getRoundState()
  650. }()
  651. hash, partsHeader, ok := cs.Prevotes.TwoThirdsMajority()
  652. if !ok {
  653. // If we don't have two thirds of prevotes,
  654. // don't do anything at all.
  655. return
  656. }
  657. // Remember this POL. (hash may be nil)
  658. cs.LockedPOL = cs.Prevotes.MakePOL()
  659. // If +2/3 prevoted nil. Just unlock.
  660. if len(hash) == 0 {
  661. cs.LockedBlock = nil
  662. cs.LockedBlockParts = nil
  663. return
  664. }
  665. // If +2/3 prevoted for already locked block, precommit it.
  666. if cs.LockedBlock.HashesTo(hash) {
  667. cs.signAddVote(types.VoteTypePrecommit, hash, partsHeader)
  668. return
  669. }
  670. // If +2/3 prevoted for cs.ProposalBlock, lock it and precommit it.
  671. if cs.ProposalBlock.HashesTo(hash) {
  672. // Validate the block.
  673. if err := cs.stageBlock(cs.ProposalBlock, cs.ProposalBlockParts); err != nil {
  674. // Prevent zombies.
  675. log.Warn("+2/3 prevoted for an invalid block", "error", err)
  676. return
  677. }
  678. cs.LockedBlock = cs.ProposalBlock
  679. cs.LockedBlockParts = cs.ProposalBlockParts
  680. cs.signAddVote(types.VoteTypePrecommit, hash, partsHeader)
  681. return
  682. }
  683. // We don't have the block that validators prevoted.
  684. // Unlock if we're locked.
  685. cs.LockedBlock = nil
  686. cs.LockedBlockParts = nil
  687. return
  688. }
  689. // Enter commit step. See the diagram for details.
  690. // There are two ways to enter this step:
  691. // * After the Precommit step with +2/3 precommits, or,
  692. // * Upon +2/3 commits regardless of current step
  693. // Either way this action is run at most once per round.
  694. func (cs *ConsensusState) RunActionCommit(height uint) {
  695. cs.mtx.Lock()
  696. defer cs.mtx.Unlock()
  697. if cs.Height != height {
  698. panic(Fmt("RunActionCommit(%v), expected %v", height, cs.Height))
  699. }
  700. defer func() {
  701. cs.Step = RoundStepCommit
  702. cs.newStepCh <- cs.getRoundState()
  703. }()
  704. // Sanity check.
  705. // There are two ways to enter:
  706. // 1. +2/3 precommits at the end of RoundStepPrecommit
  707. // 2. +2/3 commits at any time
  708. hash, partsHeader, ok := cs.Precommits.TwoThirdsMajority()
  709. if !ok {
  710. hash, partsHeader, ok = cs.Commits.TwoThirdsMajority()
  711. if !ok {
  712. panic("RunActionCommit() expects +2/3 precommits or commits")
  713. }
  714. }
  715. // Clear the Locked* fields and use cs.Proposed*
  716. if cs.LockedBlock.HashesTo(hash) {
  717. cs.ProposalBlock = cs.LockedBlock
  718. cs.ProposalBlockParts = cs.LockedBlockParts
  719. cs.LockedBlock = nil
  720. cs.LockedBlockParts = nil
  721. cs.LockedPOL = nil
  722. }
  723. // If we don't have the block being committed, set up to get it.
  724. if !cs.ProposalBlock.HashesTo(hash) {
  725. if !cs.ProposalBlockParts.HasHeader(partsHeader) {
  726. // We're getting the wrong block.
  727. // Set up ProposalBlockParts and keep waiting.
  728. cs.ProposalBlock = nil
  729. cs.ProposalBlockParts = types.NewPartSetFromHeader(partsHeader)
  730. } else {
  731. // We just need to keep waiting.
  732. }
  733. } else {
  734. // We have the block, so sign a Commit-vote.
  735. cs.commitVoteBlock(cs.ProposalBlock, cs.ProposalBlockParts)
  736. }
  737. // If we have the block AND +2/3 commits, queue RoundActionTryFinalize.
  738. // Round will immediately become finalized.
  739. if cs.ProposalBlock.HashesTo(hash) && cs.Commits.HasTwoThirdsMajority() {
  740. cs.queueAction(RoundAction{cs.Height, cs.Round, RoundActionTryFinalize})
  741. }
  742. }
  743. // Returns true if Finalize happened, which increments height && sets
  744. // the step to RoundStepNewHeight (or RoundStepNewRound, but probably not).
  745. func (cs *ConsensusState) TryFinalizeCommit(height uint) bool {
  746. cs.mtx.Lock()
  747. defer cs.mtx.Unlock()
  748. if cs.Height != height {
  749. panic(Fmt("TryFinalizeCommit(%v), expected %v", height, cs.Height))
  750. }
  751. if cs.Step == RoundStepCommit &&
  752. cs.Commits.HasTwoThirdsMajority() &&
  753. cs.ProposalBlockParts.IsComplete() {
  754. // Sanity check
  755. if cs.ProposalBlock == nil {
  756. panic(Fmt("Expected ProposalBlock to exist"))
  757. }
  758. hash, header, _ := cs.Commits.TwoThirdsMajority()
  759. if !cs.ProposalBlock.HashesTo(hash) {
  760. // XXX See: https://github.com/tendermint/tendermint/issues/44
  761. panic(Fmt("Expected ProposalBlock to hash to commit hash. Expected %X, got %X", hash, cs.ProposalBlock.Hash()))
  762. }
  763. if !cs.ProposalBlockParts.HasHeader(header) {
  764. panic(Fmt("Expected ProposalBlockParts header to be commit header"))
  765. }
  766. err := cs.stageBlock(cs.ProposalBlock, cs.ProposalBlockParts)
  767. if err == nil {
  768. log.Debug(Fmt("Finalizing commit of block: %v", cs.ProposalBlock))
  769. // We have the block, so save/stage/sign-commit-vote.
  770. cs.saveCommitVoteBlock(cs.ProposalBlock, cs.ProposalBlockParts, cs.Commits)
  771. // Increment height.
  772. cs.updateToState(cs.stagedState, true)
  773. // cs.Step is now RoundStepNewHeight or RoundStepNewRound
  774. cs.newStepCh <- cs.getRoundState()
  775. return true
  776. } else {
  777. // Prevent zombies.
  778. // TODO: Does this ever happen?
  779. panic(Fmt("+2/3 committed an invalid block: %v", err))
  780. }
  781. }
  782. return false
  783. }
  784. //-----------------------------------------------------------------------------
  785. func (cs *ConsensusState) SetProposal(proposal *Proposal) error {
  786. cs.mtx.Lock()
  787. defer cs.mtx.Unlock()
  788. // Already have one
  789. if cs.Proposal != nil {
  790. return nil
  791. }
  792. // Does not apply
  793. if proposal.Height != cs.Height || proposal.Round != cs.Round {
  794. return nil
  795. }
  796. // We don't care about the proposal if we're already in RoundStepCommit.
  797. if cs.Step == RoundStepCommit {
  798. return nil
  799. }
  800. // Verify signature
  801. if !cs.Validators.Proposer().PubKey.VerifyBytes(account.SignBytes(proposal), proposal.Signature) {
  802. return ErrInvalidProposalSignature
  803. }
  804. cs.Proposal = proposal
  805. cs.ProposalBlockParts = types.NewPartSetFromHeader(proposal.BlockParts)
  806. cs.ProposalPOLParts = types.NewPartSetFromHeader(proposal.POLParts)
  807. return nil
  808. }
  809. // NOTE: block is not necessarily valid.
  810. // NOTE: This function may increment the height.
  811. func (cs *ConsensusState) AddProposalBlockPart(height uint, round uint, part *types.Part) (added bool, err error) {
  812. cs.mtx.Lock()
  813. defer cs.mtx.Unlock()
  814. // Blocks might be reused, so round mismatch is OK
  815. if cs.Height != height {
  816. return false, nil
  817. }
  818. // We're not expecting a block part.
  819. if cs.ProposalBlockParts == nil {
  820. return false, nil // TODO: bad peer? Return error?
  821. }
  822. added, err = cs.ProposalBlockParts.AddPart(part)
  823. if err != nil {
  824. return added, err
  825. }
  826. if added && cs.ProposalBlockParts.IsComplete() {
  827. var n int64
  828. var err error
  829. cs.ProposalBlock = binary.ReadBinary(&types.Block{}, cs.ProposalBlockParts.GetReader(), &n, &err).(*types.Block)
  830. // If we're already in the commit step, try to finalize round.
  831. if cs.Step == RoundStepCommit {
  832. cs.queueAction(RoundAction{cs.Height, cs.Round, RoundActionTryFinalize})
  833. }
  834. // XXX If POL is valid, consider unlocking.
  835. return true, err
  836. }
  837. return true, nil
  838. }
  839. // NOTE: POL is not necessarily valid.
  840. func (cs *ConsensusState) AddProposalPOLPart(height uint, round uint, part *types.Part) (added bool, err error) {
  841. cs.mtx.Lock()
  842. defer cs.mtx.Unlock()
  843. if cs.Height != height || cs.Round != round {
  844. return false, nil
  845. }
  846. // We're not expecting a POL part.
  847. if cs.ProposalPOLParts == nil {
  848. return false, nil // TODO: bad peer? Return error?
  849. }
  850. added, err = cs.ProposalPOLParts.AddPart(part)
  851. if err != nil {
  852. return added, err
  853. }
  854. if added && cs.ProposalPOLParts.IsComplete() {
  855. var n int64
  856. var err error
  857. cs.ProposalPOL = binary.ReadBinary(&POL{}, cs.ProposalPOLParts.GetReader(), &n, &err).(*POL)
  858. return true, err
  859. }
  860. return true, nil
  861. }
  862. func (cs *ConsensusState) AddVote(address []byte, vote *types.Vote) (added bool, index uint, err error) {
  863. cs.mtx.Lock()
  864. defer cs.mtx.Unlock()
  865. return cs.addVote(address, vote)
  866. }
  867. //-----------------------------------------------------------------------------
  868. func (cs *ConsensusState) addVote(address []byte, vote *types.Vote) (added bool, index uint, err error) {
  869. switch vote.Type {
  870. case types.VoteTypePrevote:
  871. // Prevotes checks for height+round match.
  872. return cs.Prevotes.Add(address, vote)
  873. case types.VoteTypePrecommit:
  874. // Precommits checks for height+round match.
  875. return cs.Precommits.Add(address, vote)
  876. case types.VoteTypeCommit:
  877. if vote.Height == cs.Height {
  878. // No need to check if vote.Round < cs.Round ...
  879. // Prevotes && Precommits already checks that.
  880. cs.Prevotes.Add(address, vote)
  881. cs.Precommits.Add(address, vote)
  882. added, index, err = cs.Commits.Add(address, vote)
  883. if added && cs.Commits.HasTwoThirdsMajority() && cs.CommitTime.IsZero() {
  884. cs.CommitTime = time.Now()
  885. log.Debug(Fmt("Set CommitTime to %v", cs.CommitTime))
  886. if cs.Step < RoundStepCommit {
  887. cs.queueAction(RoundAction{cs.Height, cs.Round, RoundActionCommit})
  888. } else {
  889. cs.queueAction(RoundAction{cs.Height, cs.Round, RoundActionTryFinalize})
  890. }
  891. }
  892. return added, index, err
  893. }
  894. if vote.Height+1 == cs.Height {
  895. return cs.LastCommits.Add(address, vote)
  896. }
  897. return false, 0, nil
  898. default:
  899. panic("Unknown vote type")
  900. }
  901. }
  902. func (cs *ConsensusState) stageBlock(block *types.Block, blockParts *types.PartSet) error {
  903. if block == nil {
  904. panic("Cannot stage nil block")
  905. }
  906. // Already staged?
  907. blockHash := block.Hash()
  908. if cs.stagedBlock != nil && len(blockHash) != 0 && bytes.Equal(cs.stagedBlock.Hash(), blockHash) {
  909. return nil
  910. }
  911. // Create a copy of the state for staging
  912. stateCopy := cs.state.Copy()
  913. // Commit block onto the copied state.
  914. // NOTE: Basic validation is done in state.AppendBlock().
  915. err := sm.ExecBlock(stateCopy, block, blockParts.Header())
  916. if err != nil {
  917. return err
  918. } else {
  919. cs.stagedBlock = block
  920. cs.stagedState = stateCopy
  921. return nil
  922. }
  923. }
  924. func (cs *ConsensusState) signAddVote(type_ byte, hash []byte, header types.PartSetHeader) *types.Vote {
  925. if cs.PrivValidator == nil || !cs.Validators.HasAddress(cs.PrivValidator.Address) {
  926. return nil
  927. }
  928. vote := &types.Vote{
  929. Height: cs.Height,
  930. Round: cs.Round,
  931. Type: type_,
  932. BlockHash: hash,
  933. BlockParts: header,
  934. }
  935. err := cs.PrivValidator.SignVote(vote)
  936. if err == nil {
  937. log.Info("Signed and added vote", "height", cs.Height, "round", cs.Round, "vote", vote)
  938. cs.addVote(cs.PrivValidator.Address, vote)
  939. return vote
  940. } else {
  941. log.Warn("Error signing vote", "height", cs.Height, "round", cs.Round, "vote", vote, "error", err)
  942. return nil
  943. }
  944. }
  945. // sign a Commit-Vote
  946. func (cs *ConsensusState) commitVoteBlock(block *types.Block, blockParts *types.PartSet) {
  947. // The proposal must be valid.
  948. if err := cs.stageBlock(block, blockParts); err != nil {
  949. // Prevent zombies.
  950. log.Warn("commitVoteBlock() an invalid block", "error", err)
  951. return
  952. }
  953. // Commit-vote.
  954. if cs.lastCommitVoteHeight < block.Height {
  955. cs.signAddVote(types.VoteTypeCommit, block.Hash(), blockParts.Header())
  956. cs.lastCommitVoteHeight = block.Height
  957. } else {
  958. log.Error("Duplicate commitVoteBlock() attempt", "lastCommitVoteHeight", cs.lastCommitVoteHeight, "types.Height", block.Height)
  959. }
  960. }
  961. // Save Block, save the +2/3 Commits we've seen,
  962. // and sign a Commit-Vote if we haven't already
  963. func (cs *ConsensusState) saveCommitVoteBlock(block *types.Block, blockParts *types.PartSet, commits *VoteSet) {
  964. // The proposal must be valid.
  965. if err := cs.stageBlock(block, blockParts); err != nil {
  966. // Prevent zombies.
  967. log.Warn("saveCommitVoteBlock() an invalid block", "error", err)
  968. return
  969. }
  970. // Save to blockStore.
  971. if cs.blockStore.Height() < block.Height {
  972. seenValidation := commits.MakeValidation()
  973. cs.blockStore.SaveBlock(block, blockParts, seenValidation)
  974. }
  975. // Save the state.
  976. cs.stagedState.Save()
  977. // Update mempool.
  978. cs.mempoolReactor.Mempool.ResetForBlockAndState(block, cs.stagedState)
  979. // Commit-vote if we haven't already.
  980. if cs.lastCommitVoteHeight < block.Height {
  981. cs.signAddVote(types.VoteTypeCommit, block.Hash(), blockParts.Header())
  982. cs.lastCommitVoteHeight = block.Height
  983. }
  984. }
  985. // implements events.Eventable
  986. func (cs *ConsensusState) SetEventSwitch(evsw *events.EventSwitch) {
  987. cs.evsw = evsw
  988. cs.state.SetEventSwitch(evsw)
  989. }
  990. //-----------------------------------------------------------------------------
  991. // total duration of given round
  992. func calcRoundDuration(round uint) time.Duration {
  993. return RoundDuration0 + RoundDurationDelta*time.Duration(round)
  994. }
  995. // startTime is when round zero started.
  996. func calcRoundStartTime(round uint, startTime time.Time) time.Time {
  997. return startTime.Add(RoundDuration0*time.Duration(round) +
  998. RoundDurationDelta*(time.Duration((int64(round)*int64(round)-int64(round))/2)))
  999. }
  1000. // calculates the current round given startTime of round zero.
  1001. // NOTE: round is zero if startTime is in the future.
  1002. func calcRound(startTime time.Time) uint {
  1003. now := time.Now()
  1004. if now.Before(startTime) {
  1005. return 0
  1006. }
  1007. // Start + D_0 * R + D_delta * (R^2 - R)/2 <= Now; find largest integer R.
  1008. // D_delta * R^2 + (2D_0 - D_delta) * R + 2(Start - Now) <= 0.
  1009. // AR^2 + BR + C <= 0; A = D_delta, B = (2_D0 - D_delta), C = 2(Start - Now).
  1010. // R = Floor((-B + Sqrt(B^2 - 4AC))/2A)
  1011. A := float64(RoundDurationDelta)
  1012. B := 2.0*float64(RoundDuration0) - float64(RoundDurationDelta)
  1013. C := 2.0 * float64(startTime.Sub(now))
  1014. R := math.Floor((-B + math.Sqrt(B*B-4.0*A*C)) / (2 * A))
  1015. if math.IsNaN(R) {
  1016. panic("Could not calc round, should not happen")
  1017. }
  1018. if R > math.MaxInt32 {
  1019. panic(Fmt("Could not calc round, round overflow: %v", R))
  1020. }
  1021. if R < 0 {
  1022. return 0
  1023. }
  1024. return uint(R)
  1025. }
  1026. // convenience
  1027. // NOTE: elapsedRatio can be negative if startTime is in the future.
  1028. func calcRoundInfo(startTime time.Time) (round uint, roundStartTime time.Time, RoundDuration time.Duration,
  1029. roundElapsed time.Duration, elapsedRatio float64) {
  1030. round = calcRound(startTime)
  1031. roundStartTime = calcRoundStartTime(round, startTime)
  1032. RoundDuration = calcRoundDuration(round)
  1033. roundElapsed = time.Now().Sub(roundStartTime)
  1034. elapsedRatio = float64(roundElapsed) / float64(RoundDuration)
  1035. return
  1036. }