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.

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