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.

451 lines
14 KiB

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