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.

755 lines
21 KiB

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