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. "strings"
  6. "sync"
  7. "testing"
  8. "time"
  9. "github.com/fortytw2/leaktest"
  10. "github.com/stretchr/testify/require"
  11. "github.com/tendermint/tendermint/abci/example/kvstore"
  12. abci "github.com/tendermint/tendermint/abci/types"
  13. "github.com/tendermint/tendermint/config"
  14. tmsync "github.com/tendermint/tendermint/internal/libs/sync"
  15. "github.com/tendermint/tendermint/internal/p2p"
  16. "github.com/tendermint/tendermint/internal/p2p/p2ptest"
  17. "github.com/tendermint/tendermint/libs/log"
  18. tmrand "github.com/tendermint/tendermint/libs/rand"
  19. protomem "github.com/tendermint/tendermint/proto/tendermint/mempool"
  20. "github.com/tendermint/tendermint/types"
  21. )
  22. type reactorTestSuite struct {
  23. network *p2ptest.Network
  24. logger log.Logger
  25. reactors map[types.NodeID]*Reactor
  26. mempoolChannels map[types.NodeID]*p2p.Channel
  27. mempools map[types.NodeID]*TxMempool
  28. kvstores map[types.NodeID]*kvstore.Application
  29. peerChans map[types.NodeID]chan p2p.PeerUpdate
  30. peerUpdates map[types.NodeID]*p2p.PeerUpdates
  31. nodes []types.NodeID
  32. }
  33. func setupReactors(ctx context.Context, t *testing.T, numNodes int, chBuf uint) *reactorTestSuite {
  34. t.Helper()
  35. cfg, err := config.ResetTestRoot(strings.ReplaceAll(t.Name(), "/", "|"))
  36. require.NoError(t, err)
  37. t.Cleanup(func() { os.RemoveAll(cfg.RootDir) })
  38. rts := &reactorTestSuite{
  39. logger: log.TestingLogger().With("testCase", t.Name()),
  40. network: p2ptest.MakeNetwork(ctx, t, p2ptest.NetworkOptions{NumNodes: numNodes}),
  41. reactors: make(map[types.NodeID]*Reactor, numNodes),
  42. mempoolChannels: make(map[types.NodeID]*p2p.Channel, numNodes),
  43. mempools: make(map[types.NodeID]*TxMempool, numNodes),
  44. kvstores: make(map[types.NodeID]*kvstore.Application, numNodes),
  45. peerChans: make(map[types.NodeID]chan p2p.PeerUpdate, numNodes),
  46. peerUpdates: make(map[types.NodeID]*p2p.PeerUpdates, numNodes),
  47. }
  48. chDesc := getChannelDescriptor(cfg.Mempool)
  49. rts.mempoolChannels = rts.network.MakeChannelsNoCleanup(ctx, t, chDesc)
  50. for nodeID := range rts.network.Nodes {
  51. rts.kvstores[nodeID] = kvstore.NewApplication()
  52. mempool := setup(ctx, t, 0)
  53. rts.mempools[nodeID] = mempool
  54. rts.peerChans[nodeID] = make(chan p2p.PeerUpdate, chBuf)
  55. rts.peerUpdates[nodeID] = p2p.NewPeerUpdates(rts.peerChans[nodeID], 1)
  56. rts.network.Nodes[nodeID].PeerManager.Register(ctx, rts.peerUpdates[nodeID])
  57. chCreator := func(ctx context.Context, chDesc *p2p.ChannelDescriptor) (*p2p.Channel, error) {
  58. return rts.mempoolChannels[nodeID], nil
  59. }
  60. rts.reactors[nodeID], err = NewReactor(
  61. ctx,
  62. rts.logger.With("nodeID", nodeID),
  63. cfg.Mempool,
  64. rts.network.Nodes[nodeID].PeerManager,
  65. mempool,
  66. chCreator,
  67. rts.peerUpdates[nodeID],
  68. )
  69. require.NoError(t, err)
  70. rts.nodes = append(rts.nodes, nodeID)
  71. require.NoError(t, rts.reactors[nodeID].Start(ctx))
  72. require.True(t, rts.reactors[nodeID].IsRunning())
  73. }
  74. require.Len(t, rts.reactors, numNodes)
  75. t.Cleanup(func() {
  76. for nodeID := range rts.reactors {
  77. if rts.reactors[nodeID].IsRunning() {
  78. require.NoError(t, rts.reactors[nodeID].Stop())
  79. require.False(t, rts.reactors[nodeID].IsRunning())
  80. }
  81. }
  82. })
  83. t.Cleanup(leaktest.Check(t))
  84. return rts
  85. }
  86. func (rts *reactorTestSuite) start(ctx context.Context, t *testing.T) {
  87. t.Helper()
  88. rts.network.Start(ctx, t)
  89. require.Len(t,
  90. rts.network.RandomNode().PeerManager.Peers(),
  91. len(rts.nodes)-1,
  92. "network does not have expected number of nodes")
  93. }
  94. func (rts *reactorTestSuite) waitForTxns(t *testing.T, txs []types.Tx, ids ...types.NodeID) {
  95. t.Helper()
  96. // ensure that the transactions get fully broadcast to the
  97. // rest of the network
  98. wg := &sync.WaitGroup{}
  99. for name, pool := range rts.mempools {
  100. if !p2ptest.NodeInSlice(name, ids) {
  101. continue
  102. }
  103. if len(txs) == pool.Size() {
  104. continue
  105. }
  106. wg.Add(1)
  107. go func(pool *TxMempool) {
  108. defer wg.Done()
  109. require.Eventually(t, func() bool { return len(txs) == pool.Size() },
  110. time.Minute,
  111. 250*time.Millisecond,
  112. "ntx=%d, size=%d", len(txs), pool.Size(),
  113. )
  114. }(pool)
  115. }
  116. wg.Wait()
  117. }
  118. func TestReactorBroadcastDoesNotPanic(t *testing.T) {
  119. ctx, cancel := context.WithCancel(context.Background())
  120. defer cancel()
  121. const numNodes = 2
  122. rts := setupReactors(ctx, t, numNodes, 0)
  123. observePanic := func(r interface{}) {
  124. t.Fatal("panic detected in reactor")
  125. }
  126. primary := rts.nodes[0]
  127. secondary := rts.nodes[1]
  128. primaryReactor := rts.reactors[primary]
  129. primaryMempool := primaryReactor.mempool
  130. secondaryReactor := rts.reactors[secondary]
  131. primaryReactor.observePanic = observePanic
  132. secondaryReactor.observePanic = observePanic
  133. firstTx := &WrappedTx{}
  134. primaryMempool.insertTx(firstTx)
  135. // run the router
  136. rts.start(ctx, t)
  137. closer := tmsync.NewCloser()
  138. primaryReactor.peerWG.Add(1)
  139. go primaryReactor.broadcastTxRoutine(ctx, secondary, closer)
  140. wg := &sync.WaitGroup{}
  141. for i := 0; i < 50; i++ {
  142. next := &WrappedTx{}
  143. wg.Add(1)
  144. go func() {
  145. defer wg.Done()
  146. primaryMempool.insertTx(next)
  147. }()
  148. }
  149. err := primaryReactor.Stop()
  150. require.NoError(t, err)
  151. primaryReactor.peerWG.Wait()
  152. wg.Wait()
  153. }
  154. func TestReactorBroadcastTxs(t *testing.T) {
  155. numTxs := 1000
  156. numNodes := 10
  157. ctx, cancel := context.WithCancel(context.Background())
  158. defer cancel()
  159. rts := setupReactors(ctx, t, numNodes, uint(numTxs))
  160. primary := rts.nodes[0]
  161. secondaries := rts.nodes[1:]
  162. txs := checkTxs(ctx, t, rts.reactors[primary].mempool, numTxs, UnknownPeerID)
  163. require.Equal(t, numTxs, rts.reactors[primary].mempool.Size())
  164. rts.start(ctx, t)
  165. // Wait till all secondary suites (reactor) received all mempool txs from the
  166. // primary suite (node).
  167. rts.waitForTxns(t, convertTex(txs), secondaries...)
  168. }
  169. // regression test for https://github.com/tendermint/tendermint/issues/5408
  170. func TestReactorConcurrency(t *testing.T) {
  171. numTxs := 5
  172. numNodes := 2
  173. ctx, cancel := context.WithCancel(context.Background())
  174. defer cancel()
  175. rts := setupReactors(ctx, t, numNodes, 0)
  176. primary := rts.nodes[0]
  177. secondary := rts.nodes[1]
  178. rts.start(ctx, t)
  179. var wg sync.WaitGroup
  180. for i := 0; i < 1000; i++ {
  181. wg.Add(2)
  182. // 1. submit a bunch of txs
  183. // 2. update the whole mempool
  184. txs := checkTxs(ctx, t, rts.reactors[primary].mempool, numTxs, UnknownPeerID)
  185. go func() {
  186. defer wg.Done()
  187. mempool := rts.mempools[primary]
  188. mempool.Lock()
  189. defer mempool.Unlock()
  190. deliverTxResponses := make([]*abci.ResponseDeliverTx, len(txs))
  191. for i := range txs {
  192. deliverTxResponses[i] = &abci.ResponseDeliverTx{Code: 0}
  193. }
  194. require.NoError(t, mempool.Update(ctx, 1, convertTex(txs), deliverTxResponses, nil, nil))
  195. }()
  196. // 1. submit a bunch of txs
  197. // 2. update none
  198. _ = checkTxs(ctx, t, rts.reactors[secondary].mempool, numTxs, UnknownPeerID)
  199. go func() {
  200. defer wg.Done()
  201. mempool := rts.mempools[secondary]
  202. mempool.Lock()
  203. defer mempool.Unlock()
  204. err := mempool.Update(ctx, 1, []types.Tx{}, make([]*abci.ResponseDeliverTx, 0), nil, nil)
  205. require.NoError(t, err)
  206. }()
  207. // flush the mempool
  208. rts.mempools[secondary].Flush()
  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. }