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.

722 lines
20 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(tx, memTx.tx) {
  354. panic(fmt.Sprintf(
  355. "Unexpected tx response from proxy during recheck\nExpected %X, got %X",
  356. memTx.tx,
  357. tx))
  358. }
  359. var postCheckErr error
  360. if mem.postCheck != nil {
  361. postCheckErr = mem.postCheck(tx, r.CheckTx)
  362. }
  363. if (r.CheckTx.Code == abci.CodeTypeOK) && postCheckErr == nil {
  364. // Good, nothing to do.
  365. } else {
  366. // Tx became invalidated due to newly committed block.
  367. mem.logger.Info("Tx is no longer valid", "tx", TxID(tx), "res", r, "err", postCheckErr)
  368. mem.txs.Remove(mem.recheckCursor)
  369. mem.recheckCursor.DetachPrev()
  370. // remove from cache (it might be good later)
  371. mem.cache.Remove(tx)
  372. }
  373. if mem.recheckCursor == mem.recheckEnd {
  374. mem.recheckCursor = nil
  375. } else {
  376. mem.recheckCursor = mem.recheckCursor.Next()
  377. }
  378. if mem.recheckCursor == nil {
  379. // Done!
  380. atomic.StoreInt32(&mem.rechecking, 0)
  381. mem.logger.Info("Done rechecking txs")
  382. // incase the recheck removed all txs
  383. if mem.Size() > 0 {
  384. mem.notifyTxsAvailable()
  385. }
  386. }
  387. default:
  388. // ignore other messages
  389. }
  390. }
  391. // TxsAvailable returns a channel which fires once for every height,
  392. // and only when transactions are available in the mempool.
  393. // NOTE: the returned channel may be nil if EnableTxsAvailable was not called.
  394. func (mem *Mempool) TxsAvailable() <-chan struct{} {
  395. return mem.txsAvailable
  396. }
  397. func (mem *Mempool) notifyTxsAvailable() {
  398. if mem.Size() == 0 {
  399. panic("notified txs available but mempool is empty!")
  400. }
  401. if mem.txsAvailable != nil && !mem.notifiedTxsAvailable {
  402. // channel cap is 1, so this will send once
  403. mem.notifiedTxsAvailable = true
  404. select {
  405. case mem.txsAvailable <- struct{}{}:
  406. default:
  407. }
  408. }
  409. }
  410. // ReapMaxBytesMaxGas reaps transactions from the mempool up to maxBytes bytes total
  411. // with the condition that the total gasWanted must be less than maxGas.
  412. // If both maxes are negative, there is no cap on the size of all returned
  413. // transactions (~ all available transactions).
  414. func (mem *Mempool) ReapMaxBytesMaxGas(maxBytes, maxGas int64) types.Txs {
  415. mem.proxyMtx.Lock()
  416. defer mem.proxyMtx.Unlock()
  417. for atomic.LoadInt32(&mem.rechecking) > 0 {
  418. // TODO: Something better?
  419. time.Sleep(time.Millisecond * 10)
  420. }
  421. var totalBytes int64
  422. var totalGas int64
  423. // TODO: we will get a performance boost if we have a good estimate of avg
  424. // size per tx, and set the initial capacity based off of that.
  425. // txs := make([]types.Tx, 0, cmn.MinInt(mem.txs.Len(), max/mem.avgTxSize))
  426. txs := make([]types.Tx, 0, mem.txs.Len())
  427. for e := mem.txs.Front(); e != nil; e = e.Next() {
  428. memTx := e.Value.(*mempoolTx)
  429. // Check total size requirement
  430. aminoOverhead := types.ComputeAminoOverhead(memTx.tx, 1)
  431. if maxBytes > -1 && totalBytes+int64(len(memTx.tx))+aminoOverhead > maxBytes {
  432. return txs
  433. }
  434. totalBytes += int64(len(memTx.tx)) + aminoOverhead
  435. // Check total gas requirement.
  436. // If maxGas is negative, skip this check.
  437. // Since newTotalGas < masGas, which
  438. // must be non-negative, it follows that this won't overflow.
  439. newTotalGas := totalGas + memTx.gasWanted
  440. if maxGas > -1 && newTotalGas > maxGas {
  441. return txs
  442. }
  443. totalGas = newTotalGas
  444. txs = append(txs, memTx.tx)
  445. }
  446. return txs
  447. }
  448. // ReapMaxTxs reaps up to max transactions from the mempool.
  449. // If max is negative, there is no cap on the size of all returned
  450. // transactions (~ all available transactions).
  451. func (mem *Mempool) ReapMaxTxs(max int) types.Txs {
  452. mem.proxyMtx.Lock()
  453. defer mem.proxyMtx.Unlock()
  454. if max < 0 {
  455. max = mem.txs.Len()
  456. }
  457. for atomic.LoadInt32(&mem.rechecking) > 0 {
  458. // TODO: Something better?
  459. time.Sleep(time.Millisecond * 10)
  460. }
  461. txs := make([]types.Tx, 0, cmn.MinInt(mem.txs.Len(), max))
  462. for e := mem.txs.Front(); e != nil && len(txs) <= max; e = e.Next() {
  463. memTx := e.Value.(*mempoolTx)
  464. txs = append(txs, memTx.tx)
  465. }
  466. return txs
  467. }
  468. // Update informs the mempool that the given txs were committed and can be discarded.
  469. // NOTE: this should be called *after* block is committed by consensus.
  470. // NOTE: unsafe; Lock/Unlock must be managed by caller
  471. func (mem *Mempool) Update(
  472. height int64,
  473. txs types.Txs,
  474. preCheck PreCheckFunc,
  475. postCheck PostCheckFunc,
  476. ) error {
  477. // Set height
  478. mem.height = height
  479. mem.notifiedTxsAvailable = false
  480. if preCheck != nil {
  481. mem.preCheck = preCheck
  482. }
  483. if postCheck != nil {
  484. mem.postCheck = postCheck
  485. }
  486. // Add committed transactions to cache (if missing).
  487. for _, tx := range txs {
  488. _ = mem.cache.Push(tx)
  489. }
  490. // Remove committed transactions.
  491. txsLeft := mem.removeTxs(txs)
  492. // Either recheck non-committed txs to see if they became invalid
  493. // or just notify there're some txs left.
  494. if len(txsLeft) > 0 {
  495. if mem.config.Recheck {
  496. mem.logger.Info("Recheck txs", "numtxs", len(txsLeft), "height", height)
  497. mem.recheckTxs(txsLeft)
  498. // At this point, mem.txs are being rechecked.
  499. // mem.recheckCursor re-scans mem.txs and possibly removes some txs.
  500. // Before mem.Reap(), we should wait for mem.recheckCursor to be nil.
  501. } else {
  502. mem.notifyTxsAvailable()
  503. }
  504. }
  505. // Update metrics
  506. mem.metrics.Size.Set(float64(mem.Size()))
  507. return nil
  508. }
  509. func (mem *Mempool) removeTxs(txs types.Txs) []types.Tx {
  510. // Build a map for faster lookups.
  511. txsMap := make(map[string]struct{}, len(txs))
  512. for _, tx := range txs {
  513. txsMap[string(tx)] = struct{}{}
  514. }
  515. txsLeft := make([]types.Tx, 0, mem.txs.Len())
  516. for e := mem.txs.Front(); e != nil; e = e.Next() {
  517. memTx := e.Value.(*mempoolTx)
  518. // Remove the tx if it's already in a block.
  519. if _, ok := txsMap[string(memTx.tx)]; ok {
  520. // remove from clist
  521. mem.txs.Remove(e)
  522. e.DetachPrev()
  523. // NOTE: we don't remove committed txs from the cache.
  524. continue
  525. }
  526. txsLeft = append(txsLeft, memTx.tx)
  527. }
  528. return txsLeft
  529. }
  530. // NOTE: pass in txs because mem.txs can mutate concurrently.
  531. func (mem *Mempool) recheckTxs(txs []types.Tx) {
  532. if len(txs) == 0 {
  533. return
  534. }
  535. atomic.StoreInt32(&mem.rechecking, 1)
  536. mem.recheckCursor = mem.txs.Front()
  537. mem.recheckEnd = mem.txs.Back()
  538. // Push txs to proxyAppConn
  539. // NOTE: resCb() may be called concurrently.
  540. for _, tx := range txs {
  541. mem.proxyAppConn.CheckTxAsync(tx)
  542. }
  543. mem.proxyAppConn.FlushAsync()
  544. }
  545. //--------------------------------------------------------------------------------
  546. // mempoolTx is a transaction that successfully ran
  547. type mempoolTx struct {
  548. height int64 // height that this tx had been validated in
  549. gasWanted int64 // amount of gas this tx states it will require
  550. tx types.Tx //
  551. }
  552. // Height returns the height for this transaction
  553. func (memTx *mempoolTx) Height() int64 {
  554. return atomic.LoadInt64(&memTx.height)
  555. }
  556. //--------------------------------------------------------------------------------
  557. type txCache interface {
  558. Reset()
  559. Push(tx types.Tx) bool
  560. Remove(tx types.Tx)
  561. }
  562. // mapTxCache maintains a cache of transactions. This only stores
  563. // the hash of the tx, due to memory concerns.
  564. type mapTxCache struct {
  565. mtx sync.Mutex
  566. size int
  567. map_ map[[sha256.Size]byte]*list.Element
  568. list *list.List // to remove oldest tx when cache gets too big
  569. }
  570. var _ txCache = (*mapTxCache)(nil)
  571. // newMapTxCache returns a new mapTxCache.
  572. func newMapTxCache(cacheSize int) *mapTxCache {
  573. return &mapTxCache{
  574. size: cacheSize,
  575. map_: make(map[[sha256.Size]byte]*list.Element, cacheSize),
  576. list: list.New(),
  577. }
  578. }
  579. // Reset resets the cache to an empty state.
  580. func (cache *mapTxCache) Reset() {
  581. cache.mtx.Lock()
  582. cache.map_ = make(map[[sha256.Size]byte]*list.Element, cache.size)
  583. cache.list.Init()
  584. cache.mtx.Unlock()
  585. }
  586. // Push adds the given tx to the cache and returns true. It returns false if tx
  587. // is already in the cache.
  588. func (cache *mapTxCache) Push(tx types.Tx) bool {
  589. cache.mtx.Lock()
  590. defer cache.mtx.Unlock()
  591. // Use the tx hash in the cache
  592. txHash := sha256.Sum256(tx)
  593. if moved, exists := cache.map_[txHash]; exists {
  594. cache.list.MoveToBack(moved)
  595. return false
  596. }
  597. if cache.list.Len() >= cache.size {
  598. popped := cache.list.Front()
  599. poppedTxHash := popped.Value.([sha256.Size]byte)
  600. delete(cache.map_, poppedTxHash)
  601. if popped != nil {
  602. cache.list.Remove(popped)
  603. }
  604. }
  605. cache.list.PushBack(txHash)
  606. cache.map_[txHash] = cache.list.Back()
  607. return true
  608. }
  609. // Remove removes the given tx from the cache.
  610. func (cache *mapTxCache) Remove(tx types.Tx) {
  611. cache.mtx.Lock()
  612. txHash := sha256.Sum256(tx)
  613. popped := cache.map_[txHash]
  614. delete(cache.map_, txHash)
  615. if popped != nil {
  616. cache.list.Remove(popped)
  617. }
  618. cache.mtx.Unlock()
  619. }
  620. type nopTxCache struct{}
  621. var _ txCache = (*nopTxCache)(nil)
  622. func (nopTxCache) Reset() {}
  623. func (nopTxCache) Push(types.Tx) bool { return true }
  624. func (nopTxCache) Remove(types.Tx) {}