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.

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