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.

332 lines
9.3 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
5 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
5 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/internal/test/factory"
  10. "github.com/tendermint/tendermint/libs/log"
  11. "github.com/tendermint/tendermint/mempool/mock"
  12. "github.com/tendermint/tendermint/p2p"
  13. "github.com/tendermint/tendermint/p2p/p2ptest"
  14. bcproto "github.com/tendermint/tendermint/proto/tendermint/blockchain"
  15. "github.com/tendermint/tendermint/proxy"
  16. sm "github.com/tendermint/tendermint/state"
  17. "github.com/tendermint/tendermint/store"
  18. "github.com/tendermint/tendermint/types"
  19. dbm "github.com/tendermint/tm-db"
  20. )
  21. type reactorTestSuite struct {
  22. network *p2ptest.Network
  23. logger log.Logger
  24. nodes []p2p.NodeID
  25. reactors map[p2p.NodeID]*Reactor
  26. app map[p2p.NodeID]proxy.AppConns
  27. blockchainChannels map[p2p.NodeID]*p2p.Channel
  28. peerChans map[p2p.NodeID]chan p2p.PeerUpdate
  29. peerUpdates map[p2p.NodeID]*p2p.PeerUpdates
  30. fastSync bool
  31. }
  32. func setup(
  33. t *testing.T,
  34. genDoc *types.GenesisDoc,
  35. privVal types.PrivValidator,
  36. maxBlockHeights []int64,
  37. chBuf uint,
  38. ) *reactorTestSuite {
  39. t.Helper()
  40. numNodes := len(maxBlockHeights)
  41. require.True(t, numNodes >= 1,
  42. "must specify at least one block height (nodes)")
  43. rts := &reactorTestSuite{
  44. logger: log.TestingLogger().With("module", "blockchain", "testCase", t.Name()),
  45. network: p2ptest.MakeNetwork(t, p2ptest.NetworkOptions{NumNodes: numNodes}),
  46. nodes: make([]p2p.NodeID, 0, numNodes),
  47. reactors: make(map[p2p.NodeID]*Reactor, numNodes),
  48. app: make(map[p2p.NodeID]proxy.AppConns, numNodes),
  49. blockchainChannels: make(map[p2p.NodeID]*p2p.Channel, numNodes),
  50. peerChans: make(map[p2p.NodeID]chan p2p.PeerUpdate, numNodes),
  51. peerUpdates: make(map[p2p.NodeID]*p2p.PeerUpdates, numNodes),
  52. fastSync: true,
  53. }
  54. rts.blockchainChannels = rts.network.MakeChannelsNoCleanup(t, BlockchainChannel, new(bcproto.Message), int(chBuf))
  55. i := 0
  56. for nodeID := range rts.network.Nodes {
  57. rts.addNode(t, nodeID, genDoc, privVal, maxBlockHeights[i])
  58. i++
  59. }
  60. t.Cleanup(func() {
  61. for _, nodeID := range rts.nodes {
  62. rts.peerUpdates[nodeID].Close()
  63. if rts.reactors[nodeID].IsRunning() {
  64. require.NoError(t, rts.reactors[nodeID].Stop())
  65. require.NoError(t, rts.app[nodeID].Stop())
  66. require.False(t, rts.reactors[nodeID].IsRunning())
  67. }
  68. }
  69. })
  70. return rts
  71. }
  72. func (rts *reactorTestSuite) addNode(t *testing.T,
  73. nodeID p2p.NodeID,
  74. genDoc *types.GenesisDoc,
  75. privVal types.PrivValidator,
  76. maxBlockHeight int64,
  77. ) {
  78. t.Helper()
  79. rts.nodes = append(rts.nodes, nodeID)
  80. rts.app[nodeID] = proxy.NewAppConns(proxy.NewLocalClientCreator(&abci.BaseApplication{}))
  81. require.NoError(t, rts.app[nodeID].Start())
  82. blockDB := dbm.NewMemDB()
  83. stateDB := dbm.NewMemDB()
  84. stateStore := sm.NewStore(stateDB)
  85. blockStore := store.NewBlockStore(blockDB)
  86. state, err := stateStore.LoadFromDBOrGenesisDoc(genDoc)
  87. require.NoError(t, err)
  88. db := dbm.NewMemDB()
  89. stateStore = sm.NewStore(db)
  90. blockExec := sm.NewBlockExecutor(
  91. stateStore,
  92. log.TestingLogger(),
  93. rts.app[nodeID].Consensus(),
  94. mock.Mempool{},
  95. sm.EmptyEvidencePool{},
  96. )
  97. require.NoError(t, stateStore.Save(state))
  98. for blockHeight := int64(1); blockHeight <= maxBlockHeight; blockHeight++ {
  99. lastCommit := types.NewCommit(blockHeight-1, 0, types.BlockID{}, nil)
  100. if blockHeight > 1 {
  101. lastBlockMeta := blockStore.LoadBlockMeta(blockHeight - 1)
  102. lastBlock := blockStore.LoadBlock(blockHeight - 1)
  103. vote, err := factory.MakeVote(
  104. privVal,
  105. lastBlock.Header.ChainID, 0,
  106. lastBlock.Header.Height, 0, 2,
  107. lastBlockMeta.BlockID,
  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], 1)
  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 := factory.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 := factory.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 := factory.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 := factory.RandGenesisDoc(config, 1, false, 30)
  246. newNode := rts.network.MakeNode(t, p2ptest.NodeOptions{
  247. MaxPeers: uint16(len(rts.nodes) + 1),
  248. MaxConnected: uint16(len(rts.nodes) + 1),
  249. })
  250. rts.addNode(t, newNode.NodeID, otherGenDoc, otherPrivVals[0], maxBlockHeight)
  251. // add a fake peer just so we do not wait for the consensus ticker to timeout
  252. rts.reactors[newNode.NodeID].pool.SetPeerRange("00ff", 10, 10)
  253. // wait for the new peer to catch up and become fully synced
  254. require.Eventually(
  255. t,
  256. func() bool {
  257. return rts.reactors[newNode.NodeID].pool.MaxPeerHeight() > 0 && rts.reactors[newNode.NodeID].pool.IsCaughtUp()
  258. },
  259. 10*time.Minute,
  260. 10*time.Millisecond,
  261. "expected new node to be fully synced",
  262. )
  263. require.Eventuallyf(
  264. t,
  265. func() bool { return len(rts.reactors[newNode.NodeID].pool.peers) < len(rts.nodes)-1 },
  266. 10*time.Minute,
  267. 10*time.Millisecond,
  268. "invalid number of peers; expected < %d, got: %d",
  269. len(rts.nodes)-1,
  270. len(rts.reactors[newNode.NodeID].pool.peers),
  271. )
  272. }