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.

411 lines
10 KiB

  1. package mempool
  2. import (
  3. "context"
  4. "os"
  5. "runtime"
  6. "strings"
  7. "sync"
  8. "testing"
  9. "time"
  10. "github.com/fortytw2/leaktest"
  11. "github.com/stretchr/testify/require"
  12. "github.com/tendermint/tendermint/abci/example/kvstore"
  13. abci "github.com/tendermint/tendermint/abci/types"
  14. "github.com/tendermint/tendermint/config"
  15. tmsync "github.com/tendermint/tendermint/internal/libs/sync"
  16. "github.com/tendermint/tendermint/internal/p2p"
  17. "github.com/tendermint/tendermint/internal/p2p/p2ptest"
  18. "github.com/tendermint/tendermint/libs/log"
  19. tmrand "github.com/tendermint/tendermint/libs/rand"
  20. protomem "github.com/tendermint/tendermint/proto/tendermint/mempool"
  21. "github.com/tendermint/tendermint/types"
  22. )
  23. type reactorTestSuite struct {
  24. network *p2ptest.Network
  25. logger log.Logger
  26. reactors map[types.NodeID]*Reactor
  27. mempoolChannels map[types.NodeID]*p2p.Channel
  28. mempools map[types.NodeID]*TxMempool
  29. kvstores map[types.NodeID]*kvstore.Application
  30. peerChans map[types.NodeID]chan p2p.PeerUpdate
  31. peerUpdates map[types.NodeID]*p2p.PeerUpdates
  32. nodes []types.NodeID
  33. }
  34. func setupReactors(ctx context.Context, t *testing.T, numNodes int, chBuf uint) *reactorTestSuite {
  35. t.Helper()
  36. cfg, err := config.ResetTestRoot(strings.ReplaceAll(t.Name(), "/", "|"))
  37. require.NoError(t, err)
  38. t.Cleanup(func() { os.RemoveAll(cfg.RootDir) })
  39. rts := &reactorTestSuite{
  40. logger: log.NewNopLogger().With("testCase", t.Name()),
  41. network: p2ptest.MakeNetwork(ctx, t, p2ptest.NetworkOptions{NumNodes: numNodes}),
  42. reactors: make(map[types.NodeID]*Reactor, numNodes),
  43. mempoolChannels: make(map[types.NodeID]*p2p.Channel, numNodes),
  44. mempools: make(map[types.NodeID]*TxMempool, numNodes),
  45. kvstores: make(map[types.NodeID]*kvstore.Application, numNodes),
  46. peerChans: make(map[types.NodeID]chan p2p.PeerUpdate, numNodes),
  47. peerUpdates: make(map[types.NodeID]*p2p.PeerUpdates, numNodes),
  48. }
  49. chDesc := getChannelDescriptor(cfg.Mempool)
  50. rts.mempoolChannels = rts.network.MakeChannelsNoCleanup(ctx, t, chDesc)
  51. for nodeID := range rts.network.Nodes {
  52. rts.kvstores[nodeID] = kvstore.NewApplication()
  53. mempool := setup(ctx, t, 0)
  54. rts.mempools[nodeID] = mempool
  55. rts.peerChans[nodeID] = make(chan p2p.PeerUpdate, chBuf)
  56. rts.peerUpdates[nodeID] = p2p.NewPeerUpdates(rts.peerChans[nodeID], 1)
  57. rts.network.Nodes[nodeID].PeerManager.Register(ctx, rts.peerUpdates[nodeID])
  58. chCreator := func(ctx context.Context, chDesc *p2p.ChannelDescriptor) (*p2p.Channel, error) {
  59. return rts.mempoolChannels[nodeID], nil
  60. }
  61. rts.reactors[nodeID], err = NewReactor(
  62. ctx,
  63. rts.logger.With("nodeID", nodeID),
  64. cfg.Mempool,
  65. rts.network.Nodes[nodeID].PeerManager,
  66. mempool,
  67. chCreator,
  68. rts.peerUpdates[nodeID],
  69. )
  70. require.NoError(t, err)
  71. rts.nodes = append(rts.nodes, nodeID)
  72. require.NoError(t, rts.reactors[nodeID].Start(ctx))
  73. require.True(t, rts.reactors[nodeID].IsRunning())
  74. }
  75. require.Len(t, rts.reactors, numNodes)
  76. t.Cleanup(func() {
  77. for nodeID := range rts.reactors {
  78. if rts.reactors[nodeID].IsRunning() {
  79. require.NoError(t, rts.reactors[nodeID].Stop())
  80. rts.reactors[nodeID].Wait()
  81. require.False(t, rts.reactors[nodeID].IsRunning())
  82. }
  83. }
  84. })
  85. t.Cleanup(leaktest.Check(t))
  86. return rts
  87. }
  88. func (rts *reactorTestSuite) start(ctx context.Context, t *testing.T) {
  89. t.Helper()
  90. rts.network.Start(ctx, t)
  91. require.Len(t,
  92. rts.network.RandomNode().PeerManager.Peers(),
  93. len(rts.nodes)-1,
  94. "network does not have expected number of nodes")
  95. }
  96. func (rts *reactorTestSuite) waitForTxns(t *testing.T, txs []types.Tx, ids ...types.NodeID) {
  97. t.Helper()
  98. // ensure that the transactions get fully broadcast to the
  99. // rest of the network
  100. wg := &sync.WaitGroup{}
  101. for name, pool := range rts.mempools {
  102. if !p2ptest.NodeInSlice(name, ids) {
  103. continue
  104. }
  105. if len(txs) == pool.Size() {
  106. continue
  107. }
  108. wg.Add(1)
  109. go func(pool *TxMempool) {
  110. defer wg.Done()
  111. require.Eventually(t, func() bool { return len(txs) == pool.Size() },
  112. time.Minute,
  113. 250*time.Millisecond,
  114. "ntx=%d, size=%d", len(txs), pool.Size(),
  115. )
  116. }(pool)
  117. }
  118. wg.Wait()
  119. }
  120. func TestReactorBroadcastDoesNotPanic(t *testing.T) {
  121. ctx, cancel := context.WithCancel(context.Background())
  122. defer cancel()
  123. const numNodes = 2
  124. rts := setupReactors(ctx, t, numNodes, 0)
  125. observePanic := func(r interface{}) {
  126. t.Fatal("panic detected in reactor")
  127. }
  128. primary := rts.nodes[0]
  129. secondary := rts.nodes[1]
  130. primaryReactor := rts.reactors[primary]
  131. primaryMempool := primaryReactor.mempool
  132. secondaryReactor := rts.reactors[secondary]
  133. primaryReactor.observePanic = observePanic
  134. secondaryReactor.observePanic = observePanic
  135. firstTx := &WrappedTx{}
  136. primaryMempool.insertTx(firstTx)
  137. // run the router
  138. rts.start(ctx, t)
  139. closer := tmsync.NewCloser()
  140. primaryReactor.peerWG.Add(1)
  141. go primaryReactor.broadcastTxRoutine(ctx, secondary, closer)
  142. wg := &sync.WaitGroup{}
  143. for i := 0; i < 50; i++ {
  144. next := &WrappedTx{}
  145. wg.Add(1)
  146. go func() {
  147. defer wg.Done()
  148. primaryMempool.insertTx(next)
  149. }()
  150. }
  151. err := primaryReactor.Stop()
  152. require.NoError(t, err)
  153. primaryReactor.peerWG.Wait()
  154. wg.Wait()
  155. }
  156. func TestReactorBroadcastTxs(t *testing.T) {
  157. numTxs := 1000
  158. numNodes := 10
  159. ctx, cancel := context.WithCancel(context.Background())
  160. defer cancel()
  161. rts := setupReactors(ctx, t, numNodes, uint(numTxs))
  162. primary := rts.nodes[0]
  163. secondaries := rts.nodes[1:]
  164. txs := checkTxs(ctx, t, rts.reactors[primary].mempool, numTxs, UnknownPeerID)
  165. require.Equal(t, numTxs, rts.reactors[primary].mempool.Size())
  166. rts.start(ctx, t)
  167. // Wait till all secondary suites (reactor) received all mempool txs from the
  168. // primary suite (node).
  169. rts.waitForTxns(t, convertTex(txs), secondaries...)
  170. }
  171. // regression test for https://github.com/tendermint/tendermint/issues/5408
  172. func TestReactorConcurrency(t *testing.T) {
  173. numTxs := 10
  174. numNodes := 2
  175. ctx, cancel := context.WithCancel(context.Background())
  176. defer cancel()
  177. rts := setupReactors(ctx, t, numNodes, 0)
  178. primary := rts.nodes[0]
  179. secondary := rts.nodes[1]
  180. rts.start(ctx, t)
  181. var wg sync.WaitGroup
  182. for i := 0; i < runtime.NumCPU()*2; i++ {
  183. wg.Add(2)
  184. // 1. submit a bunch of txs
  185. // 2. update the whole mempool
  186. txs := checkTxs(ctx, t, rts.reactors[primary].mempool, numTxs, UnknownPeerID)
  187. go func() {
  188. defer wg.Done()
  189. mempool := rts.mempools[primary]
  190. mempool.Lock()
  191. defer mempool.Unlock()
  192. deliverTxResponses := make([]*abci.ResponseDeliverTx, len(txs))
  193. for i := range txs {
  194. deliverTxResponses[i] = &abci.ResponseDeliverTx{Code: 0}
  195. }
  196. require.NoError(t, mempool.Update(ctx, 1, convertTex(txs), deliverTxResponses, nil, nil))
  197. }()
  198. // 1. submit a bunch of txs
  199. // 2. update none
  200. _ = checkTxs(ctx, t, rts.reactors[secondary].mempool, numTxs, UnknownPeerID)
  201. go func() {
  202. defer wg.Done()
  203. mempool := rts.mempools[secondary]
  204. mempool.Lock()
  205. defer mempool.Unlock()
  206. err := mempool.Update(ctx, 1, []types.Tx{}, make([]*abci.ResponseDeliverTx, 0), nil, nil)
  207. require.NoError(t, err)
  208. }()
  209. }
  210. wg.Wait()
  211. }
  212. func TestReactorNoBroadcastToSender(t *testing.T) {
  213. numTxs := 1000
  214. numNodes := 2
  215. ctx, cancel := context.WithCancel(context.Background())
  216. defer cancel()
  217. rts := setupReactors(ctx, t, numNodes, uint(numTxs))
  218. primary := rts.nodes[0]
  219. secondary := rts.nodes[1]
  220. peerID := uint16(1)
  221. _ = checkTxs(ctx, t, rts.mempools[primary], numTxs, peerID)
  222. rts.start(ctx, t)
  223. time.Sleep(100 * time.Millisecond)
  224. require.Eventually(t, func() bool {
  225. return rts.mempools[secondary].Size() == 0
  226. }, time.Minute, 100*time.Millisecond)
  227. }
  228. func TestReactor_MaxTxBytes(t *testing.T) {
  229. numNodes := 2
  230. cfg := config.TestConfig()
  231. ctx, cancel := context.WithCancel(context.Background())
  232. defer cancel()
  233. rts := setupReactors(ctx, t, numNodes, 0)
  234. primary := rts.nodes[0]
  235. secondary := rts.nodes[1]
  236. // Broadcast a tx, which has the max size and ensure it's received by the
  237. // second reactor.
  238. tx1 := tmrand.Bytes(cfg.Mempool.MaxTxBytes)
  239. err := rts.reactors[primary].mempool.CheckTx(
  240. ctx,
  241. tx1,
  242. nil,
  243. TxInfo{
  244. SenderID: UnknownPeerID,
  245. },
  246. )
  247. require.NoError(t, err)
  248. rts.start(ctx, t)
  249. rts.reactors[primary].mempool.Flush()
  250. rts.reactors[secondary].mempool.Flush()
  251. // broadcast a tx, which is beyond the max size and ensure it's not sent
  252. tx2 := tmrand.Bytes(cfg.Mempool.MaxTxBytes + 1)
  253. err = rts.mempools[primary].CheckTx(ctx, tx2, nil, TxInfo{SenderID: UnknownPeerID})
  254. require.Error(t, err)
  255. }
  256. func TestDontExhaustMaxActiveIDs(t *testing.T) {
  257. // we're creating a single node network, but not starting the
  258. // network.
  259. ctx, cancel := context.WithCancel(context.Background())
  260. defer cancel()
  261. rts := setupReactors(ctx, t, 1, MaxActiveIDs+1)
  262. nodeID := rts.nodes[0]
  263. peerID, err := types.NewNodeID("0011223344556677889900112233445566778899")
  264. require.NoError(t, err)
  265. // ensure the reactor does not panic (i.e. exhaust active IDs)
  266. for i := 0; i < MaxActiveIDs+1; i++ {
  267. rts.peerChans[nodeID] <- p2p.PeerUpdate{
  268. Status: p2p.PeerStatusUp,
  269. NodeID: peerID,
  270. }
  271. require.NoError(t, rts.mempoolChannels[nodeID].Send(ctx, p2p.Envelope{
  272. To: peerID,
  273. Message: &protomem.Txs{
  274. Txs: [][]byte{},
  275. },
  276. }))
  277. }
  278. }
  279. func TestMempoolIDsPanicsIfNodeRequestsOvermaxActiveIDs(t *testing.T) {
  280. if testing.Short() {
  281. t.Skip("skipping test in short mode")
  282. }
  283. // 0 is already reserved for UnknownPeerID
  284. ids := NewMempoolIDs()
  285. peerID, err := types.NewNodeID("0011223344556677889900112233445566778899")
  286. require.NoError(t, err)
  287. for i := 0; i < MaxActiveIDs-1; i++ {
  288. ids.ReserveForPeer(peerID)
  289. }
  290. require.Panics(t, func() {
  291. ids.ReserveForPeer(peerID)
  292. })
  293. }
  294. func TestBroadcastTxForPeerStopsWhenPeerStops(t *testing.T) {
  295. if testing.Short() {
  296. t.Skip("skipping test in short mode")
  297. }
  298. ctx, cancel := context.WithCancel(context.Background())
  299. defer cancel()
  300. rts := setupReactors(ctx, t, 2, 2)
  301. primary := rts.nodes[0]
  302. secondary := rts.nodes[1]
  303. rts.start(ctx, t)
  304. // disconnect peer
  305. rts.peerChans[primary] <- p2p.PeerUpdate{
  306. Status: p2p.PeerStatusDown,
  307. NodeID: secondary,
  308. }
  309. time.Sleep(500 * time.Millisecond)
  310. txs := checkTxs(ctx, t, rts.reactors[primary].mempool, 4, UnknownPeerID)
  311. require.Equal(t, 4, len(txs))
  312. require.Equal(t, 4, rts.mempools[primary].Size())
  313. require.Equal(t, 0, rts.mempools[secondary].Size())
  314. }