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.

725 lines
21 KiB

9 years ago
9 years ago
8 years ago
8 years ago
9 years ago
8 years ago
8 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
abci: localClient improvements & bugfixes & pubsub Unsubscribe issues (#2748) * use READ lock/unlock in ConsensusState#GetLastHeight Refs #2721 * do not use defers when there's no need * fix peer formatting (output its address instead of the pointer) ``` [54310]: E[11-02|11:59:39.851] Connection failed @ sendRoutine module=p2p peer=0xb78f00 conn=MConn{74.207.236.148:26656} err="pong timeout" ``` https://github.com/tendermint/tendermint/issues/2721#issuecomment-435326581 * panic if peer has no state https://github.com/tendermint/tendermint/issues/2721#issuecomment-435347165 It's confusing that sometimes we check if peer has a state, but most of the times we expect it to be there 1. https://github.com/tendermint/tendermint/blob/add79700b5fe84417538202b6c927c8cc5383672/mempool/reactor.go#L138 2. https://github.com/tendermint/tendermint/blob/add79700b5fe84417538202b6c927c8cc5383672/rpc/core/consensus.go#L196 (edited) I will change everything to always assume peer has a state and panic otherwise that should help identify issues earlier * abci/localclient: extend lock on app callback App callback should be protected by lock as well (note this was already done for InitChainAsync, why not for others???). Otherwise, when we execute the block, tx might come in and call the callback in the same time we're updating it in execBlockOnProxyApp => DATA RACE Fixes #2721 Consensus state is locked ``` goroutine 113333 [semacquire, 309 minutes]: sync.runtime_SemacquireMutex(0xc00180009c, 0xc0000c7e00) /usr/local/go/src/runtime/sema.go:71 +0x3d sync.(*RWMutex).RLock(0xc001800090) /usr/local/go/src/sync/rwmutex.go:50 +0x4e github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus.(*ConsensusState).GetRoundState(0xc001800000, 0x0) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus/state.go:218 +0x46 github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus.(*ConsensusReactor).queryMaj23Routine(0xc0017def80, 0x11104a0, 0xc0072488f0, 0xc007248 9c0) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus/reactor.go:735 +0x16d created by github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus.(*ConsensusReactor).AddPeer /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus/reactor.go:172 +0x236 ``` because localClient is locked ``` goroutine 1899 [semacquire, 309 minutes]: sync.runtime_SemacquireMutex(0xc00003363c, 0xc0000cb500) /usr/local/go/src/runtime/sema.go:71 +0x3d sync.(*Mutex).Lock(0xc000033638) /usr/local/go/src/sync/mutex.go:134 +0xff github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/abci/client.(*localClient).SetResponseCallback(0xc0001fb560, 0xc007868540) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/abci/client/local_client.go:32 +0x33 github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/proxy.(*appConnConsensus).SetResponseCallback(0xc00002f750, 0xc007868540) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/proxy/app_conn.go:57 +0x40 github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/state.execBlockOnProxyApp(0x1104e20, 0xc002ca0ba0, 0x11092a0, 0xc00002f750, 0xc0001fe960, 0xc000bfc660, 0x110cfe0, 0xc000090330, 0xc9d12, 0xc000d9d5a0, ...) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/state/execution.go:230 +0x1fd github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/state.(*BlockExecutor).ApplyBlock(0xc002c2a230, 0x7, 0x0, 0xc000eae880, 0x6, 0xc002e52c60, 0x16, 0x1f927, 0xc9d12, 0xc000d9d5a0, ...) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/state/execution.go:96 +0x142 github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus.(*ConsensusState).finalizeCommit(0xc001800000, 0x1f928) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus/state.go:1339 +0xa3e github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus.(*ConsensusState).tryFinalizeCommit(0xc001800000, 0x1f928) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus/state.go:1270 +0x451 github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus.(*ConsensusState).enterCommit.func1(0xc001800000, 0x0, 0x1f928) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus/state.go:1218 +0x90 github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus.(*ConsensusState).enterCommit(0xc001800000, 0x1f928, 0x0) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus/state.go:1247 +0x6b8 github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus.(*ConsensusState).addVote(0xc001800000, 0xc003d8dea0, 0xc000cf4cc0, 0x28, 0xf1, 0xc003bc7ad0, 0xc003bc7b10) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus/state.go:1659 +0xbad github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus.(*ConsensusState).tryAddVote(0xc001800000, 0xc003d8dea0, 0xc000cf4cc0, 0x28, 0xf1, 0xf1, 0xf1) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus/state.go:1517 +0x59 github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus.(*ConsensusState).handleMsg(0xc001800000, 0xd98200, 0xc0070dbed0, 0xc000cf4cc0, 0x28) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus/state.go:660 +0x64b github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus.(*ConsensusState).receiveRoutine(0xc001800000, 0x0) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus/state.go:617 +0x670 created by github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus.(*ConsensusState).OnStart /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/consensus/state.go:311 +0x132 ``` tx comes in and CheckTx is executed right when we execute the block ``` goroutine 111044 [semacquire, 309 minutes]: sync.runtime_SemacquireMutex(0xc00003363c, 0x0) /usr/local/go/src/runtime/sema.go:71 +0x3d sync.(*Mutex).Lock(0xc000033638) /usr/local/go/src/sync/mutex.go:134 +0xff github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/abci/client.(*localClient).CheckTxAsync(0xc0001fb0e0, 0xc002d94500, 0x13f, 0x280, 0x0) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/abci/client/local_client.go:85 +0x47 github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/proxy.(*appConnMempool).CheckTxAsync(0xc00002f720, 0xc002d94500, 0x13f, 0x280, 0x1) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/proxy/app_conn.go:114 +0x51 github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/mempool.(*Mempool).CheckTx(0xc002d3a320, 0xc002d94500, 0x13f, 0x280, 0xc0072355f0, 0x0, 0x0) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/mempool/mempool.go:316 +0x17b github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/rpc/core.BroadcastTxSync(0xc002d94500, 0x13f, 0x280, 0x0, 0x0, 0x0) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/rpc/core/mempool.go:93 +0xb8 reflect.Value.call(0xd85560, 0x10326c0, 0x13, 0xec7b8b, 0x4, 0xc00663f180, 0x1, 0x1, 0xc00663f180, 0xc00663f188, ...) /usr/local/go/src/reflect/value.go:447 +0x449 reflect.Value.Call(0xd85560, 0x10326c0, 0x13, 0xc00663f180, 0x1, 0x1, 0x0, 0x0, 0xc005cc9344) /usr/local/go/src/reflect/value.go:308 +0xa4 github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/rpc/lib/server.makeHTTPHandler.func2(0x1102060, 0xc00663f100, 0xc0082d7900) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/rpc/lib/server/handlers.go:269 +0x188 net/http.HandlerFunc.ServeHTTP(0xc002c81f20, 0x1102060, 0xc00663f100, 0xc0082d7900) /usr/local/go/src/net/http/server.go:1964 +0x44 net/http.(*ServeMux).ServeHTTP(0xc002c81b60, 0x1102060, 0xc00663f100, 0xc0082d7900) /usr/local/go/src/net/http/server.go:2361 +0x127 github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/rpc/lib/server.maxBytesHandler.ServeHTTP(0x10f8a40, 0xc002c81b60, 0xf4240, 0x1102060, 0xc00663f100, 0xc0082d7900) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/rpc/lib/server/http_server.go:219 +0xcf github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/rpc/lib/server.RecoverAndLogHandler.func1(0x1103220, 0xc00121e620, 0xc0082d7900) /root/go/src/github.com/MinterTeam/minter-go-node/vendor/github.com/tendermint/tendermint/rpc/lib/server/http_server.go:192 +0x394 net/http.HandlerFunc.ServeHTTP(0xc002c06ea0, 0x1103220, 0xc00121e620, 0xc0082d7900) /usr/local/go/src/net/http/server.go:1964 +0x44 net/http.serverHandler.ServeHTTP(0xc001a1aa90, 0x1103220, 0xc00121e620, 0xc0082d7900) /usr/local/go/src/net/http/server.go:2741 +0xab net/http.(*conn).serve(0xc00785a3c0, 0x11041a0, 0xc000f844c0) /usr/local/go/src/net/http/server.go:1847 +0x646 created by net/http.(*Server).Serve /usr/local/go/src/net/http/server.go:2851 +0x2f5 ``` * consensus: use read lock in Receive#VoteMessage * use defer to unlock mutex because application might panic * use defer in every method of the localClient * add a changelog entry * drain channels before Unsubscribe(All) Read https://github.com/tendermint/tendermint/blob/55362ed76630f3e1ebec159a598f6a9fb5892cb1/libs/pubsub/pubsub.go#L13 for the detailed explanation of the issue. We'll need to fix it someday. Make sure to keep an eye on https://github.com/tendermint/tendermint/blob/master/docs/architecture/adr-033-pubsub.md * retry instead of panic when peer has no state in reactors other than consensus in /dump_consensus_state RPC endpoint, skip a peer with no state * rpc/core/mempool: simplify error messages * rpc/core/mempool: use time.After instead of timer also, do not log DeliverTx result (to be consistent with other memthods) * unlock before calling the callback in reqRes#SetCallback
6 years ago
9 years ago
8 years ago
8 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
7 years ago
9 years ago
7 years ago
9 years ago
9 years ago
max-bytes PR follow-up (#2318) * ReapMaxTxs: return all txs if max is negative this mirrors ReapMaxBytes behavior See https://github.com/tendermint/tendermint/pull/2184#discussion_r214439950 * increase MaxAminoOverheadForBlock tested with: ``` func TestMaxAminoOverheadForBlock(t *testing.T) { maxChainID := "" for i := 0; i < MaxChainIDLen; i++ { maxChainID += "𠜎" } h := Header{ ChainID: maxChainID, Height: 10, Time: time.Now().UTC(), NumTxs: 100, TotalTxs: 200, LastBlockID: makeBlockID(make([]byte, 20), 300, make([]byte, 20)), LastCommitHash: tmhash.Sum([]byte("last_commit_hash")), DataHash: tmhash.Sum([]byte("data_hash")), ValidatorsHash: tmhash.Sum([]byte("validators_hash")), NextValidatorsHash: tmhash.Sum([]byte("next_validators_hash")), ConsensusHash: tmhash.Sum([]byte("consensus_hash")), AppHash: tmhash.Sum([]byte("app_hash")), LastResultsHash: tmhash.Sum([]byte("last_results_hash")), EvidenceHash: tmhash.Sum([]byte("evidence_hash")), ProposerAddress: tmhash.Sum([]byte("proposer_address")), } b := Block{ Header: h, Data: Data{Txs: makeTxs(10000, 100)}, Evidence: EvidenceData{}, LastCommit: &Commit{}, } bz, err := cdc.MarshalBinary(b) require.NoError(t, err) assert.Equal(t, MaxHeaderBytes+MaxAminoOverheadForBlock-2, len(bz)-1000000-20000-1) } ``` * fix MaxYYY constants calculation by using math.MaxInt64 See https://github.com/tendermint/tendermint/pull/2184#discussion_r214444244 * pass mempool filter as an option See https://github.com/tendermint/tendermint/pull/2184#discussion_r214445869 * fixes after Dev's comments
6 years ago
max-bytes PR follow-up (#2318) * ReapMaxTxs: return all txs if max is negative this mirrors ReapMaxBytes behavior See https://github.com/tendermint/tendermint/pull/2184#discussion_r214439950 * increase MaxAminoOverheadForBlock tested with: ``` func TestMaxAminoOverheadForBlock(t *testing.T) { maxChainID := "" for i := 0; i < MaxChainIDLen; i++ { maxChainID += "𠜎" } h := Header{ ChainID: maxChainID, Height: 10, Time: time.Now().UTC(), NumTxs: 100, TotalTxs: 200, LastBlockID: makeBlockID(make([]byte, 20), 300, make([]byte, 20)), LastCommitHash: tmhash.Sum([]byte("last_commit_hash")), DataHash: tmhash.Sum([]byte("data_hash")), ValidatorsHash: tmhash.Sum([]byte("validators_hash")), NextValidatorsHash: tmhash.Sum([]byte("next_validators_hash")), ConsensusHash: tmhash.Sum([]byte("consensus_hash")), AppHash: tmhash.Sum([]byte("app_hash")), LastResultsHash: tmhash.Sum([]byte("last_results_hash")), EvidenceHash: tmhash.Sum([]byte("evidence_hash")), ProposerAddress: tmhash.Sum([]byte("proposer_address")), } b := Block{ Header: h, Data: Data{Txs: makeTxs(10000, 100)}, Evidence: EvidenceData{}, LastCommit: &Commit{}, } bz, err := cdc.MarshalBinary(b) require.NoError(t, err) assert.Equal(t, MaxHeaderBytes+MaxAminoOverheadForBlock-2, len(bz)-1000000-20000-1) } ``` * fix MaxYYY constants calculation by using math.MaxInt64 See https://github.com/tendermint/tendermint/pull/2184#discussion_r214444244 * pass mempool filter as an option See https://github.com/tendermint/tendermint/pull/2184#discussion_r214445869 * fixes after Dev's comments
6 years ago
7 years ago
mempool: notifyTxsAvailable if there're txs left, but recheck=false (#2991) (left after committing a block) Fixes #2961 -------------- ORIGINAL ISSUE Tendermint version : 0.26.4-b771798d ABCI app : kv-store Environment: OS (e.g. from /etc/os-release): macOS 10.14.1 What happened: Set mempool.recheck = false and create empty block = false in config.toml. When transactions get added right between a new empty block is being proposed and committed, the proposer won't propose new block for that transactions immediately after. That transactions are stuck in the mempool until a new transaction is added and trigger the proposer. What you expected to happen: If there is a transaction left in the mempool, new block should be proposed immediately. Have you tried the latest version: yes How to reproduce it (as minimally and precisely as possible): Fire two transaction using broadcast_tx_sync with specific delay between them. (You may need to do it multiple time before the right delay is found, on my machine the delay is 0.98s) Logs (paste a small part showing an error (< 10 lines) or link a pastebin, gist, etc. containing more of the log file): https://pastebin.com/0Wt6uhPF Config (you can paste only the changes you've made): [mempool] recheck = false create_empty_block = false Anything else we need to know: In mempool.go, we found that proposer will immediately propose new block if Last committed block has some transaction (causing AppHash to changed) or mem.notifyTxsAvailable() is called. Our scenario is as followed. A transaction is fired, it will create 1 block with 1 tx (line 1-4 in the log) and 1 empty block. After the empty block is proposed but before it is committed, second transaction is fired and added to mempool. (line 8-16) Now, since the last committed block is empty and mem.notifyTxsAvailable() will be called only if mempool.recheck = true. The proposer won't immediately propose new block, causing the second transaction to stuck in mempool until another transaction is added to mempool and trigger mem.notifyTxsAvailable().
6 years ago
9 years ago
9 years ago
  1. package mempool
  2. import (
  3. "bytes"
  4. "container/list"
  5. "crypto/sha256"
  6. "fmt"
  7. "sync"
  8. "sync/atomic"
  9. "time"
  10. "github.com/pkg/errors"
  11. abci "github.com/tendermint/tendermint/abci/types"
  12. cfg "github.com/tendermint/tendermint/config"
  13. auto "github.com/tendermint/tendermint/libs/autofile"
  14. "github.com/tendermint/tendermint/libs/clist"
  15. cmn "github.com/tendermint/tendermint/libs/common"
  16. "github.com/tendermint/tendermint/libs/log"
  17. "github.com/tendermint/tendermint/proxy"
  18. "github.com/tendermint/tendermint/types"
  19. )
  20. // PreCheckFunc is an optional filter executed before CheckTx and rejects
  21. // transaction if false is returned. An example would be to ensure that a
  22. // transaction doesn't exceeded the block size.
  23. type PreCheckFunc func(types.Tx) error
  24. // PostCheckFunc is an optional filter executed after CheckTx and rejects
  25. // transaction if false is returned. An example would be to ensure a
  26. // transaction doesn't require more gas than available for the block.
  27. type PostCheckFunc func(types.Tx, *abci.ResponseCheckTx) error
  28. /*
  29. The mempool pushes new txs onto the proxyAppConn.
  30. It gets a stream of (req, res) tuples from the proxy.
  31. The mempool stores good txs in a concurrent linked-list.
  32. Multiple concurrent go-routines can traverse this linked-list
  33. safely by calling .NextWait() on each element.
  34. So we have several go-routines:
  35. 1. Consensus calling Update() and Reap() synchronously
  36. 2. Many mempool reactor's peer routines calling CheckTx()
  37. 3. Many mempool reactor's peer routines traversing the txs linked list
  38. 4. Another goroutine calling GarbageCollectTxs() periodically
  39. To manage these goroutines, there are three methods of locking.
  40. 1. Mutations to the linked-list is protected by an internal mtx (CList is goroutine-safe)
  41. 2. Mutations to the linked-list elements are atomic
  42. 3. CheckTx() calls can be paused upon Update() and Reap(), protected by .proxyMtx
  43. Garbage collection of old elements from mempool.txs is handlde via
  44. the DetachPrev() call, which makes old elements not reachable by
  45. peer broadcastTxRoutine() automatically garbage collected.
  46. TODO: Better handle abci client errors. (make it automatically handle connection errors)
  47. */
  48. var (
  49. // ErrTxInCache is returned to the client if we saw tx earlier
  50. ErrTxInCache = errors.New("Tx already exists in cache")
  51. // ErrMempoolIsFull means Tendermint & an application can't handle that much load
  52. ErrMempoolIsFull = errors.New("Mempool is full")
  53. // ErrTxTooLarge means the tx is too big to be sent in a message to other peers
  54. ErrTxTooLarge = fmt.Errorf("Tx too large. Max size is %d", maxTxSize)
  55. )
  56. // ErrPreCheck is returned when tx is too big
  57. type ErrPreCheck struct {
  58. Reason error
  59. }
  60. func (e ErrPreCheck) Error() string {
  61. return e.Reason.Error()
  62. }
  63. // IsPreCheckError returns true if err is due to pre check failure.
  64. func IsPreCheckError(err error) bool {
  65. _, ok := err.(ErrPreCheck)
  66. return ok
  67. }
  68. // PreCheckAminoMaxBytes checks that the size of the transaction plus the amino
  69. // overhead is smaller or equal to the expected maxBytes.
  70. func PreCheckAminoMaxBytes(maxBytes int64) PreCheckFunc {
  71. return func(tx types.Tx) error {
  72. // We have to account for the amino overhead in the tx size as well
  73. // NOTE: fieldNum = 1 as types.Block.Data contains Txs []Tx as first field.
  74. // If this field order ever changes this needs to updated here accordingly.
  75. // NOTE: if some []Tx are encoded without a parenting struct, the
  76. // fieldNum is also equal to 1.
  77. aminoOverhead := types.ComputeAminoOverhead(tx, 1)
  78. txSize := int64(len(tx)) + aminoOverhead
  79. if txSize > maxBytes {
  80. return fmt.Errorf("Tx size (including amino overhead) is too big: %d, max: %d",
  81. txSize, maxBytes)
  82. }
  83. return nil
  84. }
  85. }
  86. // PostCheckMaxGas checks that the wanted gas is smaller or equal to the passed
  87. // maxGas. Returns nil if maxGas is -1.
  88. func PostCheckMaxGas(maxGas int64) PostCheckFunc {
  89. return func(tx types.Tx, res *abci.ResponseCheckTx) error {
  90. if maxGas == -1 {
  91. return nil
  92. }
  93. if res.GasWanted < 0 {
  94. return fmt.Errorf("gas wanted %d is negative",
  95. res.GasWanted)
  96. }
  97. if res.GasWanted > maxGas {
  98. return fmt.Errorf("gas wanted %d is greater than max gas %d",
  99. res.GasWanted, maxGas)
  100. }
  101. return nil
  102. }
  103. }
  104. // TxID is the hex encoded hash of the bytes as a types.Tx.
  105. func TxID(tx []byte) string {
  106. return fmt.Sprintf("%X", types.Tx(tx).Hash())
  107. }
  108. // Mempool is an ordered in-memory pool for transactions before they are proposed in a consensus
  109. // round. Transaction validity is checked using the CheckTx abci message before the transaction is
  110. // added to the pool. The Mempool uses a concurrent list structure for storing transactions that
  111. // can be efficiently accessed by multiple concurrent readers.
  112. type Mempool struct {
  113. config *cfg.MempoolConfig
  114. proxyMtx sync.Mutex
  115. proxyAppConn proxy.AppConnMempool
  116. txs *clist.CList // concurrent linked-list of good txs
  117. height int64 // the last block Update()'d to
  118. rechecking int32 // for re-checking filtered txs on Update()
  119. recheckCursor *clist.CElement // next expected response
  120. recheckEnd *clist.CElement // re-checking stops here
  121. notifiedTxsAvailable bool
  122. txsAvailable chan struct{} // fires once for each height, when the mempool is not empty
  123. preCheck PreCheckFunc
  124. postCheck PostCheckFunc
  125. // Keep a cache of already-seen txs.
  126. // This reduces the pressure on the proxyApp.
  127. cache txCache
  128. // A log of mempool txs
  129. wal *auto.AutoFile
  130. logger log.Logger
  131. metrics *Metrics
  132. }
  133. // MempoolOption sets an optional parameter on the Mempool.
  134. type MempoolOption func(*Mempool)
  135. // NewMempool returns a new Mempool with the given configuration and connection to an application.
  136. func NewMempool(
  137. config *cfg.MempoolConfig,
  138. proxyAppConn proxy.AppConnMempool,
  139. height int64,
  140. options ...MempoolOption,
  141. ) *Mempool {
  142. mempool := &Mempool{
  143. config: config,
  144. proxyAppConn: proxyAppConn,
  145. txs: clist.New(),
  146. height: height,
  147. rechecking: 0,
  148. recheckCursor: nil,
  149. recheckEnd: nil,
  150. logger: log.NewNopLogger(),
  151. metrics: NopMetrics(),
  152. }
  153. if config.CacheSize > 0 {
  154. mempool.cache = newMapTxCache(config.CacheSize)
  155. } else {
  156. mempool.cache = nopTxCache{}
  157. }
  158. proxyAppConn.SetResponseCallback(mempool.resCb)
  159. for _, option := range options {
  160. option(mempool)
  161. }
  162. return mempool
  163. }
  164. // EnableTxsAvailable initializes the TxsAvailable channel,
  165. // ensuring it will trigger once every height when transactions are available.
  166. // NOTE: not thread safe - should only be called once, on startup
  167. func (mem *Mempool) EnableTxsAvailable() {
  168. mem.txsAvailable = make(chan struct{}, 1)
  169. }
  170. // SetLogger sets the Logger.
  171. func (mem *Mempool) SetLogger(l log.Logger) {
  172. mem.logger = l
  173. }
  174. // WithPreCheck sets a filter for the mempool to reject a tx if f(tx) returns
  175. // false. This is ran before CheckTx.
  176. func WithPreCheck(f PreCheckFunc) MempoolOption {
  177. return func(mem *Mempool) { mem.preCheck = f }
  178. }
  179. // WithPostCheck sets a filter for the mempool to reject a tx if f(tx) returns
  180. // false. This is ran after CheckTx.
  181. func WithPostCheck(f PostCheckFunc) MempoolOption {
  182. return func(mem *Mempool) { mem.postCheck = f }
  183. }
  184. // WithMetrics sets the metrics.
  185. func WithMetrics(metrics *Metrics) MempoolOption {
  186. return func(mem *Mempool) { mem.metrics = metrics }
  187. }
  188. // InitWAL creates a directory for the WAL file and opens a file itself.
  189. //
  190. // *panics* if can't create directory or open file.
  191. // *not thread safe*
  192. func (mem *Mempool) InitWAL() {
  193. walDir := mem.config.WalDir()
  194. err := cmn.EnsureDir(walDir, 0700)
  195. if err != nil {
  196. panic(errors.Wrap(err, "Error ensuring Mempool WAL dir"))
  197. }
  198. af, err := auto.OpenAutoFile(walDir + "/wal")
  199. if err != nil {
  200. panic(errors.Wrap(err, "Error opening Mempool WAL file"))
  201. }
  202. mem.wal = af
  203. }
  204. // CloseWAL closes and discards the underlying WAL file.
  205. // Any further writes will not be relayed to disk.
  206. func (mem *Mempool) CloseWAL() {
  207. mem.proxyMtx.Lock()
  208. defer mem.proxyMtx.Unlock()
  209. if err := mem.wal.Close(); err != nil {
  210. mem.logger.Error("Error closing WAL", "err", err)
  211. }
  212. mem.wal = nil
  213. }
  214. // Lock locks the mempool. The consensus must be able to hold lock to safely update.
  215. func (mem *Mempool) Lock() {
  216. mem.proxyMtx.Lock()
  217. }
  218. // Unlock unlocks the mempool.
  219. func (mem *Mempool) Unlock() {
  220. mem.proxyMtx.Unlock()
  221. }
  222. // Size returns the number of transactions in the mempool.
  223. func (mem *Mempool) Size() int {
  224. return mem.txs.Len()
  225. }
  226. // Flushes the mempool connection to ensure async resCb calls are done e.g.
  227. // from CheckTx.
  228. func (mem *Mempool) FlushAppConn() error {
  229. return mem.proxyAppConn.FlushSync()
  230. }
  231. // Flush removes all transactions from the mempool and cache
  232. func (mem *Mempool) Flush() {
  233. mem.proxyMtx.Lock()
  234. defer mem.proxyMtx.Unlock()
  235. mem.cache.Reset()
  236. for e := mem.txs.Front(); e != nil; e = e.Next() {
  237. mem.txs.Remove(e)
  238. e.DetachPrev()
  239. }
  240. }
  241. // TxsFront returns the first transaction in the ordered list for peer
  242. // goroutines to call .NextWait() on.
  243. func (mem *Mempool) TxsFront() *clist.CElement {
  244. return mem.txs.Front()
  245. }
  246. // TxsWaitChan returns a channel to wait on transactions. It will be closed
  247. // once the mempool is not empty (ie. the internal `mem.txs` has at least one
  248. // element)
  249. func (mem *Mempool) TxsWaitChan() <-chan struct{} {
  250. return mem.txs.WaitChan()
  251. }
  252. // CheckTx executes a new transaction against the application to determine its validity
  253. // and whether it should be added to the mempool.
  254. // It blocks if we're waiting on Update() or Reap().
  255. // cb: A callback from the CheckTx command.
  256. // It gets called from another goroutine.
  257. // CONTRACT: Either cb will get called, or err returned.
  258. func (mem *Mempool) CheckTx(tx types.Tx, cb func(*abci.Response)) (err error) {
  259. mem.proxyMtx.Lock()
  260. // use defer to unlock mutex because application (*local client*) might panic
  261. defer mem.proxyMtx.Unlock()
  262. if mem.Size() >= mem.config.Size {
  263. return ErrMempoolIsFull
  264. }
  265. // The size of the corresponding amino-encoded TxMessage
  266. // can't be larger than the maxMsgSize, otherwise we can't
  267. // relay it to peers.
  268. if len(tx) > maxTxSize {
  269. return ErrTxTooLarge
  270. }
  271. if mem.preCheck != nil {
  272. if err := mem.preCheck(tx); err != nil {
  273. return ErrPreCheck{err}
  274. }
  275. }
  276. // CACHE
  277. if !mem.cache.Push(tx) {
  278. return ErrTxInCache
  279. }
  280. // END CACHE
  281. // WAL
  282. if mem.wal != nil {
  283. // TODO: Notify administrators when WAL fails
  284. _, err := mem.wal.Write([]byte(tx))
  285. if err != nil {
  286. mem.logger.Error("Error writing to WAL", "err", err)
  287. }
  288. _, err = mem.wal.Write([]byte("\n"))
  289. if err != nil {
  290. mem.logger.Error("Error writing to WAL", "err", err)
  291. }
  292. }
  293. // END WAL
  294. // NOTE: proxyAppConn may error if tx buffer is full
  295. if err = mem.proxyAppConn.Error(); err != nil {
  296. return err
  297. }
  298. reqRes := mem.proxyAppConn.CheckTxAsync(tx)
  299. if cb != nil {
  300. reqRes.SetCallback(cb)
  301. }
  302. return nil
  303. }
  304. // ABCI callback function
  305. func (mem *Mempool) resCb(req *abci.Request, res *abci.Response) {
  306. if mem.recheckCursor == nil {
  307. mem.resCbNormal(req, res)
  308. } else {
  309. mem.metrics.RecheckTimes.Add(1)
  310. mem.resCbRecheck(req, res)
  311. }
  312. mem.metrics.Size.Set(float64(mem.Size()))
  313. }
  314. func (mem *Mempool) resCbNormal(req *abci.Request, res *abci.Response) {
  315. switch r := res.Value.(type) {
  316. case *abci.Response_CheckTx:
  317. tx := req.GetCheckTx().Tx
  318. var postCheckErr error
  319. if mem.postCheck != nil {
  320. postCheckErr = mem.postCheck(tx, r.CheckTx)
  321. }
  322. if (r.CheckTx.Code == abci.CodeTypeOK) && postCheckErr == nil {
  323. memTx := &mempoolTx{
  324. height: mem.height,
  325. gasWanted: r.CheckTx.GasWanted,
  326. tx: tx,
  327. }
  328. mem.txs.PushBack(memTx)
  329. mem.logger.Info("Added good transaction",
  330. "tx", TxID(tx),
  331. "res", r,
  332. "height", memTx.height,
  333. "total", mem.Size(),
  334. )
  335. mem.metrics.TxSizeBytes.Observe(float64(len(tx)))
  336. mem.notifyTxsAvailable()
  337. } else {
  338. // ignore bad transaction
  339. mem.logger.Info("Rejected bad transaction", "tx", TxID(tx), "res", r, "err", postCheckErr)
  340. mem.metrics.FailedTxs.Add(1)
  341. // remove from cache (it might be good later)
  342. mem.cache.Remove(tx)
  343. }
  344. default:
  345. // ignore other messages
  346. }
  347. }
  348. func (mem *Mempool) resCbRecheck(req *abci.Request, res *abci.Response) {
  349. switch r := res.Value.(type) {
  350. case *abci.Response_CheckTx:
  351. tx := req.GetCheckTx().Tx
  352. memTx := mem.recheckCursor.Value.(*mempoolTx)
  353. if !bytes.Equal(req.GetCheckTx().Tx, memTx.tx) {
  354. cmn.PanicSanity(
  355. fmt.Sprintf(
  356. "Unexpected tx response from proxy during recheck\nExpected %X, got %X",
  357. r.CheckTx.Data,
  358. memTx.tx,
  359. ),
  360. )
  361. }
  362. var postCheckErr error
  363. if mem.postCheck != nil {
  364. postCheckErr = mem.postCheck(tx, r.CheckTx)
  365. }
  366. if (r.CheckTx.Code == abci.CodeTypeOK) && postCheckErr == nil {
  367. // Good, nothing to do.
  368. } else {
  369. // Tx became invalidated due to newly committed block.
  370. mem.logger.Info("Tx is no longer valid", "tx", TxID(tx), "res", r, "err", postCheckErr)
  371. mem.txs.Remove(mem.recheckCursor)
  372. mem.recheckCursor.DetachPrev()
  373. // remove from cache (it might be good later)
  374. mem.cache.Remove(tx)
  375. }
  376. if mem.recheckCursor == mem.recheckEnd {
  377. mem.recheckCursor = nil
  378. } else {
  379. mem.recheckCursor = mem.recheckCursor.Next()
  380. }
  381. if mem.recheckCursor == nil {
  382. // Done!
  383. atomic.StoreInt32(&mem.rechecking, 0)
  384. mem.logger.Info("Done rechecking txs")
  385. // incase the recheck removed all txs
  386. if mem.Size() > 0 {
  387. mem.notifyTxsAvailable()
  388. }
  389. }
  390. default:
  391. // ignore other messages
  392. }
  393. }
  394. // TxsAvailable returns a channel which fires once for every height,
  395. // and only when transactions are available in the mempool.
  396. // NOTE: the returned channel may be nil if EnableTxsAvailable was not called.
  397. func (mem *Mempool) TxsAvailable() <-chan struct{} {
  398. return mem.txsAvailable
  399. }
  400. func (mem *Mempool) notifyTxsAvailable() {
  401. if mem.Size() == 0 {
  402. panic("notified txs available but mempool is empty!")
  403. }
  404. if mem.txsAvailable != nil && !mem.notifiedTxsAvailable {
  405. // channel cap is 1, so this will send once
  406. mem.notifiedTxsAvailable = true
  407. select {
  408. case mem.txsAvailable <- struct{}{}:
  409. default:
  410. }
  411. }
  412. }
  413. // ReapMaxBytesMaxGas reaps transactions from the mempool up to maxBytes bytes total
  414. // with the condition that the total gasWanted must be less than maxGas.
  415. // If both maxes are negative, there is no cap on the size of all returned
  416. // transactions (~ all available transactions).
  417. func (mem *Mempool) ReapMaxBytesMaxGas(maxBytes, maxGas int64) types.Txs {
  418. mem.proxyMtx.Lock()
  419. defer mem.proxyMtx.Unlock()
  420. for atomic.LoadInt32(&mem.rechecking) > 0 {
  421. // TODO: Something better?
  422. time.Sleep(time.Millisecond * 10)
  423. }
  424. var totalBytes int64
  425. var totalGas int64
  426. // TODO: we will get a performance boost if we have a good estimate of avg
  427. // size per tx, and set the initial capacity based off of that.
  428. // txs := make([]types.Tx, 0, cmn.MinInt(mem.txs.Len(), max/mem.avgTxSize))
  429. txs := make([]types.Tx, 0, mem.txs.Len())
  430. for e := mem.txs.Front(); e != nil; e = e.Next() {
  431. memTx := e.Value.(*mempoolTx)
  432. // Check total size requirement
  433. aminoOverhead := types.ComputeAminoOverhead(memTx.tx, 1)
  434. if maxBytes > -1 && totalBytes+int64(len(memTx.tx))+aminoOverhead > maxBytes {
  435. return txs
  436. }
  437. totalBytes += int64(len(memTx.tx)) + aminoOverhead
  438. // Check total gas requirement.
  439. // If maxGas is negative, skip this check.
  440. // Since newTotalGas < masGas, which
  441. // must be non-negative, it follows that this won't overflow.
  442. newTotalGas := totalGas + memTx.gasWanted
  443. if maxGas > -1 && newTotalGas > maxGas {
  444. return txs
  445. }
  446. totalGas = newTotalGas
  447. txs = append(txs, memTx.tx)
  448. }
  449. return txs
  450. }
  451. // ReapMaxTxs reaps up to max transactions from the mempool.
  452. // If max is negative, there is no cap on the size of all returned
  453. // transactions (~ all available transactions).
  454. func (mem *Mempool) ReapMaxTxs(max int) types.Txs {
  455. mem.proxyMtx.Lock()
  456. defer mem.proxyMtx.Unlock()
  457. if max < 0 {
  458. max = mem.txs.Len()
  459. }
  460. for atomic.LoadInt32(&mem.rechecking) > 0 {
  461. // TODO: Something better?
  462. time.Sleep(time.Millisecond * 10)
  463. }
  464. txs := make([]types.Tx, 0, cmn.MinInt(mem.txs.Len(), max))
  465. for e := mem.txs.Front(); e != nil && len(txs) <= max; e = e.Next() {
  466. memTx := e.Value.(*mempoolTx)
  467. txs = append(txs, memTx.tx)
  468. }
  469. return txs
  470. }
  471. // Update informs the mempool that the given txs were committed and can be discarded.
  472. // NOTE: this should be called *after* block is committed by consensus.
  473. // NOTE: unsafe; Lock/Unlock must be managed by caller
  474. func (mem *Mempool) Update(
  475. height int64,
  476. txs types.Txs,
  477. preCheck PreCheckFunc,
  478. postCheck PostCheckFunc,
  479. ) error {
  480. // Set height
  481. mem.height = height
  482. mem.notifiedTxsAvailable = false
  483. if preCheck != nil {
  484. mem.preCheck = preCheck
  485. }
  486. if postCheck != nil {
  487. mem.postCheck = postCheck
  488. }
  489. // Add committed transactions to cache (if missing).
  490. for _, tx := range txs {
  491. _ = mem.cache.Push(tx)
  492. }
  493. // Remove committed transactions.
  494. txsLeft := mem.removeTxs(txs)
  495. // Either recheck non-committed txs to see if they became invalid
  496. // or just notify there're some txs left.
  497. if len(txsLeft) > 0 {
  498. if mem.config.Recheck {
  499. mem.logger.Info("Recheck txs", "numtxs", len(txsLeft), "height", height)
  500. mem.recheckTxs(txsLeft)
  501. // At this point, mem.txs are being rechecked.
  502. // mem.recheckCursor re-scans mem.txs and possibly removes some txs.
  503. // Before mem.Reap(), we should wait for mem.recheckCursor to be nil.
  504. } else {
  505. mem.notifyTxsAvailable()
  506. }
  507. }
  508. // Update metrics
  509. mem.metrics.Size.Set(float64(mem.Size()))
  510. return nil
  511. }
  512. func (mem *Mempool) removeTxs(txs types.Txs) []types.Tx {
  513. // Build a map for faster lookups.
  514. txsMap := make(map[string]struct{}, len(txs))
  515. for _, tx := range txs {
  516. txsMap[string(tx)] = struct{}{}
  517. }
  518. txsLeft := make([]types.Tx, 0, mem.txs.Len())
  519. for e := mem.txs.Front(); e != nil; e = e.Next() {
  520. memTx := e.Value.(*mempoolTx)
  521. // Remove the tx if it's already in a block.
  522. if _, ok := txsMap[string(memTx.tx)]; ok {
  523. // remove from clist
  524. mem.txs.Remove(e)
  525. e.DetachPrev()
  526. // NOTE: we don't remove committed txs from the cache.
  527. continue
  528. }
  529. txsLeft = append(txsLeft, memTx.tx)
  530. }
  531. return txsLeft
  532. }
  533. // NOTE: pass in txs because mem.txs can mutate concurrently.
  534. func (mem *Mempool) recheckTxs(txs []types.Tx) {
  535. if len(txs) == 0 {
  536. return
  537. }
  538. atomic.StoreInt32(&mem.rechecking, 1)
  539. mem.recheckCursor = mem.txs.Front()
  540. mem.recheckEnd = mem.txs.Back()
  541. // Push txs to proxyAppConn
  542. // NOTE: resCb() may be called concurrently.
  543. for _, tx := range txs {
  544. mem.proxyAppConn.CheckTxAsync(tx)
  545. }
  546. mem.proxyAppConn.FlushAsync()
  547. }
  548. //--------------------------------------------------------------------------------
  549. // mempoolTx is a transaction that successfully ran
  550. type mempoolTx struct {
  551. height int64 // height that this tx had been validated in
  552. gasWanted int64 // amount of gas this tx states it will require
  553. tx types.Tx //
  554. }
  555. // Height returns the height for this transaction
  556. func (memTx *mempoolTx) Height() int64 {
  557. return atomic.LoadInt64(&memTx.height)
  558. }
  559. //--------------------------------------------------------------------------------
  560. type txCache interface {
  561. Reset()
  562. Push(tx types.Tx) bool
  563. Remove(tx types.Tx)
  564. }
  565. // mapTxCache maintains a cache of transactions. This only stores
  566. // the hash of the tx, due to memory concerns.
  567. type mapTxCache struct {
  568. mtx sync.Mutex
  569. size int
  570. map_ map[[sha256.Size]byte]*list.Element
  571. list *list.List // to remove oldest tx when cache gets too big
  572. }
  573. var _ txCache = (*mapTxCache)(nil)
  574. // newMapTxCache returns a new mapTxCache.
  575. func newMapTxCache(cacheSize int) *mapTxCache {
  576. return &mapTxCache{
  577. size: cacheSize,
  578. map_: make(map[[sha256.Size]byte]*list.Element, cacheSize),
  579. list: list.New(),
  580. }
  581. }
  582. // Reset resets the cache to an empty state.
  583. func (cache *mapTxCache) Reset() {
  584. cache.mtx.Lock()
  585. cache.map_ = make(map[[sha256.Size]byte]*list.Element, cache.size)
  586. cache.list.Init()
  587. cache.mtx.Unlock()
  588. }
  589. // Push adds the given tx to the cache and returns true. It returns false if tx
  590. // is already in the cache.
  591. func (cache *mapTxCache) Push(tx types.Tx) bool {
  592. cache.mtx.Lock()
  593. defer cache.mtx.Unlock()
  594. // Use the tx hash in the cache
  595. txHash := sha256.Sum256(tx)
  596. if moved, exists := cache.map_[txHash]; exists {
  597. cache.list.MoveToBack(moved)
  598. return false
  599. }
  600. if cache.list.Len() >= cache.size {
  601. popped := cache.list.Front()
  602. poppedTxHash := popped.Value.([sha256.Size]byte)
  603. delete(cache.map_, poppedTxHash)
  604. if popped != nil {
  605. cache.list.Remove(popped)
  606. }
  607. }
  608. cache.list.PushBack(txHash)
  609. cache.map_[txHash] = cache.list.Back()
  610. return true
  611. }
  612. // Remove removes the given tx from the cache.
  613. func (cache *mapTxCache) Remove(tx types.Tx) {
  614. cache.mtx.Lock()
  615. txHash := sha256.Sum256(tx)
  616. popped := cache.map_[txHash]
  617. delete(cache.map_, txHash)
  618. if popped != nil {
  619. cache.list.Remove(popped)
  620. }
  621. cache.mtx.Unlock()
  622. }
  623. type nopTxCache struct{}
  624. var _ txCache = (*nopTxCache)(nil)
  625. func (nopTxCache) Reset() {}
  626. func (nopTxCache) Push(types.Tx) bool { return true }
  627. func (nopTxCache) Remove(types.Tx) {}