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.

416 lines
9.8 KiB

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