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.

691 lines
21 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
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 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
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 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
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 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
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 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/mock"
  15. "github.com/stretchr/testify/require"
  16. abciclient "github.com/tendermint/tendermint/abci/client"
  17. abciclimocks "github.com/tendermint/tendermint/abci/client/mocks"
  18. "github.com/tendermint/tendermint/abci/example/kvstore"
  19. abciserver "github.com/tendermint/tendermint/abci/server"
  20. abci "github.com/tendermint/tendermint/abci/types"
  21. "github.com/tendermint/tendermint/config"
  22. "github.com/tendermint/tendermint/internal/mempool"
  23. "github.com/tendermint/tendermint/libs/log"
  24. tmrand "github.com/tendermint/tendermint/libs/rand"
  25. "github.com/tendermint/tendermint/libs/service"
  26. "github.com/tendermint/tendermint/types"
  27. )
  28. // A cleanupFunc cleans up any config / test files created for a particular
  29. // test.
  30. type cleanupFunc func()
  31. func newMempoolWithApp(cc abciclient.Creator) (*CListMempool, cleanupFunc, error) {
  32. conf, err := config.ResetTestRoot("mempool_test")
  33. if err != nil {
  34. return nil, func() {}, err
  35. }
  36. mp, cu := newMempoolWithAppAndConfig(cc, conf)
  37. return mp, cu, nil
  38. }
  39. func newMempoolWithAppAndConfig(cc abciclient.Creator, cfg *config.Config) (*CListMempool, cleanupFunc) {
  40. appConnMem, _ := cc()
  41. appConnMem.SetLogger(log.TestingLogger().With("module", "abci-client", "connection", "mempool"))
  42. err := appConnMem.Start()
  43. if err != nil {
  44. panic(err)
  45. }
  46. mp := NewCListMempool(cfg.Mempool, appConnMem, 0)
  47. mp.SetLogger(log.TestingLogger())
  48. return mp, func() { os.RemoveAll(cfg.RootDir) }
  49. }
  50. func ensureNoFire(t *testing.T, ch <-chan struct{}, timeoutMS int) {
  51. timer := time.NewTimer(time.Duration(timeoutMS) * time.Millisecond)
  52. select {
  53. case <-ch:
  54. t.Fatal("Expected not to fire")
  55. case <-timer.C:
  56. }
  57. }
  58. func ensureFire(t *testing.T, ch <-chan struct{}, timeoutMS int) {
  59. timer := time.NewTimer(time.Duration(timeoutMS) * time.Millisecond)
  60. select {
  61. case <-ch:
  62. case <-timer.C:
  63. t.Fatal("Expected to fire")
  64. }
  65. }
  66. func checkTxs(t *testing.T, mp mempool.Mempool, count int, peerID uint16) types.Txs {
  67. txs := make(types.Txs, count)
  68. txInfo := mempool.TxInfo{SenderID: peerID}
  69. for i := 0; i < count; i++ {
  70. txBytes := make([]byte, 20)
  71. txs[i] = txBytes
  72. _, err := rand.Read(txBytes)
  73. if err != nil {
  74. t.Error(err)
  75. }
  76. if err := mp.CheckTx(context.Background(), txBytes, nil, txInfo); err != nil {
  77. // Skip invalid txs.
  78. // TestMempoolFilters will fail otherwise. It asserts a number of txs
  79. // returned.
  80. if types.IsPreCheckError(err) {
  81. continue
  82. }
  83. t.Fatalf("CheckTx failed: %v while checking #%d tx", err, i)
  84. }
  85. }
  86. return txs
  87. }
  88. func TestReapMaxBytesMaxGas(t *testing.T) {
  89. app := kvstore.NewApplication()
  90. cc := abciclient.NewLocalCreator(app)
  91. mp, cleanup, err := newMempoolWithApp(cc)
  92. require.NoError(t, err)
  93. defer cleanup()
  94. // Ensure gas calculation behaves as expected
  95. checkTxs(t, mp, 1, mempool.UnknownPeerID)
  96. tx0 := mp.TxsFront().Value.(*mempoolTx)
  97. // assert that kv store has gas wanted = 1.
  98. require.Equal(t, app.CheckTx(abci.RequestCheckTx{Tx: tx0.tx}).GasWanted, int64(1), "KVStore had a gas value neq to 1")
  99. require.Equal(t, tx0.gasWanted, int64(1), "transactions gas was set incorrectly")
  100. // ensure each tx is 20 bytes long
  101. require.Equal(t, len(tx0.tx), 20, "Tx is longer than 20 bytes")
  102. mp.Flush()
  103. // each table driven test creates numTxsToCreate txs with checkTx, and at the end clears all remaining txs.
  104. // each tx has 20 bytes
  105. tests := []struct {
  106. numTxsToCreate int
  107. maxBytes int64
  108. maxGas int64
  109. expectedNumTxs int
  110. }{
  111. {20, -1, -1, 20},
  112. {20, -1, 0, 0},
  113. {20, -1, 10, 10},
  114. {20, -1, 30, 20},
  115. {20, 0, -1, 0},
  116. {20, 0, 10, 0},
  117. {20, 10, 10, 0},
  118. {20, 24, 10, 1},
  119. {20, 240, 5, 5},
  120. {20, 240, -1, 10},
  121. {20, 240, 10, 10},
  122. {20, 240, 15, 10},
  123. {20, 20000, -1, 20},
  124. {20, 20000, 5, 5},
  125. {20, 20000, 30, 20},
  126. }
  127. for tcIndex, tt := range tests {
  128. checkTxs(t, mp, tt.numTxsToCreate, mempool.UnknownPeerID)
  129. got := mp.ReapMaxBytesMaxGas(tt.maxBytes, tt.maxGas)
  130. assert.Equal(t, tt.expectedNumTxs, len(got), "Got %d txs, expected %d, tc #%d",
  131. len(got), tt.expectedNumTxs, tcIndex)
  132. mp.Flush()
  133. }
  134. }
  135. func TestMempoolFilters(t *testing.T) {
  136. app := kvstore.NewApplication()
  137. cc := abciclient.NewLocalCreator(app)
  138. mp, cleanup, err := newMempoolWithApp(cc)
  139. require.NoError(t, err)
  140. defer cleanup()
  141. emptyTxArr := []types.Tx{[]byte{}}
  142. nopPreFilter := func(tx types.Tx) error { return nil }
  143. nopPostFilter := func(tx types.Tx, res *abci.ResponseCheckTx) error { return nil }
  144. // each table driven test creates numTxsToCreate txs with checkTx, and at the end clears all remaining txs.
  145. // each tx has 20 bytes
  146. tests := []struct {
  147. numTxsToCreate int
  148. preFilter mempool.PreCheckFunc
  149. postFilter mempool.PostCheckFunc
  150. expectedNumTxs int
  151. }{
  152. {10, nopPreFilter, nopPostFilter, 10},
  153. {10, mempool.PreCheckMaxBytes(10), nopPostFilter, 0},
  154. {10, mempool.PreCheckMaxBytes(22), nopPostFilter, 10},
  155. {10, nopPreFilter, mempool.PostCheckMaxGas(-1), 10},
  156. {10, nopPreFilter, mempool.PostCheckMaxGas(0), 0},
  157. {10, nopPreFilter, mempool.PostCheckMaxGas(1), 10},
  158. {10, nopPreFilter, mempool.PostCheckMaxGas(3000), 10},
  159. {10, mempool.PreCheckMaxBytes(10), mempool.PostCheckMaxGas(20), 0},
  160. {10, mempool.PreCheckMaxBytes(30), mempool.PostCheckMaxGas(20), 10},
  161. {10, mempool.PreCheckMaxBytes(22), mempool.PostCheckMaxGas(1), 10},
  162. {10, mempool.PreCheckMaxBytes(22), mempool.PostCheckMaxGas(0), 0},
  163. }
  164. for tcIndex, tt := range tests {
  165. err := mp.Update(1, emptyTxArr, abciResponses(len(emptyTxArr), abci.CodeTypeOK), tt.preFilter, tt.postFilter)
  166. require.NoError(t, err)
  167. checkTxs(t, mp, tt.numTxsToCreate, mempool.UnknownPeerID)
  168. require.Equal(t, tt.expectedNumTxs, mp.Size(), "mempool had the incorrect size, on test case %d", tcIndex)
  169. mp.Flush()
  170. }
  171. }
  172. func TestMempoolUpdate(t *testing.T) {
  173. app := kvstore.NewApplication()
  174. cc := abciclient.NewLocalCreator(app)
  175. mp, cleanup, err := newMempoolWithApp(cc)
  176. require.NoError(t, err)
  177. defer cleanup()
  178. // 1. Adds valid txs to the cache
  179. {
  180. err := mp.Update(1, []types.Tx{[]byte{0x01}}, abciResponses(1, abci.CodeTypeOK), nil, nil)
  181. require.NoError(t, err)
  182. err = mp.CheckTx(context.Background(), []byte{0x01}, nil, mempool.TxInfo{})
  183. require.NoError(t, err)
  184. }
  185. // 2. Removes valid txs from the mempool
  186. {
  187. err := mp.CheckTx(context.Background(), []byte{0x02}, nil, mempool.TxInfo{})
  188. require.NoError(t, err)
  189. err = mp.Update(1, []types.Tx{[]byte{0x02}}, abciResponses(1, abci.CodeTypeOK), nil, nil)
  190. require.NoError(t, err)
  191. assert.Zero(t, mp.Size())
  192. }
  193. // 3. Removes invalid transactions from the cache and the mempool (if present)
  194. {
  195. err := mp.CheckTx(context.Background(), []byte{0x03}, nil, mempool.TxInfo{})
  196. require.NoError(t, err)
  197. err = mp.Update(1, []types.Tx{[]byte{0x03}}, abciResponses(1, 1), nil, nil)
  198. require.NoError(t, err)
  199. assert.Zero(t, mp.Size())
  200. err = mp.CheckTx(context.Background(), []byte{0x03}, nil, mempool.TxInfo{})
  201. require.NoError(t, err)
  202. }
  203. }
  204. func TestMempoolUpdateDoesNotPanicWhenApplicationMissedTx(t *testing.T) {
  205. var callback abciclient.Callback
  206. mockClient := new(abciclimocks.Client)
  207. mockClient.On("Start").Return(nil)
  208. mockClient.On("SetLogger", mock.Anything)
  209. mockClient.On("Error").Return(nil).Times(4)
  210. mockClient.On("FlushAsync", mock.Anything).Return(abciclient.NewReqRes(abci.ToRequestFlush()), nil)
  211. mockClient.On("SetResponseCallback", mock.MatchedBy(func(cb abciclient.Callback) bool { callback = cb; return true }))
  212. cc := func() (abciclient.Client, error) {
  213. return mockClient, nil
  214. }
  215. mp, cleanup, err := newMempoolWithApp(cc)
  216. require.NoError(t, err)
  217. defer cleanup()
  218. // Add 4 transactions to the mempool by calling the mempool's `CheckTx` on each of them.
  219. txs := []types.Tx{[]byte{0x01}, []byte{0x02}, []byte{0x03}, []byte{0x04}}
  220. for _, tx := range txs {
  221. reqRes := abciclient.NewReqRes(abci.ToRequestCheckTx(abci.RequestCheckTx{Tx: tx}))
  222. reqRes.Response = abci.ToResponseCheckTx(abci.ResponseCheckTx{Code: abci.CodeTypeOK})
  223. // SetDone allows the ReqRes to process its callback synchronously.
  224. // This simulates the Response being ready for the client immediately.
  225. reqRes.SetDone()
  226. mockClient.On("CheckTxAsync", mock.Anything, mock.Anything).Return(reqRes, nil)
  227. err := mp.CheckTx(context.Background(), tx, nil, mempool.TxInfo{})
  228. require.NoError(t, err)
  229. }
  230. // Calling update to remove the first transaction from the mempool.
  231. // This call also triggers the mempool to recheck its remaining transactions.
  232. err = mp.Update(0, []types.Tx{txs[0]}, abciResponses(1, abci.CodeTypeOK), nil, nil)
  233. require.Nil(t, err)
  234. // The mempool has now sent its requests off to the client to be rechecked
  235. // and is waiting for the corresponding callbacks to be called.
  236. // We now call the mempool-supplied callback on the first and third transaction.
  237. // This simulates the client dropping the second request.
  238. // Previous versions of this code panicked when the ABCI application missed
  239. // a recheck-tx request.
  240. resp := abci.ResponseCheckTx{Code: abci.CodeTypeOK}
  241. req := abci.RequestCheckTx{Tx: txs[1]}
  242. callback(abci.ToRequestCheckTx(req), abci.ToResponseCheckTx(resp))
  243. req = abci.RequestCheckTx{Tx: txs[3]}
  244. callback(abci.ToRequestCheckTx(req), abci.ToResponseCheckTx(resp))
  245. mockClient.AssertExpectations(t)
  246. }
  247. func TestMempool_KeepInvalidTxsInCache(t *testing.T) {
  248. app := kvstore.NewApplication()
  249. cc := abciclient.NewLocalCreator(app)
  250. wcfg := config.DefaultConfig()
  251. wcfg.Mempool.KeepInvalidTxsInCache = true
  252. mp, cleanup := newMempoolWithAppAndConfig(cc, wcfg)
  253. defer cleanup()
  254. // 1. An invalid transaction must remain in the cache after Update
  255. {
  256. a := make([]byte, 8)
  257. binary.BigEndian.PutUint64(a, 0)
  258. b := make([]byte, 8)
  259. binary.BigEndian.PutUint64(b, 1)
  260. err := mp.CheckTx(context.Background(), b, nil, mempool.TxInfo{})
  261. require.NoError(t, err)
  262. // simulate new block
  263. _ = app.DeliverTx(abci.RequestDeliverTx{Tx: a})
  264. _ = app.DeliverTx(abci.RequestDeliverTx{Tx: b})
  265. err = mp.Update(1, []types.Tx{a, b},
  266. []*abci.ResponseDeliverTx{{Code: abci.CodeTypeOK}, {Code: 2}}, nil, nil)
  267. require.NoError(t, err)
  268. // a must be added to the cache
  269. err = mp.CheckTx(context.Background(), a, nil, mempool.TxInfo{})
  270. require.NoError(t, err)
  271. // b must remain in the cache
  272. err = mp.CheckTx(context.Background(), b, nil, mempool.TxInfo{})
  273. require.NoError(t, err)
  274. }
  275. // 2. An invalid transaction must remain in the cache
  276. {
  277. a := make([]byte, 8)
  278. binary.BigEndian.PutUint64(a, 0)
  279. // remove a from the cache to test (2)
  280. mp.cache.Remove(a)
  281. err := mp.CheckTx(context.Background(), a, nil, mempool.TxInfo{})
  282. require.NoError(t, err)
  283. }
  284. }
  285. func TestTxsAvailable(t *testing.T) {
  286. app := kvstore.NewApplication()
  287. cc := abciclient.NewLocalCreator(app)
  288. mp, cleanup, err := newMempoolWithApp(cc)
  289. require.NoError(t, err)
  290. defer cleanup()
  291. mp.EnableTxsAvailable()
  292. timeoutMS := 500
  293. // with no txs, it shouldnt fire
  294. ensureNoFire(t, mp.TxsAvailable(), timeoutMS)
  295. // send a bunch of txs, it should only fire once
  296. txs := checkTxs(t, mp, 100, mempool.UnknownPeerID)
  297. ensureFire(t, mp.TxsAvailable(), timeoutMS)
  298. ensureNoFire(t, mp.TxsAvailable(), timeoutMS)
  299. // call update with half the txs.
  300. // it should fire once now for the new height
  301. // since there are still txs left
  302. committedTxs, txs := txs[:50], txs[50:]
  303. if err := mp.Update(1, committedTxs, abciResponses(len(committedTxs), abci.CodeTypeOK), nil, nil); err != nil {
  304. t.Error(err)
  305. }
  306. ensureFire(t, mp.TxsAvailable(), timeoutMS)
  307. ensureNoFire(t, mp.TxsAvailable(), timeoutMS)
  308. // send a bunch more txs. we already fired for this height so it shouldnt fire again
  309. moreTxs := checkTxs(t, mp, 50, mempool.UnknownPeerID)
  310. ensureNoFire(t, mp.TxsAvailable(), timeoutMS)
  311. // now call update with all the txs. it should not fire as there are no txs left
  312. committedTxs = append(txs, moreTxs...) //nolint: gocritic
  313. if err := mp.Update(2, committedTxs, abciResponses(len(committedTxs), abci.CodeTypeOK), nil, nil); err != nil {
  314. t.Error(err)
  315. }
  316. ensureNoFire(t, mp.TxsAvailable(), timeoutMS)
  317. // send a bunch more txs, it should only fire once
  318. checkTxs(t, mp, 100, mempool.UnknownPeerID)
  319. ensureFire(t, mp.TxsAvailable(), timeoutMS)
  320. ensureNoFire(t, mp.TxsAvailable(), timeoutMS)
  321. }
  322. func TestSerialReap(t *testing.T) {
  323. app := kvstore.NewApplication()
  324. cc := abciclient.NewLocalCreator(app)
  325. mp, cleanup, err := newMempoolWithApp(cc)
  326. require.NoError(t, err)
  327. defer cleanup()
  328. appConnCon, _ := cc()
  329. appConnCon.SetLogger(log.TestingLogger().With("module", "abci-client", "connection", "consensus"))
  330. err = appConnCon.Start()
  331. require.Nil(t, err)
  332. cacheMap := make(map[string]struct{})
  333. deliverTxsRange := func(start, end int) {
  334. // Deliver some txs.
  335. for i := start; i < end; i++ {
  336. // This will succeed
  337. txBytes := make([]byte, 8)
  338. binary.BigEndian.PutUint64(txBytes, uint64(i))
  339. err := mp.CheckTx(context.Background(), txBytes, nil, mempool.TxInfo{})
  340. _, cached := cacheMap[string(txBytes)]
  341. if cached {
  342. require.NotNil(t, err, "expected error for cached tx")
  343. } else {
  344. require.Nil(t, err, "expected no err for uncached tx")
  345. }
  346. cacheMap[string(txBytes)] = struct{}{}
  347. // Duplicates are cached and should return error
  348. err = mp.CheckTx(context.Background(), txBytes, nil, mempool.TxInfo{})
  349. require.NotNil(t, err, "Expected error after CheckTx on duplicated tx")
  350. }
  351. }
  352. reapCheck := func(exp int) {
  353. txs := mp.ReapMaxBytesMaxGas(-1, -1)
  354. require.Equal(t, len(txs), exp, fmt.Sprintf("Expected to reap %v txs but got %v", exp, len(txs)))
  355. }
  356. updateRange := func(start, end int) {
  357. txs := make([]types.Tx, 0)
  358. for i := start; i < end; i++ {
  359. txBytes := make([]byte, 8)
  360. binary.BigEndian.PutUint64(txBytes, uint64(i))
  361. txs = append(txs, txBytes)
  362. }
  363. if err := mp.Update(0, txs, abciResponses(len(txs), abci.CodeTypeOK), nil, nil); err != nil {
  364. t.Error(err)
  365. }
  366. }
  367. commitRange := func(start, end int) {
  368. ctx := context.Background()
  369. // Deliver some txs.
  370. for i := start; i < end; i++ {
  371. txBytes := make([]byte, 8)
  372. binary.BigEndian.PutUint64(txBytes, uint64(i))
  373. res, err := appConnCon.DeliverTxSync(ctx, abci.RequestDeliverTx{Tx: txBytes})
  374. if err != nil {
  375. t.Errorf("client error committing tx: %v", err)
  376. }
  377. if res.IsErr() {
  378. t.Errorf("error committing tx. Code:%v result:%X log:%v",
  379. res.Code, res.Data, res.Log)
  380. }
  381. }
  382. res, err := appConnCon.CommitSync(ctx)
  383. if err != nil {
  384. t.Errorf("client error committing: %v", err)
  385. }
  386. if len(res.Data) != 8 {
  387. t.Errorf("error committing. Hash:%X", res.Data)
  388. }
  389. }
  390. //----------------------------------------
  391. // Deliver some txs.
  392. deliverTxsRange(0, 100)
  393. // Reap the txs.
  394. reapCheck(100)
  395. // Reap again. We should get the same amount
  396. reapCheck(100)
  397. // Deliver 0 to 999, we should reap 900 new txs
  398. // because 100 were already counted.
  399. deliverTxsRange(0, 1000)
  400. // Reap the txs.
  401. reapCheck(1000)
  402. // Reap again. We should get the same amount
  403. reapCheck(1000)
  404. // Commit from the conensus AppConn
  405. commitRange(0, 500)
  406. updateRange(0, 500)
  407. // We should have 500 left.
  408. reapCheck(500)
  409. // Deliver 100 invalid txs and 100 valid txs
  410. deliverTxsRange(900, 1100)
  411. // We should have 600 now.
  412. reapCheck(600)
  413. }
  414. func TestMempool_CheckTxChecksTxSize(t *testing.T) {
  415. app := kvstore.NewApplication()
  416. cc := abciclient.NewLocalCreator(app)
  417. mempl, cleanup, err := newMempoolWithApp(cc)
  418. require.NoError(t, err)
  419. defer cleanup()
  420. maxTxSize := mempl.config.MaxTxBytes
  421. testCases := []struct {
  422. len int
  423. err bool
  424. }{
  425. // check small txs. no error
  426. 0: {10, false},
  427. 1: {1000, false},
  428. 2: {1000000, false},
  429. // check around maxTxSize
  430. 3: {maxTxSize - 1, false},
  431. 4: {maxTxSize, false},
  432. 5: {maxTxSize + 1, true},
  433. }
  434. for i, testCase := range testCases {
  435. caseString := fmt.Sprintf("case %d, len %d", i, testCase.len)
  436. tx := tmrand.Bytes(testCase.len)
  437. err := mempl.CheckTx(context.Background(), tx, nil, mempool.TxInfo{})
  438. bv := gogotypes.BytesValue{Value: tx}
  439. bz, err2 := bv.Marshal()
  440. require.NoError(t, err2)
  441. require.Equal(t, len(bz), proto.Size(&bv), caseString)
  442. if !testCase.err {
  443. require.NoError(t, err, caseString)
  444. } else {
  445. require.Equal(t, err, types.ErrTxTooLarge{
  446. Max: maxTxSize,
  447. Actual: testCase.len,
  448. }, caseString)
  449. }
  450. }
  451. }
  452. func TestMempoolTxsBytes(t *testing.T) {
  453. app := kvstore.NewApplication()
  454. cc := abciclient.NewLocalCreator(app)
  455. cfg, err := config.ResetTestRoot("mempool_test")
  456. require.NoError(t, err)
  457. cfg.Mempool.MaxTxsBytes = 10
  458. mp, cleanup := newMempoolWithAppAndConfig(cc, cfg)
  459. defer cleanup()
  460. // 1. zero by default
  461. assert.EqualValues(t, 0, mp.SizeBytes())
  462. // 2. len(tx) after CheckTx
  463. err = mp.CheckTx(context.Background(), []byte{0x01}, nil, mempool.TxInfo{})
  464. require.NoError(t, err)
  465. assert.EqualValues(t, 1, mp.SizeBytes())
  466. // 3. zero again after tx is removed by Update
  467. err = mp.Update(1, []types.Tx{[]byte{0x01}}, abciResponses(1, abci.CodeTypeOK), nil, nil)
  468. require.NoError(t, err)
  469. assert.EqualValues(t, 0, mp.SizeBytes())
  470. // 4. zero after Flush
  471. err = mp.CheckTx(context.Background(), []byte{0x02, 0x03}, nil, mempool.TxInfo{})
  472. require.NoError(t, err)
  473. assert.EqualValues(t, 2, mp.SizeBytes())
  474. mp.Flush()
  475. assert.EqualValues(t, 0, mp.SizeBytes())
  476. // 5. ErrMempoolIsFull is returned when/if MaxTxsBytes limit is reached.
  477. err = mp.CheckTx(
  478. context.Background(),
  479. []byte{0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04},
  480. nil,
  481. mempool.TxInfo{},
  482. )
  483. require.NoError(t, err)
  484. err = mp.CheckTx(context.Background(), []byte{0x05}, nil, mempool.TxInfo{})
  485. if assert.Error(t, err) {
  486. assert.IsType(t, types.ErrMempoolIsFull{}, err)
  487. }
  488. // 6. zero after tx is rechecked and removed due to not being valid anymore
  489. app2 := kvstore.NewApplication()
  490. cc = abciclient.NewLocalCreator(app2)
  491. mp, cleanup, err = newMempoolWithApp(cc)
  492. require.NoError(t, err)
  493. defer cleanup()
  494. txBytes := make([]byte, 8)
  495. binary.BigEndian.PutUint64(txBytes, uint64(0))
  496. err = mp.CheckTx(context.Background(), txBytes, nil, mempool.TxInfo{})
  497. require.NoError(t, err)
  498. assert.EqualValues(t, 8, mp.SizeBytes())
  499. appConnCon, _ := cc()
  500. appConnCon.SetLogger(log.TestingLogger().With("module", "abci-client", "connection", "consensus"))
  501. err = appConnCon.Start()
  502. require.Nil(t, err)
  503. t.Cleanup(func() {
  504. if err := appConnCon.Stop(); err != nil {
  505. t.Error(err)
  506. }
  507. })
  508. ctx := context.Background()
  509. res, err := appConnCon.DeliverTxSync(ctx, abci.RequestDeliverTx{Tx: txBytes})
  510. require.NoError(t, err)
  511. require.EqualValues(t, 0, res.Code)
  512. res2, err := appConnCon.CommitSync(ctx)
  513. require.NoError(t, err)
  514. require.NotEmpty(t, res2.Data)
  515. // Pretend like we committed nothing so txBytes gets rechecked and removed.
  516. err = mp.Update(1, []types.Tx{}, abciResponses(0, abci.CodeTypeOK), nil, nil)
  517. require.NoError(t, err)
  518. assert.EqualValues(t, 8, mp.SizeBytes())
  519. // 7. Test RemoveTxByKey function
  520. err = mp.CheckTx(context.Background(), []byte{0x06}, nil, mempool.TxInfo{})
  521. require.NoError(t, err)
  522. assert.EqualValues(t, 9, mp.SizeBytes())
  523. assert.Error(t, mp.RemoveTxByKey(types.Tx([]byte{0x07}).Key()))
  524. assert.EqualValues(t, 9, mp.SizeBytes())
  525. assert.NoError(t, mp.RemoveTxByKey(types.Tx([]byte{0x06}).Key()))
  526. assert.EqualValues(t, 8, mp.SizeBytes())
  527. }
  528. // This will non-deterministically catch some concurrency failures like
  529. // https://github.com/tendermint/tendermint/issues/3509
  530. // TODO: all of the tests should probably also run using the remote proxy app
  531. // since otherwise we're not actually testing the concurrency of the mempool here!
  532. func TestMempoolRemoteAppConcurrency(t *testing.T) {
  533. sockPath := fmt.Sprintf("unix:///tmp/echo_%v.sock", tmrand.Str(6))
  534. app := kvstore.NewApplication()
  535. cc, server := newRemoteApp(t, sockPath, app)
  536. t.Cleanup(func() {
  537. if err := server.Stop(); err != nil {
  538. t.Error(err)
  539. }
  540. })
  541. cfg, err := config.ResetTestRoot("mempool_test")
  542. require.NoError(t, err)
  543. mp, cleanup := newMempoolWithAppAndConfig(cc, cfg)
  544. defer cleanup()
  545. // generate small number of txs
  546. nTxs := 10
  547. txLen := 200
  548. txs := make([]types.Tx, nTxs)
  549. for i := 0; i < nTxs; i++ {
  550. txs[i] = tmrand.Bytes(txLen)
  551. }
  552. // simulate a group of peers sending them over and over
  553. N := cfg.Mempool.Size
  554. maxPeers := 5
  555. for i := 0; i < N; i++ {
  556. peerID := mrand.Intn(maxPeers)
  557. txNum := mrand.Intn(nTxs)
  558. tx := txs[txNum]
  559. // this will err with ErrTxInCache many times ...
  560. mp.CheckTx(context.Background(), tx, nil, mempool.TxInfo{SenderID: uint16(peerID)}) //nolint: errcheck // will error
  561. }
  562. err = mp.FlushAppConn()
  563. require.NoError(t, err)
  564. }
  565. // caller must close server
  566. func newRemoteApp(
  567. t *testing.T,
  568. addr string,
  569. app abci.Application,
  570. ) (
  571. clientCreator abciclient.Creator,
  572. server service.Service,
  573. ) {
  574. clientCreator = abciclient.NewRemoteCreator(addr, "socket", true)
  575. // Start server
  576. server = abciserver.NewSocketServer(addr, app)
  577. server.SetLogger(log.TestingLogger().With("module", "abci-server"))
  578. if err := server.Start(); err != nil {
  579. t.Fatalf("Error starting socket server: %v", err.Error())
  580. }
  581. return clientCreator, server
  582. }
  583. func abciResponses(n int, code uint32) []*abci.ResponseDeliverTx {
  584. responses := make([]*abci.ResponseDeliverTx, 0, n)
  585. for i := 0; i < n; i++ {
  586. responses = append(responses, &abci.ResponseDeliverTx{Code: code})
  587. }
  588. return responses
  589. }