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.

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