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.

333 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. chDesc := p2p.ChannelDescriptor{ID: byte(BlockchainChannel)}
  55. rts.blockchainChannels = rts.network.MakeChannelsNoCleanup(t, chDesc, new(bcproto.Message), int(chBuf))
  56. i := 0
  57. for nodeID := range rts.network.Nodes {
  58. rts.addNode(t, nodeID, genDoc, privVal, maxBlockHeights[i])
  59. i++
  60. }
  61. t.Cleanup(func() {
  62. for _, nodeID := range rts.nodes {
  63. rts.peerUpdates[nodeID].Close()
  64. if rts.reactors[nodeID].IsRunning() {
  65. require.NoError(t, rts.reactors[nodeID].Stop())
  66. require.NoError(t, rts.app[nodeID].Stop())
  67. require.False(t, rts.reactors[nodeID].IsRunning())
  68. }
  69. }
  70. })
  71. return rts
  72. }
  73. func (rts *reactorTestSuite) addNode(t *testing.T,
  74. nodeID p2p.NodeID,
  75. genDoc *types.GenesisDoc,
  76. privVal types.PrivValidator,
  77. maxBlockHeight int64,
  78. ) {
  79. t.Helper()
  80. rts.nodes = append(rts.nodes, nodeID)
  81. rts.app[nodeID] = proxy.NewAppConns(proxy.NewLocalClientCreator(&abci.BaseApplication{}))
  82. require.NoError(t, rts.app[nodeID].Start())
  83. blockDB := dbm.NewMemDB()
  84. stateDB := dbm.NewMemDB()
  85. stateStore := sm.NewStore(stateDB)
  86. blockStore := store.NewBlockStore(blockDB)
  87. state, err := stateStore.LoadFromDBOrGenesisDoc(genDoc)
  88. require.NoError(t, err)
  89. db := dbm.NewMemDB()
  90. stateStore = sm.NewStore(db)
  91. blockExec := sm.NewBlockExecutor(
  92. stateStore,
  93. log.TestingLogger(),
  94. rts.app[nodeID].Consensus(),
  95. mock.Mempool{},
  96. sm.EmptyEvidencePool{},
  97. )
  98. require.NoError(t, stateStore.Save(state))
  99. for blockHeight := int64(1); blockHeight <= maxBlockHeight; blockHeight++ {
  100. lastCommit := types.NewCommit(blockHeight-1, 0, types.BlockID{}, nil)
  101. if blockHeight > 1 {
  102. lastBlockMeta := blockStore.LoadBlockMeta(blockHeight - 1)
  103. lastBlock := blockStore.LoadBlock(blockHeight - 1)
  104. vote, err := factory.MakeVote(
  105. privVal,
  106. lastBlock.Header.ChainID, 0,
  107. lastBlock.Header.Height, 0, 2,
  108. lastBlockMeta.BlockID,
  109. time.Now(),
  110. )
  111. require.NoError(t, err)
  112. lastCommit = types.NewCommit(
  113. vote.Height,
  114. vote.Round,
  115. lastBlockMeta.BlockID,
  116. []types.CommitSig{vote.CommitSig()},
  117. )
  118. }
  119. thisBlock := makeBlock(blockHeight, state, lastCommit)
  120. thisParts := thisBlock.MakePartSet(types.BlockPartSizeBytes)
  121. blockID := types.BlockID{Hash: thisBlock.Hash(), PartSetHeader: thisParts.Header()}
  122. state, _, err = blockExec.ApplyBlock(state, blockID, thisBlock)
  123. require.NoError(t, err)
  124. blockStore.SaveBlock(thisBlock, thisParts, lastCommit)
  125. }
  126. rts.peerChans[nodeID] = make(chan p2p.PeerUpdate)
  127. rts.peerUpdates[nodeID] = p2p.NewPeerUpdates(rts.peerChans[nodeID], 1)
  128. rts.network.Nodes[nodeID].PeerManager.Register(rts.peerUpdates[nodeID])
  129. rts.reactors[nodeID], err = NewReactor(
  130. rts.logger.With("nodeID", nodeID),
  131. state.Copy(),
  132. blockExec,
  133. blockStore,
  134. nil,
  135. rts.blockchainChannels[nodeID],
  136. rts.peerUpdates[nodeID],
  137. rts.fastSync)
  138. require.NoError(t, err)
  139. require.NoError(t, rts.reactors[nodeID].Start())
  140. require.True(t, rts.reactors[nodeID].IsRunning())
  141. }
  142. func (rts *reactorTestSuite) start(t *testing.T) {
  143. t.Helper()
  144. rts.network.Start(t)
  145. require.Len(t,
  146. rts.network.RandomNode().PeerManager.Peers(),
  147. len(rts.nodes)-1,
  148. "network does not have expected number of nodes")
  149. }
  150. func TestReactor_AbruptDisconnect(t *testing.T) {
  151. config := cfg.ResetTestRoot("blockchain_reactor_test")
  152. defer os.RemoveAll(config.RootDir)
  153. genDoc, privVals := factory.RandGenesisDoc(config, 1, false, 30)
  154. maxBlockHeight := int64(64)
  155. rts := setup(t, genDoc, privVals[0], []int64{maxBlockHeight, 0}, 0)
  156. require.Equal(t, maxBlockHeight, rts.reactors[rts.nodes[0]].store.Height())
  157. rts.start(t)
  158. secondaryPool := rts.reactors[rts.nodes[1]].pool
  159. require.Eventually(
  160. t,
  161. func() bool {
  162. height, _, _ := secondaryPool.GetStatus()
  163. return secondaryPool.MaxPeerHeight() > 0 && height > 0 && height < 10
  164. },
  165. 10*time.Second,
  166. 10*time.Millisecond,
  167. "expected node to be partially synced",
  168. )
  169. // Remove synced node from the syncing node which should not result in any
  170. // deadlocks or race conditions within the context of poolRoutine.
  171. rts.peerChans[rts.nodes[1]] <- p2p.PeerUpdate{
  172. Status: p2p.PeerStatusDown,
  173. NodeID: rts.nodes[0],
  174. }
  175. require.NoError(t, rts.network.Nodes[rts.nodes[1]].PeerManager.Disconnected(rts.nodes[0]))
  176. }
  177. func TestReactor_NoBlockResponse(t *testing.T) {
  178. config := cfg.ResetTestRoot("blockchain_reactor_test")
  179. defer os.RemoveAll(config.RootDir)
  180. genDoc, privVals := factory.RandGenesisDoc(config, 1, false, 30)
  181. maxBlockHeight := int64(65)
  182. rts := setup(t, genDoc, privVals[0], []int64{maxBlockHeight, 0}, 0)
  183. require.Equal(t, maxBlockHeight, rts.reactors[rts.nodes[0]].store.Height())
  184. rts.start(t)
  185. testCases := []struct {
  186. height int64
  187. existent bool
  188. }{
  189. {maxBlockHeight + 2, false},
  190. {10, true},
  191. {1, true},
  192. {100, false},
  193. }
  194. secondaryPool := rts.reactors[rts.nodes[1]].pool
  195. require.Eventually(
  196. t,
  197. func() bool { return secondaryPool.MaxPeerHeight() > 0 && secondaryPool.IsCaughtUp() },
  198. 10*time.Second,
  199. 10*time.Millisecond,
  200. "expected node to be fully synced",
  201. )
  202. for _, tc := range testCases {
  203. block := rts.reactors[rts.nodes[1]].store.LoadBlock(tc.height)
  204. if tc.existent {
  205. require.True(t, block != nil)
  206. } else {
  207. require.Nil(t, block)
  208. }
  209. }
  210. }
  211. func TestReactor_BadBlockStopsPeer(t *testing.T) {
  212. // Ultimately, this should be refactored to be less integration test oriented
  213. // and more unit test oriented by simply testing channel sends and receives.
  214. // See: https://github.com/tendermint/tendermint/issues/6005
  215. t.SkipNow()
  216. config := cfg.ResetTestRoot("blockchain_reactor_test")
  217. defer os.RemoveAll(config.RootDir)
  218. maxBlockHeight := int64(48)
  219. genDoc, privVals := factory.RandGenesisDoc(config, 1, false, 30)
  220. rts := setup(t, genDoc, privVals[0], []int64{maxBlockHeight, 0, 0, 0, 0}, 1000)
  221. require.Equal(t, maxBlockHeight, rts.reactors[rts.nodes[0]].store.Height())
  222. rts.start(t)
  223. require.Eventually(
  224. t,
  225. func() bool {
  226. caughtUp := true
  227. for _, id := range rts.nodes[1 : len(rts.nodes)-1] {
  228. if rts.reactors[id].pool.MaxPeerHeight() == 0 || !rts.reactors[id].pool.IsCaughtUp() {
  229. caughtUp = false
  230. }
  231. }
  232. return caughtUp
  233. },
  234. 10*time.Minute,
  235. 10*time.Millisecond,
  236. "expected all nodes to be fully synced",
  237. )
  238. for _, id := range rts.nodes[:len(rts.nodes)-1] {
  239. require.Len(t, rts.reactors[id].pool.peers, 3)
  240. }
  241. // Mark testSuites[3] as an invalid peer which will cause newSuite to disconnect
  242. // from this peer.
  243. //
  244. // XXX: This causes a potential race condition.
  245. // See: https://github.com/tendermint/tendermint/issues/6005
  246. otherGenDoc, otherPrivVals := factory.RandGenesisDoc(config, 1, false, 30)
  247. newNode := rts.network.MakeNode(t, p2ptest.NodeOptions{
  248. MaxPeers: uint16(len(rts.nodes) + 1),
  249. MaxConnected: uint16(len(rts.nodes) + 1),
  250. })
  251. rts.addNode(t, newNode.NodeID, otherGenDoc, otherPrivVals[0], maxBlockHeight)
  252. // add a fake peer just so we do not wait for the consensus ticker to timeout
  253. rts.reactors[newNode.NodeID].pool.SetPeerRange("00ff", 10, 10)
  254. // wait for the new peer to catch up and become fully synced
  255. require.Eventually(
  256. t,
  257. func() bool {
  258. return rts.reactors[newNode.NodeID].pool.MaxPeerHeight() > 0 && rts.reactors[newNode.NodeID].pool.IsCaughtUp()
  259. },
  260. 10*time.Minute,
  261. 10*time.Millisecond,
  262. "expected new node to be fully synced",
  263. )
  264. require.Eventuallyf(
  265. t,
  266. func() bool { return len(rts.reactors[newNode.NodeID].pool.peers) < len(rts.nodes)-1 },
  267. 10*time.Minute,
  268. 10*time.Millisecond,
  269. "invalid number of peers; expected < %d, got: %d",
  270. len(rts.nodes)-1,
  271. len(rts.reactors[newNode.NodeID].pool.peers),
  272. )
  273. }