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.

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