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.

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