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.

1230 lines
39 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
  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. log.Debug("Block was locked")
  646. cs.signAddVote(types.VoteTypePrevote, cs.LockedBlock.Hash(), cs.LockedBlockParts.Header())
  647. return
  648. }
  649. // If ProposalBlock is nil, prevote nil.
  650. if cs.ProposalBlock == nil {
  651. log.Warn("ProposalBlock is nil")
  652. cs.signAddVote(types.VoteTypePrevote, nil, types.PartSetHeader{})
  653. return
  654. }
  655. // Try staging cs.ProposalBlock
  656. err := cs.stageBlock(cs.ProposalBlock, cs.ProposalBlockParts)
  657. if err != nil {
  658. // ProposalBlock is invalid, prevote nil.
  659. log.Warn("ProposalBlock is invalid", "error", err)
  660. cs.signAddVote(types.VoteTypePrevote, nil, types.PartSetHeader{})
  661. return
  662. }
  663. // Prevote cs.ProposalBlock
  664. cs.signAddVote(types.VoteTypePrevote, cs.ProposalBlock.Hash(), cs.ProposalBlockParts.Header())
  665. return
  666. }
  667. // Lock & Precommit the ProposalBlock if we have enough prevotes for it,
  668. // or unlock an existing lock if +2/3 of prevotes were nil.
  669. func (cs *ConsensusState) RunActionPrecommit(height uint, round uint) {
  670. cs.mtx.Lock()
  671. defer cs.mtx.Unlock()
  672. if cs.Height != height || cs.Round != round {
  673. panic(Fmt("RunActionPrecommit(%v/%v), expected %v/%v", height, round, cs.Height, cs.Round))
  674. }
  675. defer func() {
  676. cs.Step = RoundStepPrecommit
  677. cs.newStepCh <- cs.getRoundState()
  678. }()
  679. hash, partsHeader, ok := cs.Prevotes.TwoThirdsMajority()
  680. if !ok {
  681. // If we don't have two thirds of prevotes,
  682. // don't do anything at all.
  683. log.Info("Insufficient prevotes for precommit")
  684. return
  685. }
  686. // Remember this POL. (hash may be nil)
  687. cs.LockedPOL = cs.Prevotes.MakePOL()
  688. // If +2/3 prevoted nil. Just unlock.
  689. if len(hash) == 0 {
  690. if cs.LockedBlock == nil {
  691. log.Info("+2/3 prevoted for nil.")
  692. } else {
  693. log.Info("+2/3 prevoted for nil. Unlocking")
  694. cs.LockedBlock = nil
  695. cs.LockedBlockParts = nil
  696. }
  697. return
  698. }
  699. // If +2/3 prevoted for already locked block, precommit it.
  700. if cs.LockedBlock.HashesTo(hash) {
  701. log.Info("+2/3 prevoted locked block.")
  702. cs.signAddVote(types.VoteTypePrecommit, hash, partsHeader)
  703. return
  704. }
  705. // If +2/3 prevoted for cs.ProposalBlock, lock it and precommit it.
  706. if !cs.ProposalBlock.HashesTo(hash) {
  707. log.Warn("Proposal does not hash to +2/3 prevotes")
  708. // We don't have the block that validators prevoted.
  709. // Unlock if we're locked.
  710. cs.LockedBlock = nil
  711. cs.LockedBlockParts = nil
  712. return
  713. }
  714. // Validate the block.
  715. if err := cs.stageBlock(cs.ProposalBlock, cs.ProposalBlockParts); err != nil {
  716. // Prevent zombies.
  717. log.Warn("+2/3 prevoted for an invalid block", "error", err)
  718. return
  719. }
  720. cs.LockedBlock = cs.ProposalBlock
  721. cs.LockedBlockParts = cs.ProposalBlockParts
  722. cs.signAddVote(types.VoteTypePrecommit, hash, partsHeader)
  723. return
  724. }
  725. // Enter commit step. See the diagram for details.
  726. // There are two ways to enter this step:
  727. // * After the Precommit step with +2/3 precommits, or,
  728. // * Upon +2/3 commits regardless of current step
  729. // Either way this action is run at most once per round.
  730. func (cs *ConsensusState) RunActionCommit(height uint) {
  731. cs.mtx.Lock()
  732. defer cs.mtx.Unlock()
  733. if cs.Height != height {
  734. panic(Fmt("RunActionCommit(%v), expected %v", height, cs.Height))
  735. }
  736. defer func() {
  737. cs.Step = RoundStepCommit
  738. cs.newStepCh <- cs.getRoundState()
  739. }()
  740. // Sanity check.
  741. // There are two ways to enter:
  742. // 1. +2/3 precommits at the end of RoundStepPrecommit
  743. // 2. +2/3 commits at any time
  744. hash, partsHeader, ok := cs.Precommits.TwoThirdsMajority()
  745. if !ok {
  746. hash, partsHeader, ok = cs.Commits.TwoThirdsMajority()
  747. if !ok {
  748. panic("RunActionCommit() expects +2/3 precommits or commits")
  749. }
  750. }
  751. // Clear the Locked* fields and use cs.Proposed*
  752. if cs.LockedBlock.HashesTo(hash) {
  753. cs.ProposalBlock = cs.LockedBlock
  754. cs.ProposalBlockParts = cs.LockedBlockParts
  755. cs.LockedBlock = nil
  756. cs.LockedBlockParts = nil
  757. cs.LockedPOL = nil
  758. }
  759. // If we don't have the block being committed, set up to get it.
  760. if !cs.ProposalBlock.HashesTo(hash) {
  761. if !cs.ProposalBlockParts.HasHeader(partsHeader) {
  762. // We're getting the wrong block.
  763. // Set up ProposalBlockParts and keep waiting.
  764. cs.ProposalBlock = nil
  765. cs.ProposalBlockParts = types.NewPartSetFromHeader(partsHeader)
  766. } else {
  767. // We just need to keep waiting.
  768. }
  769. } else {
  770. // We have the block, so sign a Commit-vote.
  771. cs.commitVoteBlock(cs.ProposalBlock, cs.ProposalBlockParts)
  772. }
  773. // If we have the block AND +2/3 commits, queue RoundActionTryFinalize.
  774. // Round will immediately become finalized.
  775. if cs.ProposalBlock.HashesTo(hash) && cs.Commits.HasTwoThirdsMajority() {
  776. cs.queueAction(RoundAction{cs.Height, cs.Round, RoundActionTryFinalize})
  777. }
  778. }
  779. // Returns true if Finalize happened, which increments height && sets
  780. // the step to RoundStepNewHeight (or RoundStepNewRound, but probably not).
  781. func (cs *ConsensusState) TryFinalizeCommit(height uint) bool {
  782. cs.mtx.Lock()
  783. defer cs.mtx.Unlock()
  784. if cs.Height != height {
  785. panic(Fmt("TryFinalizeCommit(%v), expected %v", height, cs.Height))
  786. }
  787. if cs.Step == RoundStepCommit &&
  788. cs.Commits.HasTwoThirdsMajority() &&
  789. cs.ProposalBlockParts.IsComplete() {
  790. // Sanity check
  791. if cs.ProposalBlock == nil {
  792. panic(Fmt("Expected ProposalBlock to exist"))
  793. }
  794. hash, header, _ := cs.Commits.TwoThirdsMajority()
  795. if !cs.ProposalBlock.HashesTo(hash) {
  796. // XXX See: https://github.com/tendermint/tendermint/issues/44
  797. panic(Fmt("Expected ProposalBlock to hash to commit hash. Expected %X, got %X", hash, cs.ProposalBlock.Hash()))
  798. }
  799. if !cs.ProposalBlockParts.HasHeader(header) {
  800. panic(Fmt("Expected ProposalBlockParts header to be commit header"))
  801. }
  802. err := cs.stageBlock(cs.ProposalBlock, cs.ProposalBlockParts)
  803. if err == nil {
  804. log.Debug(Fmt("Finalizing commit of block: %v", cs.ProposalBlock))
  805. // We have the block, so save/stage/sign-commit-vote.
  806. cs.saveCommitVoteBlock(cs.ProposalBlock, cs.ProposalBlockParts, cs.Commits)
  807. // Increment height.
  808. cs.updateToState(cs.stagedState, true)
  809. // cs.Step is now RoundStepNewHeight or RoundStepNewRound
  810. cs.newStepCh <- cs.getRoundState()
  811. return true
  812. } else {
  813. // Prevent zombies.
  814. // TODO: Does this ever happen?
  815. panic(Fmt("+2/3 committed an invalid block: %v", err))
  816. }
  817. }
  818. return false
  819. }
  820. //-----------------------------------------------------------------------------
  821. func (cs *ConsensusState) SetProposal(proposal *Proposal) error {
  822. cs.mtx.Lock()
  823. defer cs.mtx.Unlock()
  824. // Already have one
  825. if cs.Proposal != nil {
  826. return nil
  827. }
  828. // Does not apply
  829. if proposal.Height != cs.Height || proposal.Round != cs.Round {
  830. return nil
  831. }
  832. // We don't care about the proposal if we're already in RoundStepCommit.
  833. if cs.Step == RoundStepCommit {
  834. return nil
  835. }
  836. // Verify signature
  837. if !cs.Validators.Proposer().PubKey.VerifyBytes(account.SignBytes(proposal), proposal.Signature) {
  838. return ErrInvalidProposalSignature
  839. }
  840. cs.Proposal = proposal
  841. cs.ProposalBlockParts = types.NewPartSetFromHeader(proposal.BlockParts)
  842. cs.ProposalPOLParts = types.NewPartSetFromHeader(proposal.POLParts)
  843. return nil
  844. }
  845. // NOTE: block is not necessarily valid.
  846. // NOTE: This function may increment the height.
  847. func (cs *ConsensusState) AddProposalBlockPart(height uint, round uint, part *types.Part) (added bool, err error) {
  848. cs.mtx.Lock()
  849. defer cs.mtx.Unlock()
  850. // Blocks might be reused, so round mismatch is OK
  851. if cs.Height != height {
  852. return false, nil
  853. }
  854. // We're not expecting a block part.
  855. if cs.ProposalBlockParts == nil {
  856. return false, nil // TODO: bad peer? Return error?
  857. }
  858. added, err = cs.ProposalBlockParts.AddPart(part)
  859. if err != nil {
  860. return added, err
  861. }
  862. if added && cs.ProposalBlockParts.IsComplete() {
  863. var n int64
  864. var err error
  865. cs.ProposalBlock = binary.ReadBinary(&types.Block{}, cs.ProposalBlockParts.GetReader(), &n, &err).(*types.Block)
  866. log.Debug("Received complete proposal", "hash", cs.ProposalBlock.Hash())
  867. // If we're already in the commit step, try to finalize round.
  868. if cs.Step == RoundStepCommit {
  869. cs.queueAction(RoundAction{cs.Height, cs.Round, RoundActionTryFinalize})
  870. }
  871. // XXX If POL is valid, consider unlocking.
  872. return true, err
  873. }
  874. return true, nil
  875. }
  876. // NOTE: POL is not necessarily valid.
  877. func (cs *ConsensusState) AddProposalPOLPart(height uint, round uint, part *types.Part) (added bool, err error) {
  878. cs.mtx.Lock()
  879. defer cs.mtx.Unlock()
  880. if cs.Height != height || cs.Round != round {
  881. return false, nil
  882. }
  883. // We're not expecting a POL part.
  884. if cs.ProposalPOLParts == nil {
  885. return false, nil // TODO: bad peer? Return error?
  886. }
  887. added, err = cs.ProposalPOLParts.AddPart(part)
  888. if err != nil {
  889. return added, err
  890. }
  891. if added && cs.ProposalPOLParts.IsComplete() {
  892. var n int64
  893. var err error
  894. cs.ProposalPOL = binary.ReadBinary(&POL{}, cs.ProposalPOLParts.GetReader(), &n, &err).(*POL)
  895. return true, err
  896. }
  897. return true, nil
  898. }
  899. func (cs *ConsensusState) AddVote(address []byte, vote *types.Vote) (added bool, index uint, err error) {
  900. cs.mtx.Lock()
  901. defer cs.mtx.Unlock()
  902. return cs.addVote(address, vote)
  903. }
  904. //-----------------------------------------------------------------------------
  905. func (cs *ConsensusState) addVote(address []byte, vote *types.Vote) (added bool, index uint, err error) {
  906. switch vote.Type {
  907. case types.VoteTypePrevote:
  908. // Prevotes checks for height+round match.
  909. added, index, err = cs.Prevotes.Add(address, vote)
  910. if added {
  911. log.Debug(Fmt("Added prevote: %v", cs.Prevotes.StringShort()))
  912. }
  913. return
  914. case types.VoteTypePrecommit:
  915. // Precommits checks for height+round match.
  916. added, index, err = cs.Precommits.Add(address, vote)
  917. if added {
  918. log.Debug(Fmt("Added precommit: %v", cs.Precommits.StringShort()))
  919. }
  920. return
  921. case types.VoteTypeCommit:
  922. if vote.Height == cs.Height {
  923. // No need to check if vote.Round < cs.Round ...
  924. // Prevotes && Precommits already checks that.
  925. cs.Prevotes.Add(address, vote)
  926. cs.Precommits.Add(address, vote)
  927. added, index, err = cs.Commits.Add(address, vote)
  928. if added && cs.Commits.HasTwoThirdsMajority() && cs.CommitTime.IsZero() {
  929. cs.CommitTime = time.Now()
  930. log.Debug(Fmt("Set CommitTime to %v", cs.CommitTime))
  931. if cs.Step < RoundStepCommit {
  932. cs.queueAction(RoundAction{cs.Height, cs.Round, RoundActionCommit})
  933. } else {
  934. cs.queueAction(RoundAction{cs.Height, cs.Round, RoundActionTryFinalize})
  935. }
  936. }
  937. if added {
  938. log.Debug(Fmt("Added commit: %v\nprecommits: %v\nprevotes: %v",
  939. cs.Commits.StringShort(),
  940. cs.Precommits.StringShort(),
  941. cs.Prevotes.StringShort()))
  942. }
  943. return
  944. }
  945. if vote.Height+1 == cs.Height {
  946. added, index, err = cs.LastCommits.Add(address, vote)
  947. log.Debug(Fmt("Added lastCommits: %v", cs.LastCommits.StringShort()))
  948. return
  949. }
  950. return false, 0, nil
  951. default:
  952. panic("Unknown vote type")
  953. }
  954. }
  955. func (cs *ConsensusState) stageBlock(block *types.Block, blockParts *types.PartSet) error {
  956. if block == nil {
  957. panic("Cannot stage nil block")
  958. }
  959. // Already staged?
  960. blockHash := block.Hash()
  961. if cs.stagedBlock != nil && len(blockHash) != 0 && bytes.Equal(cs.stagedBlock.Hash(), blockHash) {
  962. return nil
  963. }
  964. // Create a copy of the state for staging
  965. stateCopy := cs.state.Copy()
  966. // reset the event cache and pass it into the state
  967. cs.evc = events.NewEventCache(cs.evsw)
  968. stateCopy.SetFireable(cs.evc)
  969. // Commit block onto the copied state.
  970. // NOTE: Basic validation is done in state.AppendBlock().
  971. err := sm.ExecBlock(stateCopy, block, blockParts.Header())
  972. if err != nil {
  973. return err
  974. } else {
  975. cs.stagedBlock = block
  976. cs.stagedState = stateCopy
  977. return nil
  978. }
  979. }
  980. func (cs *ConsensusState) signAddVote(type_ byte, hash []byte, header types.PartSetHeader) *types.Vote {
  981. if cs.privValidator == nil || !cs.Validators.HasAddress(cs.privValidator.Address) {
  982. return nil
  983. }
  984. vote := &types.Vote{
  985. Height: cs.Height,
  986. Round: cs.Round,
  987. Type: type_,
  988. BlockHash: hash,
  989. BlockParts: header,
  990. }
  991. err := cs.privValidator.SignVote(vote)
  992. if err == nil {
  993. log.Info("Signed and added vote", "height", cs.Height, "round", cs.Round, "vote", vote)
  994. cs.addVote(cs.privValidator.Address, vote)
  995. return vote
  996. } else {
  997. log.Warn("Error signing vote", "height", cs.Height, "round", cs.Round, "vote", vote, "error", err)
  998. return nil
  999. }
  1000. }
  1001. // sign a Commit-Vote
  1002. func (cs *ConsensusState) commitVoteBlock(block *types.Block, blockParts *types.PartSet) {
  1003. // The proposal must be valid.
  1004. if err := cs.stageBlock(block, blockParts); err != nil {
  1005. // Prevent zombies.
  1006. log.Warn("commitVoteBlock() an invalid block", "error", err)
  1007. return
  1008. }
  1009. // Commit-vote.
  1010. if cs.lastCommitVoteHeight < block.Height {
  1011. cs.signAddVote(types.VoteTypeCommit, block.Hash(), blockParts.Header())
  1012. cs.lastCommitVoteHeight = block.Height
  1013. } else {
  1014. log.Error("Duplicate commitVoteBlock() attempt", "lastCommitVoteHeight", cs.lastCommitVoteHeight, "types.Height", block.Height)
  1015. }
  1016. }
  1017. // Save Block, save the +2/3 Commits we've seen,
  1018. // and sign a Commit-Vote if we haven't already
  1019. func (cs *ConsensusState) saveCommitVoteBlock(block *types.Block, blockParts *types.PartSet, commits *VoteSet) {
  1020. // The proposal must be valid.
  1021. if err := cs.stageBlock(block, blockParts); err != nil {
  1022. // Prevent zombies.
  1023. log.Warn("saveCommitVoteBlock() an invalid block", "error", err)
  1024. return
  1025. }
  1026. // Save to blockStore.
  1027. if cs.blockStore.Height() < block.Height {
  1028. seenValidation := commits.MakeValidation()
  1029. cs.blockStore.SaveBlock(block, blockParts, seenValidation)
  1030. }
  1031. // Save the state.
  1032. cs.stagedState.Save()
  1033. // Update mempool.
  1034. cs.mempoolReactor.Mempool.ResetForBlockAndState(block, cs.stagedState)
  1035. // Commit-vote if we haven't already.
  1036. if cs.lastCommitVoteHeight < block.Height {
  1037. cs.signAddVote(types.VoteTypeCommit, block.Hash(), blockParts.Header())
  1038. cs.lastCommitVoteHeight = block.Height
  1039. }
  1040. }
  1041. // implements events.Eventable
  1042. func (cs *ConsensusState) SetFireable(evsw events.Fireable) {
  1043. cs.evsw = evsw
  1044. }
  1045. //-----------------------------------------------------------------------------
  1046. // total duration of given round
  1047. func calcRoundDuration(round uint) time.Duration {
  1048. return RoundDuration0 + RoundDurationDelta*time.Duration(round)
  1049. }
  1050. // startTime is when round zero started.
  1051. func calcRoundStartTime(round uint, startTime time.Time) time.Time {
  1052. return startTime.Add(RoundDuration0*time.Duration(round) +
  1053. RoundDurationDelta*(time.Duration((int64(round)*int64(round)-int64(round))/2)))
  1054. }
  1055. // calculates the current round given startTime of round zero.
  1056. // NOTE: round is zero if startTime is in the future.
  1057. func calcRound(startTime time.Time) uint {
  1058. now := time.Now()
  1059. if now.Before(startTime) {
  1060. return 0
  1061. }
  1062. // Start + D_0 * R + D_delta * (R^2 - R)/2 <= Now; find largest integer R.
  1063. // D_delta * R^2 + (2D_0 - D_delta) * R + 2(Start - Now) <= 0.
  1064. // AR^2 + BR + C <= 0; A = D_delta, B = (2_D0 - D_delta), C = 2(Start - Now).
  1065. // R = Floor((-B + Sqrt(B^2 - 4AC))/2A)
  1066. A := float64(RoundDurationDelta)
  1067. B := 2.0*float64(RoundDuration0) - float64(RoundDurationDelta)
  1068. C := 2.0 * float64(startTime.Sub(now))
  1069. R := math.Floor((-B + math.Sqrt(B*B-4.0*A*C)) / (2 * A))
  1070. if math.IsNaN(R) {
  1071. panic("Could not calc round, should not happen")
  1072. }
  1073. if R > math.MaxInt32 {
  1074. panic(Fmt("Could not calc round, round overflow: %v", R))
  1075. }
  1076. if R < 0 {
  1077. return 0
  1078. }
  1079. return uint(R)
  1080. }
  1081. // convenience
  1082. // NOTE: elapsedRatio can be negative if startTime is in the future.
  1083. func calcRoundInfo(startTime time.Time) (round uint, roundStartTime time.Time, RoundDuration time.Duration,
  1084. roundElapsed time.Duration, elapsedRatio float64) {
  1085. round = calcRound(startTime)
  1086. roundStartTime = calcRoundStartTime(round, startTime)
  1087. RoundDuration = calcRoundDuration(round)
  1088. roundElapsed = time.Now().Sub(roundStartTime)
  1089. elapsedRatio = float64(roundElapsed) / float64(RoundDuration)
  1090. return
  1091. }