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.

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