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.

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