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.

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