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.

1967 lines
62 KiB

  1. package consensus
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "io/ioutil"
  7. "os"
  8. "reflect"
  9. "runtime/debug"
  10. "sync"
  11. "time"
  12. "github.com/gogo/protobuf/proto"
  13. cfg "github.com/tendermint/tendermint/config"
  14. tmcon "github.com/tendermint/tendermint/consensus"
  15. cstypes "github.com/tendermint/tendermint/consensus/types"
  16. "github.com/tendermint/tendermint/crypto"
  17. tmevents "github.com/tendermint/tendermint/libs/events"
  18. "github.com/tendermint/tendermint/libs/fail"
  19. tmjson "github.com/tendermint/tendermint/libs/json"
  20. "github.com/tendermint/tendermint/libs/log"
  21. tmmath "github.com/tendermint/tendermint/libs/math"
  22. tmos "github.com/tendermint/tendermint/libs/os"
  23. "github.com/tendermint/tendermint/libs/service"
  24. "github.com/tendermint/tendermint/p2p"
  25. tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
  26. sm "github.com/tendermint/tendermint/state"
  27. "github.com/tendermint/tendermint/types"
  28. tmtime "github.com/tendermint/tendermint/types/time"
  29. )
  30. // State handles execution of the consensus algorithm.
  31. // It processes votes and proposals, and upon reaching agreement,
  32. // commits blocks to the chain and executes them against the application.
  33. // The internal state machine receives input from peers, the internal validator, and from a timer.
  34. type State struct {
  35. service.BaseService
  36. // config details
  37. config *cfg.ConsensusConfig
  38. privValidator types.PrivValidator // for signing votes
  39. // store blocks and commits
  40. blockStore sm.BlockStore
  41. // create and execute blocks
  42. blockExec *sm.BlockExecutor
  43. // notify us if txs are available
  44. txNotifier txNotifier
  45. // add evidence to the pool
  46. // when it's detected
  47. evpool evidencePool
  48. // internal state
  49. mtx sync.RWMutex
  50. cstypes.RoundState
  51. state sm.State // State until height-1.
  52. // state changes may be triggered by: msgs from peers,
  53. // msgs from ourself, or by timeouts
  54. peerMsgQueue chan msgInfo
  55. internalMsgQueue chan msgInfo
  56. timeoutTicker TimeoutTicker
  57. // privValidator pubkey, memoized for the duration of one block
  58. // to avoid extra requests to HSM
  59. privValidatorPubKey crypto.PubKey
  60. // information about about added votes and block parts are written on this channel
  61. // so statistics can be computed by reactor
  62. statsMsgQueue chan msgInfo
  63. // we use eventBus to trigger msg broadcasts in the reactor,
  64. // and to notify external subscribers, eg. through a websocket
  65. eventBus *types.EventBus
  66. // a Write-Ahead Log ensures we can recover from any kind of crash
  67. // and helps us avoid signing conflicting votes
  68. wal tmcon.WAL
  69. replayMode bool // so we don't log signing errors during replay
  70. doWALCatchup bool // determines if we even try to do the catchup
  71. // for tests where we want to limit the number of transitions the state makes
  72. nSteps int
  73. // some functions can be overwritten for testing
  74. decideProposal func(height int64, round int32)
  75. // closed when we finish shutting down
  76. done chan struct{}
  77. // synchronous pubsub between consensus state and reactor.
  78. // state only emits EventNewRoundStep and EventVote
  79. evsw tmevents.EventSwitch
  80. // for reporting metrics
  81. metrics *tmcon.Metrics
  82. // misbehaviors mapped for each height (can't have more than one misbehavior per height)
  83. misbehaviors map[int64]Misbehavior
  84. // the switch is passed to the state so that maveick misbehaviors can directly control which
  85. // information they send to which nodes
  86. sw *p2p.Switch
  87. }
  88. // StateOption sets an optional parameter on the State.
  89. type StateOption func(*State)
  90. // NewState returns a new State.
  91. func NewState(
  92. config *cfg.ConsensusConfig,
  93. state sm.State,
  94. blockExec *sm.BlockExecutor,
  95. blockStore sm.BlockStore,
  96. txNotifier txNotifier,
  97. evpool evidencePool,
  98. misbehaviors map[int64]Misbehavior,
  99. options ...StateOption,
  100. ) *State {
  101. cs := &State{
  102. config: config,
  103. blockExec: blockExec,
  104. blockStore: blockStore,
  105. txNotifier: txNotifier,
  106. peerMsgQueue: make(chan msgInfo, msgQueueSize),
  107. internalMsgQueue: make(chan msgInfo, msgQueueSize),
  108. timeoutTicker: NewTimeoutTicker(),
  109. statsMsgQueue: make(chan msgInfo, msgQueueSize),
  110. done: make(chan struct{}),
  111. doWALCatchup: true,
  112. wal: nilWAL{},
  113. evpool: evpool,
  114. evsw: tmevents.NewEventSwitch(),
  115. metrics: tmcon.NopMetrics(),
  116. misbehaviors: misbehaviors,
  117. }
  118. // set function defaults (may be overwritten before calling Start)
  119. cs.decideProposal = cs.defaultDecideProposal
  120. // We have no votes, so reconstruct LastCommit from SeenCommit.
  121. if state.LastBlockHeight > 0 {
  122. cs.reconstructLastCommit(state)
  123. }
  124. cs.updateToState(state)
  125. // Don't call scheduleRound0 yet.
  126. // We do that upon Start().
  127. cs.BaseService = *service.NewBaseService(nil, "State", cs)
  128. for _, option := range options {
  129. option(cs)
  130. }
  131. return cs
  132. }
  133. // I know this is not great but the maverick consensus state needs access to the peers
  134. func (cs *State) SetSwitch(sw *p2p.Switch) {
  135. cs.sw = sw
  136. }
  137. // state transitions on complete-proposal, 2/3-any, 2/3-one
  138. func (cs *State) handleMsg(mi msgInfo) {
  139. cs.mtx.Lock()
  140. defer cs.mtx.Unlock()
  141. var (
  142. added bool
  143. err error
  144. )
  145. msg, peerID := mi.Msg, mi.PeerID
  146. switch msg := msg.(type) {
  147. case *tmcon.ProposalMessage:
  148. // will not cause transition.
  149. // once proposal is set, we can receive block parts
  150. // err = cs.setProposal(msg.Proposal)
  151. if b, ok := cs.misbehaviors[cs.Height]; ok {
  152. err = b.ReceiveProposal(cs, msg.Proposal)
  153. } else {
  154. err = defaultReceiveProposal(cs, msg.Proposal)
  155. }
  156. case *tmcon.BlockPartMessage:
  157. // if the proposal is complete, we'll enterPrevote or tryFinalizeCommit
  158. added, err = cs.addProposalBlockPart(msg, peerID)
  159. if added {
  160. cs.statsMsgQueue <- mi
  161. }
  162. if err != nil && msg.Round != cs.Round {
  163. cs.Logger.Debug(
  164. "Received block part from wrong round",
  165. "height",
  166. cs.Height,
  167. "csRound",
  168. cs.Round,
  169. "blockRound",
  170. msg.Round)
  171. err = nil
  172. }
  173. case *tmcon.VoteMessage:
  174. // attempt to add the vote and dupeout the validator if its a duplicate signature
  175. // if the vote gives us a 2/3-any or 2/3-one, we transition
  176. added, err = cs.tryAddVote(msg.Vote, peerID)
  177. if added {
  178. cs.statsMsgQueue <- mi
  179. }
  180. // if err == ErrAddingVote {
  181. // TODO: punish peer
  182. // We probably don't want to stop the peer here. The vote does not
  183. // necessarily comes from a malicious peer but can be just broadcasted by
  184. // a typical peer.
  185. // https://github.com/tendermint/tendermint/issues/1281
  186. // }
  187. // NOTE: the vote is broadcast to peers by the reactor listening
  188. // for vote events
  189. // TODO: If rs.Height == vote.Height && rs.Round < vote.Round,
  190. // the peer is sending us CatchupCommit precommits.
  191. // We could make note of this and help filter in broadcastHasVoteMessage().
  192. default:
  193. cs.Logger.Error("Unknown msg type", "type", reflect.TypeOf(msg))
  194. return
  195. }
  196. if err != nil {
  197. cs.Logger.Error("Error with msg", "height", cs.Height, "round", cs.Round,
  198. "peer", peerID, "err", err, "msg", msg)
  199. }
  200. }
  201. // Enter (CreateEmptyBlocks): from enterNewRound(height,round)
  202. // Enter (CreateEmptyBlocks, CreateEmptyBlocksInterval > 0 ):
  203. // after enterNewRound(height,round), after timeout of CreateEmptyBlocksInterval
  204. // Enter (!CreateEmptyBlocks) : after enterNewRound(height,round), once txs are in the mempool
  205. func (cs *State) enterPropose(height int64, round int32) {
  206. logger := cs.Logger.With("height", height, "round", round)
  207. if cs.Height != height || round < cs.Round || (cs.Round == round && cstypes.RoundStepPropose <= cs.Step) {
  208. logger.Debug(fmt.Sprintf(
  209. "enterPropose(%v/%v): Invalid args. Current step: %v/%v/%v",
  210. height,
  211. round,
  212. cs.Height,
  213. cs.Round,
  214. cs.Step))
  215. return
  216. }
  217. logger.Info(fmt.Sprintf("enterPropose(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  218. defer func() {
  219. // Done enterPropose:
  220. cs.updateRoundStep(round, cstypes.RoundStepPropose)
  221. cs.newStep()
  222. // If we have the whole proposal + POL, then goto Prevote now.
  223. // else, we'll enterPrevote when the rest of the proposal is received (in AddProposalBlockPart),
  224. // or else after timeoutPropose
  225. if cs.isProposalComplete() {
  226. cs.enterPrevote(height, cs.Round)
  227. }
  228. }()
  229. if b, ok := cs.misbehaviors[cs.Height]; ok {
  230. b.EnterPropose(cs, height, round)
  231. } else {
  232. defaultEnterPropose(cs, height, round)
  233. }
  234. }
  235. // Enter: `timeoutPropose` after entering Propose.
  236. // Enter: proposal block and POL is ready.
  237. // Prevote for LockedBlock if we're locked, or ProposalBlock if valid.
  238. // Otherwise vote nil.
  239. func (cs *State) enterPrevote(height int64, round int32) {
  240. if cs.Height != height || round < cs.Round || (cs.Round == round && cstypes.RoundStepPrevote <= cs.Step) {
  241. cs.Logger.Debug(fmt.Sprintf(
  242. "enterPrevote(%v/%v): Invalid args. Current step: %v/%v/%v",
  243. height,
  244. round,
  245. cs.Height,
  246. cs.Round,
  247. cs.Step))
  248. return
  249. }
  250. defer func() {
  251. // Done enterPrevote:
  252. cs.updateRoundStep(round, cstypes.RoundStepPrevote)
  253. cs.newStep()
  254. }()
  255. cs.Logger.Debug(fmt.Sprintf("enterPrevote(%v/%v); current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  256. // Sign and broadcast vote as necessary
  257. if b, ok := cs.misbehaviors[cs.Height]; ok {
  258. b.EnterPrevote(cs, height, round)
  259. } else {
  260. defaultEnterPrevote(cs, height, round)
  261. }
  262. // Once `addVote` hits any +2/3 prevotes, we will go to PrevoteWait
  263. // (so we have more time to try and collect +2/3 prevotes for a single block)
  264. }
  265. // Enter: `timeoutPrevote` after any +2/3 prevotes.
  266. // Enter: `timeoutPrecommit` after any +2/3 precommits.
  267. // Enter: +2/3 precomits for block or nil.
  268. // Lock & precommit the ProposalBlock if we have enough prevotes for it (a POL in this round)
  269. // else, unlock an existing lock and precommit nil if +2/3 of prevotes were nil,
  270. // else, precommit nil otherwise.
  271. func (cs *State) enterPrecommit(height int64, round int32) {
  272. logger := cs.Logger.With("height", height, "round", round)
  273. if cs.Height != height || round < cs.Round || (cs.Round == round && cstypes.RoundStepPrecommit <= cs.Step) {
  274. logger.Debug(fmt.Sprintf(
  275. "enterPrecommit(%v/%v): Invalid args. Current step: %v/%v/%v",
  276. height,
  277. round,
  278. cs.Height,
  279. cs.Round,
  280. cs.Step))
  281. return
  282. }
  283. logger.Info(fmt.Sprintf("enterPrecommit(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  284. defer func() {
  285. // Done enterPrecommit:
  286. cs.updateRoundStep(round, cstypes.RoundStepPrecommit)
  287. cs.newStep()
  288. }()
  289. if b, ok := cs.misbehaviors[cs.Height]; ok {
  290. b.EnterPrecommit(cs, height, round)
  291. } else {
  292. defaultEnterPrecommit(cs, height, round)
  293. }
  294. }
  295. func (cs *State) addVote(
  296. vote *types.Vote,
  297. peerID p2p.ID) (added bool, err error) {
  298. cs.Logger.Debug(
  299. "addVote",
  300. "voteHeight",
  301. vote.Height,
  302. "voteType",
  303. vote.Type,
  304. "valIndex",
  305. vote.ValidatorIndex,
  306. "csHeight",
  307. cs.Height,
  308. )
  309. // A precommit for the previous height?
  310. // These come in while we wait timeoutCommit
  311. if vote.Height+1 == cs.Height && vote.Type == tmproto.PrecommitType {
  312. if cs.Step != cstypes.RoundStepNewHeight {
  313. // Late precommit at prior height is ignored
  314. cs.Logger.Debug("Precommit vote came in after commit timeout and has been ignored", "vote", vote)
  315. return
  316. }
  317. added, err = cs.LastCommit.AddVote(vote)
  318. if !added {
  319. return
  320. }
  321. cs.Logger.Info(fmt.Sprintf("Added to lastPrecommits: %v", cs.LastCommit.StringShort()))
  322. _ = cs.eventBus.PublishEventVote(types.EventDataVote{Vote: vote})
  323. cs.evsw.FireEvent(types.EventVote, vote)
  324. // if we can skip timeoutCommit and have all the votes now,
  325. if cs.config.SkipTimeoutCommit && cs.LastCommit.HasAll() {
  326. // go straight to new round (skip timeout commit)
  327. // cs.scheduleTimeout(time.Duration(0), cs.Height, 0, cstypes.RoundStepNewHeight)
  328. cs.enterNewRound(cs.Height, 0)
  329. }
  330. return
  331. }
  332. // Height mismatch is ignored.
  333. // Not necessarily a bad peer, but not favourable behaviour.
  334. if vote.Height != cs.Height {
  335. cs.Logger.Debug("vote ignored and not added", "voteHeight", vote.Height, "csHeight", cs.Height, "peerID", peerID)
  336. return
  337. }
  338. added, err = cs.Votes.AddVote(vote, peerID)
  339. if !added {
  340. // Either duplicate, or error upon cs.Votes.AddByIndex()
  341. return
  342. }
  343. _ = cs.eventBus.PublishEventVote(types.EventDataVote{Vote: vote})
  344. cs.evsw.FireEvent(types.EventVote, vote)
  345. switch vote.Type {
  346. case tmproto.PrevoteType:
  347. if b, ok := cs.misbehaviors[cs.Height]; ok {
  348. b.ReceivePrevote(cs, vote)
  349. } else {
  350. defaultReceivePrevote(cs, vote)
  351. }
  352. case tmproto.PrecommitType:
  353. if b, ok := cs.misbehaviors[cs.Height]; ok {
  354. b.ReceivePrecommit(cs, vote)
  355. }
  356. defaultReceivePrecommit(cs, vote)
  357. default:
  358. panic(fmt.Sprintf("Unexpected vote type %v", vote.Type))
  359. }
  360. return added, err
  361. }
  362. //-----------------------------------------------------------------------------
  363. // Errors
  364. var (
  365. ErrInvalidProposalSignature = errors.New("error invalid proposal signature")
  366. ErrInvalidProposalPOLRound = errors.New("error invalid proposal POL round")
  367. ErrAddingVote = errors.New("error adding vote")
  368. ErrSignatureFoundInPastBlocks = errors.New("found signature from the same key")
  369. errPubKeyIsNotSet = errors.New("pubkey is not set. Look for \"Can't get private validator pubkey\" errors")
  370. )
  371. //-----------------------------------------------------------------------------
  372. var (
  373. msgQueueSize = 1000
  374. )
  375. // msgs from the reactor which may update the state
  376. type msgInfo struct {
  377. Msg tmcon.Message `json:"msg"`
  378. PeerID p2p.ID `json:"peer_key"`
  379. }
  380. // internally generated messages which may update the state
  381. type timeoutInfo struct {
  382. Duration time.Duration `json:"duration"`
  383. Height int64 `json:"height"`
  384. Round int32 `json:"round"`
  385. Step cstypes.RoundStepType `json:"step"`
  386. }
  387. func (ti *timeoutInfo) String() string {
  388. return fmt.Sprintf("%v ; %d/%d %v", ti.Duration, ti.Height, ti.Round, ti.Step)
  389. }
  390. // interface to the mempool
  391. type txNotifier interface {
  392. TxsAvailable() <-chan struct{}
  393. }
  394. // interface to the evidence pool
  395. type evidencePool interface {
  396. // reports conflicting votes to the evidence pool to be processed into evidence
  397. ReportConflictingVotes(voteA, voteB *types.Vote)
  398. }
  399. //----------------------------------------
  400. // Public interface
  401. // SetLogger implements Service.
  402. func (cs *State) SetLogger(l log.Logger) {
  403. cs.BaseService.Logger = l
  404. cs.timeoutTicker.SetLogger(l)
  405. }
  406. // SetEventBus sets event bus.
  407. func (cs *State) SetEventBus(b *types.EventBus) {
  408. cs.eventBus = b
  409. cs.blockExec.SetEventBus(b)
  410. }
  411. // StateMetrics sets the metrics.
  412. func StateMetrics(metrics *tmcon.Metrics) StateOption {
  413. return func(cs *State) { cs.metrics = metrics }
  414. }
  415. // String returns a string.
  416. func (cs *State) String() string {
  417. // better not to access shared variables
  418. return "ConsensusState"
  419. }
  420. // GetState returns a copy of the chain state.
  421. func (cs *State) GetState() sm.State {
  422. cs.mtx.RLock()
  423. defer cs.mtx.RUnlock()
  424. return cs.state.Copy()
  425. }
  426. // GetLastHeight returns the last height committed.
  427. // If there were no blocks, returns 0.
  428. func (cs *State) GetLastHeight() int64 {
  429. cs.mtx.RLock()
  430. defer cs.mtx.RUnlock()
  431. return cs.RoundState.Height - 1
  432. }
  433. // GetRoundState returns a shallow copy of the internal consensus state.
  434. func (cs *State) GetRoundState() *cstypes.RoundState {
  435. cs.mtx.RLock()
  436. rs := cs.RoundState // copy
  437. cs.mtx.RUnlock()
  438. return &rs
  439. }
  440. // GetRoundStateJSON returns a json of RoundState.
  441. func (cs *State) GetRoundStateJSON() ([]byte, error) {
  442. cs.mtx.RLock()
  443. defer cs.mtx.RUnlock()
  444. return tmjson.Marshal(cs.RoundState)
  445. }
  446. // GetRoundStateSimpleJSON returns a json of RoundStateSimple
  447. func (cs *State) GetRoundStateSimpleJSON() ([]byte, error) {
  448. cs.mtx.RLock()
  449. defer cs.mtx.RUnlock()
  450. return tmjson.Marshal(cs.RoundState.RoundStateSimple())
  451. }
  452. // GetValidators returns a copy of the current validators.
  453. func (cs *State) GetValidators() (int64, []*types.Validator) {
  454. cs.mtx.RLock()
  455. defer cs.mtx.RUnlock()
  456. return cs.state.LastBlockHeight, cs.state.Validators.Copy().Validators
  457. }
  458. // SetPrivValidator sets the private validator account for signing votes. It
  459. // immediately requests pubkey and caches it.
  460. func (cs *State) SetPrivValidator(priv types.PrivValidator) {
  461. cs.mtx.Lock()
  462. defer cs.mtx.Unlock()
  463. cs.privValidator = priv
  464. if err := cs.updatePrivValidatorPubKey(); err != nil {
  465. cs.Logger.Error("Can't get private validator pubkey", "err", err)
  466. }
  467. }
  468. // SetTimeoutTicker sets the local timer. It may be useful to overwrite for testing.
  469. func (cs *State) SetTimeoutTicker(timeoutTicker TimeoutTicker) {
  470. cs.mtx.Lock()
  471. cs.timeoutTicker = timeoutTicker
  472. cs.mtx.Unlock()
  473. }
  474. // LoadCommit loads the commit for a given height.
  475. func (cs *State) LoadCommit(height int64) *types.Commit {
  476. cs.mtx.RLock()
  477. defer cs.mtx.RUnlock()
  478. if height == cs.blockStore.Height() {
  479. return cs.blockStore.LoadSeenCommit(height)
  480. }
  481. return cs.blockStore.LoadBlockCommit(height)
  482. }
  483. // OnStart loads the latest state via the WAL, and starts the timeout and
  484. // receive routines.
  485. func (cs *State) OnStart() error {
  486. // We may set the WAL in testing before calling Start, so only OpenWAL if its
  487. // still the nilWAL.
  488. if _, ok := cs.wal.(nilWAL); ok {
  489. if err := cs.loadWalFile(); err != nil {
  490. return err
  491. }
  492. }
  493. // We may have lost some votes if the process crashed reload from consensus
  494. // log to catchup.
  495. if cs.doWALCatchup {
  496. repairAttempted := false
  497. LOOP:
  498. for {
  499. err := cs.catchupReplay(cs.Height)
  500. switch {
  501. case err == nil:
  502. break LOOP
  503. case !IsDataCorruptionError(err):
  504. cs.Logger.Error("Error on catchup replay. Proceeding to start State anyway", "err", err)
  505. break LOOP
  506. case repairAttempted:
  507. return err
  508. }
  509. cs.Logger.Info("WAL file is corrupted. Attempting repair", "err", err)
  510. // 1) prep work
  511. if err := cs.wal.Stop(); err != nil {
  512. return err
  513. }
  514. repairAttempted = true
  515. // 2) backup original WAL file
  516. corruptedFile := fmt.Sprintf("%s.CORRUPTED", cs.config.WalFile())
  517. if err := tmos.CopyFile(cs.config.WalFile(), corruptedFile); err != nil {
  518. return err
  519. }
  520. cs.Logger.Info("Backed up WAL file", "src", cs.config.WalFile(), "dst", corruptedFile)
  521. // 3) try to repair (WAL file will be overwritten!)
  522. if err := repairWalFile(corruptedFile, cs.config.WalFile()); err != nil {
  523. cs.Logger.Error("Repair failed", "err", err)
  524. return err
  525. }
  526. cs.Logger.Info("Successful repair")
  527. // reload WAL file
  528. if err := cs.loadWalFile(); err != nil {
  529. return err
  530. }
  531. }
  532. }
  533. if err := cs.evsw.Start(); err != nil {
  534. return err
  535. }
  536. // we need the timeoutRoutine for replay so
  537. // we don't block on the tick chan.
  538. // NOTE: we will get a build up of garbage go routines
  539. // firing on the tockChan until the receiveRoutine is started
  540. // to deal with them (by that point, at most one will be valid)
  541. if err := cs.timeoutTicker.Start(); err != nil {
  542. return err
  543. }
  544. // Double Signing Risk Reduction
  545. if err := cs.checkDoubleSigningRisk(cs.Height); err != nil {
  546. return err
  547. }
  548. // now start the receiveRoutine
  549. go cs.receiveRoutine(0)
  550. // schedule the first round!
  551. // use GetRoundState so we don't race the receiveRoutine for access
  552. cs.scheduleRound0(cs.GetRoundState())
  553. return nil
  554. }
  555. // loadWalFile loads WAL data from file. It overwrites cs.wal.
  556. func (cs *State) loadWalFile() error {
  557. wal, err := cs.OpenWAL(cs.config.WalFile())
  558. if err != nil {
  559. cs.Logger.Error("Error loading State wal", "err", err)
  560. return err
  561. }
  562. cs.wal = wal
  563. return nil
  564. }
  565. // OnStop implements service.Service.
  566. func (cs *State) OnStop() {
  567. if err := cs.evsw.Stop(); err != nil {
  568. cs.Logger.Error("error trying to stop eventSwitch", "error", err)
  569. }
  570. if err := cs.timeoutTicker.Stop(); err != nil {
  571. cs.Logger.Error("error trying to stop timeoutTicket", "error", err)
  572. }
  573. // WAL is stopped in receiveRoutine.
  574. }
  575. // Wait waits for the the main routine to return.
  576. // NOTE: be sure to Stop() the event switch and drain
  577. // any event channels or this may deadlock
  578. func (cs *State) Wait() {
  579. <-cs.done
  580. }
  581. // OpenWAL opens a file to log all consensus messages and timeouts for
  582. // deterministic accountability.
  583. func (cs *State) OpenWAL(walFile string) (tmcon.WAL, error) {
  584. wal, err := NewWAL(walFile)
  585. if err != nil {
  586. cs.Logger.Error("Failed to open WAL", "file", walFile, "err", err)
  587. return nil, err
  588. }
  589. wal.SetLogger(cs.Logger.With("wal", walFile))
  590. if err := wal.Start(); err != nil {
  591. cs.Logger.Error("Failed to start WAL", "err", err)
  592. return nil, err
  593. }
  594. return wal, nil
  595. }
  596. //------------------------------------------------------------
  597. // Public interface for passing messages into the consensus state, possibly causing a state transition.
  598. // If peerID == "", the msg is considered internal.
  599. // Messages are added to the appropriate queue (peer or internal).
  600. // If the queue is full, the function may block.
  601. // TODO: should these return anything or let callers just use events?
  602. // AddVote inputs a vote.
  603. func (cs *State) AddVote(vote *types.Vote, peerID p2p.ID) (added bool, err error) {
  604. if peerID == "" {
  605. cs.internalMsgQueue <- msgInfo{&tmcon.VoteMessage{Vote: vote}, ""}
  606. } else {
  607. cs.peerMsgQueue <- msgInfo{&tmcon.VoteMessage{Vote: vote}, peerID}
  608. }
  609. // TODO: wait for event?!
  610. return false, nil
  611. }
  612. // SetProposal inputs a proposal.
  613. func (cs *State) SetProposal(proposal *types.Proposal, peerID p2p.ID) error {
  614. if peerID == "" {
  615. cs.internalMsgQueue <- msgInfo{&tmcon.ProposalMessage{Proposal: proposal}, ""}
  616. } else {
  617. cs.peerMsgQueue <- msgInfo{&tmcon.ProposalMessage{Proposal: proposal}, peerID}
  618. }
  619. // TODO: wait for event?!
  620. return nil
  621. }
  622. // AddProposalBlockPart inputs a part of the proposal block.
  623. func (cs *State) AddProposalBlockPart(height int64, round int32, part *types.Part, peerID p2p.ID) error {
  624. if peerID == "" {
  625. cs.internalMsgQueue <- msgInfo{&tmcon.BlockPartMessage{Height: height, Round: round, Part: part}, ""}
  626. } else {
  627. cs.peerMsgQueue <- msgInfo{&tmcon.BlockPartMessage{Height: height, Round: round, Part: part}, peerID}
  628. }
  629. // TODO: wait for event?!
  630. return nil
  631. }
  632. // SetProposalAndBlock inputs the proposal and all block parts.
  633. func (cs *State) SetProposalAndBlock(
  634. proposal *types.Proposal,
  635. block *types.Block,
  636. parts *types.PartSet,
  637. peerID p2p.ID,
  638. ) error {
  639. if err := cs.SetProposal(proposal, peerID); err != nil {
  640. return err
  641. }
  642. for i := 0; i < int(parts.Total()); i++ {
  643. part := parts.GetPart(i)
  644. if err := cs.AddProposalBlockPart(proposal.Height, proposal.Round, part, peerID); err != nil {
  645. return err
  646. }
  647. }
  648. return nil
  649. }
  650. //------------------------------------------------------------
  651. // internal functions for managing the state
  652. func (cs *State) updateHeight(height int64) {
  653. cs.metrics.Height.Set(float64(height))
  654. cs.Height = height
  655. }
  656. func (cs *State) updateRoundStep(round int32, step cstypes.RoundStepType) {
  657. cs.Round = round
  658. cs.Step = step
  659. }
  660. // enterNewRound(height, 0) at cs.StartTime.
  661. func (cs *State) scheduleRound0(rs *cstypes.RoundState) {
  662. // cs.Logger.Info("scheduleRound0", "now", tmtime.Now(), "startTime", cs.StartTime)
  663. sleepDuration := rs.StartTime.Sub(tmtime.Now())
  664. cs.scheduleTimeout(sleepDuration, rs.Height, 0, cstypes.RoundStepNewHeight)
  665. }
  666. // Attempt to schedule a timeout (by sending timeoutInfo on the tickChan)
  667. func (cs *State) scheduleTimeout(duration time.Duration, height int64, round int32, step cstypes.RoundStepType) {
  668. cs.timeoutTicker.ScheduleTimeout(timeoutInfo{duration, height, round, step})
  669. }
  670. // send a msg into the receiveRoutine regarding our own proposal, block part, or vote
  671. func (cs *State) sendInternalMessage(mi msgInfo) {
  672. select {
  673. case cs.internalMsgQueue <- mi:
  674. default:
  675. // NOTE: using the go-routine means our votes can
  676. // be processed out of order.
  677. // TODO: use CList here for strict determinism and
  678. // attempt push to internalMsgQueue in receiveRoutine
  679. cs.Logger.Info("Internal msg queue is full. Using a go-routine")
  680. go func() { cs.internalMsgQueue <- mi }()
  681. }
  682. }
  683. // Reconstruct LastCommit from SeenCommit, which we saved along with the block,
  684. // (which happens even before saving the state)
  685. func (cs *State) reconstructLastCommit(state sm.State) {
  686. seenCommit := cs.blockStore.LoadSeenCommit(state.LastBlockHeight)
  687. if seenCommit == nil {
  688. panic(fmt.Sprintf("Failed to reconstruct LastCommit: seen commit for height %v not found",
  689. state.LastBlockHeight))
  690. }
  691. lastPrecommits := types.CommitToVoteSet(state.ChainID, seenCommit, state.LastValidators)
  692. if !lastPrecommits.HasTwoThirdsMajority() {
  693. panic("Failed to reconstruct LastCommit: Does not have +2/3 maj")
  694. }
  695. cs.LastCommit = lastPrecommits
  696. }
  697. // Updates State and increments height to match that of state.
  698. // The round becomes 0 and cs.Step becomes cstypes.RoundStepNewHeight.
  699. func (cs *State) updateToState(state sm.State) {
  700. if cs.CommitRound > -1 && 0 < cs.Height && cs.Height != state.LastBlockHeight {
  701. panic(fmt.Sprintf("updateToState() expected state height of %v but found %v",
  702. cs.Height, state.LastBlockHeight))
  703. }
  704. if !cs.state.IsEmpty() {
  705. if cs.state.LastBlockHeight > 0 && cs.state.LastBlockHeight+1 != cs.Height {
  706. // This might happen when someone else is mutating cs.state.
  707. // Someone forgot to pass in state.Copy() somewhere?!
  708. panic(fmt.Sprintf("Inconsistent cs.state.LastBlockHeight+1 %v vs cs.Height %v",
  709. cs.state.LastBlockHeight+1, cs.Height))
  710. }
  711. if cs.state.LastBlockHeight > 0 && cs.Height == cs.state.InitialHeight {
  712. panic(fmt.Sprintf("Inconsistent cs.state.LastBlockHeight %v, expected 0 for initial height %v",
  713. cs.state.LastBlockHeight, cs.state.InitialHeight))
  714. }
  715. // If state isn't further out than cs.state, just ignore.
  716. // This happens when SwitchToConsensus() is called in the reactor.
  717. // We don't want to reset e.g. the Votes, but we still want to
  718. // signal the new round step, because other services (eg. txNotifier)
  719. // depend on having an up-to-date peer state!
  720. if state.LastBlockHeight <= cs.state.LastBlockHeight {
  721. cs.Logger.Info(
  722. "Ignoring updateToState()",
  723. "newHeight",
  724. state.LastBlockHeight+1,
  725. "oldHeight",
  726. cs.state.LastBlockHeight+1)
  727. cs.newStep()
  728. return
  729. }
  730. }
  731. // Reset fields based on state.
  732. validators := state.Validators
  733. switch {
  734. case state.LastBlockHeight == 0: // Very first commit should be empty.
  735. cs.LastCommit = (*types.VoteSet)(nil)
  736. case cs.CommitRound > -1 && cs.Votes != nil: // Otherwise, use cs.Votes
  737. if !cs.Votes.Precommits(cs.CommitRound).HasTwoThirdsMajority() {
  738. panic(fmt.Sprintf("Wanted to form a Commit, but Precommits (H/R: %d/%d) didn't have 2/3+: %v",
  739. state.LastBlockHeight,
  740. cs.CommitRound,
  741. cs.Votes.Precommits(cs.CommitRound)))
  742. }
  743. cs.LastCommit = cs.Votes.Precommits(cs.CommitRound)
  744. case cs.LastCommit == nil:
  745. // NOTE: when Tendermint starts, it has no votes. reconstructLastCommit
  746. // must be called to reconstruct LastCommit from SeenCommit.
  747. panic(fmt.Sprintf("LastCommit cannot be empty after initial block (H:%d)",
  748. state.LastBlockHeight+1,
  749. ))
  750. }
  751. // Next desired block height
  752. height := state.LastBlockHeight + 1
  753. if height == 1 {
  754. height = state.InitialHeight
  755. }
  756. // RoundState fields
  757. cs.updateHeight(height)
  758. cs.updateRoundStep(0, cstypes.RoundStepNewHeight)
  759. if cs.CommitTime.IsZero() {
  760. // "Now" makes it easier to sync up dev nodes.
  761. // We add timeoutCommit to allow transactions
  762. // to be gathered for the first block.
  763. // And alternative solution that relies on clocks:
  764. // cs.StartTime = state.LastBlockTime.Add(timeoutCommit)
  765. cs.StartTime = cs.config.Commit(tmtime.Now())
  766. } else {
  767. cs.StartTime = cs.config.Commit(cs.CommitTime)
  768. }
  769. cs.Validators = validators
  770. cs.Proposal = nil
  771. cs.ProposalBlock = nil
  772. cs.ProposalBlockParts = nil
  773. cs.LockedRound = -1
  774. cs.LockedBlock = nil
  775. cs.LockedBlockParts = nil
  776. cs.ValidRound = -1
  777. cs.ValidBlock = nil
  778. cs.ValidBlockParts = nil
  779. cs.Votes = cstypes.NewHeightVoteSet(state.ChainID, height, validators)
  780. cs.CommitRound = -1
  781. cs.LastValidators = state.LastValidators
  782. cs.TriggeredTimeoutPrecommit = false
  783. cs.state = state
  784. // Finally, broadcast RoundState
  785. cs.newStep()
  786. }
  787. func (cs *State) newStep() {
  788. rs := cs.RoundStateEvent()
  789. if err := cs.wal.Write(rs); err != nil {
  790. cs.Logger.Error("Error writing to wal", "err", err)
  791. }
  792. cs.nSteps++
  793. // newStep is called by updateToState in NewState before the eventBus is set!
  794. if cs.eventBus != nil {
  795. if err := cs.eventBus.PublishEventNewRoundStep(rs); err != nil {
  796. cs.Logger.Error("Error publishing new round step", "err", err)
  797. }
  798. cs.evsw.FireEvent(types.EventNewRoundStep, &cs.RoundState)
  799. }
  800. }
  801. //-----------------------------------------
  802. // the main go routines
  803. // receiveRoutine handles messages which may cause state transitions.
  804. // it's argument (n) is the number of messages to process before exiting - use 0 to run forever
  805. // It keeps the RoundState and is the only thing that updates it.
  806. // Updates (state transitions) happen on timeouts, complete proposals, and 2/3 majorities.
  807. // State must be locked before any internal state is updated.
  808. func (cs *State) receiveRoutine(maxSteps int) {
  809. onExit := func(cs *State) {
  810. // NOTE: the internalMsgQueue may have signed messages from our
  811. // priv_val that haven't hit the WAL, but its ok because
  812. // priv_val tracks LastSig
  813. // close wal now that we're done writing to it
  814. if err := cs.wal.Stop(); err != nil {
  815. cs.Logger.Error("error trying to stop wal", "error", err)
  816. }
  817. cs.wal.Wait()
  818. close(cs.done)
  819. }
  820. defer func() {
  821. if r := recover(); r != nil {
  822. cs.Logger.Error("CONSENSUS FAILURE!!!", "err", r, "stack", string(debug.Stack()))
  823. // stop gracefully
  824. //
  825. // NOTE: We most probably shouldn't be running any further when there is
  826. // some unexpected panic. Some unknown error happened, and so we don't
  827. // know if that will result in the validator signing an invalid thing. It
  828. // might be worthwhile to explore a mechanism for manual resuming via
  829. // some console or secure RPC system, but for now, halting the chain upon
  830. // unexpected consensus bugs sounds like the better option.
  831. onExit(cs)
  832. }
  833. }()
  834. for {
  835. if maxSteps > 0 {
  836. if cs.nSteps >= maxSteps {
  837. cs.Logger.Info("reached max steps. exiting receive routine")
  838. cs.nSteps = 0
  839. return
  840. }
  841. }
  842. rs := cs.RoundState
  843. var mi msgInfo
  844. select {
  845. case <-cs.txNotifier.TxsAvailable():
  846. cs.handleTxsAvailable()
  847. case mi = <-cs.peerMsgQueue:
  848. if err := cs.wal.Write(mi); err != nil {
  849. cs.Logger.Error("Error writing to wal", "err", err)
  850. }
  851. // handles proposals, block parts, votes
  852. // may generate internal events (votes, complete proposals, 2/3 majorities)
  853. cs.handleMsg(mi)
  854. case mi = <-cs.internalMsgQueue:
  855. err := cs.wal.WriteSync(mi) // NOTE: fsync
  856. if err != nil {
  857. panic(fmt.Sprintf("Failed to write %v msg to consensus wal due to %v. Check your FS and restart the node", mi, err))
  858. }
  859. if _, ok := mi.Msg.(*tmcon.VoteMessage); ok {
  860. // we actually want to simulate failing during
  861. // the previous WriteSync, but this isn't easy to do.
  862. // Equivalent would be to fail here and manually remove
  863. // some bytes from the end of the wal.
  864. fail.Fail() // XXX
  865. }
  866. // handles proposals, block parts, votes
  867. cs.handleMsg(mi)
  868. case ti := <-cs.timeoutTicker.Chan(): // tockChan:
  869. if err := cs.wal.Write(ti); err != nil {
  870. cs.Logger.Error("Error writing to wal", "err", err)
  871. }
  872. // if the timeout is relevant to the rs
  873. // go to the next step
  874. cs.handleTimeout(ti, rs)
  875. case <-cs.Quit():
  876. onExit(cs)
  877. return
  878. }
  879. }
  880. }
  881. func (cs *State) handleTimeout(ti timeoutInfo, rs cstypes.RoundState) {
  882. cs.Logger.Debug("Received tock", "timeout", ti.Duration, "height", ti.Height, "round", ti.Round, "step", ti.Step)
  883. // timeouts must be for current height, round, step
  884. if ti.Height != rs.Height || ti.Round < rs.Round || (ti.Round == rs.Round && ti.Step < rs.Step) {
  885. cs.Logger.Debug("Ignoring tock because we're ahead", "height", rs.Height, "round", rs.Round, "step", rs.Step)
  886. return
  887. }
  888. // the timeout will now cause a state transition
  889. cs.mtx.Lock()
  890. defer cs.mtx.Unlock()
  891. switch ti.Step {
  892. case cstypes.RoundStepNewHeight:
  893. // NewRound event fired from enterNewRound.
  894. // XXX: should we fire timeout here (for timeout commit)?
  895. cs.enterNewRound(ti.Height, 0)
  896. case cstypes.RoundStepNewRound:
  897. cs.enterPropose(ti.Height, 0)
  898. case cstypes.RoundStepPropose:
  899. if err := cs.eventBus.PublishEventTimeoutPropose(cs.RoundStateEvent()); err != nil {
  900. cs.Logger.Error("Error publishing timeout propose", "err", err)
  901. }
  902. cs.enterPrevote(ti.Height, ti.Round)
  903. case cstypes.RoundStepPrevoteWait:
  904. if err := cs.eventBus.PublishEventTimeoutWait(cs.RoundStateEvent()); err != nil {
  905. cs.Logger.Error("Error publishing timeout wait", "err", err)
  906. }
  907. cs.enterPrecommit(ti.Height, ti.Round)
  908. case cstypes.RoundStepPrecommitWait:
  909. if err := cs.eventBus.PublishEventTimeoutWait(cs.RoundStateEvent()); err != nil {
  910. cs.Logger.Error("Error publishing timeout wait", "err", err)
  911. }
  912. cs.enterPrecommit(ti.Height, ti.Round)
  913. cs.enterNewRound(ti.Height, ti.Round+1)
  914. default:
  915. panic(fmt.Sprintf("Invalid timeout step: %v", ti.Step))
  916. }
  917. }
  918. func (cs *State) handleTxsAvailable() {
  919. cs.mtx.Lock()
  920. defer cs.mtx.Unlock()
  921. // We only need to do this for round 0.
  922. if cs.Round != 0 {
  923. return
  924. }
  925. switch cs.Step {
  926. case cstypes.RoundStepNewHeight: // timeoutCommit phase
  927. if cs.needProofBlock(cs.Height) {
  928. // enterPropose will be called by enterNewRound
  929. return
  930. }
  931. // +1ms to ensure RoundStepNewRound timeout always happens after RoundStepNewHeight
  932. timeoutCommit := cs.StartTime.Sub(tmtime.Now()) + 1*time.Millisecond
  933. cs.scheduleTimeout(timeoutCommit, cs.Height, 0, cstypes.RoundStepNewRound)
  934. case cstypes.RoundStepNewRound: // after timeoutCommit
  935. cs.enterPropose(cs.Height, 0)
  936. }
  937. }
  938. //-----------------------------------------------------------------------------
  939. // State functions
  940. // Used internally by handleTimeout and handleMsg to make state transitions
  941. // Enter: `timeoutNewHeight` by startTime (commitTime+timeoutCommit),
  942. // or, if SkipTimeoutCommit==true, after receiving all precommits from (height,round-1)
  943. // Enter: `timeoutPrecommits` after any +2/3 precommits from (height,round-1)
  944. // Enter: +2/3 precommits for nil at (height,round-1)
  945. // Enter: +2/3 prevotes any or +2/3 precommits for block or any from (height, round)
  946. // NOTE: cs.StartTime was already set for height.
  947. func (cs *State) enterNewRound(height int64, round int32) {
  948. logger := cs.Logger.With("height", height, "round", round)
  949. if cs.Height != height || round < cs.Round || (cs.Round == round && cs.Step != cstypes.RoundStepNewHeight) {
  950. logger.Debug(fmt.Sprintf(
  951. "enterNewRound(%v/%v): Invalid args. Current step: %v/%v/%v",
  952. height,
  953. round,
  954. cs.Height,
  955. cs.Round,
  956. cs.Step))
  957. return
  958. }
  959. if now := tmtime.Now(); cs.StartTime.After(now) {
  960. logger.Debug("need to set a buffer and log message here for sanity", "startTime", cs.StartTime, "now", now)
  961. }
  962. logger.Info(fmt.Sprintf("enterNewRound(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  963. // Increment validators if necessary
  964. validators := cs.Validators
  965. if cs.Round < round {
  966. validators = validators.Copy()
  967. validators.IncrementProposerPriority(tmmath.SafeSubInt32(round, cs.Round))
  968. }
  969. // Setup new round
  970. // we don't fire newStep for this step,
  971. // but we fire an event, so update the round step first
  972. cs.updateRoundStep(round, cstypes.RoundStepNewRound)
  973. cs.Validators = validators
  974. if round == 0 {
  975. // We've already reset these upon new height,
  976. // and meanwhile we might have received a proposal
  977. // for round 0.
  978. } else {
  979. logger.Info("Resetting Proposal info")
  980. cs.Proposal = nil
  981. cs.ProposalBlock = nil
  982. cs.ProposalBlockParts = nil
  983. }
  984. cs.Votes.SetRound(tmmath.SafeAddInt32(round, 1)) // also track next round (round+1) to allow round-skipping
  985. cs.TriggeredTimeoutPrecommit = false
  986. if err := cs.eventBus.PublishEventNewRound(cs.NewRoundEvent()); err != nil {
  987. cs.Logger.Error("Error publishing new round", "err", err)
  988. }
  989. cs.metrics.Rounds.Set(float64(round))
  990. // Wait for txs to be available in the mempool
  991. // before we enterPropose in round 0. If the last block changed the app hash,
  992. // we may need an empty "proof" block, and enterPropose immediately.
  993. waitForTxs := cs.config.WaitForTxs() && round == 0 && !cs.needProofBlock(height)
  994. if waitForTxs {
  995. if cs.config.CreateEmptyBlocksInterval > 0 {
  996. cs.scheduleTimeout(cs.config.CreateEmptyBlocksInterval, height, round,
  997. cstypes.RoundStepNewRound)
  998. }
  999. } else {
  1000. cs.enterPropose(height, round)
  1001. }
  1002. }
  1003. // needProofBlock returns true on the first height (so the genesis app hash is signed right away)
  1004. // and where the last block (height-1) caused the app hash to change
  1005. func (cs *State) needProofBlock(height int64) bool {
  1006. if height == cs.state.InitialHeight {
  1007. return true
  1008. }
  1009. lastBlockMeta := cs.blockStore.LoadBlockMeta(height - 1)
  1010. if lastBlockMeta == nil {
  1011. panic(fmt.Sprintf("needProofBlock: last block meta for height %d not found", height-1))
  1012. }
  1013. return !bytes.Equal(cs.state.AppHash, lastBlockMeta.Header.AppHash)
  1014. }
  1015. func (cs *State) isProposer(address []byte) bool {
  1016. return bytes.Equal(cs.Validators.GetProposer().Address, address)
  1017. }
  1018. func (cs *State) defaultDecideProposal(height int64, round int32) {
  1019. var block *types.Block
  1020. var blockParts *types.PartSet
  1021. // Decide on block
  1022. if cs.ValidBlock != nil {
  1023. // If there is valid block, choose that.
  1024. block, blockParts = cs.ValidBlock, cs.ValidBlockParts
  1025. } else {
  1026. // Create a new proposal block from state/txs from the mempool.
  1027. block, blockParts = cs.createProposalBlock()
  1028. if block == nil {
  1029. return
  1030. }
  1031. }
  1032. // Flush the WAL. Otherwise, we may not recompute the same proposal to sign,
  1033. // and the privValidator will refuse to sign anything.
  1034. if err := cs.wal.FlushAndSync(); err != nil {
  1035. cs.Logger.Error("Error flushing to disk")
  1036. }
  1037. // Make proposal
  1038. propBlockID := types.BlockID{Hash: block.Hash(), PartSetHeader: blockParts.Header()}
  1039. proposal := types.NewProposal(height, round, cs.ValidRound, propBlockID)
  1040. p := proposal.ToProto()
  1041. if err := cs.privValidator.SignProposal(cs.state.ChainID, p); err == nil {
  1042. proposal.Signature = p.Signature
  1043. // send proposal and block parts on internal msg queue
  1044. cs.sendInternalMessage(msgInfo{&tmcon.ProposalMessage{Proposal: proposal}, ""})
  1045. for i := 0; i < int(blockParts.Total()); i++ {
  1046. part := blockParts.GetPart(i)
  1047. cs.sendInternalMessage(msgInfo{&tmcon.BlockPartMessage{Height: cs.Height, Round: cs.Round, Part: part}, ""})
  1048. }
  1049. cs.Logger.Info("Signed proposal", "height", height, "round", round, "proposal", proposal)
  1050. cs.Logger.Debug(fmt.Sprintf("Signed proposal block: %v", block))
  1051. } else if !cs.replayMode {
  1052. cs.Logger.Error("enterPropose: Error signing proposal", "height", height, "round", round, "err", err)
  1053. }
  1054. }
  1055. // Returns true if the proposal block is complete &&
  1056. // (if POLRound was proposed, we have +2/3 prevotes from there).
  1057. func (cs *State) isProposalComplete() bool {
  1058. if cs.Proposal == nil || cs.ProposalBlock == nil {
  1059. return false
  1060. }
  1061. // we have the proposal. if there's a POLRound,
  1062. // make sure we have the prevotes from it too
  1063. if cs.Proposal.POLRound < 0 {
  1064. return true
  1065. }
  1066. // if this is false the proposer is lying or we haven't received the POL yet
  1067. return cs.Votes.Prevotes(cs.Proposal.POLRound).HasTwoThirdsMajority()
  1068. }
  1069. // Create the next block to propose and return it. Returns nil block upon error.
  1070. //
  1071. // We really only need to return the parts, but the block is returned for
  1072. // convenience so we can log the proposal block.
  1073. //
  1074. // NOTE: keep it side-effect free for clarity.
  1075. // CONTRACT: cs.privValidator is not nil.
  1076. func (cs *State) createProposalBlock() (block *types.Block, blockParts *types.PartSet) {
  1077. if cs.privValidator == nil {
  1078. panic("entered createProposalBlock with privValidator being nil")
  1079. }
  1080. var commit *types.Commit
  1081. switch {
  1082. case cs.Height == cs.state.InitialHeight:
  1083. // We're creating a proposal for the first block.
  1084. // The commit is empty, but not nil.
  1085. commit = types.NewCommit(0, 0, types.BlockID{}, nil)
  1086. case cs.LastCommit.HasTwoThirdsMajority():
  1087. // Make the commit from LastCommit
  1088. commit = cs.LastCommit.MakeCommit()
  1089. default: // This shouldn't happen.
  1090. cs.Logger.Error("enterPropose: Cannot propose anything: No commit for the previous block")
  1091. return
  1092. }
  1093. if cs.privValidatorPubKey == nil {
  1094. // If this node is a validator & proposer in the current round, it will
  1095. // miss the opportunity to create a block.
  1096. cs.Logger.Error(fmt.Sprintf("enterPropose: %v", errPubKeyIsNotSet))
  1097. return
  1098. }
  1099. proposerAddr := cs.privValidatorPubKey.Address()
  1100. return cs.blockExec.CreateProposalBlock(cs.Height, cs.state, commit, proposerAddr)
  1101. }
  1102. // Enter: any +2/3 prevotes at next round.
  1103. func (cs *State) enterPrevoteWait(height int64, round int32) {
  1104. logger := cs.Logger.With("height", height, "round", round)
  1105. if cs.Height != height || round < cs.Round || (cs.Round == round && cstypes.RoundStepPrevoteWait <= cs.Step) {
  1106. logger.Debug(fmt.Sprintf(
  1107. "enterPrevoteWait(%v/%v): Invalid args. Current step: %v/%v/%v",
  1108. height,
  1109. round,
  1110. cs.Height,
  1111. cs.Round,
  1112. cs.Step))
  1113. return
  1114. }
  1115. if !cs.Votes.Prevotes(round).HasTwoThirdsAny() {
  1116. panic(fmt.Sprintf("enterPrevoteWait(%v/%v), but Prevotes does not have any +2/3 votes", height, round))
  1117. }
  1118. logger.Debug(fmt.Sprintf("enterPrevoteWait(%v/%v); current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  1119. defer func() {
  1120. // Done enterPrevoteWait:
  1121. cs.updateRoundStep(round, cstypes.RoundStepPrevoteWait)
  1122. cs.newStep()
  1123. }()
  1124. // Wait for some more prevotes; enterPrecommit
  1125. cs.scheduleTimeout(cs.config.Prevote(round), height, round, cstypes.RoundStepPrevoteWait)
  1126. }
  1127. // Enter: any +2/3 precommits for next round.
  1128. func (cs *State) enterPrecommitWait(height int64, round int32) {
  1129. logger := cs.Logger.With("height", height, "round", round)
  1130. if cs.Height != height || round < cs.Round || (cs.Round == round && cs.TriggeredTimeoutPrecommit) {
  1131. logger.Debug(
  1132. fmt.Sprintf(
  1133. "enterPrecommitWait(%v/%v): Invalid args. "+
  1134. "Current state is Height/Round: %v/%v/, TriggeredTimeoutPrecommit:%v",
  1135. height, round, cs.Height, cs.Round, cs.TriggeredTimeoutPrecommit))
  1136. return
  1137. }
  1138. if !cs.Votes.Precommits(round).HasTwoThirdsAny() {
  1139. panic(fmt.Sprintf("enterPrecommitWait(%v/%v), but Precommits does not have any +2/3 votes", height, round))
  1140. }
  1141. logger.Info(fmt.Sprintf("enterPrecommitWait(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  1142. defer func() {
  1143. // Done enterPrecommitWait:
  1144. cs.TriggeredTimeoutPrecommit = true
  1145. cs.newStep()
  1146. }()
  1147. // Wait for some more precommits; enterNewRound
  1148. cs.scheduleTimeout(cs.config.Precommit(round), height, round, cstypes.RoundStepPrecommitWait)
  1149. }
  1150. // Enter: +2/3 precommits for block
  1151. func (cs *State) enterCommit(height int64, commitRound int32) {
  1152. logger := cs.Logger.With("height", height, "commitRound", commitRound)
  1153. if cs.Height != height || cstypes.RoundStepCommit <= cs.Step {
  1154. logger.Debug(fmt.Sprintf(
  1155. "enterCommit(%v/%v): Invalid args. Current step: %v/%v/%v",
  1156. height,
  1157. commitRound,
  1158. cs.Height,
  1159. cs.Round,
  1160. cs.Step))
  1161. return
  1162. }
  1163. logger.Info(fmt.Sprintf("enterCommit(%v/%v). Current: %v/%v/%v", height, commitRound, cs.Height, cs.Round, cs.Step))
  1164. defer func() {
  1165. // Done enterCommit:
  1166. // keep cs.Round the same, commitRound points to the right Precommits set.
  1167. cs.updateRoundStep(cs.Round, cstypes.RoundStepCommit)
  1168. cs.CommitRound = commitRound
  1169. cs.CommitTime = tmtime.Now()
  1170. cs.newStep()
  1171. // Maybe finalize immediately.
  1172. cs.tryFinalizeCommit(height)
  1173. }()
  1174. blockID, ok := cs.Votes.Precommits(commitRound).TwoThirdsMajority()
  1175. if !ok {
  1176. panic("RunActionCommit() expects +2/3 precommits")
  1177. }
  1178. // The Locked* fields no longer matter.
  1179. // Move them over to ProposalBlock if they match the commit hash,
  1180. // otherwise they'll be cleared in updateToState.
  1181. if cs.LockedBlock.HashesTo(blockID.Hash) {
  1182. logger.Info("Commit is for locked block. Set ProposalBlock=LockedBlock", "blockHash", blockID.Hash)
  1183. cs.ProposalBlock = cs.LockedBlock
  1184. cs.ProposalBlockParts = cs.LockedBlockParts
  1185. }
  1186. // If we don't have the block being committed, set up to get it.
  1187. if !cs.ProposalBlock.HashesTo(blockID.Hash) {
  1188. if !cs.ProposalBlockParts.HasHeader(blockID.PartSetHeader) {
  1189. logger.Info(
  1190. "commit is for a block we do not know about; set ProposalBlock=nil",
  1191. "proposal", cs.ProposalBlock.Hash(),
  1192. "commit", blockID.Hash,
  1193. )
  1194. // We're getting the wrong block.
  1195. // Set up ProposalBlockParts and keep waiting.
  1196. cs.ProposalBlock = nil
  1197. cs.ProposalBlockParts = types.NewPartSetFromHeader(blockID.PartSetHeader)
  1198. if err := cs.eventBus.PublishEventValidBlock(cs.RoundStateEvent()); err != nil {
  1199. cs.Logger.Error("Error publishing valid block", "err", err)
  1200. }
  1201. cs.evsw.FireEvent(types.EventValidBlock, &cs.RoundState)
  1202. }
  1203. // else {
  1204. // We just need to keep waiting.
  1205. // }
  1206. }
  1207. }
  1208. // If we have the block AND +2/3 commits for it, finalize.
  1209. func (cs *State) tryFinalizeCommit(height int64) {
  1210. logger := cs.Logger.With("height", height)
  1211. if cs.Height != height {
  1212. panic(fmt.Sprintf("tryFinalizeCommit() cs.Height: %v vs height: %v", cs.Height, height))
  1213. }
  1214. blockID, ok := cs.Votes.Precommits(cs.CommitRound).TwoThirdsMajority()
  1215. if !ok || len(blockID.Hash) == 0 {
  1216. logger.Error("Attempt to finalize failed. There was no +2/3 majority, or +2/3 was for <nil>.")
  1217. return
  1218. }
  1219. if !cs.ProposalBlock.HashesTo(blockID.Hash) {
  1220. // TODO: this happens every time if we're not a validator (ugly logs)
  1221. // TODO: ^^ wait, why does it matter that we're a validator?
  1222. logger.Debug(
  1223. "attempt to finalize failed; we do not have the commit block",
  1224. "proposal-block", cs.ProposalBlock.Hash(),
  1225. "commit-block", blockID.Hash,
  1226. )
  1227. return
  1228. }
  1229. // go
  1230. cs.finalizeCommit(height)
  1231. }
  1232. // Increment height and goto cstypes.RoundStepNewHeight
  1233. func (cs *State) finalizeCommit(height int64) {
  1234. if cs.Height != height || cs.Step != cstypes.RoundStepCommit {
  1235. cs.Logger.Debug(fmt.Sprintf(
  1236. "finalizeCommit(%v): Invalid args. Current step: %v/%v/%v",
  1237. height,
  1238. cs.Height,
  1239. cs.Round,
  1240. cs.Step))
  1241. return
  1242. }
  1243. blockID, ok := cs.Votes.Precommits(cs.CommitRound).TwoThirdsMajority()
  1244. block, blockParts := cs.ProposalBlock, cs.ProposalBlockParts
  1245. if !ok {
  1246. panic("Cannot finalizeCommit, commit does not have two thirds majority")
  1247. }
  1248. if !blockParts.HasHeader(blockID.PartSetHeader) {
  1249. panic("Expected ProposalBlockParts header to be commit header")
  1250. }
  1251. if !block.HashesTo(blockID.Hash) {
  1252. panic("Cannot finalizeCommit, ProposalBlock does not hash to commit hash")
  1253. }
  1254. if err := cs.blockExec.ValidateBlock(cs.state, block); err != nil {
  1255. panic(fmt.Errorf("+2/3 committed an invalid block: %w", err))
  1256. }
  1257. cs.Logger.Info("finalizing commit of block with N txs",
  1258. "height", block.Height,
  1259. "hash", block.Hash(),
  1260. "root", block.AppHash,
  1261. "N", len(block.Txs),
  1262. )
  1263. cs.Logger.Debug(fmt.Sprintf("%v", block))
  1264. fail.Fail() // XXX
  1265. // Save to blockStore.
  1266. if cs.blockStore.Height() < block.Height {
  1267. // NOTE: the seenCommit is local justification to commit this block,
  1268. // but may differ from the LastCommit included in the next block
  1269. precommits := cs.Votes.Precommits(cs.CommitRound)
  1270. seenCommit := precommits.MakeCommit()
  1271. cs.blockStore.SaveBlock(block, blockParts, seenCommit)
  1272. } else {
  1273. // Happens during replay if we already saved the block but didn't commit
  1274. cs.Logger.Debug("calling finalizeCommit on already stored block", "height", block.Height)
  1275. }
  1276. fail.Fail() // XXX
  1277. // Write EndHeightMessage{} for this height, implying that the blockstore
  1278. // has saved the block.
  1279. //
  1280. // If we crash before writing this EndHeightMessage{}, we will recover by
  1281. // running ApplyBlock during the ABCI handshake when we restart. If we
  1282. // didn't save the block to the blockstore before writing
  1283. // EndHeightMessage{}, we'd have to change WAL replay -- currently it
  1284. // complains about replaying for heights where an #ENDHEIGHT entry already
  1285. // exists.
  1286. //
  1287. // Either way, the State should not be resumed until we
  1288. // successfully call ApplyBlock (ie. later here, or in Handshake after
  1289. // restart).
  1290. endMsg := tmcon.EndHeightMessage{Height: height}
  1291. if err := cs.wal.WriteSync(endMsg); err != nil { // NOTE: fsync
  1292. panic(fmt.Sprintf("Failed to write %v msg to consensus wal due to %v. Check your FS and restart the node",
  1293. endMsg, err))
  1294. }
  1295. fail.Fail() // XXX
  1296. // Create a copy of the state for staging and an event cache for txs.
  1297. stateCopy := cs.state.Copy()
  1298. // Execute and commit the block, update and save the state, and update the mempool.
  1299. // NOTE The block.AppHash wont reflect these txs until the next block.
  1300. var err error
  1301. var retainHeight int64
  1302. stateCopy, retainHeight, err = cs.blockExec.ApplyBlock(
  1303. stateCopy,
  1304. types.BlockID{Hash: block.Hash(), PartSetHeader: blockParts.Header()},
  1305. block)
  1306. if err != nil {
  1307. cs.Logger.Error("Error on ApplyBlock", "err", err)
  1308. return
  1309. }
  1310. fail.Fail() // XXX
  1311. // Prune old heights, if requested by ABCI app.
  1312. if retainHeight > 0 {
  1313. pruned, err := cs.pruneBlocks(retainHeight)
  1314. if err != nil {
  1315. cs.Logger.Error("Failed to prune blocks", "retainHeight", retainHeight, "err", err)
  1316. } else {
  1317. cs.Logger.Info("Pruned blocks", "pruned", pruned, "retainHeight", retainHeight)
  1318. }
  1319. }
  1320. // must be called before we update state
  1321. cs.recordMetrics(height, block)
  1322. // NewHeightStep!
  1323. cs.updateToState(stateCopy)
  1324. fail.Fail() // XXX
  1325. // Private validator might have changed it's key pair => refetch pubkey.
  1326. if err := cs.updatePrivValidatorPubKey(); err != nil {
  1327. cs.Logger.Error("Can't get private validator pubkey", "err", err)
  1328. }
  1329. // cs.StartTime is already set.
  1330. // Schedule Round0 to start soon.
  1331. cs.scheduleRound0(&cs.RoundState)
  1332. // By here,
  1333. // * cs.Height has been increment to height+1
  1334. // * cs.Step is now cstypes.RoundStepNewHeight
  1335. // * cs.StartTime is set to when we will start round0.
  1336. }
  1337. func (cs *State) pruneBlocks(retainHeight int64) (uint64, error) {
  1338. base := cs.blockStore.Base()
  1339. if retainHeight <= base {
  1340. return 0, nil
  1341. }
  1342. pruned, err := cs.blockStore.PruneBlocks(retainHeight)
  1343. if err != nil {
  1344. return 0, fmt.Errorf("failed to prune block store: %w", err)
  1345. }
  1346. err = cs.blockExec.Store().PruneStates(base, retainHeight)
  1347. if err != nil {
  1348. return 0, fmt.Errorf("failed to prune state database: %w", err)
  1349. }
  1350. return pruned, nil
  1351. }
  1352. func (cs *State) recordMetrics(height int64, block *types.Block) {
  1353. cs.metrics.Validators.Set(float64(cs.Validators.Size()))
  1354. cs.metrics.ValidatorsPower.Set(float64(cs.Validators.TotalVotingPower()))
  1355. var (
  1356. missingValidators int
  1357. missingValidatorsPower int64
  1358. )
  1359. // height=0 -> MissingValidators and MissingValidatorsPower are both 0.
  1360. // Remember that the first LastCommit is intentionally empty, so it's not
  1361. // fair to increment missing validators number.
  1362. if height > cs.state.InitialHeight {
  1363. // Sanity check that commit size matches validator set size - only applies
  1364. // after first block.
  1365. var (
  1366. commitSize = block.LastCommit.Size()
  1367. valSetLen = len(cs.LastValidators.Validators)
  1368. address types.Address
  1369. )
  1370. if commitSize != valSetLen {
  1371. panic(fmt.Sprintf("commit size (%d) doesn't match valset length (%d) at height %d\n\n%v\n\n%v",
  1372. commitSize, valSetLen, block.Height, block.LastCommit.Signatures, cs.LastValidators.Validators))
  1373. }
  1374. if cs.privValidator != nil {
  1375. if cs.privValidatorPubKey == nil {
  1376. // Metrics won't be updated, but it's not critical.
  1377. cs.Logger.Error(fmt.Sprintf("recordMetrics: %v", errPubKeyIsNotSet))
  1378. } else {
  1379. address = cs.privValidatorPubKey.Address()
  1380. }
  1381. }
  1382. for i, val := range cs.LastValidators.Validators {
  1383. commitSig := block.LastCommit.Signatures[i]
  1384. if commitSig.Absent() {
  1385. missingValidators++
  1386. missingValidatorsPower += val.VotingPower
  1387. }
  1388. if bytes.Equal(val.Address, address) {
  1389. label := []string{
  1390. "validator_address", val.Address.String(),
  1391. }
  1392. cs.metrics.ValidatorPower.With(label...).Set(float64(val.VotingPower))
  1393. if commitSig.ForBlock() {
  1394. cs.metrics.ValidatorLastSignedHeight.With(label...).Set(float64(height))
  1395. } else {
  1396. cs.metrics.ValidatorMissedBlocks.With(label...).Add(float64(1))
  1397. }
  1398. }
  1399. }
  1400. }
  1401. cs.metrics.MissingValidators.Set(float64(missingValidators))
  1402. cs.metrics.MissingValidatorsPower.Set(float64(missingValidatorsPower))
  1403. // NOTE: byzantine validators power and count is only for consensus evidence i.e. duplicate vote
  1404. var (
  1405. byzantineValidatorsPower = int64(0)
  1406. byzantineValidatorsCount = int64(0)
  1407. )
  1408. for _, ev := range block.Evidence.Evidence {
  1409. if dve, ok := ev.(*types.DuplicateVoteEvidence); ok {
  1410. if _, val := cs.Validators.GetByAddress(dve.VoteA.ValidatorAddress); val != nil {
  1411. byzantineValidatorsCount++
  1412. byzantineValidatorsPower += val.VotingPower
  1413. }
  1414. }
  1415. }
  1416. cs.metrics.ByzantineValidators.Set(float64(byzantineValidatorsCount))
  1417. cs.metrics.ByzantineValidatorsPower.Set(float64(byzantineValidatorsPower))
  1418. if height > 1 {
  1419. lastBlockMeta := cs.blockStore.LoadBlockMeta(height - 1)
  1420. if lastBlockMeta != nil {
  1421. cs.metrics.BlockIntervalSeconds.Observe(
  1422. block.Time.Sub(lastBlockMeta.Header.Time).Seconds(),
  1423. )
  1424. }
  1425. }
  1426. cs.metrics.NumTxs.Set(float64(len(block.Data.Txs)))
  1427. cs.metrics.TotalTxs.Add(float64(len(block.Data.Txs)))
  1428. cs.metrics.BlockSizeBytes.Set(float64(block.Size()))
  1429. cs.metrics.CommittedHeight.Set(float64(block.Height))
  1430. }
  1431. //-----------------------------------------------------------------------------
  1432. // NOTE: block is not necessarily valid.
  1433. // Asynchronously triggers either enterPrevote (before we timeout of propose) or tryFinalizeCommit,
  1434. // once we have the full block.
  1435. func (cs *State) addProposalBlockPart(msg *tmcon.BlockPartMessage, peerID p2p.ID) (added bool, err error) {
  1436. height, round, part := msg.Height, msg.Round, msg.Part
  1437. // Blocks might be reused, so round mismatch is OK
  1438. if cs.Height != height {
  1439. cs.Logger.Debug("Received block part from wrong height", "height", height, "round", round)
  1440. return false, nil
  1441. }
  1442. // We're not expecting a block part.
  1443. if cs.ProposalBlockParts == nil {
  1444. // NOTE: this can happen when we've gone to a higher round and
  1445. // then receive parts from the previous round - not necessarily a bad peer.
  1446. cs.Logger.Info("Received a block part when we're not expecting any",
  1447. "height", height, "round", round, "index", part.Index, "peer", peerID)
  1448. return false, nil
  1449. }
  1450. added, err = cs.ProposalBlockParts.AddPart(part)
  1451. if err != nil {
  1452. return added, err
  1453. }
  1454. if cs.ProposalBlockParts.ByteSize() > cs.state.ConsensusParams.Block.MaxBytes {
  1455. return added, fmt.Errorf("total size of proposal block parts exceeds maximum block bytes (%d > %d)",
  1456. cs.ProposalBlockParts.ByteSize(), cs.state.ConsensusParams.Block.MaxBytes,
  1457. )
  1458. }
  1459. if added && cs.ProposalBlockParts.IsComplete() {
  1460. bz, err := ioutil.ReadAll(cs.ProposalBlockParts.GetReader())
  1461. if err != nil {
  1462. return added, err
  1463. }
  1464. var pbb = new(tmproto.Block)
  1465. err = proto.Unmarshal(bz, pbb)
  1466. if err != nil {
  1467. return added, err
  1468. }
  1469. block, err := types.BlockFromProto(pbb)
  1470. if err != nil {
  1471. return added, err
  1472. }
  1473. cs.ProposalBlock = block
  1474. // NOTE: it's possible to receive complete proposal blocks for future rounds without having the proposal
  1475. cs.Logger.Info("Received complete proposal block", "height", cs.ProposalBlock.Height, "hash", cs.ProposalBlock.Hash())
  1476. if err := cs.eventBus.PublishEventCompleteProposal(cs.CompleteProposalEvent()); err != nil {
  1477. cs.Logger.Error("Error publishing event complete proposal", "err", err)
  1478. }
  1479. // Update Valid* if we can.
  1480. prevotes := cs.Votes.Prevotes(cs.Round)
  1481. blockID, hasTwoThirds := prevotes.TwoThirdsMajority()
  1482. if hasTwoThirds && !blockID.IsZero() && (cs.ValidRound < cs.Round) {
  1483. if cs.ProposalBlock.HashesTo(blockID.Hash) {
  1484. cs.Logger.Info("Updating valid block to new proposal block",
  1485. "valid-round", cs.Round, "valid-block-hash", cs.ProposalBlock.Hash())
  1486. cs.ValidRound = cs.Round
  1487. cs.ValidBlock = cs.ProposalBlock
  1488. cs.ValidBlockParts = cs.ProposalBlockParts
  1489. }
  1490. // TODO: In case there is +2/3 majority in Prevotes set for some
  1491. // block and cs.ProposalBlock contains different block, either
  1492. // proposer is faulty or voting power of faulty processes is more
  1493. // than 1/3. We should trigger in the future accountability
  1494. // procedure at this point.
  1495. }
  1496. if cs.Step <= cstypes.RoundStepPropose && cs.isProposalComplete() {
  1497. // Move onto the next step
  1498. cs.enterPrevote(height, cs.Round)
  1499. if hasTwoThirds { // this is optimisation as this will be triggered when prevote is added
  1500. cs.enterPrecommit(height, cs.Round)
  1501. }
  1502. } else if cs.Step == cstypes.RoundStepCommit {
  1503. // If we're waiting on the proposal block...
  1504. cs.tryFinalizeCommit(height)
  1505. }
  1506. return added, nil
  1507. }
  1508. return added, nil
  1509. }
  1510. // Attempt to add the vote. if its a duplicate signature, dupeout the validator
  1511. func (cs *State) tryAddVote(vote *types.Vote, peerID p2p.ID) (bool, error) {
  1512. added, err := cs.addVote(vote, peerID)
  1513. if err != nil {
  1514. // If the vote height is off, we'll just ignore it,
  1515. // But if it's a conflicting sig, add it to the cs.evpool.
  1516. // If it's otherwise invalid, punish peer.
  1517. // nolint: gocritic
  1518. if voteErr, ok := err.(*types.ErrVoteConflictingVotes); ok {
  1519. if cs.privValidatorPubKey == nil {
  1520. return false, errPubKeyIsNotSet
  1521. }
  1522. if bytes.Equal(vote.ValidatorAddress, cs.privValidatorPubKey.Address()) {
  1523. cs.Logger.Error(
  1524. "Found conflicting vote from ourselves. Did you unsafe_reset a validator?",
  1525. "height",
  1526. vote.Height,
  1527. "round",
  1528. vote.Round,
  1529. "type",
  1530. vote.Type)
  1531. return added, err
  1532. }
  1533. cs.evpool.ReportConflictingVotes(voteErr.VoteA, voteErr.VoteB)
  1534. return added, err
  1535. } else if err == types.ErrVoteNonDeterministicSignature {
  1536. cs.Logger.Debug("Vote has non-deterministic signature", "err", err)
  1537. } else {
  1538. // Either
  1539. // 1) bad peer OR
  1540. // 2) not a bad peer? this can also err sometimes with "Unexpected step" OR
  1541. // 3) tmkms use with multiple validators connecting to a single tmkms instance
  1542. // (https://github.com/tendermint/tendermint/issues/3839).
  1543. cs.Logger.Info("Error attempting to add vote", "err", err)
  1544. return added, ErrAddingVote
  1545. }
  1546. }
  1547. return added, nil
  1548. }
  1549. //-----------------------------------------------------------------------------
  1550. // CONTRACT: cs.privValidator is not nil.
  1551. func (cs *State) signVote(
  1552. msgType tmproto.SignedMsgType,
  1553. hash []byte,
  1554. header types.PartSetHeader,
  1555. ) (*types.Vote, error) {
  1556. // Flush the WAL. Otherwise, we may not recompute the same vote to sign,
  1557. // and the privValidator will refuse to sign anything.
  1558. if err := cs.wal.FlushAndSync(); err != nil {
  1559. return nil, err
  1560. }
  1561. if cs.privValidatorPubKey == nil {
  1562. return nil, errPubKeyIsNotSet
  1563. }
  1564. addr := cs.privValidatorPubKey.Address()
  1565. valIdx, _ := cs.Validators.GetByAddress(addr)
  1566. vote := &types.Vote{
  1567. ValidatorAddress: addr,
  1568. ValidatorIndex: valIdx,
  1569. Height: cs.Height,
  1570. Round: cs.Round,
  1571. Timestamp: cs.voteTime(),
  1572. Type: msgType,
  1573. BlockID: types.BlockID{Hash: hash, PartSetHeader: header},
  1574. }
  1575. v := vote.ToProto()
  1576. err := cs.privValidator.SignVote(cs.state.ChainID, v)
  1577. vote.Signature = v.Signature
  1578. return vote, err
  1579. }
  1580. func (cs *State) voteTime() time.Time {
  1581. now := tmtime.Now()
  1582. minVoteTime := now
  1583. // TODO: We should remove next line in case we don't vote for v in case cs.ProposalBlock == nil,
  1584. // even if cs.LockedBlock != nil. See https://docs.tendermint.com/master/spec/.
  1585. timeIota := time.Duration(cs.state.ConsensusParams.Block.TimeIotaMs) * time.Millisecond
  1586. if cs.LockedBlock != nil {
  1587. // See the BFT time spec https://docs.tendermint.com/master/spec/consensus/bft-time.html
  1588. minVoteTime = cs.LockedBlock.Time.Add(timeIota)
  1589. } else if cs.ProposalBlock != nil {
  1590. minVoteTime = cs.ProposalBlock.Time.Add(timeIota)
  1591. }
  1592. if now.After(minVoteTime) {
  1593. return now
  1594. }
  1595. return minVoteTime
  1596. }
  1597. // sign the vote and publish on internalMsgQueue
  1598. func (cs *State) signAddVote(msgType tmproto.SignedMsgType, hash []byte, header types.PartSetHeader) *types.Vote {
  1599. if cs.privValidator == nil { // the node does not have a key
  1600. return nil
  1601. }
  1602. if cs.privValidatorPubKey == nil {
  1603. // Vote won't be signed, but it's not critical.
  1604. cs.Logger.Error(fmt.Sprintf("signAddVote: %v", errPubKeyIsNotSet))
  1605. return nil
  1606. }
  1607. // If the node not in the validator set, do nothing.
  1608. if !cs.Validators.HasAddress(cs.privValidatorPubKey.Address()) {
  1609. return nil
  1610. }
  1611. // TODO: pass pubKey to signVote
  1612. vote, err := cs.signVote(msgType, hash, header)
  1613. if err == nil {
  1614. cs.sendInternalMessage(msgInfo{&tmcon.VoteMessage{Vote: vote}, ""})
  1615. cs.Logger.Info("Signed and pushed vote", "height", cs.Height, "round", cs.Round, "vote", vote)
  1616. return vote
  1617. }
  1618. // if !cs.replayMode {
  1619. cs.Logger.Error("Error signing vote", "height", cs.Height, "round", cs.Round, "vote", vote, "err", err)
  1620. //}
  1621. return nil
  1622. }
  1623. // updatePrivValidatorPubKey get's the private validator public key and
  1624. // memoizes it. This func returns an error if the private validator is not
  1625. // responding or responds with an error.
  1626. func (cs *State) updatePrivValidatorPubKey() error {
  1627. if cs.privValidator == nil {
  1628. return nil
  1629. }
  1630. pubKey, err := cs.privValidator.GetPubKey()
  1631. if err != nil {
  1632. return err
  1633. }
  1634. cs.privValidatorPubKey = pubKey
  1635. return nil
  1636. }
  1637. // look back to check existence of the node's consensus votes before joining consensus
  1638. func (cs *State) checkDoubleSigningRisk(height int64) error {
  1639. if cs.privValidator != nil && cs.privValidatorPubKey != nil && cs.config.DoubleSignCheckHeight > 0 && height > 0 {
  1640. valAddr := cs.privValidatorPubKey.Address()
  1641. doubleSignCheckHeight := cs.config.DoubleSignCheckHeight
  1642. if doubleSignCheckHeight > height {
  1643. doubleSignCheckHeight = height
  1644. }
  1645. for i := int64(1); i < doubleSignCheckHeight; i++ {
  1646. lastCommit := cs.blockStore.LoadSeenCommit(height - i)
  1647. if lastCommit != nil {
  1648. for sigIdx, s := range lastCommit.Signatures {
  1649. if s.BlockIDFlag == types.BlockIDFlagCommit && bytes.Equal(s.ValidatorAddress, valAddr) {
  1650. cs.Logger.Info("Found signature from the same key", "sig", s, "idx", sigIdx, "height", height-i)
  1651. return ErrSignatureFoundInPastBlocks
  1652. }
  1653. }
  1654. }
  1655. }
  1656. }
  1657. return nil
  1658. }
  1659. //---------------------------------------------------------
  1660. func CompareHRS(h1 int64, r1 int32, s1 cstypes.RoundStepType, h2 int64, r2 int32, s2 cstypes.RoundStepType) int {
  1661. if h1 < h2 {
  1662. return -1
  1663. } else if h1 > h2 {
  1664. return 1
  1665. }
  1666. if r1 < r2 {
  1667. return -1
  1668. } else if r1 > r2 {
  1669. return 1
  1670. }
  1671. if s1 < s2 {
  1672. return -1
  1673. } else if s1 > s2 {
  1674. return 1
  1675. }
  1676. return 0
  1677. }
  1678. // repairWalFile decodes messages from src (until the decoder errors) and
  1679. // writes them to dst.
  1680. func repairWalFile(src, dst string) error {
  1681. in, err := os.Open(src)
  1682. if err != nil {
  1683. return err
  1684. }
  1685. defer in.Close()
  1686. out, err := os.Open(dst)
  1687. if err != nil {
  1688. return err
  1689. }
  1690. defer out.Close()
  1691. var (
  1692. dec = NewWALDecoder(in)
  1693. enc = NewWALEncoder(out)
  1694. )
  1695. // best-case repair (until first error is encountered)
  1696. for {
  1697. msg, err := dec.Decode()
  1698. if err != nil {
  1699. break
  1700. }
  1701. err = enc.Encode(msg)
  1702. if err != nil {
  1703. return fmt.Errorf("failed to encode msg: %w", err)
  1704. }
  1705. }
  1706. return nil
  1707. }