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.

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