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.

561 lines
18 KiB

7 years ago
7 years ago
7 years ago
7 years ago
pubsub 2.0 (#3227) * green pubsub tests :OK: * get rid of clientToQueryMap * Subscribe and SubscribeUnbuffered * start adapting other pkgs to new pubsub * nope * rename MsgAndTags to Message * remove TagMap it does not bring any additional benefits * bring back EventSubscriber * fix test * fix data race in TestStartNextHeightCorrectly ``` Write at 0x00c0001c7418 by goroutine 796: github.com/tendermint/tendermint/consensus.TestStartNextHeightCorrectly() /go/src/github.com/tendermint/tendermint/consensus/state_test.go:1296 +0xad testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Previous read at 0x00c0001c7418 by goroutine 858: github.com/tendermint/tendermint/consensus.(*ConsensusState).addVote() /go/src/github.com/tendermint/tendermint/consensus/state.go:1631 +0x1366 github.com/tendermint/tendermint/consensus.(*ConsensusState).tryAddVote() /go/src/github.com/tendermint/tendermint/consensus/state.go:1476 +0x8f github.com/tendermint/tendermint/consensus.(*ConsensusState).handleMsg() /go/src/github.com/tendermint/tendermint/consensus/state.go:667 +0xa1e github.com/tendermint/tendermint/consensus.(*ConsensusState).receiveRoutine() /go/src/github.com/tendermint/tendermint/consensus/state.go:628 +0x794 Goroutine 796 (running) created at: testing.(*T).Run() /usr/local/go/src/testing/testing.go:878 +0x659 testing.runTests.func1() /usr/local/go/src/testing/testing.go:1119 +0xa8 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 testing.runTests() /usr/local/go/src/testing/testing.go:1117 +0x4ee testing.(*M).Run() /usr/local/go/src/testing/testing.go:1034 +0x2ee main.main() _testmain.go:214 +0x332 Goroutine 858 (running) created at: github.com/tendermint/tendermint/consensus.(*ConsensusState).startRoutines() /go/src/github.com/tendermint/tendermint/consensus/state.go:334 +0x221 github.com/tendermint/tendermint/consensus.startTestRound() /go/src/github.com/tendermint/tendermint/consensus/common_test.go:122 +0x63 github.com/tendermint/tendermint/consensus.TestStateFullRound1() /go/src/github.com/tendermint/tendermint/consensus/state_test.go:255 +0x397 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 ``` * fixes after my own review * fix formatting * wait 100ms before kicking a subscriber out + a test for indexer_service * fixes after my second review * no timeout * add changelog entries * fix merge conflicts * fix typos after Thane's review Co-Authored-By: melekes <anton.kalyaev@gmail.com> * reformat code * rewrite indexer service in the attempt to fix failing test https://github.com/tendermint/tendermint/pull/3227/#issuecomment-462316527 * Revert "rewrite indexer service in the attempt to fix failing test" This reverts commit 0d9107a098230de7138abb1c201877c246e89ed1. * another attempt to fix indexer * fixes after Ethan's review * use unbuffered channel when indexing transactions Refs https://github.com/tendermint/tendermint/pull/3227#discussion_r258786716 * add a comment for EventBus#SubscribeUnbuffered * format code
6 years ago
7 years ago
7 years ago
7 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
7 years ago
8 years ago
8 years ago
7 years ago
WAL: better errors and new fail point (#3246) * privval: more info in errors * wal: change Debug logs to Info * wal: log and return error on corrupted wal instead of panicing * fail: Exit right away instead of sending interupt * consensus: FAIL before handling our own vote allows to replicate #3089: - run using `FAIL_TEST_INDEX=0` - delete some bytes from the end of the WAL - start normally Results in logs like: ``` I[2019-02-03|18:12:58.225] Searching for height module=consensus wal=/Users/ethanbuchman/.tendermint/data/cs.wal/wal height=1 min=0 max=0 E[2019-02-03|18:12:58.225] Error on catchup replay. Proceeding to start ConsensusState anyway module=consensus err="failed to read data: EOF" I[2019-02-03|18:12:58.225] Started node module=main nodeInfo="{ProtocolVersion:{P2P:6 Block:9 App:1} ID_:35e87e93f2e31f305b65a5517fd2102331b56002 ListenAddr:tcp://0.0.0.0:26656 Network:test-chain-J8JvJH Version:0.29.1 Channels:4020212223303800 Moniker:Ethans-MacBook-Pro.local Other:{TxIndex:on RPCAddress:tcp://0.0.0.0:26657}}" E[2019-02-03|18:12:58.226] Couldn't connect to any seeds module=p2p I[2019-02-03|18:12:59.229] Timed out module=consensus dur=998.568ms height=1 round=0 step=RoundStepNewHeight I[2019-02-03|18:12:59.230] enterNewRound(1/0). Current: 1/0/RoundStepNewHeight module=consensus height=1 round=0 I[2019-02-03|18:12:59.230] enterPropose(1/0). Current: 1/0/RoundStepNewRound module=consensus height=1 round=0 I[2019-02-03|18:12:59.230] enterPropose: Our turn to propose module=consensus height=1 round=0 proposer=AD278B7767B05D7FBEB76207024C650988FA77D5 privValidator="PrivValidator{AD278B7767B05D7FBEB76207024C650988FA77D5 LH:1, LR:0, LS:2}" E[2019-02-03|18:12:59.230] enterPropose: Error signing proposal module=consensus height=1 round=0 err="Error signing proposal: Step regression at height 1 round 0. Got 1, last step 2" I[2019-02-03|18:13:02.233] Timed out module=consensus dur=3s height=1 round=0 step=RoundStepPropose I[2019-02-03|18:13:02.233] enterPrevote(1/0). Current: 1/0/RoundStepPropose module=consensus I[2019-02-03|18:13:02.233] enterPrevote: ProposalBlock is nil module=consensus height=1 round=0 E[2019-02-03|18:13:02.234] Error signing vote module=consensus height=1 round=0 vote="Vote{0:AD278B7767B0 1/00/1(Prevote) 000000000000 000000000000 @ 2019-02-04T02:13:02.233897Z}" err="Error signing vote: Conflicting data" ``` Notice the EOF, the step regression, and the conflicting data. * wal: change errors to be DataCorruptionError * exit on corrupt WAL * fix log * fix new line
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
8 years ago
7 years ago
cs/replay: execCommitBlock should not read from state.lastValidators (#3067) * execCommitBlock should not read from state.lastValidators * fix height 1 * fix blockchain/reactor_test * fix consensus/mempool_test * fix consensus/reactor_test * fix consensus/replay_test * add CHANGELOG * fix consensus/reactor_test * fix consensus/replay_test * add a test for replay validators change * fix mem_pool test * fix byzantine test * remove a redundant code * reduce validator change blocks to 6 * fix * return peer0 config * seperate testName * seperate testName 1 * seperate testName 2 * seperate app db path * seperate app db path 1 * add a lock before startNet * move the lock to reactor_test * simulate just once * try to find problem * handshake only saveState when app version changed * update gometalinter to 3.0.0 (#3233) in the attempt to fix https://circleci.com/gh/tendermint/tendermint/43165 also code is simplified by running gofmt -s . remove unused vars enable linters we're currently passing remove deprecated linters (cherry picked from commit d47094550315c094512a242445e0dde24b5a03f5) * gofmt code * goimport code * change the bool name to testValidatorsChange * adjust receive kvstore.ProtocolVersion * adjust receive kvstore.ProtocolVersion 1 * adjust receive kvstore.ProtocolVersion 3 * fix merge execution.go * fix merge develop * fix merge develop 1 * fix run cleanupFunc * adjust code according to reviewers' opinion * modify the func name match the convention * simplify simulate a chain containing some validator change txs 1 * test CI error * Merge remote-tracking branch 'upstream/develop' into fixReplay 1 * fix pubsub_test * subscribeUnbuffered vote channel
6 years ago
7 years ago
7 years ago
7 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
7 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 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. "context"
  5. "errors"
  6. "fmt"
  7. "hash/crc32"
  8. "io"
  9. "reflect"
  10. "time"
  11. abci "github.com/tendermint/tendermint/abci/types"
  12. "github.com/tendermint/tendermint/crypto/merkle"
  13. "github.com/tendermint/tendermint/internal/eventbus"
  14. "github.com/tendermint/tendermint/internal/proxy"
  15. sm "github.com/tendermint/tendermint/internal/state"
  16. "github.com/tendermint/tendermint/libs/log"
  17. "github.com/tendermint/tendermint/types"
  18. )
  19. var crc32c = crc32.MakeTable(crc32.Castagnoli)
  20. // Functionality to replay blocks and messages on recovery from a crash.
  21. // There are two general failure scenarios:
  22. //
  23. // 1. failure during consensus
  24. // 2. failure while applying the block
  25. //
  26. // The former is handled by the WAL, the latter by the proxyApp Handshake on
  27. // restart, which ultimately hands off the work to the WAL.
  28. //-----------------------------------------
  29. // 1. Recover from failure during consensus
  30. // (by replaying messages from the WAL)
  31. //-----------------------------------------
  32. // Unmarshal and apply a single message to the consensus state as if it were
  33. // received in receiveRoutine. Lines that start with "#" are ignored.
  34. // NOTE: receiveRoutine should not be running.
  35. func (cs *State) readReplayMessage(ctx context.Context, msg *TimedWALMessage, newStepSub eventbus.Subscription) error {
  36. // Skip meta messages which exist for demarcating boundaries.
  37. if _, ok := msg.Msg.(EndHeightMessage); ok {
  38. return nil
  39. }
  40. // for logging
  41. switch m := msg.Msg.(type) {
  42. case types.EventDataRoundState:
  43. cs.logger.Info("Replay: New Step", "height", m.Height, "round", m.Round, "step", m.Step)
  44. // these are playback checks
  45. if newStepSub != nil {
  46. ctxto, cancel := context.WithTimeout(ctx, 2*time.Second)
  47. defer cancel()
  48. stepMsg, err := newStepSub.Next(ctxto)
  49. if errors.Is(err, context.DeadlineExceeded) {
  50. return fmt.Errorf("subscription timed out: %w", err)
  51. } else if err != nil {
  52. return fmt.Errorf("subscription canceled: %w", err)
  53. }
  54. m2 := stepMsg.Data().(types.EventDataRoundState)
  55. if m.Height != m2.Height || m.Round != m2.Round || m.Step != m2.Step {
  56. return fmt.Errorf("roundState mismatch. Got %v; Expected %v", m2, m)
  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.PartSetHeader, "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(ctx, 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(ctx, 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 *State) catchupReplay(ctx context.Context, 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 State 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. if csHeight < cs.state.InitialHeight {
  113. return fmt.Errorf("cannot replay height %v, below initial height %v", csHeight, cs.state.InitialHeight)
  114. }
  115. endHeight := csHeight - 1
  116. if csHeight == cs.state.InitialHeight {
  117. endHeight = 0
  118. }
  119. gr, found, err = cs.wal.SearchForEndHeight(endHeight, &WALSearchOptions{IgnoreDataCorruptionErrors: true})
  120. if err == io.EOF {
  121. cs.logger.Error("Replay: wal.group.Search returned EOF", "#ENDHEIGHT", endHeight)
  122. } else if err != nil {
  123. return err
  124. }
  125. if !found {
  126. return fmt.Errorf("cannot replay height %d. WAL does not contain #ENDHEIGHT for %d", csHeight, endHeight)
  127. }
  128. defer gr.Close()
  129. cs.logger.Info("Catchup by replaying consensus messages", "height", csHeight)
  130. var msg *TimedWALMessage
  131. dec := WALDecoder{gr}
  132. LOOP:
  133. for {
  134. msg, err = dec.Decode()
  135. switch {
  136. case err == io.EOF:
  137. break LOOP
  138. case IsDataCorruptionError(err):
  139. cs.logger.Error("data has been corrupted in last height of consensus WAL", "err", err, "height", csHeight)
  140. return err
  141. case err != nil:
  142. return err
  143. }
  144. // NOTE: since the priv key is set when the msgs are received
  145. // it will attempt to eg double sign but we can just ignore it
  146. // since the votes will be replayed and we'll get to the next step
  147. if err := cs.readReplayMessage(ctx, msg, nil); err != nil {
  148. return err
  149. }
  150. }
  151. cs.logger.Info("Replay: Done")
  152. return nil
  153. }
  154. //--------------------------------------------------------------------------------
  155. // Parses marker lines of the form:
  156. // #ENDHEIGHT: 12345
  157. /*
  158. func makeHeightSearchFunc(height int64) auto.SearchFunc {
  159. return func(line string) (int, error) {
  160. line = strings.TrimRight(line, "\n")
  161. parts := strings.Split(line, " ")
  162. if len(parts) != 2 {
  163. return -1, errors.New("line did not have 2 parts")
  164. }
  165. i, err := strconv.Atoi(parts[1])
  166. if err != nil {
  167. return -1, errors.New("failed to parse INFO: " + err.Error())
  168. }
  169. if height < i {
  170. return 1, nil
  171. } else if height == i {
  172. return 0, nil
  173. } else {
  174. return -1, nil
  175. }
  176. }
  177. }*/
  178. //---------------------------------------------------
  179. // 2. Recover from failure while applying the block.
  180. // (by handshaking with the app to figure out where
  181. // we were last, and using the WAL to recover there.)
  182. //---------------------------------------------------
  183. type Handshaker struct {
  184. stateStore sm.Store
  185. initialState sm.State
  186. store sm.BlockStore
  187. eventBus types.BlockEventPublisher
  188. genDoc *types.GenesisDoc
  189. logger log.Logger
  190. nBlocks int // number of blocks applied to the state
  191. }
  192. func NewHandshaker(
  193. logger log.Logger,
  194. stateStore sm.Store,
  195. state sm.State,
  196. store sm.BlockStore,
  197. eventBus types.BlockEventPublisher,
  198. genDoc *types.GenesisDoc,
  199. ) *Handshaker {
  200. return &Handshaker{
  201. stateStore: stateStore,
  202. initialState: state,
  203. store: store,
  204. eventBus: eventBus,
  205. genDoc: genDoc,
  206. logger: logger,
  207. nBlocks: 0,
  208. }
  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(ctx context.Context, proxyApp proxy.AppConns) error {
  216. // Handshake is done via ABCI Info on the query conn.
  217. res, err := proxyApp.Query().InfoSync(ctx, proxy.RequestInfo)
  218. if err != nil {
  219. return fmt.Errorf("error calling Info: %w", 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", 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(ctx, h.initialState, appHash, blockHeight, proxyApp)
  238. if err != nil {
  239. return fmt.Errorf("error on replay: %w", err)
  240. }
  241. h.logger.Info("Completed ABCI Handshake - Tendermint and App are synced",
  242. "appHeight", blockHeight, "appHash", 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. ctx context.Context,
  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(ctx, 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(ctx, 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(ctx, 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(ctx, 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, err := newMockProxyApp(ctx, h.logger, appHash, abciResponses)
  377. if err != nil {
  378. return nil, err
  379. }
  380. h.logger.Info("Replay last block using mock app")
  381. state, err = h.replayBlock(ctx, state, storeBlockHeight, mockApp)
  382. if err != nil {
  383. return nil, err
  384. }
  385. return state.AppHash, err
  386. }
  387. }
  388. panic(fmt.Sprintf("uncovered case! appHeight: %d, storeHeight: %d, stateHeight: %d",
  389. appBlockHeight, storeBlockHeight, stateBlockHeight))
  390. }
  391. func (h *Handshaker) replayBlocks(
  392. ctx context.Context,
  393. state sm.State,
  394. proxyApp proxy.AppConns,
  395. appBlockHeight,
  396. storeBlockHeight int64,
  397. mutateState bool) ([]byte, error) {
  398. // App is further behind than it should be, so we need to replay blocks.
  399. // We replay all blocks from appBlockHeight+1.
  400. //
  401. // Note that we don't have an old version of the state,
  402. // so we by-pass state validation/mutation using sm.ExecCommitBlock.
  403. // This also means we won't be saving validator sets if they change during this period.
  404. // TODO: Load the historical information to fix this and just use state.ApplyBlock
  405. //
  406. // If mutateState == true, the final block is replayed with h.replayBlock()
  407. var appHash []byte
  408. var err error
  409. finalBlock := storeBlockHeight
  410. if mutateState {
  411. finalBlock--
  412. }
  413. firstBlock := appBlockHeight + 1
  414. if firstBlock == 1 {
  415. firstBlock = state.InitialHeight
  416. }
  417. for i := firstBlock; i <= finalBlock; i++ {
  418. h.logger.Info("Applying block", "height", i)
  419. block := h.store.LoadBlock(i)
  420. // Extra check to ensure the app was not changed in a way it shouldn't have.
  421. if len(appHash) > 0 {
  422. assertAppHashEqualsOneFromBlock(appHash, block)
  423. }
  424. if i == finalBlock && !mutateState {
  425. // We emit events for the index services at the final block due to the sync issue when
  426. // the node shutdown during the block committing status.
  427. blockExec := sm.NewBlockExecutor(
  428. h.stateStore, h.logger, proxyApp.Consensus(), emptyMempool{}, sm.EmptyEvidencePool{}, h.store)
  429. blockExec.SetEventBus(h.eventBus)
  430. appHash, err = sm.ExecCommitBlock(ctx,
  431. blockExec, proxyApp.Consensus(), block, h.logger, h.stateStore, h.genDoc.InitialHeight, state)
  432. if err != nil {
  433. return nil, err
  434. }
  435. } else {
  436. appHash, err = sm.ExecCommitBlock(ctx,
  437. nil, proxyApp.Consensus(), block, h.logger, h.stateStore, h.genDoc.InitialHeight, state)
  438. if err != nil {
  439. return nil, err
  440. }
  441. }
  442. h.nBlocks++
  443. }
  444. if mutateState {
  445. // sync the final block
  446. state, err = h.replayBlock(ctx, state, storeBlockHeight, proxyApp.Consensus())
  447. if err != nil {
  448. return nil, err
  449. }
  450. appHash = state.AppHash
  451. }
  452. assertAppHashEqualsOneFromState(appHash, state)
  453. return appHash, nil
  454. }
  455. // ApplyBlock on the proxyApp with the last block.
  456. func (h *Handshaker) replayBlock(
  457. ctx context.Context,
  458. state sm.State,
  459. height int64,
  460. proxyApp proxy.AppConnConsensus,
  461. ) (sm.State, error) {
  462. block := h.store.LoadBlock(height)
  463. meta := h.store.LoadBlockMeta(height)
  464. // Use stubs for both mempool and evidence pool since no transactions nor
  465. // evidence are needed here - block already exists.
  466. blockExec := sm.NewBlockExecutor(h.stateStore, h.logger, proxyApp, emptyMempool{}, sm.EmptyEvidencePool{}, h.store)
  467. blockExec.SetEventBus(h.eventBus)
  468. var err error
  469. state, err = blockExec.ApplyBlock(ctx, state, meta.BlockID, block)
  470. if err != nil {
  471. return sm.State{}, err
  472. }
  473. h.nBlocks++
  474. return state, nil
  475. }
  476. func assertAppHashEqualsOneFromBlock(appHash []byte, block *types.Block) {
  477. if !bytes.Equal(appHash, block.AppHash) {
  478. panic(fmt.Sprintf(`block.AppHash does not match AppHash after replay. Got %X, expected %X.
  479. Block: %v
  480. `,
  481. appHash, block.AppHash, block))
  482. }
  483. }
  484. func assertAppHashEqualsOneFromState(appHash []byte, state sm.State) {
  485. if !bytes.Equal(appHash, state.AppHash) {
  486. panic(fmt.Sprintf(`state.AppHash does not match AppHash after replay. Got
  487. %X, expected %X.
  488. State: %v
  489. Did you reset Tendermint without resetting your application's data?`,
  490. appHash, state.AppHash, state))
  491. }
  492. }