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.

715 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
8 years ago
9 years ago
8 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
8 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. )
  54. // ErrPreCheck is returned when tx is too big
  55. type ErrPreCheck struct {
  56. Reason error
  57. }
  58. func (e ErrPreCheck) Error() string {
  59. return e.Reason.Error()
  60. }
  61. // IsPreCheckError returns true if err is due to pre check failure.
  62. func IsPreCheckError(err error) bool {
  63. _, ok := err.(ErrPreCheck)
  64. return ok
  65. }
  66. // PreCheckAminoMaxBytes checks that the size of the transaction plus the amino
  67. // overhead is smaller or equal to the expected maxBytes.
  68. func PreCheckAminoMaxBytes(maxBytes int64) PreCheckFunc {
  69. return func(tx types.Tx) error {
  70. // We have to account for the amino overhead in the tx size as well
  71. // NOTE: fieldNum = 1 as types.Block.Data contains Txs []Tx as first field.
  72. // If this field order ever changes this needs to updated here accordingly.
  73. // NOTE: if some []Tx are encoded without a parenting struct, the
  74. // fieldNum is also equal to 1.
  75. aminoOverhead := types.ComputeAminoOverhead(tx, 1)
  76. txSize := int64(len(tx)) + aminoOverhead
  77. if txSize > maxBytes {
  78. return fmt.Errorf("Tx size (including amino overhead) is too big: %d, max: %d",
  79. txSize, maxBytes)
  80. }
  81. return nil
  82. }
  83. }
  84. // PostCheckMaxGas checks that the wanted gas is smaller or equal to the passed
  85. // maxGas. Returns nil if maxGas is -1.
  86. func PostCheckMaxGas(maxGas int64) PostCheckFunc {
  87. return func(tx types.Tx, res *abci.ResponseCheckTx) error {
  88. if maxGas == -1 {
  89. return nil
  90. }
  91. if res.GasWanted < 0 {
  92. return fmt.Errorf("gas wanted %d is negative",
  93. res.GasWanted)
  94. }
  95. if res.GasWanted > maxGas {
  96. return fmt.Errorf("gas wanted %d is greater than max gas %d",
  97. res.GasWanted, maxGas)
  98. }
  99. return nil
  100. }
  101. }
  102. // TxID is the hex encoded hash of the bytes as a types.Tx.
  103. func TxID(tx []byte) string {
  104. return fmt.Sprintf("%X", types.Tx(tx).Hash())
  105. }
  106. // Mempool is an ordered in-memory pool for transactions before they are proposed in a consensus
  107. // round. Transaction validity is checked using the CheckTx abci message before the transaction is
  108. // added to the pool. The Mempool uses a concurrent list structure for storing transactions that
  109. // can be efficiently accessed by multiple concurrent readers.
  110. type Mempool struct {
  111. config *cfg.MempoolConfig
  112. proxyMtx sync.Mutex
  113. proxyAppConn proxy.AppConnMempool
  114. txs *clist.CList // concurrent linked-list of good txs
  115. height int64 // the last block Update()'d to
  116. rechecking int32 // for re-checking filtered txs on Update()
  117. recheckCursor *clist.CElement // next expected response
  118. recheckEnd *clist.CElement // re-checking stops here
  119. notifiedTxsAvailable bool
  120. txsAvailable chan struct{} // fires once for each height, when the mempool is not empty
  121. preCheck PreCheckFunc
  122. postCheck PostCheckFunc
  123. // Keep a cache of already-seen txs.
  124. // This reduces the pressure on the proxyApp.
  125. cache txCache
  126. // A log of mempool txs
  127. wal *auto.AutoFile
  128. logger log.Logger
  129. metrics *Metrics
  130. }
  131. // MempoolOption sets an optional parameter on the Mempool.
  132. type MempoolOption func(*Mempool)
  133. // NewMempool returns a new Mempool with the given configuration and connection to an application.
  134. func NewMempool(
  135. config *cfg.MempoolConfig,
  136. proxyAppConn proxy.AppConnMempool,
  137. height int64,
  138. options ...MempoolOption,
  139. ) *Mempool {
  140. mempool := &Mempool{
  141. config: config,
  142. proxyAppConn: proxyAppConn,
  143. txs: clist.New(),
  144. height: height,
  145. rechecking: 0,
  146. recheckCursor: nil,
  147. recheckEnd: nil,
  148. logger: log.NewNopLogger(),
  149. metrics: NopMetrics(),
  150. }
  151. if config.CacheSize > 0 {
  152. mempool.cache = newMapTxCache(config.CacheSize)
  153. } else {
  154. mempool.cache = nopTxCache{}
  155. }
  156. proxyAppConn.SetResponseCallback(mempool.resCb)
  157. for _, option := range options {
  158. option(mempool)
  159. }
  160. return mempool
  161. }
  162. // EnableTxsAvailable initializes the TxsAvailable channel,
  163. // ensuring it will trigger once every height when transactions are available.
  164. // NOTE: not thread safe - should only be called once, on startup
  165. func (mem *Mempool) EnableTxsAvailable() {
  166. mem.txsAvailable = make(chan struct{}, 1)
  167. }
  168. // SetLogger sets the Logger.
  169. func (mem *Mempool) SetLogger(l log.Logger) {
  170. mem.logger = l
  171. }
  172. // WithPreCheck sets a filter for the mempool to reject a tx if f(tx) returns
  173. // false. This is ran before CheckTx.
  174. func WithPreCheck(f PreCheckFunc) MempoolOption {
  175. return func(mem *Mempool) { mem.preCheck = f }
  176. }
  177. // WithPostCheck sets a filter for the mempool to reject a tx if f(tx) returns
  178. // false. This is ran after CheckTx.
  179. func WithPostCheck(f PostCheckFunc) MempoolOption {
  180. return func(mem *Mempool) { mem.postCheck = f }
  181. }
  182. // WithMetrics sets the metrics.
  183. func WithMetrics(metrics *Metrics) MempoolOption {
  184. return func(mem *Mempool) { mem.metrics = metrics }
  185. }
  186. // InitWAL creates a directory for the WAL file and opens a file itself.
  187. //
  188. // *panics* if can't create directory or open file.
  189. // *not thread safe*
  190. func (mem *Mempool) InitWAL() {
  191. walDir := mem.config.WalDir()
  192. err := cmn.EnsureDir(walDir, 0700)
  193. if err != nil {
  194. panic(errors.Wrap(err, "Error ensuring Mempool WAL dir"))
  195. }
  196. af, err := auto.OpenAutoFile(walDir + "/wal")
  197. if err != nil {
  198. panic(errors.Wrap(err, "Error opening Mempool WAL file"))
  199. }
  200. mem.wal = af
  201. }
  202. // CloseWAL closes and discards the underlying WAL file.
  203. // Any further writes will not be relayed to disk.
  204. func (mem *Mempool) CloseWAL() {
  205. mem.proxyMtx.Lock()
  206. defer mem.proxyMtx.Unlock()
  207. if err := mem.wal.Close(); err != nil {
  208. mem.logger.Error("Error closing WAL", "err", err)
  209. }
  210. mem.wal = nil
  211. }
  212. // Lock locks the mempool. The consensus must be able to hold lock to safely update.
  213. func (mem *Mempool) Lock() {
  214. mem.proxyMtx.Lock()
  215. }
  216. // Unlock unlocks the mempool.
  217. func (mem *Mempool) Unlock() {
  218. mem.proxyMtx.Unlock()
  219. }
  220. // Size returns the number of transactions in the mempool.
  221. func (mem *Mempool) Size() int {
  222. return mem.txs.Len()
  223. }
  224. // Flushes the mempool connection to ensure async resCb calls are done e.g.
  225. // from CheckTx.
  226. func (mem *Mempool) FlushAppConn() error {
  227. return mem.proxyAppConn.FlushSync()
  228. }
  229. // Flush removes all transactions from the mempool and cache
  230. func (mem *Mempool) Flush() {
  231. mem.proxyMtx.Lock()
  232. defer mem.proxyMtx.Unlock()
  233. mem.cache.Reset()
  234. for e := mem.txs.Front(); e != nil; e = e.Next() {
  235. mem.txs.Remove(e)
  236. e.DetachPrev()
  237. }
  238. }
  239. // TxsFront returns the first transaction in the ordered list for peer
  240. // goroutines to call .NextWait() on.
  241. func (mem *Mempool) TxsFront() *clist.CElement {
  242. return mem.txs.Front()
  243. }
  244. // TxsWaitChan returns a channel to wait on transactions. It will be closed
  245. // once the mempool is not empty (ie. the internal `mem.txs` has at least one
  246. // element)
  247. func (mem *Mempool) TxsWaitChan() <-chan struct{} {
  248. return mem.txs.WaitChan()
  249. }
  250. // CheckTx executes a new transaction against the application to determine its validity
  251. // and whether it should be added to the mempool.
  252. // It blocks if we're waiting on Update() or Reap().
  253. // cb: A callback from the CheckTx command.
  254. // It gets called from another goroutine.
  255. // CONTRACT: Either cb will get called, or err returned.
  256. func (mem *Mempool) CheckTx(tx types.Tx, cb func(*abci.Response)) (err error) {
  257. mem.proxyMtx.Lock()
  258. // use defer to unlock mutex because application (*local client*) might panic
  259. defer mem.proxyMtx.Unlock()
  260. if mem.Size() >= mem.config.Size {
  261. return ErrMempoolIsFull
  262. }
  263. if mem.preCheck != nil {
  264. if err := mem.preCheck(tx); err != nil {
  265. return ErrPreCheck{err}
  266. }
  267. }
  268. // CACHE
  269. if !mem.cache.Push(tx) {
  270. return ErrTxInCache
  271. }
  272. // END CACHE
  273. // WAL
  274. if mem.wal != nil {
  275. // TODO: Notify administrators when WAL fails
  276. _, err := mem.wal.Write([]byte(tx))
  277. if err != nil {
  278. mem.logger.Error("Error writing to WAL", "err", err)
  279. }
  280. _, err = mem.wal.Write([]byte("\n"))
  281. if err != nil {
  282. mem.logger.Error("Error writing to WAL", "err", err)
  283. }
  284. }
  285. // END WAL
  286. // NOTE: proxyAppConn may error if tx buffer is full
  287. if err = mem.proxyAppConn.Error(); err != nil {
  288. return err
  289. }
  290. reqRes := mem.proxyAppConn.CheckTxAsync(tx)
  291. if cb != nil {
  292. reqRes.SetCallback(cb)
  293. }
  294. return nil
  295. }
  296. // ABCI callback function
  297. func (mem *Mempool) resCb(req *abci.Request, res *abci.Response) {
  298. if mem.recheckCursor == nil {
  299. mem.resCbNormal(req, res)
  300. } else {
  301. mem.metrics.RecheckTimes.Add(1)
  302. mem.resCbRecheck(req, res)
  303. }
  304. mem.metrics.Size.Set(float64(mem.Size()))
  305. }
  306. func (mem *Mempool) resCbNormal(req *abci.Request, res *abci.Response) {
  307. switch r := res.Value.(type) {
  308. case *abci.Response_CheckTx:
  309. tx := req.GetCheckTx().Tx
  310. var postCheckErr error
  311. if mem.postCheck != nil {
  312. postCheckErr = mem.postCheck(tx, r.CheckTx)
  313. }
  314. if (r.CheckTx.Code == abci.CodeTypeOK) && postCheckErr == nil {
  315. memTx := &mempoolTx{
  316. height: mem.height,
  317. gasWanted: r.CheckTx.GasWanted,
  318. tx: tx,
  319. }
  320. mem.txs.PushBack(memTx)
  321. mem.logger.Info("Added good transaction",
  322. "tx", TxID(tx),
  323. "res", r,
  324. "height", memTx.height,
  325. "total", mem.Size(),
  326. )
  327. mem.metrics.TxSizeBytes.Observe(float64(len(tx)))
  328. mem.notifyTxsAvailable()
  329. } else {
  330. // ignore bad transaction
  331. mem.logger.Info("Rejected bad transaction", "tx", TxID(tx), "res", r, "err", postCheckErr)
  332. mem.metrics.FailedTxs.Add(1)
  333. // remove from cache (it might be good later)
  334. mem.cache.Remove(tx)
  335. }
  336. default:
  337. // ignore other messages
  338. }
  339. }
  340. func (mem *Mempool) resCbRecheck(req *abci.Request, res *abci.Response) {
  341. switch r := res.Value.(type) {
  342. case *abci.Response_CheckTx:
  343. tx := req.GetCheckTx().Tx
  344. memTx := mem.recheckCursor.Value.(*mempoolTx)
  345. if !bytes.Equal(req.GetCheckTx().Tx, memTx.tx) {
  346. cmn.PanicSanity(
  347. fmt.Sprintf(
  348. "Unexpected tx response from proxy during recheck\nExpected %X, got %X",
  349. r.CheckTx.Data,
  350. memTx.tx,
  351. ),
  352. )
  353. }
  354. var postCheckErr error
  355. if mem.postCheck != nil {
  356. postCheckErr = mem.postCheck(tx, r.CheckTx)
  357. }
  358. if (r.CheckTx.Code == abci.CodeTypeOK) && postCheckErr == nil {
  359. // Good, nothing to do.
  360. } else {
  361. // Tx became invalidated due to newly committed block.
  362. mem.logger.Info("Tx is no longer valid", "tx", TxID(tx), "res", r, "err", postCheckErr)
  363. mem.txs.Remove(mem.recheckCursor)
  364. mem.recheckCursor.DetachPrev()
  365. // remove from cache (it might be good later)
  366. mem.cache.Remove(tx)
  367. }
  368. if mem.recheckCursor == mem.recheckEnd {
  369. mem.recheckCursor = nil
  370. } else {
  371. mem.recheckCursor = mem.recheckCursor.Next()
  372. }
  373. if mem.recheckCursor == nil {
  374. // Done!
  375. atomic.StoreInt32(&mem.rechecking, 0)
  376. mem.logger.Info("Done rechecking txs")
  377. // incase the recheck removed all txs
  378. if mem.Size() > 0 {
  379. mem.notifyTxsAvailable()
  380. }
  381. }
  382. default:
  383. // ignore other messages
  384. }
  385. }
  386. // TxsAvailable returns a channel which fires once for every height,
  387. // and only when transactions are available in the mempool.
  388. // NOTE: the returned channel may be nil if EnableTxsAvailable was not called.
  389. func (mem *Mempool) TxsAvailable() <-chan struct{} {
  390. return mem.txsAvailable
  391. }
  392. func (mem *Mempool) notifyTxsAvailable() {
  393. if mem.Size() == 0 {
  394. panic("notified txs available but mempool is empty!")
  395. }
  396. if mem.txsAvailable != nil && !mem.notifiedTxsAvailable {
  397. // channel cap is 1, so this will send once
  398. mem.notifiedTxsAvailable = true
  399. select {
  400. case mem.txsAvailable <- struct{}{}:
  401. default:
  402. }
  403. }
  404. }
  405. // ReapMaxBytesMaxGas reaps transactions from the mempool up to maxBytes bytes total
  406. // with the condition that the total gasWanted must be less than maxGas.
  407. // If both maxes are negative, there is no cap on the size of all returned
  408. // transactions (~ all available transactions).
  409. func (mem *Mempool) ReapMaxBytesMaxGas(maxBytes, maxGas int64) types.Txs {
  410. mem.proxyMtx.Lock()
  411. defer mem.proxyMtx.Unlock()
  412. for atomic.LoadInt32(&mem.rechecking) > 0 {
  413. // TODO: Something better?
  414. time.Sleep(time.Millisecond * 10)
  415. }
  416. var totalBytes int64
  417. var totalGas int64
  418. // TODO: we will get a performance boost if we have a good estimate of avg
  419. // size per tx, and set the initial capacity based off of that.
  420. // txs := make([]types.Tx, 0, cmn.MinInt(mem.txs.Len(), max/mem.avgTxSize))
  421. txs := make([]types.Tx, 0, mem.txs.Len())
  422. for e := mem.txs.Front(); e != nil; e = e.Next() {
  423. memTx := e.Value.(*mempoolTx)
  424. // Check total size requirement
  425. aminoOverhead := types.ComputeAminoOverhead(memTx.tx, 1)
  426. if maxBytes > -1 && totalBytes+int64(len(memTx.tx))+aminoOverhead > maxBytes {
  427. return txs
  428. }
  429. totalBytes += int64(len(memTx.tx)) + aminoOverhead
  430. // Check total gas requirement.
  431. // If maxGas is negative, skip this check.
  432. // Since newTotalGas < masGas, which
  433. // must be non-negative, it follows that this won't overflow.
  434. newTotalGas := totalGas + memTx.gasWanted
  435. if maxGas > -1 && newTotalGas > maxGas {
  436. return txs
  437. }
  438. totalGas = newTotalGas
  439. txs = append(txs, memTx.tx)
  440. }
  441. return txs
  442. }
  443. // ReapMaxTxs reaps up to max transactions from the mempool.
  444. // If max is negative, there is no cap on the size of all returned
  445. // transactions (~ all available transactions).
  446. func (mem *Mempool) ReapMaxTxs(max int) types.Txs {
  447. mem.proxyMtx.Lock()
  448. defer mem.proxyMtx.Unlock()
  449. if max < 0 {
  450. max = mem.txs.Len()
  451. }
  452. for atomic.LoadInt32(&mem.rechecking) > 0 {
  453. // TODO: Something better?
  454. time.Sleep(time.Millisecond * 10)
  455. }
  456. txs := make([]types.Tx, 0, cmn.MinInt(mem.txs.Len(), max))
  457. for e := mem.txs.Front(); e != nil && len(txs) <= max; e = e.Next() {
  458. memTx := e.Value.(*mempoolTx)
  459. txs = append(txs, memTx.tx)
  460. }
  461. return txs
  462. }
  463. // Update informs the mempool that the given txs were committed and can be discarded.
  464. // NOTE: this should be called *after* block is committed by consensus.
  465. // NOTE: unsafe; Lock/Unlock must be managed by caller
  466. func (mem *Mempool) Update(
  467. height int64,
  468. txs types.Txs,
  469. preCheck PreCheckFunc,
  470. postCheck PostCheckFunc,
  471. ) error {
  472. // Set height
  473. mem.height = height
  474. mem.notifiedTxsAvailable = false
  475. if preCheck != nil {
  476. mem.preCheck = preCheck
  477. }
  478. if postCheck != nil {
  479. mem.postCheck = postCheck
  480. }
  481. // Add committed transactions to cache (if missing).
  482. for _, tx := range txs {
  483. _ = mem.cache.Push(tx)
  484. }
  485. // Remove committed transactions.
  486. txsLeft := mem.removeTxs(txs)
  487. // Either recheck non-committed txs to see if they became invalid
  488. // or just notify there're some txs left.
  489. if len(txsLeft) > 0 {
  490. if mem.config.Recheck {
  491. mem.logger.Info("Recheck txs", "numtxs", len(txsLeft), "height", height)
  492. mem.recheckTxs(txsLeft)
  493. // At this point, mem.txs are being rechecked.
  494. // mem.recheckCursor re-scans mem.txs and possibly removes some txs.
  495. // Before mem.Reap(), we should wait for mem.recheckCursor to be nil.
  496. } else {
  497. mem.notifyTxsAvailable()
  498. }
  499. }
  500. // Update metrics
  501. mem.metrics.Size.Set(float64(mem.Size()))
  502. return nil
  503. }
  504. func (mem *Mempool) removeTxs(txs types.Txs) []types.Tx {
  505. // Build a map for faster lookups.
  506. txsMap := make(map[string]struct{}, len(txs))
  507. for _, tx := range txs {
  508. txsMap[string(tx)] = struct{}{}
  509. }
  510. txsLeft := make([]types.Tx, 0, mem.txs.Len())
  511. for e := mem.txs.Front(); e != nil; e = e.Next() {
  512. memTx := e.Value.(*mempoolTx)
  513. // Remove the tx if it's already in a block.
  514. if _, ok := txsMap[string(memTx.tx)]; ok {
  515. // remove from clist
  516. mem.txs.Remove(e)
  517. e.DetachPrev()
  518. // NOTE: we don't remove committed txs from the cache.
  519. continue
  520. }
  521. txsLeft = append(txsLeft, memTx.tx)
  522. }
  523. return txsLeft
  524. }
  525. // NOTE: pass in txs because mem.txs can mutate concurrently.
  526. func (mem *Mempool) recheckTxs(txs []types.Tx) {
  527. if len(txs) == 0 {
  528. return
  529. }
  530. atomic.StoreInt32(&mem.rechecking, 1)
  531. mem.recheckCursor = mem.txs.Front()
  532. mem.recheckEnd = mem.txs.Back()
  533. // Push txs to proxyAppConn
  534. // NOTE: resCb() may be called concurrently.
  535. for _, tx := range txs {
  536. mem.proxyAppConn.CheckTxAsync(tx)
  537. }
  538. mem.proxyAppConn.FlushAsync()
  539. }
  540. //--------------------------------------------------------------------------------
  541. // mempoolTx is a transaction that successfully ran
  542. type mempoolTx struct {
  543. height int64 // height that this tx had been validated in
  544. gasWanted int64 // amount of gas this tx states it will require
  545. tx types.Tx //
  546. }
  547. // Height returns the height for this transaction
  548. func (memTx *mempoolTx) Height() int64 {
  549. return atomic.LoadInt64(&memTx.height)
  550. }
  551. //--------------------------------------------------------------------------------
  552. type txCache interface {
  553. Reset()
  554. Push(tx types.Tx) bool
  555. Remove(tx types.Tx)
  556. }
  557. // mapTxCache maintains a cache of transactions. This only stores
  558. // the hash of the tx, due to memory concerns.
  559. type mapTxCache struct {
  560. mtx sync.Mutex
  561. size int
  562. map_ map[[sha256.Size]byte]*list.Element
  563. list *list.List // to remove oldest tx when cache gets too big
  564. }
  565. var _ txCache = (*mapTxCache)(nil)
  566. // newMapTxCache returns a new mapTxCache.
  567. func newMapTxCache(cacheSize int) *mapTxCache {
  568. return &mapTxCache{
  569. size: cacheSize,
  570. map_: make(map[[sha256.Size]byte]*list.Element, cacheSize),
  571. list: list.New(),
  572. }
  573. }
  574. // Reset resets the cache to an empty state.
  575. func (cache *mapTxCache) Reset() {
  576. cache.mtx.Lock()
  577. cache.map_ = make(map[[sha256.Size]byte]*list.Element, cache.size)
  578. cache.list.Init()
  579. cache.mtx.Unlock()
  580. }
  581. // Push adds the given tx to the cache and returns true. It returns false if tx
  582. // is already in the cache.
  583. func (cache *mapTxCache) Push(tx types.Tx) bool {
  584. cache.mtx.Lock()
  585. defer cache.mtx.Unlock()
  586. // Use the tx hash in the cache
  587. txHash := sha256.Sum256(tx)
  588. if moved, exists := cache.map_[txHash]; exists {
  589. cache.list.MoveToBack(moved)
  590. return false
  591. }
  592. if cache.list.Len() >= cache.size {
  593. popped := cache.list.Front()
  594. poppedTxHash := popped.Value.([sha256.Size]byte)
  595. delete(cache.map_, poppedTxHash)
  596. if popped != nil {
  597. cache.list.Remove(popped)
  598. }
  599. }
  600. cache.list.PushBack(txHash)
  601. cache.map_[txHash] = cache.list.Back()
  602. return true
  603. }
  604. // Remove removes the given tx from the cache.
  605. func (cache *mapTxCache) Remove(tx types.Tx) {
  606. cache.mtx.Lock()
  607. txHash := sha256.Sum256(tx)
  608. popped := cache.map_[txHash]
  609. delete(cache.map_, txHash)
  610. if popped != nil {
  611. cache.list.Remove(popped)
  612. }
  613. cache.mtx.Unlock()
  614. }
  615. type nopTxCache struct{}
  616. var _ txCache = (*nopTxCache)(nil)
  617. func (nopTxCache) Reset() {}
  618. func (nopTxCache) Push(types.Tx) bool { return true }
  619. func (nopTxCache) Remove(types.Tx) {}