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.

620 lines
18 KiB

mempool no gossip back (#2778) Closes #1798 This is done by making every mempool tx maintain a list of peers who its received the tx from. Instead of using the 20byte peer ID, it instead uses a local map from peerID to uint16 counter, so every peer adds 2 bytes. (Word aligned to probably make it 8 bytes) This also required resetting the callback function on every CheckTx. This likely has performance ramifications for instruction caching. The actual setting operation isn't costly with the removal of defers in this PR. * Make the mempool not gossip txs back to peers its received it from * Fix adversarial memleak * Don't break interface * Update changelog * Forgot to add a mtx * forgot a mutex * Update mempool/reactor.go Co-Authored-By: ValarDragon <ValarDragon@users.noreply.github.com> * Update mempool/mempool.go Co-Authored-By: ValarDragon <ValarDragon@users.noreply.github.com> * Use unknown peer ID Co-Authored-By: ValarDragon <ValarDragon@users.noreply.github.com> * fix compilation * use next wait chan logic when skipping * Minor fixes * Add TxInfo * Add reverse map * Make activeID's auto-reserve 0 * 0 -> UnknownPeerID Co-Authored-By: ValarDragon <ValarDragon@users.noreply.github.com> * Switch to making the normal case set a callback on the reqres object The recheck case is still done via the global callback, and stats are also set via global callback * fix merge conflict * Addres comments * Add cache tests * add cache tests * minor fixes * update metrics in reqResCb and reformat code * goimport -w mempool/reactor.go * mempool: update memTx senders I had to introduce txsMap for quick mempoolTx lookups. * change senders type from []uint16 to sync.Map Fixes DATA RACE: ``` Read at 0x00c0013fcd3a by goroutine 183: github.com/tendermint/tendermint/mempool.(*MempoolReactor).broadcastTxRoutine() /go/src/github.com/tendermint/tendermint/mempool/reactor.go:195 +0x3c7 Previous write at 0x00c0013fcd3a by D[2019-02-27|10:10:49.058] Read PacketMsg switch=3 peer=35bc1e3558c182927b31987eeff3feb3d58a0fc5@127.0.0.1 :46552 conn=MConn{pipe} packet="PacketMsg{30:2B06579D0A143EB78F3D3299DE8213A51D4E11FB05ACE4D6A14F T:1}" goroutine 190: github.com/tendermint/tendermint/mempool.(*Mempool).CheckTxWithInfo() /go/src/github.com/tendermint/tendermint/mempool/mempool.go:387 +0xdc1 github.com/tendermint/tendermint/mempool.(*MempoolReactor).Receive() /go/src/github.com/tendermint/tendermint/mempool/reactor.go:134 +0xb04 github.com/tendermint/tendermint/p2p.createMConnection.func1() /go/src/github.com/tendermint/tendermint/p2p/peer.go:374 +0x25b github.com/tendermint/tendermint/p2p/conn.(*MConnection).recvRoutine() /go/src/github.com/tendermint/tendermint/p2p/conn/connection.go:599 +0xcce Goroutine 183 (running) created at: D[2019-02-27|10:10:49.058] Send switch=2 peer=1efafad5443abeea4b7a8155218e4369525d987e@127.0.0.1:46193 channel=48 conn=MConn{pipe} m sgBytes=2B06579D0A146194480ADAE00C2836ED7125FEE65C1D9DD51049 github.com/tendermint/tendermint/mempool.(*MempoolReactor).AddPeer() /go/src/github.com/tendermint/tendermint/mempool/reactor.go:105 +0x1b1 github.com/tendermint/tendermint/p2p.(*Switch).startInitPeer() /go/src/github.com/tendermint/tendermint/p2p/switch.go:683 +0x13b github.com/tendermint/tendermint/p2p.(*Switch).addPeer() /go/src/github.com/tendermint/tendermint/p2p/switch.go:650 +0x585 github.com/tendermint/tendermint/p2p.(*Switch).addPeerWithConnection() /go/src/github.com/tendermint/tendermint/p2p/test_util.go:145 +0x939 github.com/tendermint/tendermint/p2p.Connect2Switches.func2() /go/src/github.com/tendermint/tendermint/p2p/test_util.go:109 +0x50 I[2019-02-27|10:10:49.058] Added good transaction validator=0 tx=43B4D1F0F03460BD262835C4AA560DB860CFBBE85BD02386D83DAC38C67B3AD7 res="&{CheckTx:gas_w anted:1 }" height=0 total=375 Goroutine 190 (running) created at: github.com/tendermint/tendermint/p2p/conn.(*MConnection).OnStart() /go/src/github.com/tendermint/tendermint/p2p/conn/connection.go:210 +0x313 github.com/tendermint/tendermint/libs/common.(*BaseService).Start() /go/src/github.com/tendermint/tendermint/libs/common/service.go:139 +0x4df github.com/tendermint/tendermint/p2p.(*peer).OnStart() /go/src/github.com/tendermint/tendermint/p2p/peer.go:179 +0x56 github.com/tendermint/tendermint/libs/common.(*BaseService).Start() /go/src/github.com/tendermint/tendermint/libs/common/service.go:139 +0x4df github.com/tendermint/tendermint/p2p.(*peer).Start() <autogenerated>:1 +0x43 github.com/tendermint/tendermint/p2p.(*Switch).startInitPeer() ``` * explain the choice of a map DS for senders * extract ids pool/mapper to a separate struct * fix literal copies lock value from senders: sync.Map contains sync.Mutex * use sync.Map#LoadOrStore instead of Load * fixes after Ismail's review * rename resCbNormal to resCbFirstTime
6 years ago
mempool: move interface into mempool package (#3524) ## Description Refs #2659 Breaking changes in the mempool package: [mempool] #2659 Mempool now an interface old Mempool renamed to CListMempool NewMempool renamed to NewCListMempool Option renamed to CListOption MempoolReactor renamed to Reactor NewMempoolReactor renamed to NewReactor unexpose TxID method TxInfo.PeerID renamed to SenderID unexpose MempoolReactor.Mempool Breaking changes in the state package: [state] #2659 Mempool interface moved to mempool package MockMempool moved to top-level mock package and renamed to Mempool Non Breaking changes in the node package: [node] #2659 Add Mempool method, which allows you to access mempool ## Commits * move Mempool interface into mempool package Refs #2659 Breaking changes in the mempool package: - Mempool now an interface - old Mempool renamed to CListMempool Breaking changes to state package: - MockMempool moved to mempool/mock package and renamed to Mempool - Mempool interface moved to mempool package * assert CListMempool impl Mempool * gofmt code * rename MempoolReactor to Reactor - combine everything into one interface - rename TxInfo.PeerID to TxInfo.SenderID - unexpose MempoolReactor.Mempool * move mempool mock into top-level mock package * add a fixme TxsFront should not be a part of the Mempool interface because it leaks implementation details. Instead, we need to come up with general interface for querying the mempool so the MempoolReactor can fetch and broadcast txs to peers. * change node#Mempool to return interface * save commit = new reactor arch * Revert "save commit = new reactor arch" This reverts commit 1bfceacd9d65a720574683a7f22771e69af9af4d. * require CListMempool in mempool.Reactor * add two changelog entries * fixes after my own review * quote interfaces, structs and functions * fixes after Ismail's review * make node's mempool an interface * make InitWAL/CloseWAL methods a part of Mempool interface * fix merge conflicts * make node's mempool an interface
6 years ago
mempool: move interface into mempool package (#3524) ## Description Refs #2659 Breaking changes in the mempool package: [mempool] #2659 Mempool now an interface old Mempool renamed to CListMempool NewMempool renamed to NewCListMempool Option renamed to CListOption MempoolReactor renamed to Reactor NewMempoolReactor renamed to NewReactor unexpose TxID method TxInfo.PeerID renamed to SenderID unexpose MempoolReactor.Mempool Breaking changes in the state package: [state] #2659 Mempool interface moved to mempool package MockMempool moved to top-level mock package and renamed to Mempool Non Breaking changes in the node package: [node] #2659 Add Mempool method, which allows you to access mempool ## Commits * move Mempool interface into mempool package Refs #2659 Breaking changes in the mempool package: - Mempool now an interface - old Mempool renamed to CListMempool Breaking changes to state package: - MockMempool moved to mempool/mock package and renamed to Mempool - Mempool interface moved to mempool package * assert CListMempool impl Mempool * gofmt code * rename MempoolReactor to Reactor - combine everything into one interface - rename TxInfo.PeerID to TxInfo.SenderID - unexpose MempoolReactor.Mempool * move mempool mock into top-level mock package * add a fixme TxsFront should not be a part of the Mempool interface because it leaks implementation details. Instead, we need to come up with general interface for querying the mempool so the MempoolReactor can fetch and broadcast txs to peers. * change node#Mempool to return interface * save commit = new reactor arch * Revert "save commit = new reactor arch" This reverts commit 1bfceacd9d65a720574683a7f22771e69af9af4d. * require CListMempool in mempool.Reactor * add two changelog entries * fixes after my own review * quote interfaces, structs and functions * fixes after Ismail's review * make node's mempool an interface * make InitWAL/CloseWAL methods a part of Mempool interface * fix merge conflicts * make node's mempool an interface
6 years ago
8 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
8 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
  1. package v0
  2. import (
  3. "context"
  4. "crypto/rand"
  5. "encoding/binary"
  6. "fmt"
  7. mrand "math/rand"
  8. "os"
  9. "testing"
  10. "time"
  11. "github.com/gogo/protobuf/proto"
  12. gogotypes "github.com/gogo/protobuf/types"
  13. "github.com/stretchr/testify/assert"
  14. "github.com/stretchr/testify/require"
  15. "github.com/tendermint/tendermint/abci/example/kvstore"
  16. abciserver "github.com/tendermint/tendermint/abci/server"
  17. abci "github.com/tendermint/tendermint/abci/types"
  18. cfg "github.com/tendermint/tendermint/config"
  19. "github.com/tendermint/tendermint/internal/mempool"
  20. "github.com/tendermint/tendermint/libs/log"
  21. tmrand "github.com/tendermint/tendermint/libs/rand"
  22. "github.com/tendermint/tendermint/libs/service"
  23. "github.com/tendermint/tendermint/proxy"
  24. "github.com/tendermint/tendermint/types"
  25. )
  26. // A cleanupFunc cleans up any config / test files created for a particular
  27. // test.
  28. type cleanupFunc func()
  29. func newMempoolWithApp(cc proxy.ClientCreator) (*CListMempool, cleanupFunc) {
  30. return newMempoolWithAppAndConfig(cc, cfg.ResetTestRoot("mempool_test"))
  31. }
  32. func newMempoolWithAppAndConfig(cc proxy.ClientCreator, config *cfg.Config) (*CListMempool, cleanupFunc) {
  33. appConnMem, _ := cc.NewABCIClient()
  34. appConnMem.SetLogger(log.TestingLogger().With("module", "abci-client", "connection", "mempool"))
  35. err := appConnMem.Start()
  36. if err != nil {
  37. panic(err)
  38. }
  39. mp := NewCListMempool(config.Mempool, appConnMem, 0)
  40. mp.SetLogger(log.TestingLogger())
  41. return mp, func() { os.RemoveAll(config.RootDir) }
  42. }
  43. func ensureNoFire(t *testing.T, ch <-chan struct{}, timeoutMS int) {
  44. timer := time.NewTimer(time.Duration(timeoutMS) * time.Millisecond)
  45. select {
  46. case <-ch:
  47. t.Fatal("Expected not to fire")
  48. case <-timer.C:
  49. }
  50. }
  51. func ensureFire(t *testing.T, ch <-chan struct{}, timeoutMS int) {
  52. timer := time.NewTimer(time.Duration(timeoutMS) * time.Millisecond)
  53. select {
  54. case <-ch:
  55. case <-timer.C:
  56. t.Fatal("Expected to fire")
  57. }
  58. }
  59. func checkTxs(t *testing.T, mp mempool.Mempool, count int, peerID uint16) types.Txs {
  60. txs := make(types.Txs, count)
  61. txInfo := mempool.TxInfo{SenderID: peerID}
  62. for i := 0; i < count; i++ {
  63. txBytes := make([]byte, 20)
  64. txs[i] = txBytes
  65. _, err := rand.Read(txBytes)
  66. if err != nil {
  67. t.Error(err)
  68. }
  69. if err := mp.CheckTx(context.Background(), txBytes, nil, txInfo); err != nil {
  70. // Skip invalid txs.
  71. // TestMempoolFilters will fail otherwise. It asserts a number of txs
  72. // returned.
  73. if types.IsPreCheckError(err) {
  74. continue
  75. }
  76. t.Fatalf("CheckTx failed: %v while checking #%d tx", err, i)
  77. }
  78. }
  79. return txs
  80. }
  81. func TestReapMaxBytesMaxGas(t *testing.T) {
  82. app := kvstore.NewApplication()
  83. cc := proxy.NewLocalClientCreator(app)
  84. mp, cleanup := newMempoolWithApp(cc)
  85. defer cleanup()
  86. // Ensure gas calculation behaves as expected
  87. checkTxs(t, mp, 1, mempool.UnknownPeerID)
  88. tx0 := mp.TxsFront().Value.(*mempoolTx)
  89. // assert that kv store has gas wanted = 1.
  90. require.Equal(t, app.CheckTx(abci.RequestCheckTx{Tx: tx0.tx}).GasWanted, int64(1), "KVStore had a gas value neq to 1")
  91. require.Equal(t, tx0.gasWanted, int64(1), "transactions gas was set incorrectly")
  92. // ensure each tx is 20 bytes long
  93. require.Equal(t, len(tx0.tx), 20, "Tx is longer than 20 bytes")
  94. mp.Flush()
  95. // each table driven test creates numTxsToCreate txs with checkTx, and at the end clears all remaining txs.
  96. // each tx has 20 bytes
  97. tests := []struct {
  98. numTxsToCreate int
  99. maxBytes int64
  100. maxGas int64
  101. expectedNumTxs int
  102. }{
  103. {20, -1, -1, 20},
  104. {20, -1, 0, 0},
  105. {20, -1, 10, 10},
  106. {20, -1, 30, 20},
  107. {20, 0, -1, 0},
  108. {20, 0, 10, 0},
  109. {20, 10, 10, 0},
  110. {20, 24, 10, 1},
  111. {20, 240, 5, 5},
  112. {20, 240, -1, 10},
  113. {20, 240, 10, 10},
  114. {20, 240, 15, 10},
  115. {20, 20000, -1, 20},
  116. {20, 20000, 5, 5},
  117. {20, 20000, 30, 20},
  118. }
  119. for tcIndex, tt := range tests {
  120. checkTxs(t, mp, tt.numTxsToCreate, mempool.UnknownPeerID)
  121. got := mp.ReapMaxBytesMaxGas(tt.maxBytes, tt.maxGas)
  122. assert.Equal(t, tt.expectedNumTxs, len(got), "Got %d txs, expected %d, tc #%d",
  123. len(got), tt.expectedNumTxs, tcIndex)
  124. mp.Flush()
  125. }
  126. }
  127. func TestMempoolFilters(t *testing.T) {
  128. app := kvstore.NewApplication()
  129. cc := proxy.NewLocalClientCreator(app)
  130. mp, cleanup := newMempoolWithApp(cc)
  131. defer cleanup()
  132. emptyTxArr := []types.Tx{[]byte{}}
  133. nopPreFilter := func(tx types.Tx) error { return nil }
  134. nopPostFilter := func(tx types.Tx, res *abci.ResponseCheckTx) error { return nil }
  135. // each table driven test creates numTxsToCreate txs with checkTx, and at the end clears all remaining txs.
  136. // each tx has 20 bytes
  137. tests := []struct {
  138. numTxsToCreate int
  139. preFilter mempool.PreCheckFunc
  140. postFilter mempool.PostCheckFunc
  141. expectedNumTxs int
  142. }{
  143. {10, nopPreFilter, nopPostFilter, 10},
  144. {10, mempool.PreCheckMaxBytes(10), nopPostFilter, 0},
  145. {10, mempool.PreCheckMaxBytes(22), nopPostFilter, 10},
  146. {10, nopPreFilter, mempool.PostCheckMaxGas(-1), 10},
  147. {10, nopPreFilter, mempool.PostCheckMaxGas(0), 0},
  148. {10, nopPreFilter, mempool.PostCheckMaxGas(1), 10},
  149. {10, nopPreFilter, mempool.PostCheckMaxGas(3000), 10},
  150. {10, mempool.PreCheckMaxBytes(10), mempool.PostCheckMaxGas(20), 0},
  151. {10, mempool.PreCheckMaxBytes(30), mempool.PostCheckMaxGas(20), 10},
  152. {10, mempool.PreCheckMaxBytes(22), mempool.PostCheckMaxGas(1), 10},
  153. {10, mempool.PreCheckMaxBytes(22), mempool.PostCheckMaxGas(0), 0},
  154. }
  155. for tcIndex, tt := range tests {
  156. err := mp.Update(1, emptyTxArr, abciResponses(len(emptyTxArr), abci.CodeTypeOK), tt.preFilter, tt.postFilter)
  157. require.NoError(t, err)
  158. checkTxs(t, mp, tt.numTxsToCreate, mempool.UnknownPeerID)
  159. require.Equal(t, tt.expectedNumTxs, mp.Size(), "mempool had the incorrect size, on test case %d", tcIndex)
  160. mp.Flush()
  161. }
  162. }
  163. func TestMempoolUpdate(t *testing.T) {
  164. app := kvstore.NewApplication()
  165. cc := proxy.NewLocalClientCreator(app)
  166. mp, cleanup := newMempoolWithApp(cc)
  167. defer cleanup()
  168. // 1. Adds valid txs to the cache
  169. {
  170. err := mp.Update(1, []types.Tx{[]byte{0x01}}, abciResponses(1, abci.CodeTypeOK), nil, nil)
  171. require.NoError(t, err)
  172. err = mp.CheckTx(context.Background(), []byte{0x01}, nil, mempool.TxInfo{})
  173. require.NoError(t, err)
  174. }
  175. // 2. Removes valid txs from the mempool
  176. {
  177. err := mp.CheckTx(context.Background(), []byte{0x02}, nil, mempool.TxInfo{})
  178. require.NoError(t, err)
  179. err = mp.Update(1, []types.Tx{[]byte{0x02}}, abciResponses(1, abci.CodeTypeOK), nil, nil)
  180. require.NoError(t, err)
  181. assert.Zero(t, mp.Size())
  182. }
  183. // 3. Removes invalid transactions from the cache and the mempool (if present)
  184. {
  185. err := mp.CheckTx(context.Background(), []byte{0x03}, nil, mempool.TxInfo{})
  186. require.NoError(t, err)
  187. err = mp.Update(1, []types.Tx{[]byte{0x03}}, abciResponses(1, 1), nil, nil)
  188. require.NoError(t, err)
  189. assert.Zero(t, mp.Size())
  190. err = mp.CheckTx(context.Background(), []byte{0x03}, nil, mempool.TxInfo{})
  191. require.NoError(t, err)
  192. }
  193. }
  194. func TestMempool_KeepInvalidTxsInCache(t *testing.T) {
  195. app := kvstore.NewApplication()
  196. cc := proxy.NewLocalClientCreator(app)
  197. wcfg := cfg.DefaultConfig()
  198. wcfg.Mempool.KeepInvalidTxsInCache = true
  199. mp, cleanup := newMempoolWithAppAndConfig(cc, wcfg)
  200. defer cleanup()
  201. // 1. An invalid transaction must remain in the cache after Update
  202. {
  203. a := make([]byte, 8)
  204. binary.BigEndian.PutUint64(a, 0)
  205. b := make([]byte, 8)
  206. binary.BigEndian.PutUint64(b, 1)
  207. err := mp.CheckTx(context.Background(), b, nil, mempool.TxInfo{})
  208. require.NoError(t, err)
  209. // simulate new block
  210. _ = app.DeliverTx(abci.RequestDeliverTx{Tx: a})
  211. _ = app.DeliverTx(abci.RequestDeliverTx{Tx: b})
  212. err = mp.Update(1, []types.Tx{a, b},
  213. []*abci.ResponseDeliverTx{{Code: abci.CodeTypeOK}, {Code: 2}}, nil, nil)
  214. require.NoError(t, err)
  215. // a must be added to the cache
  216. err = mp.CheckTx(context.Background(), a, nil, mempool.TxInfo{})
  217. require.NoError(t, err)
  218. // b must remain in the cache
  219. err = mp.CheckTx(context.Background(), b, nil, mempool.TxInfo{})
  220. require.NoError(t, err)
  221. }
  222. // 2. An invalid transaction must remain in the cache
  223. {
  224. a := make([]byte, 8)
  225. binary.BigEndian.PutUint64(a, 0)
  226. // remove a from the cache to test (2)
  227. mp.cache.Remove(a)
  228. err := mp.CheckTx(context.Background(), a, nil, mempool.TxInfo{})
  229. require.NoError(t, err)
  230. }
  231. }
  232. func TestTxsAvailable(t *testing.T) {
  233. app := kvstore.NewApplication()
  234. cc := proxy.NewLocalClientCreator(app)
  235. mp, cleanup := newMempoolWithApp(cc)
  236. defer cleanup()
  237. mp.EnableTxsAvailable()
  238. timeoutMS := 500
  239. // with no txs, it shouldnt fire
  240. ensureNoFire(t, mp.TxsAvailable(), timeoutMS)
  241. // send a bunch of txs, it should only fire once
  242. txs := checkTxs(t, mp, 100, mempool.UnknownPeerID)
  243. ensureFire(t, mp.TxsAvailable(), timeoutMS)
  244. ensureNoFire(t, mp.TxsAvailable(), timeoutMS)
  245. // call update with half the txs.
  246. // it should fire once now for the new height
  247. // since there are still txs left
  248. committedTxs, txs := txs[:50], txs[50:]
  249. if err := mp.Update(1, committedTxs, abciResponses(len(committedTxs), abci.CodeTypeOK), nil, nil); err != nil {
  250. t.Error(err)
  251. }
  252. ensureFire(t, mp.TxsAvailable(), timeoutMS)
  253. ensureNoFire(t, mp.TxsAvailable(), timeoutMS)
  254. // send a bunch more txs. we already fired for this height so it shouldnt fire again
  255. moreTxs := checkTxs(t, mp, 50, mempool.UnknownPeerID)
  256. ensureNoFire(t, mp.TxsAvailable(), timeoutMS)
  257. // now call update with all the txs. it should not fire as there are no txs left
  258. committedTxs = append(txs, moreTxs...) //nolint: gocritic
  259. if err := mp.Update(2, committedTxs, abciResponses(len(committedTxs), abci.CodeTypeOK), nil, nil); err != nil {
  260. t.Error(err)
  261. }
  262. ensureNoFire(t, mp.TxsAvailable(), timeoutMS)
  263. // send a bunch more txs, it should only fire once
  264. checkTxs(t, mp, 100, mempool.UnknownPeerID)
  265. ensureFire(t, mp.TxsAvailable(), timeoutMS)
  266. ensureNoFire(t, mp.TxsAvailable(), timeoutMS)
  267. }
  268. func TestSerialReap(t *testing.T) {
  269. app := kvstore.NewApplication()
  270. cc := proxy.NewLocalClientCreator(app)
  271. mp, cleanup := newMempoolWithApp(cc)
  272. defer cleanup()
  273. appConnCon, _ := cc.NewABCIClient()
  274. appConnCon.SetLogger(log.TestingLogger().With("module", "abci-client", "connection", "consensus"))
  275. err := appConnCon.Start()
  276. require.Nil(t, err)
  277. cacheMap := make(map[string]struct{})
  278. deliverTxsRange := func(start, end int) {
  279. // Deliver some txs.
  280. for i := start; i < end; i++ {
  281. // This will succeed
  282. txBytes := make([]byte, 8)
  283. binary.BigEndian.PutUint64(txBytes, uint64(i))
  284. err := mp.CheckTx(context.Background(), txBytes, nil, mempool.TxInfo{})
  285. _, cached := cacheMap[string(txBytes)]
  286. if cached {
  287. require.NotNil(t, err, "expected error for cached tx")
  288. } else {
  289. require.Nil(t, err, "expected no err for uncached tx")
  290. }
  291. cacheMap[string(txBytes)] = struct{}{}
  292. // Duplicates are cached and should return error
  293. err = mp.CheckTx(context.Background(), txBytes, nil, mempool.TxInfo{})
  294. require.NotNil(t, err, "Expected error after CheckTx on duplicated tx")
  295. }
  296. }
  297. reapCheck := func(exp int) {
  298. txs := mp.ReapMaxBytesMaxGas(-1, -1)
  299. require.Equal(t, len(txs), exp, fmt.Sprintf("Expected to reap %v txs but got %v", exp, len(txs)))
  300. }
  301. updateRange := func(start, end int) {
  302. txs := make([]types.Tx, 0)
  303. for i := start; i < end; i++ {
  304. txBytes := make([]byte, 8)
  305. binary.BigEndian.PutUint64(txBytes, uint64(i))
  306. txs = append(txs, txBytes)
  307. }
  308. if err := mp.Update(0, txs, abciResponses(len(txs), abci.CodeTypeOK), nil, nil); err != nil {
  309. t.Error(err)
  310. }
  311. }
  312. commitRange := func(start, end int) {
  313. ctx := context.Background()
  314. // Deliver some txs.
  315. for i := start; i < end; i++ {
  316. txBytes := make([]byte, 8)
  317. binary.BigEndian.PutUint64(txBytes, uint64(i))
  318. res, err := appConnCon.DeliverTxSync(ctx, abci.RequestDeliverTx{Tx: txBytes})
  319. if err != nil {
  320. t.Errorf("client error committing tx: %v", err)
  321. }
  322. if res.IsErr() {
  323. t.Errorf("error committing tx. Code:%v result:%X log:%v",
  324. res.Code, res.Data, res.Log)
  325. }
  326. }
  327. res, err := appConnCon.CommitSync(ctx)
  328. if err != nil {
  329. t.Errorf("client error committing: %v", err)
  330. }
  331. if len(res.Data) != 8 {
  332. t.Errorf("error committing. Hash:%X", res.Data)
  333. }
  334. }
  335. //----------------------------------------
  336. // Deliver some txs.
  337. deliverTxsRange(0, 100)
  338. // Reap the txs.
  339. reapCheck(100)
  340. // Reap again. We should get the same amount
  341. reapCheck(100)
  342. // Deliver 0 to 999, we should reap 900 new txs
  343. // because 100 were already counted.
  344. deliverTxsRange(0, 1000)
  345. // Reap the txs.
  346. reapCheck(1000)
  347. // Reap again. We should get the same amount
  348. reapCheck(1000)
  349. // Commit from the conensus AppConn
  350. commitRange(0, 500)
  351. updateRange(0, 500)
  352. // We should have 500 left.
  353. reapCheck(500)
  354. // Deliver 100 invalid txs and 100 valid txs
  355. deliverTxsRange(900, 1100)
  356. // We should have 600 now.
  357. reapCheck(600)
  358. }
  359. func TestMempool_CheckTxChecksTxSize(t *testing.T) {
  360. app := kvstore.NewApplication()
  361. cc := proxy.NewLocalClientCreator(app)
  362. mempl, cleanup := newMempoolWithApp(cc)
  363. defer cleanup()
  364. maxTxSize := mempl.config.MaxTxBytes
  365. testCases := []struct {
  366. len int
  367. err bool
  368. }{
  369. // check small txs. no error
  370. 0: {10, false},
  371. 1: {1000, false},
  372. 2: {1000000, false},
  373. // check around maxTxSize
  374. 3: {maxTxSize - 1, false},
  375. 4: {maxTxSize, false},
  376. 5: {maxTxSize + 1, true},
  377. }
  378. for i, testCase := range testCases {
  379. caseString := fmt.Sprintf("case %d, len %d", i, testCase.len)
  380. tx := tmrand.Bytes(testCase.len)
  381. err := mempl.CheckTx(context.Background(), tx, nil, mempool.TxInfo{})
  382. bv := gogotypes.BytesValue{Value: tx}
  383. bz, err2 := bv.Marshal()
  384. require.NoError(t, err2)
  385. require.Equal(t, len(bz), proto.Size(&bv), caseString)
  386. if !testCase.err {
  387. require.NoError(t, err, caseString)
  388. } else {
  389. require.Equal(t, err, types.ErrTxTooLarge{
  390. Max: maxTxSize,
  391. Actual: testCase.len,
  392. }, caseString)
  393. }
  394. }
  395. }
  396. func TestMempoolTxsBytes(t *testing.T) {
  397. app := kvstore.NewApplication()
  398. cc := proxy.NewLocalClientCreator(app)
  399. config := cfg.ResetTestRoot("mempool_test")
  400. config.Mempool.MaxTxsBytes = 10
  401. mp, cleanup := newMempoolWithAppAndConfig(cc, config)
  402. defer cleanup()
  403. // 1. zero by default
  404. assert.EqualValues(t, 0, mp.SizeBytes())
  405. // 2. len(tx) after CheckTx
  406. err := mp.CheckTx(context.Background(), []byte{0x01}, nil, mempool.TxInfo{})
  407. require.NoError(t, err)
  408. assert.EqualValues(t, 1, mp.SizeBytes())
  409. // 3. zero again after tx is removed by Update
  410. err = mp.Update(1, []types.Tx{[]byte{0x01}}, abciResponses(1, abci.CodeTypeOK), nil, nil)
  411. require.NoError(t, err)
  412. assert.EqualValues(t, 0, mp.SizeBytes())
  413. // 4. zero after Flush
  414. err = mp.CheckTx(context.Background(), []byte{0x02, 0x03}, nil, mempool.TxInfo{})
  415. require.NoError(t, err)
  416. assert.EqualValues(t, 2, mp.SizeBytes())
  417. mp.Flush()
  418. assert.EqualValues(t, 0, mp.SizeBytes())
  419. // 5. ErrMempoolIsFull is returned when/if MaxTxsBytes limit is reached.
  420. err = mp.CheckTx(
  421. context.Background(),
  422. []byte{0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04},
  423. nil,
  424. mempool.TxInfo{},
  425. )
  426. require.NoError(t, err)
  427. err = mp.CheckTx(context.Background(), []byte{0x05}, nil, mempool.TxInfo{})
  428. if assert.Error(t, err) {
  429. assert.IsType(t, types.ErrMempoolIsFull{}, err)
  430. }
  431. // 6. zero after tx is rechecked and removed due to not being valid anymore
  432. app2 := kvstore.NewApplication()
  433. cc = proxy.NewLocalClientCreator(app2)
  434. mp, cleanup = newMempoolWithApp(cc)
  435. defer cleanup()
  436. txBytes := make([]byte, 8)
  437. binary.BigEndian.PutUint64(txBytes, uint64(0))
  438. err = mp.CheckTx(context.Background(), txBytes, nil, mempool.TxInfo{})
  439. require.NoError(t, err)
  440. assert.EqualValues(t, 8, mp.SizeBytes())
  441. appConnCon, _ := cc.NewABCIClient()
  442. appConnCon.SetLogger(log.TestingLogger().With("module", "abci-client", "connection", "consensus"))
  443. err = appConnCon.Start()
  444. require.Nil(t, err)
  445. t.Cleanup(func() {
  446. if err := appConnCon.Stop(); err != nil {
  447. t.Error(err)
  448. }
  449. })
  450. ctx := context.Background()
  451. res, err := appConnCon.DeliverTxSync(ctx, abci.RequestDeliverTx{Tx: txBytes})
  452. require.NoError(t, err)
  453. require.EqualValues(t, 0, res.Code)
  454. res2, err := appConnCon.CommitSync(ctx)
  455. require.NoError(t, err)
  456. require.NotEmpty(t, res2.Data)
  457. // Pretend like we committed nothing so txBytes gets rechecked and removed.
  458. err = mp.Update(1, []types.Tx{}, abciResponses(0, abci.CodeTypeOK), nil, nil)
  459. require.NoError(t, err)
  460. assert.EqualValues(t, 8, mp.SizeBytes())
  461. // 7. Test RemoveTxByKey function
  462. err = mp.CheckTx(context.Background(), []byte{0x06}, nil, mempool.TxInfo{})
  463. require.NoError(t, err)
  464. assert.EqualValues(t, 9, mp.SizeBytes())
  465. mp.RemoveTxByKey(mempool.TxKey([]byte{0x07}), true)
  466. assert.EqualValues(t, 9, mp.SizeBytes())
  467. mp.RemoveTxByKey(mempool.TxKey([]byte{0x06}), true)
  468. assert.EqualValues(t, 8, mp.SizeBytes())
  469. }
  470. // This will non-deterministically catch some concurrency failures like
  471. // https://github.com/tendermint/tendermint/issues/3509
  472. // TODO: all of the tests should probably also run using the remote proxy app
  473. // since otherwise we're not actually testing the concurrency of the mempool here!
  474. func TestMempoolRemoteAppConcurrency(t *testing.T) {
  475. sockPath := fmt.Sprintf("unix:///tmp/echo_%v.sock", tmrand.Str(6))
  476. app := kvstore.NewApplication()
  477. cc, server := newRemoteApp(t, sockPath, app)
  478. t.Cleanup(func() {
  479. if err := server.Stop(); err != nil {
  480. t.Error(err)
  481. }
  482. })
  483. config := cfg.ResetTestRoot("mempool_test")
  484. mp, cleanup := newMempoolWithAppAndConfig(cc, config)
  485. defer cleanup()
  486. // generate small number of txs
  487. nTxs := 10
  488. txLen := 200
  489. txs := make([]types.Tx, nTxs)
  490. for i := 0; i < nTxs; i++ {
  491. txs[i] = tmrand.Bytes(txLen)
  492. }
  493. // simulate a group of peers sending them over and over
  494. N := config.Mempool.Size
  495. maxPeers := 5
  496. for i := 0; i < N; i++ {
  497. peerID := mrand.Intn(maxPeers)
  498. txNum := mrand.Intn(nTxs)
  499. tx := txs[txNum]
  500. // this will err with ErrTxInCache many times ...
  501. mp.CheckTx(context.Background(), tx, nil, mempool.TxInfo{SenderID: uint16(peerID)}) //nolint: errcheck // will error
  502. }
  503. err := mp.FlushAppConn()
  504. require.NoError(t, err)
  505. }
  506. // caller must close server
  507. func newRemoteApp(
  508. t *testing.T,
  509. addr string,
  510. app abci.Application,
  511. ) (
  512. clientCreator proxy.ClientCreator,
  513. server service.Service,
  514. ) {
  515. clientCreator = proxy.NewRemoteClientCreator(addr, "socket", true)
  516. // Start server
  517. server = abciserver.NewSocketServer(addr, app)
  518. server.SetLogger(log.TestingLogger().With("module", "abci-server"))
  519. if err := server.Start(); err != nil {
  520. t.Fatalf("Error starting socket server: %v", err.Error())
  521. }
  522. return clientCreator, server
  523. }
  524. func abciResponses(n int, code uint32) []*abci.ResponseDeliverTx {
  525. responses := make([]*abci.ResponseDeliverTx, 0, n)
  526. for i := 0; i < n; i++ {
  527. responses = append(responses, &abci.ResponseDeliverTx{Code: code})
  528. }
  529. return responses
  530. }