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.

329 lines
9.0 KiB

blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
6 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
6 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
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
  1. package v0
  2. import (
  3. "os"
  4. "testing"
  5. "time"
  6. "github.com/stretchr/testify/require"
  7. abci "github.com/tendermint/tendermint/abci/types"
  8. cfg "github.com/tendermint/tendermint/config"
  9. "github.com/tendermint/tendermint/libs/log"
  10. "github.com/tendermint/tendermint/mempool/mock"
  11. "github.com/tendermint/tendermint/p2p"
  12. "github.com/tendermint/tendermint/p2p/p2ptest"
  13. bcproto "github.com/tendermint/tendermint/proto/tendermint/blockchain"
  14. "github.com/tendermint/tendermint/proxy"
  15. sm "github.com/tendermint/tendermint/state"
  16. "github.com/tendermint/tendermint/store"
  17. "github.com/tendermint/tendermint/types"
  18. dbm "github.com/tendermint/tm-db"
  19. )
  20. type reactorTestSuite struct {
  21. network *p2ptest.Network
  22. logger log.Logger
  23. nodes []p2p.NodeID
  24. reactors map[p2p.NodeID]*Reactor
  25. app map[p2p.NodeID]proxy.AppConns
  26. blockchainChannels map[p2p.NodeID]*p2p.Channel
  27. peerChans map[p2p.NodeID]chan p2p.PeerUpdate
  28. peerUpdates map[p2p.NodeID]*p2p.PeerUpdates
  29. fastSync bool
  30. }
  31. func setup(
  32. t *testing.T,
  33. genDoc *types.GenesisDoc,
  34. privVal types.PrivValidator,
  35. maxBlockHeights []int64,
  36. chBuf uint,
  37. ) *reactorTestSuite {
  38. t.Helper()
  39. numNodes := len(maxBlockHeights)
  40. require.True(t, numNodes >= 1,
  41. "must specify at least one block height (nodes)")
  42. rts := &reactorTestSuite{
  43. logger: log.TestingLogger().With("module", "blockchain", "testCase", t.Name()),
  44. network: p2ptest.MakeNetwork(t, numNodes),
  45. nodes: make([]p2p.NodeID, 0, numNodes),
  46. reactors: make(map[p2p.NodeID]*Reactor, numNodes),
  47. app: make(map[p2p.NodeID]proxy.AppConns, numNodes),
  48. blockchainChannels: make(map[p2p.NodeID]*p2p.Channel, numNodes),
  49. peerChans: make(map[p2p.NodeID]chan p2p.PeerUpdate, numNodes),
  50. peerUpdates: make(map[p2p.NodeID]*p2p.PeerUpdates, numNodes),
  51. fastSync: true,
  52. }
  53. rts.blockchainChannels = rts.network.MakeChannelsNoCleanup(t, BlockchainChannel, new(bcproto.Message), int(chBuf))
  54. i := 0
  55. for nodeID := range rts.network.Nodes {
  56. rts.addNode(t, nodeID, genDoc, privVal, maxBlockHeights[i])
  57. i++
  58. }
  59. t.Cleanup(func() {
  60. for _, nodeID := range rts.nodes {
  61. rts.peerUpdates[nodeID].Close()
  62. if rts.reactors[nodeID].IsRunning() {
  63. require.NoError(t, rts.reactors[nodeID].Stop())
  64. require.NoError(t, rts.app[nodeID].Stop())
  65. require.False(t, rts.reactors[nodeID].IsRunning())
  66. }
  67. }
  68. })
  69. return rts
  70. }
  71. func (rts *reactorTestSuite) addNode(t *testing.T,
  72. nodeID p2p.NodeID,
  73. genDoc *types.GenesisDoc,
  74. privVal types.PrivValidator,
  75. maxBlockHeight int64,
  76. ) {
  77. t.Helper()
  78. rts.nodes = append(rts.nodes, nodeID)
  79. rts.app[nodeID] = proxy.NewAppConns(proxy.NewLocalClientCreator(&abci.BaseApplication{}))
  80. require.NoError(t, rts.app[nodeID].Start())
  81. blockDB := dbm.NewMemDB()
  82. stateDB := dbm.NewMemDB()
  83. stateStore := sm.NewStore(stateDB)
  84. blockStore := store.NewBlockStore(blockDB)
  85. state, err := stateStore.LoadFromDBOrGenesisDoc(genDoc)
  86. require.NoError(t, err)
  87. db := dbm.NewMemDB()
  88. stateStore = sm.NewStore(db)
  89. blockExec := sm.NewBlockExecutor(
  90. stateStore,
  91. log.TestingLogger(),
  92. rts.app[nodeID].Consensus(),
  93. mock.Mempool{},
  94. sm.EmptyEvidencePool{},
  95. )
  96. require.NoError(t, stateStore.Save(state))
  97. for blockHeight := int64(1); blockHeight <= maxBlockHeight; blockHeight++ {
  98. lastCommit := types.NewCommit(blockHeight-1, 0, types.BlockID{}, nil)
  99. if blockHeight > 1 {
  100. lastBlockMeta := blockStore.LoadBlockMeta(blockHeight - 1)
  101. lastBlock := blockStore.LoadBlock(blockHeight - 1)
  102. vote, err := types.MakeVote(
  103. lastBlock.Header.Height,
  104. lastBlockMeta.BlockID,
  105. state.Validators,
  106. privVal,
  107. lastBlock.Header.ChainID,
  108. time.Now(),
  109. )
  110. require.NoError(t, err)
  111. lastCommit = types.NewCommit(
  112. vote.Height,
  113. vote.Round,
  114. lastBlockMeta.BlockID,
  115. []types.CommitSig{vote.CommitSig()},
  116. )
  117. }
  118. thisBlock := makeBlock(blockHeight, state, lastCommit)
  119. thisParts := thisBlock.MakePartSet(types.BlockPartSizeBytes)
  120. blockID := types.BlockID{Hash: thisBlock.Hash(), PartSetHeader: thisParts.Header()}
  121. state, _, err = blockExec.ApplyBlock(state, blockID, thisBlock)
  122. require.NoError(t, err)
  123. blockStore.SaveBlock(thisBlock, thisParts, lastCommit)
  124. }
  125. rts.peerChans[nodeID] = make(chan p2p.PeerUpdate)
  126. rts.peerUpdates[nodeID] = p2p.NewPeerUpdates(rts.peerChans[nodeID])
  127. rts.network.Nodes[nodeID].PeerManager.Register(rts.peerUpdates[nodeID])
  128. rts.reactors[nodeID], err = NewReactor(
  129. rts.logger.With("nodeID", nodeID),
  130. state.Copy(),
  131. blockExec,
  132. blockStore,
  133. nil,
  134. rts.blockchainChannels[nodeID],
  135. rts.peerUpdates[nodeID],
  136. rts.fastSync)
  137. require.NoError(t, err)
  138. require.NoError(t, rts.reactors[nodeID].Start())
  139. require.True(t, rts.reactors[nodeID].IsRunning())
  140. }
  141. func (rts *reactorTestSuite) start(t *testing.T) {
  142. t.Helper()
  143. rts.network.Start(t)
  144. require.Len(t,
  145. rts.network.RandomNode().PeerManager.Peers(),
  146. len(rts.nodes)-1,
  147. "network does not have expected number of nodes")
  148. }
  149. func TestReactor_AbruptDisconnect(t *testing.T) {
  150. config := cfg.ResetTestRoot("blockchain_reactor_test")
  151. defer os.RemoveAll(config.RootDir)
  152. genDoc, privVals := randGenesisDoc(config, 1, false, 30)
  153. maxBlockHeight := int64(64)
  154. rts := setup(t, genDoc, privVals[0], []int64{maxBlockHeight, 0}, 0)
  155. require.Equal(t, maxBlockHeight, rts.reactors[rts.nodes[0]].store.Height())
  156. rts.start(t)
  157. secondaryPool := rts.reactors[rts.nodes[1]].pool
  158. require.Eventually(
  159. t,
  160. func() bool {
  161. height, _, _ := secondaryPool.GetStatus()
  162. return secondaryPool.MaxPeerHeight() > 0 && height > 0 && height < 10
  163. },
  164. 10*time.Second,
  165. 10*time.Millisecond,
  166. "expected node to be partially synced",
  167. )
  168. // Remove synced node from the syncing node which should not result in any
  169. // deadlocks or race conditions within the context of poolRoutine.
  170. rts.peerChans[rts.nodes[1]] <- p2p.PeerUpdate{
  171. Status: p2p.PeerStatusDown,
  172. NodeID: rts.nodes[0],
  173. }
  174. require.NoError(t, rts.network.Nodes[rts.nodes[1]].PeerManager.Disconnected(rts.nodes[0]))
  175. }
  176. func TestReactor_NoBlockResponse(t *testing.T) {
  177. config := cfg.ResetTestRoot("blockchain_reactor_test")
  178. defer os.RemoveAll(config.RootDir)
  179. genDoc, privVals := randGenesisDoc(config, 1, false, 30)
  180. maxBlockHeight := int64(65)
  181. rts := setup(t, genDoc, privVals[0], []int64{maxBlockHeight, 0}, 0)
  182. require.Equal(t, maxBlockHeight, rts.reactors[rts.nodes[0]].store.Height())
  183. rts.start(t)
  184. testCases := []struct {
  185. height int64
  186. existent bool
  187. }{
  188. {maxBlockHeight + 2, false},
  189. {10, true},
  190. {1, true},
  191. {100, false},
  192. }
  193. secondaryPool := rts.reactors[rts.nodes[1]].pool
  194. require.Eventually(
  195. t,
  196. func() bool { return secondaryPool.MaxPeerHeight() > 0 && secondaryPool.IsCaughtUp() },
  197. 10*time.Second,
  198. 10*time.Millisecond,
  199. "expected node to be fully synced",
  200. )
  201. for _, tc := range testCases {
  202. block := rts.reactors[rts.nodes[1]].store.LoadBlock(tc.height)
  203. if tc.existent {
  204. require.True(t, block != nil)
  205. } else {
  206. require.Nil(t, block)
  207. }
  208. }
  209. }
  210. func TestReactor_BadBlockStopsPeer(t *testing.T) {
  211. // Ultimately, this should be refactored to be less integration test oriented
  212. // and more unit test oriented by simply testing channel sends and receives.
  213. // See: https://github.com/tendermint/tendermint/issues/6005
  214. t.SkipNow()
  215. config := cfg.ResetTestRoot("blockchain_reactor_test")
  216. defer os.RemoveAll(config.RootDir)
  217. maxBlockHeight := int64(48)
  218. genDoc, privVals := randGenesisDoc(config, 1, false, 30)
  219. rts := setup(t, genDoc, privVals[0], []int64{maxBlockHeight, 0, 0, 0, 0}, 1000)
  220. require.Equal(t, maxBlockHeight, rts.reactors[rts.nodes[0]].store.Height())
  221. rts.start(t)
  222. require.Eventually(
  223. t,
  224. func() bool {
  225. caughtUp := true
  226. for _, id := range rts.nodes[1 : len(rts.nodes)-1] {
  227. if rts.reactors[id].pool.MaxPeerHeight() == 0 || !rts.reactors[id].pool.IsCaughtUp() {
  228. caughtUp = false
  229. }
  230. }
  231. return caughtUp
  232. },
  233. 10*time.Minute,
  234. 10*time.Millisecond,
  235. "expected all nodes to be fully synced",
  236. )
  237. for _, id := range rts.nodes[:len(rts.nodes)-1] {
  238. require.Len(t, rts.reactors[id].pool.peers, 3)
  239. }
  240. // Mark testSuites[3] as an invalid peer which will cause newSuite to disconnect
  241. // from this peer.
  242. //
  243. // XXX: This causes a potential race condition.
  244. // See: https://github.com/tendermint/tendermint/issues/6005
  245. otherGenDoc, otherPrivVals := randGenesisDoc(config, 1, false, 30)
  246. newNode := rts.network.MakeNode(t)
  247. rts.addNode(t, newNode.NodeID, otherGenDoc, otherPrivVals[0], maxBlockHeight)
  248. // add a fake peer just so we do not wait for the consensus ticker to timeout
  249. rts.reactors[newNode.NodeID].pool.SetPeerRange("00ff", 10, 10)
  250. // wait for the new peer to catch up and become fully synced
  251. require.Eventually(
  252. t,
  253. func() bool {
  254. return rts.reactors[newNode.NodeID].pool.MaxPeerHeight() > 0 && rts.reactors[newNode.NodeID].pool.IsCaughtUp()
  255. },
  256. 10*time.Minute,
  257. 10*time.Millisecond,
  258. "expected new node to be fully synced",
  259. )
  260. require.Eventuallyf(
  261. t,
  262. func() bool { return len(rts.reactors[newNode.NodeID].pool.peers) < len(rts.nodes)-1 },
  263. 10*time.Minute,
  264. 10*time.Millisecond,
  265. "invalid number of peers; expected < %d, got: %d",
  266. len(rts.nodes)-1,
  267. len(rts.reactors[newNode.NodeID].pool.peers),
  268. )
  269. }