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
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
  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. sf "github.com/tendermint/tendermint/state/test/factory"
  18. "github.com/tendermint/tendermint/store"
  19. "github.com/tendermint/tendermint/types"
  20. dbm "github.com/tendermint/tm-db"
  21. )
  22. type reactorTestSuite struct {
  23. network *p2ptest.Network
  24. logger log.Logger
  25. nodes []p2p.NodeID
  26. reactors map[p2p.NodeID]*Reactor
  27. app map[p2p.NodeID]proxy.AppConns
  28. blockchainChannels map[p2p.NodeID]*p2p.Channel
  29. peerChans map[p2p.NodeID]chan p2p.PeerUpdate
  30. peerUpdates map[p2p.NodeID]*p2p.PeerUpdates
  31. fastSync bool
  32. }
  33. func setup(
  34. t *testing.T,
  35. genDoc *types.GenesisDoc,
  36. privVal types.PrivValidator,
  37. maxBlockHeights []int64,
  38. chBuf uint,
  39. ) *reactorTestSuite {
  40. t.Helper()
  41. numNodes := len(maxBlockHeights)
  42. require.True(t, numNodes >= 1,
  43. "must specify at least one block height (nodes)")
  44. rts := &reactorTestSuite{
  45. logger: log.TestingLogger().With("module", "blockchain", "testCase", t.Name()),
  46. network: p2ptest.MakeNetwork(t, p2ptest.NetworkOptions{NumNodes: numNodes}),
  47. nodes: make([]p2p.NodeID, 0, numNodes),
  48. reactors: make(map[p2p.NodeID]*Reactor, numNodes),
  49. app: make(map[p2p.NodeID]proxy.AppConns, numNodes),
  50. blockchainChannels: make(map[p2p.NodeID]*p2p.Channel, numNodes),
  51. peerChans: make(map[p2p.NodeID]chan p2p.PeerUpdate, numNodes),
  52. peerUpdates: make(map[p2p.NodeID]*p2p.PeerUpdates, numNodes),
  53. fastSync: true,
  54. }
  55. chDesc := p2p.ChannelDescriptor{ID: byte(BlockchainChannel)}
  56. rts.blockchainChannels = rts.network.MakeChannelsNoCleanup(t, chDesc, new(bcproto.Message), int(chBuf))
  57. i := 0
  58. for nodeID := range rts.network.Nodes {
  59. rts.addNode(t, nodeID, genDoc, privVal, maxBlockHeights[i])
  60. i++
  61. }
  62. t.Cleanup(func() {
  63. for _, nodeID := range rts.nodes {
  64. rts.peerUpdates[nodeID].Close()
  65. if rts.reactors[nodeID].IsRunning() {
  66. require.NoError(t, rts.reactors[nodeID].Stop())
  67. require.NoError(t, rts.app[nodeID].Stop())
  68. require.False(t, rts.reactors[nodeID].IsRunning())
  69. }
  70. }
  71. })
  72. return rts
  73. }
  74. func (rts *reactorTestSuite) addNode(t *testing.T,
  75. nodeID p2p.NodeID,
  76. genDoc *types.GenesisDoc,
  77. privVal types.PrivValidator,
  78. maxBlockHeight int64,
  79. ) {
  80. t.Helper()
  81. rts.nodes = append(rts.nodes, nodeID)
  82. rts.app[nodeID] = proxy.NewAppConns(proxy.NewLocalClientCreator(&abci.BaseApplication{}))
  83. require.NoError(t, rts.app[nodeID].Start())
  84. blockDB := dbm.NewMemDB()
  85. stateDB := dbm.NewMemDB()
  86. stateStore := sm.NewStore(stateDB)
  87. blockStore := store.NewBlockStore(blockDB)
  88. state, err := sm.MakeGenesisState(genDoc)
  89. require.NoError(t, err)
  90. require.NoError(t, stateStore.Save(state))
  91. blockExec := sm.NewBlockExecutor(
  92. stateStore,
  93. log.TestingLogger(),
  94. rts.app[nodeID].Consensus(),
  95. mock.Mempool{},
  96. sm.EmptyEvidencePool{},
  97. blockStore,
  98. )
  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 := sf.MakeBlock(state, blockHeight, 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. 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. }