github.com/okex/exchain@v1.8.0/libs/tendermint/consensus/replay.go (about)

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