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.

1153 lines
36 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
  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/block"
  59. . "github.com/tendermint/tendermint/common"
  60. "github.com/tendermint/tendermint/config"
  61. . "github.com/tendermint/tendermint/consensus/types"
  62. "github.com/tendermint/tendermint/mempool"
  63. "github.com/tendermint/tendermint/state"
  64. )
  65. const (
  66. roundDuration0 = 60 * time.Second // The first round is 60 seconds long.
  67. roundDurationDelta = 15 * 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 *state.ValidatorSet
  151. Proposal *Proposal
  152. ProposalBlock *Block
  153. ProposalBlockParts *PartSet
  154. ProposalPOL *POL
  155. ProposalPOLParts *PartSet
  156. LockedBlock *Block
  157. LockedBlockParts *PartSet
  158. LockedPOL *POL // Rarely needed, so no LockedPOLParts.
  159. Prevotes *VoteSet
  160. Precommits *VoteSet
  161. Commits *VoteSet
  162. LastCommits *VoteSet
  163. PrivValidator *state.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 *BlockStore
  210. mempoolReactor *mempool.MempoolReactor
  211. runActionCh chan RoundAction
  212. newStepCh chan *RoundState
  213. mtx sync.Mutex
  214. RoundState
  215. state *state.State // State until height-1.
  216. stagedBlock *Block // Cache last staged block.
  217. stagedState *state.State // Cache result of staged block.
  218. lastCommitVoteHeight uint // Last called commitVoteBlock() or saveCommitVoteBlock() on.
  219. }
  220. func NewConsensusState(state *state.State, blockStore *BlockStore, mempoolReactor *mempool.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() *state.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.Info("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 *state.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, VoteTypePrevote, validators)
  433. cs.Precommits = NewVoteSet(height, 0, VoteTypePrecommit, validators)
  434. cs.LastCommits = cs.Commits
  435. cs.Commits = NewVoteSet(height, 0, 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 := &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, VoteTypePrevote, validators)
  477. cs.Prevotes.AddFromCommits(cs.Commits)
  478. cs.Precommits = NewVoteSet(cs.Height, round, VoteTypePrecommit, validators)
  479. cs.Precommits.AddFromCommits(cs.Commits)
  480. }
  481. func (cs *ConsensusState) SetPrivValidator(priv *state.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 *Block
  523. var blockParts *PartSet
  524. var pol *POL
  525. var polParts *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 *Validation
  535. if cs.Height == 1 {
  536. // We're creating a proposal for the first block.
  537. // The validation is empty.
  538. validation = &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 = &Block{
  553. Header: &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: &Data{
  565. Txs: txs,
  566. },
  567. }
  568. // Set the block.Header.StateHash.
  569. // TODO: we could cache the resulting state to cs.stagedState.
  570. // TODO: This is confusing, not clear that we're mutating block.
  571. cs.state.Copy().AppendBlock(block, PartSetHeader{}, false)
  572. blockParts = NewPartSetFromData(BinaryBytes(block))
  573. pol = cs.LockedPOL // If exists, is a PoUnlock.
  574. }
  575. if pol != nil {
  576. polParts = NewPartSetFromData(BinaryBytes(pol))
  577. }
  578. // Make proposal
  579. proposal := NewProposal(cs.Height, cs.Round, blockParts.Header(), polParts.Header())
  580. err := cs.PrivValidator.SignProposal(proposal)
  581. if err == nil {
  582. log.Info("Signed and set proposal", "height", cs.Height, "round", cs.Round, "proposal", proposal)
  583. log.Debug(Fmt("Signed and set proposal block: %v", block))
  584. // Set fields
  585. cs.Proposal = proposal
  586. cs.ProposalBlock = block
  587. cs.ProposalBlockParts = blockParts
  588. cs.ProposalPOL = pol
  589. cs.ProposalPOLParts = polParts
  590. } else {
  591. log.Warn("Error signing proposal", "height", cs.Height, "round", cs.Round, "error", err)
  592. }
  593. }
  594. // Prevote for LockedBlock if we're locked, or ProposealBlock if valid.
  595. // Otherwise vote nil.
  596. func (cs *ConsensusState) RunActionPrevote(height uint, round uint) {
  597. cs.mtx.Lock()
  598. defer cs.mtx.Unlock()
  599. if cs.Height != height || cs.Round != round {
  600. panic(Fmt("RunActionPrevote(%v/%v), expected %v/%v", height, round, cs.Height, cs.Round))
  601. }
  602. defer func() {
  603. cs.Step = RoundStepPrevote
  604. cs.newStepCh <- cs.getRoundState()
  605. }()
  606. // If a block is locked, prevote that.
  607. if cs.LockedBlock != nil {
  608. cs.signAddVote(VoteTypePrevote, cs.LockedBlock.Hash(), cs.LockedBlockParts.Header())
  609. return
  610. }
  611. // If ProposalBlock is nil, prevote nil.
  612. if cs.ProposalBlock == nil {
  613. log.Warn("ProposalBlock is nil")
  614. cs.signAddVote(VoteTypePrevote, nil, PartSetHeader{})
  615. return
  616. }
  617. // Try staging cs.ProposalBlock
  618. err := cs.stageBlock(cs.ProposalBlock, cs.ProposalBlockParts)
  619. if err != nil {
  620. // ProposalBlock is invalid, prevote nil.
  621. log.Warn("ProposalBlock is invalid", "error", err)
  622. cs.signAddVote(VoteTypePrevote, nil, PartSetHeader{})
  623. return
  624. }
  625. // Prevote cs.ProposalBlock
  626. cs.signAddVote(VoteTypePrevote, cs.ProposalBlock.Hash(), cs.ProposalBlockParts.Header())
  627. return
  628. }
  629. // Lock & Precommit the ProposalBlock if we have enough prevotes for it,
  630. // or unlock an existing lock if +2/3 of prevotes were nil.
  631. func (cs *ConsensusState) RunActionPrecommit(height uint, round uint) {
  632. cs.mtx.Lock()
  633. defer cs.mtx.Unlock()
  634. if cs.Height != height || cs.Round != round {
  635. panic(Fmt("RunActionPrecommit(%v/%v), expected %v/%v", height, round, cs.Height, cs.Round))
  636. }
  637. defer func() {
  638. cs.Step = RoundStepPrecommit
  639. cs.newStepCh <- cs.getRoundState()
  640. }()
  641. hash, partsHeader, ok := cs.Prevotes.TwoThirdsMajority()
  642. if !ok {
  643. // If we don't have two thirds of prevotes,
  644. // don't do anything at all.
  645. return
  646. }
  647. // Remember this POL. (hash may be nil)
  648. cs.LockedPOL = cs.Prevotes.MakePOL()
  649. // If +2/3 prevoted nil. Just unlock.
  650. if len(hash) == 0 {
  651. cs.LockedBlock = nil
  652. cs.LockedBlockParts = nil
  653. return
  654. }
  655. // If +2/3 prevoted for already locked block, precommit it.
  656. if cs.LockedBlock.HashesTo(hash) {
  657. cs.signAddVote(VoteTypePrecommit, hash, partsHeader)
  658. return
  659. }
  660. // If +2/3 prevoted for cs.ProposalBlock, lock it and precommit it.
  661. if cs.ProposalBlock.HashesTo(hash) {
  662. // Validate the block.
  663. if err := cs.stageBlock(cs.ProposalBlock, cs.ProposalBlockParts); err != nil {
  664. // Prevent zombies.
  665. log.Warn("+2/3 prevoted for an invalid block", "error", err)
  666. return
  667. }
  668. cs.LockedBlock = cs.ProposalBlock
  669. cs.LockedBlockParts = cs.ProposalBlockParts
  670. cs.signAddVote(VoteTypePrecommit, hash, partsHeader)
  671. return
  672. }
  673. // We don't have the block that validators prevoted.
  674. // Unlock if we're locked.
  675. cs.LockedBlock = nil
  676. cs.LockedBlockParts = nil
  677. return
  678. }
  679. // Enter commit step. See the diagram for details.
  680. // There are two ways to enter this step:
  681. // * After the Precommit step with +2/3 precommits, or,
  682. // * Upon +2/3 commits regardless of current step
  683. // Either way this action is run at most once per round.
  684. func (cs *ConsensusState) RunActionCommit(height uint) {
  685. cs.mtx.Lock()
  686. defer cs.mtx.Unlock()
  687. if cs.Height != height {
  688. panic(Fmt("RunActionCommit(%v), expected %v", height, cs.Height))
  689. }
  690. defer func() {
  691. cs.Step = RoundStepCommit
  692. cs.newStepCh <- cs.getRoundState()
  693. }()
  694. // Sanity check.
  695. // There are two ways to enter:
  696. // 1. +2/3 precommits at the end of RoundStepPrecommit
  697. // 2. +2/3 commits at any time
  698. hash, partsHeader, ok := cs.Precommits.TwoThirdsMajority()
  699. if !ok {
  700. hash, partsHeader, ok = cs.Commits.TwoThirdsMajority()
  701. if !ok {
  702. panic("RunActionCommit() expects +2/3 precommits or commits")
  703. }
  704. }
  705. // Clear the Locked* fields and use cs.Proposed*
  706. if cs.LockedBlock.HashesTo(hash) {
  707. cs.ProposalBlock = cs.LockedBlock
  708. cs.ProposalBlockParts = cs.LockedBlockParts
  709. cs.LockedBlock = nil
  710. cs.LockedBlockParts = nil
  711. cs.LockedPOL = nil
  712. }
  713. // If we don't have the block being committed, set up to get it.
  714. if !cs.ProposalBlock.HashesTo(hash) {
  715. if !cs.ProposalBlockParts.HasHeader(partsHeader) {
  716. // We're getting the wrong block.
  717. // Set up ProposalBlockParts and keep waiting.
  718. cs.ProposalBlock = nil
  719. cs.ProposalBlockParts = NewPartSetFromHeader(partsHeader)
  720. } else {
  721. // We just need to keep waiting.
  722. }
  723. } else {
  724. // We have the block, so sign a Commit-vote.
  725. cs.commitVoteBlock(cs.ProposalBlock, cs.ProposalBlockParts)
  726. }
  727. // If we have the block AND +2/3 commits, queue RoundActionTryFinalize.
  728. // Round will immediately become finalized.
  729. if cs.ProposalBlock.HashesTo(hash) && cs.Commits.HasTwoThirdsMajority() {
  730. cs.queueAction(RoundAction{cs.Height, cs.Round, RoundActionTryFinalize})
  731. }
  732. }
  733. // Returns true if Finalize happened, which increments height && sets
  734. // the step to RoundStepNewHeight (or RoundStepNewRound, but probably not).
  735. func (cs *ConsensusState) TryFinalizeCommit(height uint) bool {
  736. cs.mtx.Lock()
  737. defer cs.mtx.Unlock()
  738. if cs.Height != height {
  739. panic(Fmt("TryFinalizeCommit(%v), expected %v", height, cs.Height))
  740. }
  741. if cs.Step == RoundStepCommit &&
  742. cs.Commits.HasTwoThirdsMajority() &&
  743. cs.ProposalBlockParts.IsComplete() {
  744. // Sanity check
  745. if cs.ProposalBlock == nil {
  746. panic(Fmt("Expected ProposalBlock to exist"))
  747. }
  748. hash, header, _ := cs.Commits.TwoThirdsMajority()
  749. if !cs.ProposalBlock.HashesTo(hash) {
  750. panic(Fmt("Expected ProposalBlock to hash to commit hash. Expected %X, got %X", hash, cs.ProposalBlock.Hash()))
  751. }
  752. if !cs.ProposalBlockParts.HasHeader(header) {
  753. panic(Fmt("Expected ProposalBlockParts header to be commit header"))
  754. }
  755. err := cs.stageBlock(cs.ProposalBlock, cs.ProposalBlockParts)
  756. if err == nil {
  757. log.Debug(Fmt("Finalizing commit of block: %v", cs.ProposalBlock))
  758. // We have the block, so save/stage/sign-commit-vote.
  759. cs.saveCommitVoteBlock(cs.ProposalBlock, cs.ProposalBlockParts, cs.Commits)
  760. // Increment height.
  761. cs.updateToState(cs.stagedState)
  762. // cs.Step is now RoundStepNewHeight or RoundStepNewRound
  763. cs.newStepCh <- cs.getRoundState()
  764. return true
  765. } else {
  766. // Prevent zombies.
  767. // TODO: Does this ever happen?
  768. panic(Fmt("+2/3 committed an invalid block: %v", err))
  769. }
  770. }
  771. return false
  772. }
  773. //-----------------------------------------------------------------------------
  774. func (cs *ConsensusState) SetProposal(proposal *Proposal) error {
  775. cs.mtx.Lock()
  776. defer cs.mtx.Unlock()
  777. // Already have one
  778. if cs.Proposal != nil {
  779. return nil
  780. }
  781. // Does not apply
  782. if proposal.Height != cs.Height || proposal.Round != cs.Round {
  783. return nil
  784. }
  785. // We don't care about the proposal if we're already in RoundStepCommit.
  786. if cs.Step == RoundStepCommit {
  787. return nil
  788. }
  789. // Verify signature
  790. if !cs.Validators.Proposer().PubKey.VerifyBytes(SignBytes(proposal), proposal.Signature) {
  791. return ErrInvalidProposalSignature
  792. }
  793. cs.Proposal = proposal
  794. cs.ProposalBlockParts = NewPartSetFromHeader(proposal.BlockParts)
  795. cs.ProposalPOLParts = NewPartSetFromHeader(proposal.POLParts)
  796. return nil
  797. }
  798. // NOTE: block is not necessarily valid.
  799. // NOTE: This function may increment the height.
  800. func (cs *ConsensusState) AddProposalBlockPart(height uint, round uint, part *Part) (added bool, err error) {
  801. cs.mtx.Lock()
  802. defer cs.mtx.Unlock()
  803. // Blocks might be reused, so round mismatch is OK
  804. if cs.Height != height {
  805. return false, nil
  806. }
  807. // We're not expecting a block part.
  808. if cs.ProposalBlockParts == nil {
  809. return false, nil // TODO: bad peer? Return error?
  810. }
  811. added, err = cs.ProposalBlockParts.AddPart(part)
  812. if err != nil {
  813. return added, err
  814. }
  815. if added && cs.ProposalBlockParts.IsComplete() {
  816. var n int64
  817. var err error
  818. cs.ProposalBlock = ReadBinary(&Block{}, cs.ProposalBlockParts.GetReader(), &n, &err).(*Block)
  819. // If we're already in the commit step, try to finalize round.
  820. if cs.Step == RoundStepCommit {
  821. cs.queueAction(RoundAction{cs.Height, cs.Round, RoundActionTryFinalize})
  822. }
  823. // XXX If POL is valid, consider unlocking.
  824. return true, err
  825. }
  826. return true, nil
  827. }
  828. // NOTE: POL is not necessarily valid.
  829. func (cs *ConsensusState) AddProposalPOLPart(height uint, round uint, part *Part) (added bool, err error) {
  830. cs.mtx.Lock()
  831. defer cs.mtx.Unlock()
  832. if cs.Height != height || cs.Round != round {
  833. return false, nil
  834. }
  835. // We're not expecting a POL part.
  836. if cs.ProposalPOLParts == nil {
  837. return false, nil // TODO: bad peer? Return error?
  838. }
  839. added, err = cs.ProposalPOLParts.AddPart(part)
  840. if err != nil {
  841. return added, err
  842. }
  843. if added && cs.ProposalPOLParts.IsComplete() {
  844. var n int64
  845. var err error
  846. cs.ProposalPOL = ReadBinary(&POL{}, cs.ProposalPOLParts.GetReader(), &n, &err).(*POL)
  847. return true, err
  848. }
  849. return true, nil
  850. }
  851. func (cs *ConsensusState) AddVote(address []byte, vote *Vote) (added bool, index uint, err error) {
  852. cs.mtx.Lock()
  853. defer cs.mtx.Unlock()
  854. return cs.addVote(address, vote)
  855. }
  856. //-----------------------------------------------------------------------------
  857. func (cs *ConsensusState) addVote(address []byte, vote *Vote) (added bool, index uint, err error) {
  858. switch vote.Type {
  859. case VoteTypePrevote:
  860. // Prevotes checks for height+round match.
  861. return cs.Prevotes.Add(address, vote)
  862. case VoteTypePrecommit:
  863. // Precommits checks for height+round match.
  864. return cs.Precommits.Add(address, vote)
  865. case VoteTypeCommit:
  866. if vote.Height == cs.Height {
  867. // No need to check if vote.Round < cs.Round ...
  868. // Prevotes && Precommits already checks that.
  869. cs.Prevotes.Add(address, vote)
  870. cs.Precommits.Add(address, vote)
  871. added, index, err = cs.Commits.Add(address, vote)
  872. if added && cs.Commits.HasTwoThirdsMajority() && cs.CommitTime.IsZero() {
  873. cs.CommitTime = time.Now()
  874. log.Debug(Fmt("Set CommitTime to %v", cs.CommitTime))
  875. if cs.Step < RoundStepCommit {
  876. cs.queueAction(RoundAction{cs.Height, cs.Round, RoundActionCommit})
  877. } else {
  878. cs.queueAction(RoundAction{cs.Height, cs.Round, RoundActionTryFinalize})
  879. }
  880. }
  881. return added, index, err
  882. }
  883. if vote.Height+1 == cs.Height {
  884. return cs.LastCommits.Add(address, vote)
  885. }
  886. return false, 0, nil
  887. default:
  888. panic("Unknown vote type")
  889. }
  890. }
  891. func (cs *ConsensusState) stageBlock(block *Block, blockParts *PartSet) error {
  892. if block == nil {
  893. panic("Cannot stage nil block")
  894. }
  895. // Already staged?
  896. if cs.stagedBlock == block {
  897. return nil
  898. }
  899. // Create a copy of the state for staging
  900. stateCopy := cs.state.Copy()
  901. // Commit block onto the copied state.
  902. // NOTE: Basic validation is done in state.AppendBlock().
  903. err := stateCopy.AppendBlock(block, blockParts.Header(), true)
  904. if err != nil {
  905. return err
  906. } else {
  907. cs.stagedBlock = block
  908. cs.stagedState = stateCopy
  909. return nil
  910. }
  911. }
  912. func (cs *ConsensusState) signAddVote(type_ byte, hash []byte, header PartSetHeader) *Vote {
  913. if cs.PrivValidator == nil || !cs.Validators.HasAddress(cs.PrivValidator.Address) {
  914. return nil
  915. }
  916. vote := &Vote{
  917. Height: cs.Height,
  918. Round: cs.Round,
  919. Type: type_,
  920. BlockHash: hash,
  921. BlockParts: header,
  922. }
  923. err := cs.PrivValidator.SignVote(vote)
  924. if err == nil {
  925. log.Info("Signed and added vote", "height", cs.Height, "round", cs.Round, "vote", vote)
  926. cs.addVote(cs.PrivValidator.Address, vote)
  927. return vote
  928. } else {
  929. log.Warn("Error signing vote", "height", cs.Height, "round", cs.Round, "vote", vote, "error", err)
  930. return nil
  931. }
  932. }
  933. // sign a Commit-Vote
  934. func (cs *ConsensusState) commitVoteBlock(block *Block, blockParts *PartSet) {
  935. // The proposal must be valid.
  936. if err := cs.stageBlock(block, blockParts); err != nil {
  937. // Prevent zombies.
  938. log.Warn("commitVoteBlock() an invalid block", "error", err)
  939. return
  940. }
  941. // Commit-vote.
  942. if cs.lastCommitVoteHeight < block.Height {
  943. cs.signAddVote(VoteTypeCommit, block.Hash(), blockParts.Header())
  944. cs.lastCommitVoteHeight = block.Height
  945. } else {
  946. log.Error("Duplicate commitVoteBlock() attempt", "lastCommitVoteHeight", cs.lastCommitVoteHeight, "block.Height", block.Height)
  947. }
  948. }
  949. // Save Block, save the +2/3 Commits we've seen,
  950. // and sign a Commit-Vote if we haven't already
  951. func (cs *ConsensusState) saveCommitVoteBlock(block *Block, blockParts *PartSet, commits *VoteSet) {
  952. // The proposal must be valid.
  953. if err := cs.stageBlock(block, blockParts); err != nil {
  954. // Prevent zombies.
  955. log.Warn("saveCommitVoteBlock() an invalid block", "error", err)
  956. return
  957. }
  958. // Save to blockStore.
  959. if cs.blockStore.Height() < block.Height {
  960. seenValidation := commits.MakeValidation()
  961. cs.blockStore.SaveBlock(block, blockParts, seenValidation)
  962. }
  963. // Save the state.
  964. cs.stagedState.Save()
  965. // Update mempool.
  966. cs.mempoolReactor.Mempool.ResetForBlockAndState(block, cs.stagedState)
  967. // Commit-vote if we haven't already.
  968. if cs.lastCommitVoteHeight < block.Height {
  969. cs.signAddVote(VoteTypeCommit, block.Hash(), blockParts.Header())
  970. cs.lastCommitVoteHeight = block.Height
  971. }
  972. }
  973. //-----------------------------------------------------------------------------
  974. // total duration of given round
  975. func calcRoundDuration(round uint) time.Duration {
  976. return roundDuration0 + roundDurationDelta*time.Duration(round)
  977. }
  978. // startTime is when round zero started.
  979. func calcRoundStartTime(round uint, startTime time.Time) time.Time {
  980. return startTime.Add(roundDuration0*time.Duration(round) +
  981. roundDurationDelta*(time.Duration((int64(round)*int64(round)-int64(round))/2)))
  982. }
  983. // calculates the current round given startTime of round zero.
  984. // NOTE: round is zero if startTime is in the future.
  985. func calcRound(startTime time.Time) uint {
  986. now := time.Now()
  987. if now.Before(startTime) {
  988. return 0
  989. }
  990. // Start + D_0 * R + D_delta * (R^2 - R)/2 <= Now; find largest integer R.
  991. // D_delta * R^2 + (2D_0 - D_delta) * R + 2(Start - Now) <= 0.
  992. // AR^2 + BR + C <= 0; A = D_delta, B = (2_D0 - D_delta), C = 2(Start - Now).
  993. // R = Floor((-B + Sqrt(B^2 - 4AC))/2A)
  994. A := float64(roundDurationDelta)
  995. B := 2.0*float64(roundDuration0) - float64(roundDurationDelta)
  996. C := 2.0 * float64(startTime.Sub(now))
  997. R := math.Floor((-B + math.Sqrt(B*B-4.0*A*C)) / (2 * A))
  998. if math.IsNaN(R) {
  999. panic("Could not calc round, should not happen")
  1000. }
  1001. if R > math.MaxInt32 {
  1002. panic(Fmt("Could not calc round, round overflow: %v", R))
  1003. }
  1004. if R < 0 {
  1005. return 0
  1006. }
  1007. return uint(R)
  1008. }
  1009. // convenience
  1010. // NOTE: elapsedRatio can be negative if startTime is in the future.
  1011. func calcRoundInfo(startTime time.Time) (round uint, roundStartTime time.Time, roundDuration time.Duration,
  1012. roundElapsed time.Duration, elapsedRatio float64) {
  1013. round = calcRound(startTime)
  1014. roundStartTime = calcRoundStartTime(round, startTime)
  1015. roundDuration = calcRoundDuration(round)
  1016. roundElapsed = time.Now().Sub(roundStartTime)
  1017. elapsedRatio = float64(roundElapsed) / float64(roundDuration)
  1018. return
  1019. }