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.

1966 lines
61 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. cstypes "github.com/tendermint/tendermint/consensus/types"
  15. "github.com/tendermint/tendermint/crypto"
  16. tmevents "github.com/tendermint/tendermint/libs/events"
  17. "github.com/tendermint/tendermint/libs/fail"
  18. tmjson "github.com/tendermint/tendermint/libs/json"
  19. "github.com/tendermint/tendermint/libs/log"
  20. tmmath "github.com/tendermint/tendermint/libs/math"
  21. tmos "github.com/tendermint/tendermint/libs/os"
  22. "github.com/tendermint/tendermint/libs/service"
  23. "github.com/tendermint/tendermint/p2p"
  24. tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
  25. sm "github.com/tendermint/tendermint/state"
  26. "github.com/tendermint/tendermint/types"
  27. tmtime "github.com/tendermint/tendermint/types/time"
  28. )
  29. // State handles execution of the consensus algorithm.
  30. // It processes votes and proposals, and upon reaching agreement,
  31. // commits blocks to the chain and executes them against the application.
  32. // The internal state machine receives input from peers, the internal validator, and from a timer.
  33. type State struct {
  34. service.BaseService
  35. // config details
  36. config *cfg.ConsensusConfig
  37. privValidator types.PrivValidator // for signing votes
  38. // store blocks and commits
  39. blockStore sm.BlockStore
  40. // create and execute blocks
  41. blockExec *sm.BlockExecutor
  42. // notify us if txs are available
  43. txNotifier txNotifier
  44. // add evidence to the pool
  45. // when it's detected
  46. evpool evidencePool
  47. // internal state
  48. mtx sync.RWMutex
  49. cstypes.RoundState
  50. state sm.State // State until height-1.
  51. // state changes may be triggered by: msgs from peers,
  52. // msgs from ourself, or by timeouts
  53. peerMsgQueue chan msgInfo
  54. internalMsgQueue chan msgInfo
  55. timeoutTicker TimeoutTicker
  56. // privValidator pubkey, memoized for the duration of one block
  57. // to avoid extra requests to HSM
  58. privValidatorPubKey crypto.PubKey
  59. // information about about added votes and block parts are written on this channel
  60. // so statistics can be computed by reactor
  61. statsMsgQueue chan msgInfo
  62. // we use eventBus to trigger msg broadcasts in the reactor,
  63. // and to notify external subscribers, eg. through a websocket
  64. eventBus *types.EventBus
  65. // a Write-Ahead Log ensures we can recover from any kind of crash
  66. // and helps us avoid signing conflicting votes
  67. wal WAL
  68. replayMode bool // so we don't log signing errors during replay
  69. doWALCatchup bool // determines if we even try to do the catchup
  70. // for tests where we want to limit the number of transitions the state makes
  71. nSteps int
  72. // some functions can be overwritten for testing
  73. decideProposal func(height int64, round int32)
  74. // closed when we finish shutting down
  75. done chan struct{}
  76. // synchronous pubsub between consensus state and reactor.
  77. // state only emits EventNewRoundStep and EventVote
  78. evsw tmevents.EventSwitch
  79. // for reporting metrics
  80. metrics *Metrics
  81. // misbehaviors mapped for each height (can't have more than one misbehavior per height)
  82. misbehaviors map[int64]Misbehavior
  83. // the switch is passed to the state so that maveick misbehaviors can directly control which
  84. // information they send to which nodes
  85. sw *p2p.Switch
  86. }
  87. // StateOption sets an optional parameter on the State.
  88. type StateOption func(*State)
  89. // NewState returns a new State.
  90. func NewState(
  91. config *cfg.ConsensusConfig,
  92. state sm.State,
  93. blockExec *sm.BlockExecutor,
  94. blockStore sm.BlockStore,
  95. txNotifier txNotifier,
  96. evpool evidencePool,
  97. misbehaviors map[int64]Misbehavior,
  98. options ...StateOption,
  99. ) *State {
  100. cs := &State{
  101. config: config,
  102. blockExec: blockExec,
  103. blockStore: blockStore,
  104. txNotifier: txNotifier,
  105. peerMsgQueue: make(chan msgInfo, msgQueueSize),
  106. internalMsgQueue: make(chan msgInfo, msgQueueSize),
  107. timeoutTicker: NewTimeoutTicker(),
  108. statsMsgQueue: make(chan msgInfo, msgQueueSize),
  109. done: make(chan struct{}),
  110. doWALCatchup: true,
  111. wal: nilWAL{},
  112. evpool: evpool,
  113. evsw: tmevents.NewEventSwitch(),
  114. metrics: NopMetrics(),
  115. misbehaviors: misbehaviors,
  116. }
  117. // set function defaults (may be overwritten before calling Start)
  118. cs.decideProposal = cs.defaultDecideProposal
  119. // We have no votes, so reconstruct LastCommit from SeenCommit.
  120. if state.LastBlockHeight > 0 {
  121. cs.reconstructLastCommit(state)
  122. }
  123. cs.updateToState(state)
  124. // Don't call scheduleRound0 yet.
  125. // We do that upon Start().
  126. cs.BaseService = *service.NewBaseService(nil, "State", cs)
  127. for _, option := range options {
  128. option(cs)
  129. }
  130. return cs
  131. }
  132. // I know this is not great but the maverick consensus state needs access to the peers
  133. func (cs *State) SetSwitch(sw *p2p.Switch) {
  134. cs.sw = sw
  135. }
  136. // state transitions on complete-proposal, 2/3-any, 2/3-one
  137. func (cs *State) handleMsg(mi msgInfo) {
  138. cs.mtx.Lock()
  139. defer cs.mtx.Unlock()
  140. var (
  141. added bool
  142. err error
  143. )
  144. msg, peerID := mi.Msg, mi.PeerID
  145. switch msg := msg.(type) {
  146. case *ProposalMessage:
  147. // will not cause transition.
  148. // once proposal is set, we can receive block parts
  149. // err = cs.setProposal(msg.Proposal)
  150. if b, ok := cs.misbehaviors[cs.Height]; ok {
  151. err = b.ReceiveProposal(cs, msg.Proposal)
  152. } else {
  153. err = defaultReceiveProposal(cs, msg.Proposal)
  154. }
  155. case *BlockPartMessage:
  156. // if the proposal is complete, we'll enterPrevote or tryFinalizeCommit
  157. added, err = cs.addProposalBlockPart(msg, peerID)
  158. if added {
  159. cs.statsMsgQueue <- mi
  160. }
  161. if err != nil && msg.Round != cs.Round {
  162. cs.Logger.Debug(
  163. "Received block part from wrong round",
  164. "height",
  165. cs.Height,
  166. "csRound",
  167. cs.Round,
  168. "blockRound",
  169. msg.Round)
  170. err = nil
  171. }
  172. case *VoteMessage:
  173. // attempt to add the vote and dupeout the validator if its a duplicate signature
  174. // if the vote gives us a 2/3-any or 2/3-one, we transition
  175. added, err = cs.tryAddVote(msg.Vote, peerID)
  176. if added {
  177. cs.statsMsgQueue <- mi
  178. }
  179. // if err == ErrAddingVote {
  180. // TODO: punish peer
  181. // We probably don't want to stop the peer here. The vote does not
  182. // necessarily comes from a malicious peer but can be just broadcasted by
  183. // a typical peer.
  184. // https://github.com/tendermint/tendermint/issues/1281
  185. // }
  186. // NOTE: the vote is broadcast to peers by the reactor listening
  187. // for vote events
  188. // TODO: If rs.Height == vote.Height && rs.Round < vote.Round,
  189. // the peer is sending us CatchupCommit precommits.
  190. // We could make note of this and help filter in broadcastHasVoteMessage().
  191. default:
  192. cs.Logger.Error("Unknown msg type", "type", reflect.TypeOf(msg))
  193. return
  194. }
  195. if err != nil {
  196. cs.Logger.Error("Error with msg", "height", cs.Height, "round", cs.Round,
  197. "peer", peerID, "err", err, "msg", msg)
  198. }
  199. }
  200. // Enter (CreateEmptyBlocks): from enterNewRound(height,round)
  201. // Enter (CreateEmptyBlocks, CreateEmptyBlocksInterval > 0 ):
  202. // after enterNewRound(height,round), after timeout of CreateEmptyBlocksInterval
  203. // Enter (!CreateEmptyBlocks) : after enterNewRound(height,round), once txs are in the mempool
  204. func (cs *State) enterPropose(height int64, round int32) {
  205. logger := cs.Logger.With("height", height, "round", round)
  206. if cs.Height != height || round < cs.Round || (cs.Round == round && cstypes.RoundStepPropose <= cs.Step) {
  207. logger.Debug(fmt.Sprintf(
  208. "enterPropose(%v/%v): Invalid args. Current step: %v/%v/%v",
  209. height,
  210. round,
  211. cs.Height,
  212. cs.Round,
  213. cs.Step))
  214. return
  215. }
  216. logger.Info(fmt.Sprintf("enterPropose(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  217. defer func() {
  218. // Done enterPropose:
  219. cs.updateRoundStep(round, cstypes.RoundStepPropose)
  220. cs.newStep()
  221. // If we have the whole proposal + POL, then goto Prevote now.
  222. // else, we'll enterPrevote when the rest of the proposal is received (in AddProposalBlockPart),
  223. // or else after timeoutPropose
  224. if cs.isProposalComplete() {
  225. cs.enterPrevote(height, cs.Round)
  226. }
  227. }()
  228. if b, ok := cs.misbehaviors[cs.Height]; ok {
  229. b.EnterPropose(cs, height, round)
  230. } else {
  231. defaultEnterPropose(cs, height, round)
  232. }
  233. }
  234. // Enter: `timeoutPropose` after entering Propose.
  235. // Enter: proposal block and POL is ready.
  236. // Prevote for LockedBlock if we're locked, or ProposalBlock if valid.
  237. // Otherwise vote nil.
  238. func (cs *State) enterPrevote(height int64, round int32) {
  239. if cs.Height != height || round < cs.Round || (cs.Round == round && cstypes.RoundStepPrevote <= cs.Step) {
  240. cs.Logger.Debug(fmt.Sprintf(
  241. "enterPrevote(%v/%v): Invalid args. Current step: %v/%v/%v",
  242. height,
  243. round,
  244. cs.Height,
  245. cs.Round,
  246. cs.Step))
  247. return
  248. }
  249. defer func() {
  250. // Done enterPrevote:
  251. cs.updateRoundStep(round, cstypes.RoundStepPrevote)
  252. cs.newStep()
  253. }()
  254. cs.Logger.Info(fmt.Sprintf("enterPrevote(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  255. // Sign and broadcast vote as necessary
  256. if b, ok := cs.misbehaviors[cs.Height]; ok {
  257. b.EnterPrevote(cs, height, round)
  258. } else {
  259. defaultEnterPrevote(cs, height, round)
  260. }
  261. // Once `addVote` hits any +2/3 prevotes, we will go to PrevoteWait
  262. // (so we have more time to try and collect +2/3 prevotes for a single block)
  263. }
  264. // Enter: `timeoutPrevote` after any +2/3 prevotes.
  265. // Enter: `timeoutPrecommit` after any +2/3 precommits.
  266. // Enter: +2/3 precomits for block or nil.
  267. // Lock & precommit the ProposalBlock if we have enough prevotes for it (a POL in this round)
  268. // else, unlock an existing lock and precommit nil if +2/3 of prevotes were nil,
  269. // else, precommit nil otherwise.
  270. func (cs *State) enterPrecommit(height int64, round int32) {
  271. logger := cs.Logger.With("height", height, "round", round)
  272. if cs.Height != height || round < cs.Round || (cs.Round == round && cstypes.RoundStepPrecommit <= cs.Step) {
  273. logger.Debug(fmt.Sprintf(
  274. "enterPrecommit(%v/%v): Invalid args. Current step: %v/%v/%v",
  275. height,
  276. round,
  277. cs.Height,
  278. cs.Round,
  279. cs.Step))
  280. return
  281. }
  282. logger.Info(fmt.Sprintf("enterPrecommit(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  283. defer func() {
  284. // Done enterPrecommit:
  285. cs.updateRoundStep(round, cstypes.RoundStepPrecommit)
  286. cs.newStep()
  287. }()
  288. if b, ok := cs.misbehaviors[cs.Height]; ok {
  289. b.EnterPrecommit(cs, height, round)
  290. } else {
  291. defaultEnterPrecommit(cs, height, round)
  292. }
  293. }
  294. func (cs *State) addVote(
  295. vote *types.Vote,
  296. peerID p2p.NodeID) (added bool, err error) {
  297. cs.Logger.Debug(
  298. "addVote",
  299. "voteHeight",
  300. vote.Height,
  301. "voteType",
  302. vote.Type,
  303. "valIndex",
  304. vote.ValidatorIndex,
  305. "csHeight",
  306. cs.Height,
  307. )
  308. // A precommit for the previous height?
  309. // These come in while we wait timeoutCommit
  310. if vote.Height+1 == cs.Height && vote.Type == tmproto.PrecommitType {
  311. if cs.Step != cstypes.RoundStepNewHeight {
  312. // Late precommit at prior height is ignored
  313. cs.Logger.Debug("Precommit vote came in after commit timeout and has been ignored", "vote", vote)
  314. return
  315. }
  316. added, err = cs.LastCommit.AddVote(vote)
  317. if !added {
  318. return
  319. }
  320. cs.Logger.Info(fmt.Sprintf("Added to lastPrecommits: %v", cs.LastCommit.StringShort()))
  321. _ = cs.eventBus.PublishEventVote(types.EventDataVote{Vote: vote})
  322. cs.evsw.FireEvent(types.EventVote, vote)
  323. // if we can skip timeoutCommit and have all the votes now,
  324. if cs.config.SkipTimeoutCommit && cs.LastCommit.HasAll() {
  325. // go straight to new round (skip timeout commit)
  326. // cs.scheduleTimeout(time.Duration(0), cs.Height, 0, cstypes.RoundStepNewHeight)
  327. cs.enterNewRound(cs.Height, 0)
  328. }
  329. return
  330. }
  331. // Height mismatch is ignored.
  332. // Not necessarily a bad peer, but not favourable behaviour.
  333. if vote.Height != cs.Height {
  334. cs.Logger.Info("Vote ignored and not added", "voteHeight", vote.Height, "csHeight", cs.Height, "peerID", peerID)
  335. return
  336. }
  337. added, err = cs.Votes.AddVote(vote, peerID)
  338. if !added {
  339. // Either duplicate, or error upon cs.Votes.AddByIndex()
  340. return
  341. }
  342. _ = cs.eventBus.PublishEventVote(types.EventDataVote{Vote: vote})
  343. cs.evsw.FireEvent(types.EventVote, vote)
  344. switch vote.Type {
  345. case tmproto.PrevoteType:
  346. if b, ok := cs.misbehaviors[cs.Height]; ok {
  347. b.ReceivePrevote(cs, vote)
  348. } else {
  349. defaultReceivePrevote(cs, vote)
  350. }
  351. case tmproto.PrecommitType:
  352. if b, ok := cs.misbehaviors[cs.Height]; ok {
  353. b.ReceivePrecommit(cs, vote)
  354. }
  355. defaultReceivePrecommit(cs, vote)
  356. default:
  357. panic(fmt.Sprintf("Unexpected vote type %v", vote.Type))
  358. }
  359. return added, err
  360. }
  361. //-----------------------------------------------------------------------------
  362. // Errors
  363. var (
  364. ErrInvalidProposalSignature = errors.New("error invalid proposal signature")
  365. ErrInvalidProposalPOLRound = errors.New("error invalid proposal POL round")
  366. ErrAddingVote = errors.New("error adding vote")
  367. ErrSignatureFoundInPastBlocks = errors.New("found signature from the same key")
  368. errPubKeyIsNotSet = errors.New("pubkey is not set. Look for \"Can't get private validator pubkey\" errors")
  369. )
  370. //-----------------------------------------------------------------------------
  371. var (
  372. msgQueueSize = 1000
  373. )
  374. // msgs from the reactor which may update the state
  375. type msgInfo struct {
  376. Msg Message `json:"msg"`
  377. PeerID p2p.NodeID `json:"peer_key"`
  378. }
  379. // internally generated messages which may update the state
  380. type timeoutInfo struct {
  381. Duration time.Duration `json:"duration"`
  382. Height int64 `json:"height"`
  383. Round int32 `json:"round"`
  384. Step cstypes.RoundStepType `json:"step"`
  385. }
  386. func (ti *timeoutInfo) String() string {
  387. return fmt.Sprintf("%v ; %d/%d %v", ti.Duration, ti.Height, ti.Round, ti.Step)
  388. }
  389. // interface to the mempool
  390. type txNotifier interface {
  391. TxsAvailable() <-chan struct{}
  392. }
  393. // interface to the evidence pool
  394. type evidencePool interface {
  395. // reports conflicting votes to the evidence pool to be processed into evidence
  396. ReportConflictingVotes(voteA, voteB *types.Vote)
  397. }
  398. //----------------------------------------
  399. // Public interface
  400. // SetLogger implements Service.
  401. func (cs *State) SetLogger(l log.Logger) {
  402. cs.BaseService.Logger = l
  403. cs.timeoutTicker.SetLogger(l)
  404. }
  405. // SetEventBus sets event bus.
  406. func (cs *State) SetEventBus(b *types.EventBus) {
  407. cs.eventBus = b
  408. cs.blockExec.SetEventBus(b)
  409. }
  410. // StateMetrics sets the metrics.
  411. func StateMetrics(metrics *Metrics) StateOption {
  412. return func(cs *State) { cs.metrics = metrics }
  413. }
  414. // String returns a string.
  415. func (cs *State) String() string {
  416. // better not to access shared variables
  417. return "ConsensusState"
  418. }
  419. // GetState returns a copy of the chain state.
  420. func (cs *State) GetState() sm.State {
  421. cs.mtx.RLock()
  422. defer cs.mtx.RUnlock()
  423. return cs.state.Copy()
  424. }
  425. // GetLastHeight returns the last height committed.
  426. // If there were no blocks, returns 0.
  427. func (cs *State) GetLastHeight() int64 {
  428. cs.mtx.RLock()
  429. defer cs.mtx.RUnlock()
  430. return cs.RoundState.Height - 1
  431. }
  432. // GetRoundState returns a shallow copy of the internal consensus state.
  433. func (cs *State) GetRoundState() *cstypes.RoundState {
  434. cs.mtx.RLock()
  435. rs := cs.RoundState // copy
  436. cs.mtx.RUnlock()
  437. return &rs
  438. }
  439. // GetRoundStateJSON returns a json of RoundState.
  440. func (cs *State) GetRoundStateJSON() ([]byte, error) {
  441. cs.mtx.RLock()
  442. defer cs.mtx.RUnlock()
  443. return tmjson.Marshal(cs.RoundState)
  444. }
  445. // GetRoundStateSimpleJSON returns a json of RoundStateSimple
  446. func (cs *State) GetRoundStateSimpleJSON() ([]byte, error) {
  447. cs.mtx.RLock()
  448. defer cs.mtx.RUnlock()
  449. return tmjson.Marshal(cs.RoundState.RoundStateSimple())
  450. }
  451. // GetValidators returns a copy of the current validators.
  452. func (cs *State) GetValidators() (int64, []*types.Validator) {
  453. cs.mtx.RLock()
  454. defer cs.mtx.RUnlock()
  455. return cs.state.LastBlockHeight, cs.state.Validators.Copy().Validators
  456. }
  457. // SetPrivValidator sets the private validator account for signing votes. It
  458. // immediately requests pubkey and caches it.
  459. func (cs *State) SetPrivValidator(priv types.PrivValidator) {
  460. cs.mtx.Lock()
  461. defer cs.mtx.Unlock()
  462. cs.privValidator = priv
  463. if err := cs.updatePrivValidatorPubKey(); err != nil {
  464. cs.Logger.Error("Can't get private validator pubkey", "err", err)
  465. }
  466. }
  467. // SetTimeoutTicker sets the local timer. It may be useful to overwrite for testing.
  468. func (cs *State) SetTimeoutTicker(timeoutTicker TimeoutTicker) {
  469. cs.mtx.Lock()
  470. cs.timeoutTicker = timeoutTicker
  471. cs.mtx.Unlock()
  472. }
  473. // LoadCommit loads the commit for a given height.
  474. func (cs *State) LoadCommit(height int64) *types.Commit {
  475. cs.mtx.RLock()
  476. defer cs.mtx.RUnlock()
  477. if height == cs.blockStore.Height() {
  478. return cs.blockStore.LoadSeenCommit(height)
  479. }
  480. return cs.blockStore.LoadBlockCommit(height)
  481. }
  482. // OnStart loads the latest state via the WAL, and starts the timeout and
  483. // receive routines.
  484. func (cs *State) OnStart() error {
  485. // We may set the WAL in testing before calling Start, so only OpenWAL if its
  486. // still the nilWAL.
  487. if _, ok := cs.wal.(nilWAL); ok {
  488. if err := cs.loadWalFile(); err != nil {
  489. return err
  490. }
  491. }
  492. // We may have lost some votes if the process crashed reload from consensus
  493. // log to catchup.
  494. if cs.doWALCatchup {
  495. repairAttempted := false
  496. LOOP:
  497. for {
  498. err := cs.catchupReplay(cs.Height)
  499. switch {
  500. case err == nil:
  501. break LOOP
  502. case !IsDataCorruptionError(err):
  503. cs.Logger.Error("Error on catchup replay. Proceeding to start State anyway", "err", err)
  504. break LOOP
  505. case repairAttempted:
  506. return err
  507. }
  508. cs.Logger.Info("WAL file is corrupted. Attempting repair", "err", err)
  509. // 1) prep work
  510. if err := cs.wal.Stop(); err != nil {
  511. return err
  512. }
  513. repairAttempted = true
  514. // 2) backup original WAL file
  515. corruptedFile := fmt.Sprintf("%s.CORRUPTED", cs.config.WalFile())
  516. if err := tmos.CopyFile(cs.config.WalFile(), corruptedFile); err != nil {
  517. return err
  518. }
  519. cs.Logger.Info("Backed up WAL file", "src", cs.config.WalFile(), "dst", corruptedFile)
  520. // 3) try to repair (WAL file will be overwritten!)
  521. if err := repairWalFile(corruptedFile, cs.config.WalFile()); err != nil {
  522. cs.Logger.Error("Repair failed", "err", err)
  523. return err
  524. }
  525. cs.Logger.Info("Successful repair")
  526. // reload WAL file
  527. if err := cs.loadWalFile(); err != nil {
  528. return err
  529. }
  530. }
  531. }
  532. if err := cs.evsw.Start(); err != nil {
  533. return err
  534. }
  535. // we need the timeoutRoutine for replay so
  536. // we don't block on the tick chan.
  537. // NOTE: we will get a build up of garbage go routines
  538. // firing on the tockChan until the receiveRoutine is started
  539. // to deal with them (by that point, at most one will be valid)
  540. if err := cs.timeoutTicker.Start(); err != nil {
  541. return err
  542. }
  543. // Double Signing Risk Reduction
  544. if err := cs.checkDoubleSigningRisk(cs.Height); err != nil {
  545. return err
  546. }
  547. // now start the receiveRoutine
  548. go cs.receiveRoutine(0)
  549. // schedule the first round!
  550. // use GetRoundState so we don't race the receiveRoutine for access
  551. cs.scheduleRound0(cs.GetRoundState())
  552. return nil
  553. }
  554. // loadWalFile loads WAL data from file. It overwrites cs.wal.
  555. func (cs *State) loadWalFile() error {
  556. wal, err := cs.OpenWAL(cs.config.WalFile())
  557. if err != nil {
  558. cs.Logger.Error("Error loading State wal", "err", err)
  559. return err
  560. }
  561. cs.wal = wal
  562. return nil
  563. }
  564. // OnStop implements service.Service.
  565. func (cs *State) OnStop() {
  566. if err := cs.evsw.Stop(); err != nil {
  567. cs.Logger.Error("error trying to stop eventSwitch", "error", err)
  568. }
  569. if err := cs.timeoutTicker.Stop(); err != nil {
  570. cs.Logger.Error("error trying to stop timeoutTicket", "error", err)
  571. }
  572. // WAL is stopped in receiveRoutine.
  573. }
  574. // Wait waits for the the main routine to return.
  575. // NOTE: be sure to Stop() the event switch and drain
  576. // any event channels or this may deadlock
  577. func (cs *State) Wait() {
  578. <-cs.done
  579. }
  580. // OpenWAL opens a file to log all consensus messages and timeouts for
  581. // deterministic accountability.
  582. func (cs *State) OpenWAL(walFile string) (WAL, error) {
  583. wal, err := NewWAL(walFile)
  584. if err != nil {
  585. cs.Logger.Error("Failed to open WAL", "file", walFile, "err", err)
  586. return nil, err
  587. }
  588. wal.SetLogger(cs.Logger.With("wal", walFile))
  589. if err := wal.Start(); err != nil {
  590. cs.Logger.Error("Failed to start WAL", "err", err)
  591. return nil, err
  592. }
  593. return wal, nil
  594. }
  595. //------------------------------------------------------------
  596. // Public interface for passing messages into the consensus state, possibly causing a state transition.
  597. // If peerID == "", the msg is considered internal.
  598. // Messages are added to the appropriate queue (peer or internal).
  599. // If the queue is full, the function may block.
  600. // TODO: should these return anything or let callers just use events?
  601. // AddVote inputs a vote.
  602. func (cs *State) AddVote(vote *types.Vote, peerID p2p.NodeID) (added bool, err error) {
  603. if peerID == "" {
  604. cs.internalMsgQueue <- msgInfo{&VoteMessage{vote}, ""}
  605. } else {
  606. cs.peerMsgQueue <- msgInfo{&VoteMessage{vote}, peerID}
  607. }
  608. // TODO: wait for event?!
  609. return false, nil
  610. }
  611. // SetProposal inputs a proposal.
  612. func (cs *State) SetProposal(proposal *types.Proposal, peerID p2p.NodeID) error {
  613. if peerID == "" {
  614. cs.internalMsgQueue <- msgInfo{&ProposalMessage{proposal}, ""}
  615. } else {
  616. cs.peerMsgQueue <- msgInfo{&ProposalMessage{proposal}, peerID}
  617. }
  618. // TODO: wait for event?!
  619. return nil
  620. }
  621. // AddProposalBlockPart inputs a part of the proposal block.
  622. func (cs *State) AddProposalBlockPart(height int64, round int32, part *types.Part, peerID p2p.NodeID) error {
  623. if peerID == "" {
  624. cs.internalMsgQueue <- msgInfo{&BlockPartMessage{height, round, part}, ""}
  625. } else {
  626. cs.peerMsgQueue <- msgInfo{&BlockPartMessage{height, round, part}, peerID}
  627. }
  628. // TODO: wait for event?!
  629. return nil
  630. }
  631. // SetProposalAndBlock inputs the proposal and all block parts.
  632. func (cs *State) SetProposalAndBlock(
  633. proposal *types.Proposal,
  634. block *types.Block,
  635. parts *types.PartSet,
  636. peerID p2p.NodeID,
  637. ) error {
  638. if err := cs.SetProposal(proposal, peerID); err != nil {
  639. return err
  640. }
  641. for i := 0; i < int(parts.Total()); i++ {
  642. part := parts.GetPart(i)
  643. if err := cs.AddProposalBlockPart(proposal.Height, proposal.Round, part, peerID); err != nil {
  644. return err
  645. }
  646. }
  647. return nil
  648. }
  649. //------------------------------------------------------------
  650. // internal functions for managing the state
  651. func (cs *State) updateHeight(height int64) {
  652. cs.metrics.Height.Set(float64(height))
  653. cs.Height = height
  654. }
  655. func (cs *State) updateRoundStep(round int32, step cstypes.RoundStepType) {
  656. cs.Round = round
  657. cs.Step = step
  658. }
  659. // enterNewRound(height, 0) at cs.StartTime.
  660. func (cs *State) scheduleRound0(rs *cstypes.RoundState) {
  661. // cs.Logger.Info("scheduleRound0", "now", tmtime.Now(), "startTime", cs.StartTime)
  662. sleepDuration := rs.StartTime.Sub(tmtime.Now())
  663. cs.scheduleTimeout(sleepDuration, rs.Height, 0, cstypes.RoundStepNewHeight)
  664. }
  665. // Attempt to schedule a timeout (by sending timeoutInfo on the tickChan)
  666. func (cs *State) scheduleTimeout(duration time.Duration, height int64, round int32, step cstypes.RoundStepType) {
  667. cs.timeoutTicker.ScheduleTimeout(timeoutInfo{duration, height, round, step})
  668. }
  669. // send a msg into the receiveRoutine regarding our own proposal, block part, or vote
  670. func (cs *State) sendInternalMessage(mi msgInfo) {
  671. select {
  672. case cs.internalMsgQueue <- mi:
  673. default:
  674. // NOTE: using the go-routine means our votes can
  675. // be processed out of order.
  676. // TODO: use CList here for strict determinism and
  677. // attempt push to internalMsgQueue in receiveRoutine
  678. cs.Logger.Info("Internal msg queue is full. Using a go-routine")
  679. go func() { cs.internalMsgQueue <- mi }()
  680. }
  681. }
  682. // Reconstruct LastCommit from SeenCommit, which we saved along with the block,
  683. // (which happens even before saving the state)
  684. func (cs *State) reconstructLastCommit(state sm.State) {
  685. seenCommit := cs.blockStore.LoadSeenCommit(state.LastBlockHeight)
  686. if seenCommit == nil {
  687. panic(fmt.Sprintf("Failed to reconstruct LastCommit: seen commit for height %v not found",
  688. state.LastBlockHeight))
  689. }
  690. lastPrecommits := types.CommitToVoteSet(state.ChainID, seenCommit, state.LastValidators)
  691. if !lastPrecommits.HasTwoThirdsMajority() {
  692. panic("Failed to reconstruct LastCommit: Does not have +2/3 maj")
  693. }
  694. cs.LastCommit = lastPrecommits
  695. }
  696. // Updates State and increments height to match that of state.
  697. // The round becomes 0 and cs.Step becomes cstypes.RoundStepNewHeight.
  698. func (cs *State) updateToState(state sm.State) {
  699. if cs.CommitRound > -1 && 0 < cs.Height && cs.Height != state.LastBlockHeight {
  700. panic(fmt.Sprintf("updateToState() expected state height of %v but found %v",
  701. cs.Height, state.LastBlockHeight))
  702. }
  703. if !cs.state.IsEmpty() {
  704. if cs.state.LastBlockHeight > 0 && cs.state.LastBlockHeight+1 != cs.Height {
  705. // This might happen when someone else is mutating cs.state.
  706. // Someone forgot to pass in state.Copy() somewhere?!
  707. panic(fmt.Sprintf("Inconsistent cs.state.LastBlockHeight+1 %v vs cs.Height %v",
  708. cs.state.LastBlockHeight+1, cs.Height))
  709. }
  710. if cs.state.LastBlockHeight > 0 && cs.Height == cs.state.InitialHeight {
  711. panic(fmt.Sprintf("Inconsistent cs.state.LastBlockHeight %v, expected 0 for initial height %v",
  712. cs.state.LastBlockHeight, cs.state.InitialHeight))
  713. }
  714. // If state isn't further out than cs.state, just ignore.
  715. // This happens when SwitchToConsensus() is called in the reactor.
  716. // We don't want to reset e.g. the Votes, but we still want to
  717. // signal the new round step, because other services (eg. txNotifier)
  718. // depend on having an up-to-date peer state!
  719. if state.LastBlockHeight <= cs.state.LastBlockHeight {
  720. cs.Logger.Info(
  721. "Ignoring updateToState()",
  722. "newHeight",
  723. state.LastBlockHeight+1,
  724. "oldHeight",
  725. cs.state.LastBlockHeight+1)
  726. cs.newStep()
  727. return
  728. }
  729. }
  730. // Reset fields based on state.
  731. validators := state.Validators
  732. switch {
  733. case state.LastBlockHeight == 0: // Very first commit should be empty.
  734. cs.LastCommit = (*types.VoteSet)(nil)
  735. case cs.CommitRound > -1 && cs.Votes != nil: // Otherwise, use cs.Votes
  736. if !cs.Votes.Precommits(cs.CommitRound).HasTwoThirdsMajority() {
  737. panic(fmt.Sprintf("Wanted to form a Commit, but Precommits (H/R: %d/%d) didn't have 2/3+: %v",
  738. state.LastBlockHeight,
  739. cs.CommitRound,
  740. cs.Votes.Precommits(cs.CommitRound)))
  741. }
  742. cs.LastCommit = cs.Votes.Precommits(cs.CommitRound)
  743. case cs.LastCommit == nil:
  744. // NOTE: when Tendermint starts, it has no votes. reconstructLastCommit
  745. // must be called to reconstruct LastCommit from SeenCommit.
  746. panic(fmt.Sprintf("LastCommit cannot be empty after initial block (H:%d)",
  747. state.LastBlockHeight+1,
  748. ))
  749. }
  750. // Next desired block height
  751. height := state.LastBlockHeight + 1
  752. if height == 1 {
  753. height = state.InitialHeight
  754. }
  755. // RoundState fields
  756. cs.updateHeight(height)
  757. cs.updateRoundStep(0, cstypes.RoundStepNewHeight)
  758. if cs.CommitTime.IsZero() {
  759. // "Now" makes it easier to sync up dev nodes.
  760. // We add timeoutCommit to allow transactions
  761. // to be gathered for the first block.
  762. // And alternative solution that relies on clocks:
  763. // cs.StartTime = state.LastBlockTime.Add(timeoutCommit)
  764. cs.StartTime = cs.config.Commit(tmtime.Now())
  765. } else {
  766. cs.StartTime = cs.config.Commit(cs.CommitTime)
  767. }
  768. cs.Validators = validators
  769. cs.Proposal = nil
  770. cs.ProposalBlock = nil
  771. cs.ProposalBlockParts = nil
  772. cs.LockedRound = -1
  773. cs.LockedBlock = nil
  774. cs.LockedBlockParts = nil
  775. cs.ValidRound = -1
  776. cs.ValidBlock = nil
  777. cs.ValidBlockParts = nil
  778. cs.Votes = cstypes.NewHeightVoteSet(state.ChainID, height, validators)
  779. cs.CommitRound = -1
  780. cs.LastValidators = state.LastValidators
  781. cs.TriggeredTimeoutPrecommit = false
  782. cs.state = state
  783. // Finally, broadcast RoundState
  784. cs.newStep()
  785. }
  786. func (cs *State) newStep() {
  787. rs := cs.RoundStateEvent()
  788. if err := cs.wal.Write(rs); err != nil {
  789. cs.Logger.Error("Error writing to wal", "err", err)
  790. }
  791. cs.nSteps++
  792. // newStep is called by updateToState in NewState before the eventBus is set!
  793. if cs.eventBus != nil {
  794. if err := cs.eventBus.PublishEventNewRoundStep(rs); err != nil {
  795. cs.Logger.Error("Error publishing new round step", "err", err)
  796. }
  797. cs.evsw.FireEvent(types.EventNewRoundStep, &cs.RoundState)
  798. }
  799. }
  800. //-----------------------------------------
  801. // the main go routines
  802. // receiveRoutine handles messages which may cause state transitions.
  803. // it's argument (n) is the number of messages to process before exiting - use 0 to run forever
  804. // It keeps the RoundState and is the only thing that updates it.
  805. // Updates (state transitions) happen on timeouts, complete proposals, and 2/3 majorities.
  806. // State must be locked before any internal state is updated.
  807. func (cs *State) receiveRoutine(maxSteps int) {
  808. onExit := func(cs *State) {
  809. // NOTE: the internalMsgQueue may have signed messages from our
  810. // priv_val that haven't hit the WAL, but its ok because
  811. // priv_val tracks LastSig
  812. // close wal now that we're done writing to it
  813. if err := cs.wal.Stop(); err != nil {
  814. cs.Logger.Error("error trying to stop wal", "error", err)
  815. }
  816. cs.wal.Wait()
  817. close(cs.done)
  818. }
  819. defer func() {
  820. if r := recover(); r != nil {
  821. cs.Logger.Error("CONSENSUS FAILURE!!!", "err", r, "stack", string(debug.Stack()))
  822. // stop gracefully
  823. //
  824. // NOTE: We most probably shouldn't be running any further when there is
  825. // some unexpected panic. Some unknown error happened, and so we don't
  826. // know if that will result in the validator signing an invalid thing. It
  827. // might be worthwhile to explore a mechanism for manual resuming via
  828. // some console or secure RPC system, but for now, halting the chain upon
  829. // unexpected consensus bugs sounds like the better option.
  830. onExit(cs)
  831. }
  832. }()
  833. for {
  834. if maxSteps > 0 {
  835. if cs.nSteps >= maxSteps {
  836. cs.Logger.Info("reached max steps. exiting receive routine")
  837. cs.nSteps = 0
  838. return
  839. }
  840. }
  841. rs := cs.RoundState
  842. var mi msgInfo
  843. select {
  844. case <-cs.txNotifier.TxsAvailable():
  845. cs.handleTxsAvailable()
  846. case mi = <-cs.peerMsgQueue:
  847. if err := cs.wal.Write(mi); err != nil {
  848. cs.Logger.Error("Error writing to wal", "err", err)
  849. }
  850. // handles proposals, block parts, votes
  851. // may generate internal events (votes, complete proposals, 2/3 majorities)
  852. cs.handleMsg(mi)
  853. case mi = <-cs.internalMsgQueue:
  854. err := cs.wal.WriteSync(mi) // NOTE: fsync
  855. if err != nil {
  856. panic(fmt.Sprintf("Failed to write %v msg to consensus wal due to %v. Check your FS and restart the node", mi, err))
  857. }
  858. if _, ok := mi.Msg.(*VoteMessage); ok {
  859. // we actually want to simulate failing during
  860. // the previous WriteSync, but this isn't easy to do.
  861. // Equivalent would be to fail here and manually remove
  862. // some bytes from the end of the wal.
  863. fail.Fail() // XXX
  864. }
  865. // handles proposals, block parts, votes
  866. cs.handleMsg(mi)
  867. case ti := <-cs.timeoutTicker.Chan(): // tockChan:
  868. if err := cs.wal.Write(ti); err != nil {
  869. cs.Logger.Error("Error writing to wal", "err", err)
  870. }
  871. // if the timeout is relevant to the rs
  872. // go to the next step
  873. cs.handleTimeout(ti, rs)
  874. case <-cs.Quit():
  875. onExit(cs)
  876. return
  877. }
  878. }
  879. }
  880. func (cs *State) handleTimeout(ti timeoutInfo, rs cstypes.RoundState) {
  881. cs.Logger.Debug("Received tock", "timeout", ti.Duration, "height", ti.Height, "round", ti.Round, "step", ti.Step)
  882. // timeouts must be for current height, round, step
  883. if ti.Height != rs.Height || ti.Round < rs.Round || (ti.Round == rs.Round && ti.Step < rs.Step) {
  884. cs.Logger.Debug("Ignoring tock because we're ahead", "height", rs.Height, "round", rs.Round, "step", rs.Step)
  885. return
  886. }
  887. // the timeout will now cause a state transition
  888. cs.mtx.Lock()
  889. defer cs.mtx.Unlock()
  890. switch ti.Step {
  891. case cstypes.RoundStepNewHeight:
  892. // NewRound event fired from enterNewRound.
  893. // XXX: should we fire timeout here (for timeout commit)?
  894. cs.enterNewRound(ti.Height, 0)
  895. case cstypes.RoundStepNewRound:
  896. cs.enterPropose(ti.Height, 0)
  897. case cstypes.RoundStepPropose:
  898. if err := cs.eventBus.PublishEventTimeoutPropose(cs.RoundStateEvent()); err != nil {
  899. cs.Logger.Error("Error publishing timeout propose", "err", err)
  900. }
  901. cs.enterPrevote(ti.Height, ti.Round)
  902. case cstypes.RoundStepPrevoteWait:
  903. if err := cs.eventBus.PublishEventTimeoutWait(cs.RoundStateEvent()); err != nil {
  904. cs.Logger.Error("Error publishing timeout wait", "err", err)
  905. }
  906. cs.enterPrecommit(ti.Height, ti.Round)
  907. case cstypes.RoundStepPrecommitWait:
  908. if err := cs.eventBus.PublishEventTimeoutWait(cs.RoundStateEvent()); err != nil {
  909. cs.Logger.Error("Error publishing timeout wait", "err", err)
  910. }
  911. cs.enterPrecommit(ti.Height, ti.Round)
  912. cs.enterNewRound(ti.Height, ti.Round+1)
  913. default:
  914. panic(fmt.Sprintf("Invalid timeout step: %v", ti.Step))
  915. }
  916. }
  917. func (cs *State) handleTxsAvailable() {
  918. cs.mtx.Lock()
  919. defer cs.mtx.Unlock()
  920. // We only need to do this for round 0.
  921. if cs.Round != 0 {
  922. return
  923. }
  924. switch cs.Step {
  925. case cstypes.RoundStepNewHeight: // timeoutCommit phase
  926. if cs.needProofBlock(cs.Height) {
  927. // enterPropose will be called by enterNewRound
  928. return
  929. }
  930. // +1ms to ensure RoundStepNewRound timeout always happens after RoundStepNewHeight
  931. timeoutCommit := cs.StartTime.Sub(tmtime.Now()) + 1*time.Millisecond
  932. cs.scheduleTimeout(timeoutCommit, cs.Height, 0, cstypes.RoundStepNewRound)
  933. case cstypes.RoundStepNewRound: // after timeoutCommit
  934. cs.enterPropose(cs.Height, 0)
  935. }
  936. }
  937. //-----------------------------------------------------------------------------
  938. // State functions
  939. // Used internally by handleTimeout and handleMsg to make state transitions
  940. // Enter: `timeoutNewHeight` by startTime (commitTime+timeoutCommit),
  941. // or, if SkipTimeoutCommit==true, after receiving all precommits from (height,round-1)
  942. // Enter: `timeoutPrecommits` after any +2/3 precommits from (height,round-1)
  943. // Enter: +2/3 precommits for nil at (height,round-1)
  944. // Enter: +2/3 prevotes any or +2/3 precommits for block or any from (height, round)
  945. // NOTE: cs.StartTime was already set for height.
  946. func (cs *State) enterNewRound(height int64, round int32) {
  947. logger := cs.Logger.With("height", height, "round", round)
  948. if cs.Height != height || round < cs.Round || (cs.Round == round && cs.Step != cstypes.RoundStepNewHeight) {
  949. logger.Debug(fmt.Sprintf(
  950. "enterNewRound(%v/%v): Invalid args. Current step: %v/%v/%v",
  951. height,
  952. round,
  953. cs.Height,
  954. cs.Round,
  955. cs.Step))
  956. return
  957. }
  958. if now := tmtime.Now(); cs.StartTime.After(now) {
  959. logger.Info("Need to set a buffer and log message here for sanity.", "startTime", cs.StartTime, "now", now)
  960. }
  961. logger.Info(fmt.Sprintf("enterNewRound(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  962. // Increment validators if necessary
  963. validators := cs.Validators
  964. if cs.Round < round {
  965. validators = validators.Copy()
  966. validators.IncrementProposerPriority(tmmath.SafeSubInt32(round, cs.Round))
  967. }
  968. // Setup new round
  969. // we don't fire newStep for this step,
  970. // but we fire an event, so update the round step first
  971. cs.updateRoundStep(round, cstypes.RoundStepNewRound)
  972. cs.Validators = validators
  973. if round == 0 {
  974. // We've already reset these upon new height,
  975. // and meanwhile we might have received a proposal
  976. // for round 0.
  977. } else {
  978. logger.Info("Resetting Proposal info")
  979. cs.Proposal = nil
  980. cs.ProposalBlock = nil
  981. cs.ProposalBlockParts = nil
  982. }
  983. cs.Votes.SetRound(tmmath.SafeAddInt32(round, 1)) // also track next round (round+1) to allow round-skipping
  984. cs.TriggeredTimeoutPrecommit = false
  985. if err := cs.eventBus.PublishEventNewRound(cs.NewRoundEvent()); err != nil {
  986. cs.Logger.Error("Error publishing new round", "err", err)
  987. }
  988. cs.metrics.Rounds.Set(float64(round))
  989. // Wait for txs to be available in the mempool
  990. // before we enterPropose in round 0. If the last block changed the app hash,
  991. // we may need an empty "proof" block, and enterPropose immediately.
  992. waitForTxs := cs.config.WaitForTxs() && round == 0 && !cs.needProofBlock(height)
  993. if waitForTxs {
  994. if cs.config.CreateEmptyBlocksInterval > 0 {
  995. cs.scheduleTimeout(cs.config.CreateEmptyBlocksInterval, height, round,
  996. cstypes.RoundStepNewRound)
  997. }
  998. } else {
  999. cs.enterPropose(height, round)
  1000. }
  1001. }
  1002. // needProofBlock returns true on the first height (so the genesis app hash is signed right away)
  1003. // and where the last block (height-1) caused the app hash to change
  1004. func (cs *State) needProofBlock(height int64) bool {
  1005. if height == cs.state.InitialHeight {
  1006. return true
  1007. }
  1008. lastBlockMeta := cs.blockStore.LoadBlockMeta(height - 1)
  1009. if lastBlockMeta == nil {
  1010. panic(fmt.Sprintf("needProofBlock: last block meta for height %d not found", height-1))
  1011. }
  1012. return !bytes.Equal(cs.state.AppHash, lastBlockMeta.Header.AppHash)
  1013. }
  1014. func (cs *State) isProposer(address []byte) bool {
  1015. return bytes.Equal(cs.Validators.GetProposer().Address, address)
  1016. }
  1017. func (cs *State) defaultDecideProposal(height int64, round int32) {
  1018. var block *types.Block
  1019. var blockParts *types.PartSet
  1020. // Decide on block
  1021. if cs.ValidBlock != nil {
  1022. // If there is valid block, choose that.
  1023. block, blockParts = cs.ValidBlock, cs.ValidBlockParts
  1024. } else {
  1025. // Create a new proposal block from state/txs from the mempool.
  1026. block, blockParts = cs.createProposalBlock()
  1027. if block == nil {
  1028. return
  1029. }
  1030. }
  1031. // Flush the WAL. Otherwise, we may not recompute the same proposal to sign,
  1032. // and the privValidator will refuse to sign anything.
  1033. if err := cs.wal.FlushAndSync(); err != nil {
  1034. cs.Logger.Error("Error flushing to disk")
  1035. }
  1036. // Make proposal
  1037. propBlockID := types.BlockID{Hash: block.Hash(), PartSetHeader: blockParts.Header()}
  1038. proposal := types.NewProposal(height, round, cs.ValidRound, propBlockID)
  1039. p := proposal.ToProto()
  1040. if err := cs.privValidator.SignProposal(cs.state.ChainID, p); err == nil {
  1041. proposal.Signature = p.Signature
  1042. // send proposal and block parts on internal msg queue
  1043. cs.sendInternalMessage(msgInfo{&ProposalMessage{proposal}, ""})
  1044. for i := 0; i < int(blockParts.Total()); i++ {
  1045. part := blockParts.GetPart(i)
  1046. cs.sendInternalMessage(msgInfo{&BlockPartMessage{cs.Height, cs.Round, part}, ""})
  1047. }
  1048. cs.Logger.Info("Signed proposal", "height", height, "round", round, "proposal", proposal)
  1049. cs.Logger.Debug(fmt.Sprintf("Signed proposal block: %v", block))
  1050. } else if !cs.replayMode {
  1051. cs.Logger.Error("enterPropose: Error signing proposal", "height", height, "round", round, "err", err)
  1052. }
  1053. }
  1054. // Returns true if the proposal block is complete &&
  1055. // (if POLRound was proposed, we have +2/3 prevotes from there).
  1056. func (cs *State) isProposalComplete() bool {
  1057. if cs.Proposal == nil || cs.ProposalBlock == nil {
  1058. return false
  1059. }
  1060. // we have the proposal. if there's a POLRound,
  1061. // make sure we have the prevotes from it too
  1062. if cs.Proposal.POLRound < 0 {
  1063. return true
  1064. }
  1065. // if this is false the proposer is lying or we haven't received the POL yet
  1066. return cs.Votes.Prevotes(cs.Proposal.POLRound).HasTwoThirdsMajority()
  1067. }
  1068. // Create the next block to propose and return it. Returns nil block upon error.
  1069. //
  1070. // We really only need to return the parts, but the block is returned for
  1071. // convenience so we can log the proposal block.
  1072. //
  1073. // NOTE: keep it side-effect free for clarity.
  1074. // CONTRACT: cs.privValidator is not nil.
  1075. func (cs *State) createProposalBlock() (block *types.Block, blockParts *types.PartSet) {
  1076. if cs.privValidator == nil {
  1077. panic("entered createProposalBlock with privValidator being nil")
  1078. }
  1079. var commit *types.Commit
  1080. switch {
  1081. case cs.Height == cs.state.InitialHeight:
  1082. // We're creating a proposal for the first block.
  1083. // The commit is empty, but not nil.
  1084. commit = types.NewCommit(0, 0, types.BlockID{}, nil)
  1085. case cs.LastCommit.HasTwoThirdsMajority():
  1086. // Make the commit from LastCommit
  1087. commit = cs.LastCommit.MakeCommit()
  1088. default: // This shouldn't happen.
  1089. cs.Logger.Error("enterPropose: Cannot propose anything: No commit for the previous block")
  1090. return
  1091. }
  1092. if cs.privValidatorPubKey == nil {
  1093. // If this node is a validator & proposer in the current round, it will
  1094. // miss the opportunity to create a block.
  1095. cs.Logger.Error(fmt.Sprintf("enterPropose: %v", errPubKeyIsNotSet))
  1096. return
  1097. }
  1098. proposerAddr := cs.privValidatorPubKey.Address()
  1099. return cs.blockExec.CreateProposalBlock(cs.Height, cs.state, commit, proposerAddr)
  1100. }
  1101. // Enter: any +2/3 prevotes at next round.
  1102. func (cs *State) enterPrevoteWait(height int64, round int32) {
  1103. logger := cs.Logger.With("height", height, "round", round)
  1104. if cs.Height != height || round < cs.Round || (cs.Round == round && cstypes.RoundStepPrevoteWait <= cs.Step) {
  1105. logger.Debug(fmt.Sprintf(
  1106. "enterPrevoteWait(%v/%v): Invalid args. Current step: %v/%v/%v",
  1107. height,
  1108. round,
  1109. cs.Height,
  1110. cs.Round,
  1111. cs.Step))
  1112. return
  1113. }
  1114. if !cs.Votes.Prevotes(round).HasTwoThirdsAny() {
  1115. panic(fmt.Sprintf("enterPrevoteWait(%v/%v), but Prevotes does not have any +2/3 votes", height, round))
  1116. }
  1117. logger.Info(fmt.Sprintf("enterPrevoteWait(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  1118. defer func() {
  1119. // Done enterPrevoteWait:
  1120. cs.updateRoundStep(round, cstypes.RoundStepPrevoteWait)
  1121. cs.newStep()
  1122. }()
  1123. // Wait for some more prevotes; enterPrecommit
  1124. cs.scheduleTimeout(cs.config.Prevote(round), height, round, cstypes.RoundStepPrevoteWait)
  1125. }
  1126. // Enter: any +2/3 precommits for next round.
  1127. func (cs *State) enterPrecommitWait(height int64, round int32) {
  1128. logger := cs.Logger.With("height", height, "round", round)
  1129. if cs.Height != height || round < cs.Round || (cs.Round == round && cs.TriggeredTimeoutPrecommit) {
  1130. logger.Debug(
  1131. fmt.Sprintf(
  1132. "enterPrecommitWait(%v/%v): Invalid args. "+
  1133. "Current state is Height/Round: %v/%v/, TriggeredTimeoutPrecommit:%v",
  1134. height, round, cs.Height, cs.Round, cs.TriggeredTimeoutPrecommit))
  1135. return
  1136. }
  1137. if !cs.Votes.Precommits(round).HasTwoThirdsAny() {
  1138. panic(fmt.Sprintf("enterPrecommitWait(%v/%v), but Precommits does not have any +2/3 votes", height, round))
  1139. }
  1140. logger.Info(fmt.Sprintf("enterPrecommitWait(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  1141. defer func() {
  1142. // Done enterPrecommitWait:
  1143. cs.TriggeredTimeoutPrecommit = true
  1144. cs.newStep()
  1145. }()
  1146. // Wait for some more precommits; enterNewRound
  1147. cs.scheduleTimeout(cs.config.Precommit(round), height, round, cstypes.RoundStepPrecommitWait)
  1148. }
  1149. // Enter: +2/3 precommits for block
  1150. func (cs *State) enterCommit(height int64, commitRound int32) {
  1151. logger := cs.Logger.With("height", height, "commitRound", commitRound)
  1152. if cs.Height != height || cstypes.RoundStepCommit <= cs.Step {
  1153. logger.Debug(fmt.Sprintf(
  1154. "enterCommit(%v/%v): Invalid args. Current step: %v/%v/%v",
  1155. height,
  1156. commitRound,
  1157. cs.Height,
  1158. cs.Round,
  1159. cs.Step))
  1160. return
  1161. }
  1162. logger.Info(fmt.Sprintf("enterCommit(%v/%v). Current: %v/%v/%v", height, commitRound, cs.Height, cs.Round, cs.Step))
  1163. defer func() {
  1164. // Done enterCommit:
  1165. // keep cs.Round the same, commitRound points to the right Precommits set.
  1166. cs.updateRoundStep(cs.Round, cstypes.RoundStepCommit)
  1167. cs.CommitRound = commitRound
  1168. cs.CommitTime = tmtime.Now()
  1169. cs.newStep()
  1170. // Maybe finalize immediately.
  1171. cs.tryFinalizeCommit(height)
  1172. }()
  1173. blockID, ok := cs.Votes.Precommits(commitRound).TwoThirdsMajority()
  1174. if !ok {
  1175. panic("RunActionCommit() expects +2/3 precommits")
  1176. }
  1177. // The Locked* fields no longer matter.
  1178. // Move them over to ProposalBlock if they match the commit hash,
  1179. // otherwise they'll be cleared in updateToState.
  1180. if cs.LockedBlock.HashesTo(blockID.Hash) {
  1181. logger.Info("Commit is for locked block. Set ProposalBlock=LockedBlock", "blockHash", blockID.Hash)
  1182. cs.ProposalBlock = cs.LockedBlock
  1183. cs.ProposalBlockParts = cs.LockedBlockParts
  1184. }
  1185. // If we don't have the block being committed, set up to get it.
  1186. if !cs.ProposalBlock.HashesTo(blockID.Hash) {
  1187. if !cs.ProposalBlockParts.HasHeader(blockID.PartSetHeader) {
  1188. logger.Info(
  1189. "Commit is for a block we don't know about. Set ProposalBlock=nil",
  1190. "proposal",
  1191. cs.ProposalBlock.Hash(),
  1192. "commit",
  1193. blockID.Hash)
  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.Info(
  1223. "Attempt to finalize failed. We don't have the commit block.",
  1224. "proposal-block",
  1225. cs.ProposalBlock.Hash(),
  1226. "commit-block",
  1227. blockID.Hash)
  1228. return
  1229. }
  1230. // go
  1231. cs.finalizeCommit(height)
  1232. }
  1233. // Increment height and goto cstypes.RoundStepNewHeight
  1234. func (cs *State) finalizeCommit(height int64) {
  1235. if cs.Height != height || cs.Step != cstypes.RoundStepCommit {
  1236. cs.Logger.Debug(fmt.Sprintf(
  1237. "finalizeCommit(%v): Invalid args. Current step: %v/%v/%v",
  1238. height,
  1239. cs.Height,
  1240. cs.Round,
  1241. cs.Step))
  1242. return
  1243. }
  1244. blockID, ok := cs.Votes.Precommits(cs.CommitRound).TwoThirdsMajority()
  1245. block, blockParts := cs.ProposalBlock, cs.ProposalBlockParts
  1246. if !ok {
  1247. panic("Cannot finalizeCommit, commit does not have two thirds majority")
  1248. }
  1249. if !blockParts.HasHeader(blockID.PartSetHeader) {
  1250. panic("Expected ProposalBlockParts header to be commit header")
  1251. }
  1252. if !block.HashesTo(blockID.Hash) {
  1253. panic("Cannot finalizeCommit, ProposalBlock does not hash to commit hash")
  1254. }
  1255. if err := cs.blockExec.ValidateBlock(cs.state, block); err != nil {
  1256. panic(fmt.Errorf("+2/3 committed an invalid block: %w", err))
  1257. }
  1258. cs.Logger.Info("Finalizing commit of block with N txs",
  1259. "height", block.Height,
  1260. "hash", block.Hash(),
  1261. "root", block.AppHash,
  1262. "N", len(block.Txs))
  1263. cs.Logger.Info(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.Info("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 := EndHeightMessage{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(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 *BlockPartMessage, peerID p2p.NodeID) (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.NodeID) (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{&VoteMessage{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. }