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.

1155 lines
37 KiB

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