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.

413 lines
10 KiB

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