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.

502 lines
16 KiB

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