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.

535 lines
18 KiB

  1. package consensus
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "hash/crc32"
  7. "io"
  8. "reflect"
  9. "time"
  10. abci "github.com/tendermint/tendermint/abci/types"
  11. tmcon "github.com/tendermint/tendermint/consensus"
  12. "github.com/tendermint/tendermint/crypto/merkle"
  13. "github.com/tendermint/tendermint/libs/log"
  14. "github.com/tendermint/tendermint/proxy"
  15. sm "github.com/tendermint/tendermint/state"
  16. "github.com/tendermint/tendermint/types"
  17. )
  18. var crc32c = crc32.MakeTable(crc32.Castagnoli)
  19. // Functionality to replay blocks and messages on recovery from a crash.
  20. // There are two general failure scenarios:
  21. //
  22. // 1. failure during consensus
  23. // 2. failure while applying the block
  24. //
  25. // The former is handled by the WAL, the latter by the proxyApp Handshake on
  26. // restart, which ultimately hands off the work to the WAL.
  27. //-----------------------------------------
  28. // 1. Recover from failure during consensus
  29. // (by replaying messages from the WAL)
  30. //-----------------------------------------
  31. // Unmarshal and apply a single message to the consensus state as if it were
  32. // received in receiveRoutine. Lines that start with "#" are ignored.
  33. // NOTE: receiveRoutine should not be running.
  34. func (cs *State) readReplayMessage(msg *tmcon.TimedWALMessage, newStepSub types.Subscription) error {
  35. // Skip meta messages which exist for demarcating boundaries.
  36. if _, ok := msg.Msg.(tmcon.EndHeightMessage); ok {
  37. return nil
  38. }
  39. // for logging
  40. switch m := msg.Msg.(type) {
  41. case types.EventDataRoundState:
  42. cs.Logger.Info("Replay: New Step", "height", m.Height, "round", m.Round, "step", m.Step)
  43. // these are playback checks
  44. ticker := time.After(time.Second * 2)
  45. if newStepSub != nil {
  46. select {
  47. case stepMsg := <-newStepSub.Out():
  48. m2 := stepMsg.Data().(types.EventDataRoundState)
  49. if m.Height != m2.Height || m.Round != m2.Round || m.Step != m2.Step {
  50. return fmt.Errorf("roundState mismatch. Got %v; Expected %v", m2, m)
  51. }
  52. case <-newStepSub.Cancelled():
  53. return fmt.Errorf("failed to read off newStepSub.Out(). newStepSub was cancelled")
  54. case <-ticker:
  55. return fmt.Errorf("failed to read off newStepSub.Out()")
  56. }
  57. }
  58. case msgInfo:
  59. peerID := m.PeerID
  60. if peerID == "" {
  61. peerID = "local"
  62. }
  63. switch msg := m.Msg.(type) {
  64. case *tmcon.ProposalMessage:
  65. p := msg.Proposal
  66. cs.Logger.Info("Replay: Proposal", "height", p.Height, "round", p.Round, "header",
  67. p.BlockID.PartSetHeader, "pol", p.POLRound, "peer", peerID)
  68. case *tmcon.BlockPartMessage:
  69. cs.Logger.Info("Replay: BlockPart", "height", msg.Height, "round", msg.Round, "peer", peerID)
  70. case *tmcon.VoteMessage:
  71. v := msg.Vote
  72. cs.Logger.Info("Replay: Vote", "height", v.Height, "round", v.Round, "type", v.Type,
  73. "blockID", v.BlockID, "peer", peerID)
  74. }
  75. cs.handleMsg(m)
  76. case timeoutInfo:
  77. cs.Logger.Info("Replay: Timeout", "height", m.Height, "round", m.Round, "step", m.Step, "dur", m.Duration)
  78. cs.handleTimeout(m, cs.RoundState)
  79. default:
  80. return fmt.Errorf("replay: Unknown TimedWALMessage type: %v", reflect.TypeOf(msg.Msg))
  81. }
  82. return nil
  83. }
  84. // Replay only those messages since the last block. `timeoutRoutine` should
  85. // run concurrently to read off tickChan.
  86. func (cs *State) catchupReplay(csHeight int64) error {
  87. // Set replayMode to true so we don't log signing errors.
  88. cs.replayMode = true
  89. defer func() { cs.replayMode = false }()
  90. // Ensure that #ENDHEIGHT for this height doesn't exist.
  91. // NOTE: This is just a sanity check. As far as we know things work fine
  92. // without it, and Handshake could reuse State if it weren't for
  93. // this check (since we can crash after writing #ENDHEIGHT).
  94. //
  95. // Ignore data corruption errors since this is a sanity check.
  96. gr, found, err := cs.wal.SearchForEndHeight(csHeight, &tmcon.WALSearchOptions{IgnoreDataCorruptionErrors: true})
  97. if err != nil {
  98. return err
  99. }
  100. if gr != nil {
  101. if err := gr.Close(); err != nil {
  102. return err
  103. }
  104. }
  105. if found {
  106. return fmt.Errorf("wal should not contain #ENDHEIGHT %d", csHeight)
  107. }
  108. // Search for last height marker.
  109. //
  110. // Ignore data corruption errors in previous heights because we only care about last height
  111. if csHeight < cs.state.InitialHeight {
  112. return fmt.Errorf("cannot replay height %v, below initial height %v", csHeight, cs.state.InitialHeight)
  113. }
  114. endHeight := csHeight - 1
  115. if csHeight == cs.state.InitialHeight {
  116. endHeight = 0
  117. }
  118. gr, found, err = cs.wal.SearchForEndHeight(endHeight, &tmcon.WALSearchOptions{IgnoreDataCorruptionErrors: true})
  119. if err == io.EOF {
  120. cs.Logger.Error("Replay: wal.group.Search returned EOF", "#ENDHEIGHT", endHeight)
  121. } else if err != nil {
  122. return err
  123. }
  124. if !found {
  125. return fmt.Errorf("cannot replay height %d. WAL does not contain #ENDHEIGHT for %d", csHeight, endHeight)
  126. }
  127. defer gr.Close()
  128. cs.Logger.Info("Catchup by replaying consensus messages", "height", csHeight)
  129. var msg *tmcon.TimedWALMessage
  130. dec := WALDecoder{gr}
  131. LOOP:
  132. for {
  133. msg, err = dec.Decode()
  134. switch {
  135. case err == io.EOF:
  136. break LOOP
  137. case IsDataCorruptionError(err):
  138. cs.Logger.Error("data has been corrupted in last height of consensus WAL", "err", err, "height", csHeight)
  139. return err
  140. case err != nil:
  141. return err
  142. }
  143. // NOTE: since the priv key is set when the msgs are received
  144. // it will attempt to eg double sign but we can just ignore it
  145. // since the votes will be replayed and we'll get to the next step
  146. if err := cs.readReplayMessage(msg, nil); err != nil {
  147. return err
  148. }
  149. }
  150. cs.Logger.Info("Replay: Done")
  151. return nil
  152. }
  153. //--------------------------------------------------------------------------------
  154. // Parses marker lines of the form:
  155. // #ENDHEIGHT: 12345
  156. /*
  157. func makeHeightSearchFunc(height int64) auto.SearchFunc {
  158. return func(line string) (int, error) {
  159. line = strings.TrimRight(line, "\n")
  160. parts := strings.Split(line, " ")
  161. if len(parts) != 2 {
  162. return -1, errors.New("line did not have 2 parts")
  163. }
  164. i, err := strconv.Atoi(parts[1])
  165. if err != nil {
  166. return -1, errors.New("failed to parse INFO: " + err.Error())
  167. }
  168. if height < i {
  169. return 1, nil
  170. } else if height == i {
  171. return 0, nil
  172. } else {
  173. return -1, nil
  174. }
  175. }
  176. }*/
  177. //---------------------------------------------------
  178. // 2. Recover from failure while applying the block.
  179. // (by handshaking with the app to figure out where
  180. // we were last, and using the WAL to recover there.)
  181. //---------------------------------------------------
  182. type Handshaker struct {
  183. stateStore sm.Store
  184. initialState sm.State
  185. store sm.BlockStore
  186. eventBus types.BlockEventPublisher
  187. genDoc *types.GenesisDoc
  188. logger log.Logger
  189. nBlocks int // number of blocks applied to the state
  190. }
  191. func NewHandshaker(stateStore sm.Store, state sm.State,
  192. store sm.BlockStore, genDoc *types.GenesisDoc) *Handshaker {
  193. return &Handshaker{
  194. stateStore: stateStore,
  195. initialState: state,
  196. store: store,
  197. eventBus: types.NopEventBus{},
  198. genDoc: genDoc,
  199. logger: log.NewNopLogger(),
  200. nBlocks: 0,
  201. }
  202. }
  203. func (h *Handshaker) SetLogger(l log.Logger) {
  204. h.logger = l
  205. }
  206. // SetEventBus - sets the event bus for publishing block related events.
  207. // If not called, it defaults to types.NopEventBus.
  208. func (h *Handshaker) SetEventBus(eventBus types.BlockEventPublisher) {
  209. h.eventBus = eventBus
  210. }
  211. // NBlocks returns the number of blocks applied to the state.
  212. func (h *Handshaker) NBlocks() int {
  213. return h.nBlocks
  214. }
  215. // TODO: retry the handshake/replay if it fails ?
  216. func (h *Handshaker) Handshake(proxyApp proxy.AppConns) error {
  217. // Handshake is done via ABCI Info on the query conn.
  218. res, err := proxyApp.Query().InfoSync(context.Background(), proxy.RequestInfo)
  219. if err != nil {
  220. return fmt.Errorf("error calling Info: %v", err)
  221. }
  222. blockHeight := res.LastBlockHeight
  223. if blockHeight < 0 {
  224. return fmt.Errorf("got a negative last block height (%d) from the app", blockHeight)
  225. }
  226. appHash := res.LastBlockAppHash
  227. h.logger.Info("ABCI Handshake App Info",
  228. "height", blockHeight,
  229. "hash", appHash,
  230. "software-version", res.Version,
  231. "protocol-version", res.AppVersion,
  232. )
  233. // Only set the version if there is no existing state.
  234. if h.initialState.LastBlockHeight == 0 {
  235. h.initialState.Version.Consensus.App = res.AppVersion
  236. }
  237. // Replay blocks up to the latest in the blockstore.
  238. _, err = h.ReplayBlocks(h.initialState, appHash, blockHeight, proxyApp)
  239. if err != nil {
  240. return fmt.Errorf("error on replay: %v", err)
  241. }
  242. h.logger.Info("Completed ABCI Handshake - Tendermint and App are synced",
  243. "appHeight", blockHeight, "appHash", appHash)
  244. // TODO: (on restart) replay mempool
  245. return nil
  246. }
  247. // ReplayBlocks replays all blocks since appBlockHeight and ensures the result
  248. // matches the current state.
  249. // Returns the final AppHash or an error.
  250. func (h *Handshaker) ReplayBlocks(
  251. state sm.State,
  252. appHash []byte,
  253. appBlockHeight int64,
  254. proxyApp proxy.AppConns,
  255. ) ([]byte, error) {
  256. storeBlockBase := h.store.Base()
  257. storeBlockHeight := h.store.Height()
  258. stateBlockHeight := state.LastBlockHeight
  259. h.logger.Info(
  260. "ABCI Replay Blocks",
  261. "appHeight",
  262. appBlockHeight,
  263. "storeHeight",
  264. storeBlockHeight,
  265. "stateHeight",
  266. stateBlockHeight)
  267. // If appBlockHeight == 0 it means that we are at genesis and hence should send InitChain.
  268. if appBlockHeight == 0 {
  269. validators := make([]*types.Validator, len(h.genDoc.Validators))
  270. for i, val := range h.genDoc.Validators {
  271. validators[i] = types.NewValidator(val.PubKey, val.Power)
  272. }
  273. validatorSet := types.NewValidatorSet(validators)
  274. nextVals := types.TM2PB.ValidatorUpdates(validatorSet)
  275. pbParams := h.genDoc.ConsensusParams.ToProto()
  276. req := abci.RequestInitChain{
  277. Time: h.genDoc.GenesisTime,
  278. ChainId: h.genDoc.ChainID,
  279. InitialHeight: h.genDoc.InitialHeight,
  280. ConsensusParams: &pbParams,
  281. Validators: nextVals,
  282. AppStateBytes: h.genDoc.AppState,
  283. }
  284. res, err := proxyApp.Consensus().InitChainSync(context.Background(), req)
  285. if err != nil {
  286. return nil, err
  287. }
  288. appHash = res.AppHash
  289. if stateBlockHeight == 0 { // we only update state when we are in initial state
  290. // If the app did not return an app hash, we keep the one set from the genesis doc in
  291. // the state. We don't set appHash since we don't want the genesis doc app hash
  292. // recorded in the genesis block. We should probably just remove GenesisDoc.AppHash.
  293. if len(res.AppHash) > 0 {
  294. state.AppHash = res.AppHash
  295. }
  296. // If the app returned validators or consensus params, update the state.
  297. if len(res.Validators) > 0 {
  298. vals, err := types.PB2TM.ValidatorUpdates(res.Validators)
  299. if err != nil {
  300. return nil, err
  301. }
  302. state.Validators = types.NewValidatorSet(vals)
  303. state.NextValidators = types.NewValidatorSet(vals).CopyIncrementProposerPriority(1)
  304. } else if len(h.genDoc.Validators) == 0 {
  305. // If validator set is not set in genesis and still empty after InitChain, exit.
  306. return nil, fmt.Errorf("validator set is nil in genesis and still empty after InitChain")
  307. }
  308. if res.ConsensusParams != nil {
  309. state.ConsensusParams = state.ConsensusParams.UpdateConsensusParams(res.ConsensusParams)
  310. state.Version.Consensus.App = state.ConsensusParams.Version.AppVersion
  311. }
  312. // We update the last results hash with the empty hash, to conform with RFC-6962.
  313. state.LastResultsHash = merkle.HashFromByteSlices(nil)
  314. if err := h.stateStore.Save(state); err != nil {
  315. return nil, err
  316. }
  317. }
  318. }
  319. // First handle edge cases and constraints on the storeBlockHeight and storeBlockBase.
  320. switch {
  321. case storeBlockHeight == 0:
  322. assertAppHashEqualsOneFromState(appHash, state)
  323. return appHash, nil
  324. case appBlockHeight == 0 && state.InitialHeight < storeBlockBase:
  325. // the app has no state, and the block store is truncated above the initial height
  326. return appHash, sm.ErrAppBlockHeightTooLow{AppHeight: appBlockHeight, StoreBase: storeBlockBase}
  327. case appBlockHeight > 0 && appBlockHeight < storeBlockBase-1:
  328. // the app is too far behind truncated store (can be 1 behind since we replay the next)
  329. return appHash, sm.ErrAppBlockHeightTooLow{AppHeight: appBlockHeight, StoreBase: storeBlockBase}
  330. case storeBlockHeight < appBlockHeight:
  331. // the app should never be ahead of the store (but this is under app's control)
  332. return appHash, sm.ErrAppBlockHeightTooHigh{CoreHeight: storeBlockHeight, AppHeight: appBlockHeight}
  333. case storeBlockHeight < stateBlockHeight:
  334. // the state should never be ahead of the store (this is under tendermint's control)
  335. panic(fmt.Sprintf("StateBlockHeight (%d) > StoreBlockHeight (%d)", stateBlockHeight, storeBlockHeight))
  336. case storeBlockHeight > stateBlockHeight+1:
  337. // store should be at most one ahead of the state (this is under tendermint's control)
  338. panic(fmt.Sprintf("StoreBlockHeight (%d) > StateBlockHeight + 1 (%d)", storeBlockHeight, stateBlockHeight+1))
  339. }
  340. var err error
  341. // Now either store is equal to state, or one ahead.
  342. // For each, consider all cases of where the app could be, given app <= store
  343. if storeBlockHeight == stateBlockHeight {
  344. // Tendermint ran Commit and saved the state.
  345. // Either the app is asking for replay, or we're all synced up.
  346. if appBlockHeight < storeBlockHeight {
  347. // the app is behind, so replay blocks, but no need to go through WAL (state is already synced to store)
  348. return h.replayBlocks(state, proxyApp, appBlockHeight, storeBlockHeight, false)
  349. } else if appBlockHeight == storeBlockHeight {
  350. // We're good!
  351. assertAppHashEqualsOneFromState(appHash, state)
  352. return appHash, nil
  353. }
  354. } else if storeBlockHeight == stateBlockHeight+1 {
  355. // We saved the block in the store but haven't updated the state,
  356. // so we'll need to replay a block using the WAL.
  357. switch {
  358. case appBlockHeight < stateBlockHeight:
  359. // the app is further behind than it should be, so replay blocks
  360. // but leave the last block to go through the WAL
  361. return h.replayBlocks(state, proxyApp, appBlockHeight, storeBlockHeight, true)
  362. case appBlockHeight == stateBlockHeight:
  363. // We haven't run Commit (both the state and app are one block behind),
  364. // so replayBlock with the real app.
  365. // NOTE: We could instead use the cs.WAL on cs.Start,
  366. // but we'd have to allow the WAL to replay a block that wrote it's #ENDHEIGHT
  367. h.logger.Info("Replay last block using real app")
  368. state, err = h.replayBlock(state, storeBlockHeight, proxyApp.Consensus())
  369. return state.AppHash, err
  370. case appBlockHeight == storeBlockHeight:
  371. // We ran Commit, but didn't save the state, so replayBlock with mock app.
  372. abciResponses, err := h.stateStore.LoadABCIResponses(storeBlockHeight)
  373. if err != nil {
  374. return nil, err
  375. }
  376. mockApp := newMockProxyApp(appHash, abciResponses)
  377. h.logger.Info("Replay last block using mock app")
  378. state, err = h.replayBlock(state, storeBlockHeight, mockApp)
  379. return state.AppHash, err
  380. }
  381. }
  382. panic(fmt.Sprintf("uncovered case! appHeight: %d, storeHeight: %d, stateHeight: %d",
  383. appBlockHeight, storeBlockHeight, stateBlockHeight))
  384. }
  385. func (h *Handshaker) replayBlocks(
  386. state sm.State,
  387. proxyApp proxy.AppConns,
  388. appBlockHeight,
  389. storeBlockHeight int64,
  390. mutateState bool) ([]byte, error) {
  391. // App is further behind than it should be, so we need to replay blocks.
  392. // We replay all blocks from appBlockHeight+1.
  393. //
  394. // Note that we don't have an old version of the state,
  395. // so we by-pass state validation/mutation using sm.ExecCommitBlock.
  396. // This also means we won't be saving validator sets if they change during this period.
  397. // TODO: Load the historical information to fix this and just use state.ApplyBlock
  398. //
  399. // If mutateState == true, the final block is replayed with h.replayBlock()
  400. var appHash []byte
  401. var err error
  402. finalBlock := storeBlockHeight
  403. if mutateState {
  404. finalBlock--
  405. }
  406. firstBlock := appBlockHeight + 1
  407. if firstBlock == 1 {
  408. firstBlock = state.InitialHeight
  409. }
  410. for i := firstBlock; i <= finalBlock; i++ {
  411. h.logger.Info("Applying block", "height", i)
  412. block := h.store.LoadBlock(i)
  413. // Extra check to ensure the app was not changed in a way it shouldn't have.
  414. if len(appHash) > 0 {
  415. assertAppHashEqualsOneFromBlock(appHash, block)
  416. }
  417. appHash, err = sm.ExecCommitBlock(proxyApp.Consensus(), block, h.logger, h.stateStore, h.genDoc.InitialHeight)
  418. if err != nil {
  419. return nil, err
  420. }
  421. h.nBlocks++
  422. }
  423. if mutateState {
  424. // sync the final block
  425. state, err = h.replayBlock(state, storeBlockHeight, proxyApp.Consensus())
  426. if err != nil {
  427. return nil, err
  428. }
  429. appHash = state.AppHash
  430. }
  431. assertAppHashEqualsOneFromState(appHash, state)
  432. return appHash, nil
  433. }
  434. // ApplyBlock on the proxyApp with the last block.
  435. func (h *Handshaker) replayBlock(state sm.State, height int64, proxyApp proxy.AppConnConsensus) (sm.State, error) {
  436. block := h.store.LoadBlock(height)
  437. meta := h.store.LoadBlockMeta(height)
  438. // Use stubs for both mempool and evidence pool since no transactions nor
  439. // evidence are needed here - block already exists.
  440. blockExec := sm.NewBlockExecutor(h.stateStore, h.logger, proxyApp, emptyMempool{}, sm.EmptyEvidencePool{})
  441. blockExec.SetEventBus(h.eventBus)
  442. var err error
  443. state, _, err = blockExec.ApplyBlock(state, meta.BlockID, block)
  444. if err != nil {
  445. return sm.State{}, err
  446. }
  447. h.nBlocks++
  448. return state, nil
  449. }
  450. func assertAppHashEqualsOneFromBlock(appHash []byte, block *types.Block) {
  451. if !bytes.Equal(appHash, block.AppHash) {
  452. panic(fmt.Sprintf(`block.AppHash does not match AppHash after replay. Got %X, expected %X.
  453. Block: %v
  454. `,
  455. appHash, block.AppHash, block))
  456. }
  457. }
  458. func assertAppHashEqualsOneFromState(appHash []byte, state sm.State) {
  459. if !bytes.Equal(appHash, state.AppHash) {
  460. panic(fmt.Sprintf(`state.AppHash does not match AppHash after replay. Got
  461. %X, expected %X.
  462. State: %v
  463. Did you reset Tendermint without resetting your application's data?`,
  464. appHash, state.AppHash, state))
  465. }
  466. }