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.

768 lines
23 KiB

  1. package v1
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "sync/atomic"
  7. "time"
  8. abci "github.com/tendermint/tendermint/abci/types"
  9. "github.com/tendermint/tendermint/config"
  10. "github.com/tendermint/tendermint/internal/libs/clist"
  11. tmsync "github.com/tendermint/tendermint/internal/libs/sync"
  12. "github.com/tendermint/tendermint/libs/log"
  13. tmmath "github.com/tendermint/tendermint/libs/math"
  14. "github.com/tendermint/tendermint/mempool"
  15. "github.com/tendermint/tendermint/proxy"
  16. "github.com/tendermint/tendermint/types"
  17. )
  18. var _ mempool.Mempool = (*TxMempool)(nil)
  19. // TxMempoolOption sets an optional parameter on the TxMempool.
  20. type TxMempoolOption func(*TxMempool)
  21. // TxMempool defines a prioritized mempool data structure used by the v1 mempool
  22. // reactor. It keeps a thread-safe priority queue of transactions that is used
  23. // when a block proposer constructs a block and a thread-safe linked-list that
  24. // is used to gossip transactions to peers in a FIFO manner.
  25. type TxMempool struct {
  26. logger log.Logger
  27. metrics *mempool.Metrics
  28. config *config.MempoolConfig
  29. proxyAppConn proxy.AppConnMempool
  30. // txsAvailable fires once for each height when the mempool is not empty
  31. txsAvailable chan struct{}
  32. notifiedTxsAvailable bool
  33. // height defines the last block height process during Update()
  34. height int64
  35. // sizeBytes defines the total size of the mempool (sum of all tx bytes)
  36. sizeBytes int64
  37. // cache defines a fixed-size cache of already seen transactions as this
  38. // reduces pressure on the proxyApp.
  39. cache mempool.TxCache
  40. // txStore defines the main storage of valid transactions. Indexes are built
  41. // on top of this store.
  42. txStore *TxStore
  43. // gossipIndex defines the gossiping index of valid transactions via a
  44. // thread-safe linked-list. We also use the gossip index as a cursor for
  45. // rechecking transactions already in the mempool.
  46. gossipIndex *clist.CList
  47. // recheckCursor and recheckEnd are used as cursors based on the gossip index
  48. // to recheck transactions that are already in the mempool. Iteration is not
  49. // thread-safe and transaction may be mutated in serial order.
  50. //
  51. // XXX/TODO: It might be somewhat of a codesmell to use the gossip index for
  52. // iterator and cursor management when rechecking transactions. If the gossip
  53. // index changes or is removed in a future refactor, this will have to be
  54. // refactored. Instead, we should consider just keeping a slice of a snapshot
  55. // of the mempool's current transactions during Update and an integer cursor
  56. // into that slice. This, however, requires additional O(n) space complexity.
  57. recheckCursor *clist.CElement // next expected response
  58. recheckEnd *clist.CElement // re-checking stops here
  59. // priorityIndex defines the priority index of valid transactions via a
  60. // thread-safe priority queue.
  61. priorityIndex *TxPriorityQueue
  62. // A read/write lock is used to safe guard updates, insertions and deletions
  63. // from the mempool. A read-lock is implicitly acquired when executing CheckTx,
  64. // however, a caller must explicitly grab a write-lock via Lock when updating
  65. // the mempool via Update().
  66. mtx tmsync.RWMutex
  67. preCheck mempool.PreCheckFunc
  68. postCheck mempool.PostCheckFunc
  69. }
  70. func NewTxMempool(
  71. logger log.Logger,
  72. cfg *config.MempoolConfig,
  73. proxyAppConn proxy.AppConnMempool,
  74. height int64,
  75. options ...TxMempoolOption,
  76. ) *TxMempool {
  77. txmp := &TxMempool{
  78. logger: logger,
  79. config: cfg,
  80. proxyAppConn: proxyAppConn,
  81. height: height,
  82. cache: mempool.NopTxCache{},
  83. metrics: mempool.NopMetrics(),
  84. txStore: NewTxStore(),
  85. gossipIndex: clist.New(),
  86. priorityIndex: NewTxPriorityQueue(),
  87. }
  88. if cfg.CacheSize > 0 {
  89. txmp.cache = mempool.NewLRUTxCache(cfg.CacheSize)
  90. }
  91. proxyAppConn.SetResponseCallback(txmp.defaultTxCallback)
  92. for _, opt := range options {
  93. opt(txmp)
  94. }
  95. return txmp
  96. }
  97. // WithPreCheck sets a filter for the mempool to reject a transaction if f(tx)
  98. // returns an error. This is executed before CheckTx. It only applies to the
  99. // first created block. After that, Update() overwrites the existing value.
  100. func WithPreCheck(f mempool.PreCheckFunc) TxMempoolOption {
  101. return func(txmp *TxMempool) { txmp.preCheck = f }
  102. }
  103. // WithPostCheck sets a filter for the mempool to reject a transaction if
  104. // f(tx, resp) returns an error. This is executed after CheckTx. It only applies
  105. // to the first created block. After that, Update overwrites the existing value.
  106. func WithPostCheck(f mempool.PostCheckFunc) TxMempoolOption {
  107. return func(txmp *TxMempool) { txmp.postCheck = f }
  108. }
  109. // WithMetrics sets the mempool's metrics collector.
  110. func WithMetrics(metrics *mempool.Metrics) TxMempoolOption {
  111. return func(txmp *TxMempool) { txmp.metrics = metrics }
  112. }
  113. // Lock obtains a write-lock on the mempool. A caller must be sure to explicitly
  114. // release the lock when finished.
  115. func (txmp *TxMempool) Lock() {
  116. txmp.mtx.Lock()
  117. }
  118. // Unlock releases a write-lock on the mempool.
  119. func (txmp *TxMempool) Unlock() {
  120. txmp.mtx.Unlock()
  121. }
  122. // Size returns the number of valid transactions in the mempool. It is
  123. // thread-safe.
  124. func (txmp *TxMempool) Size() int {
  125. return txmp.txStore.Size()
  126. }
  127. // SizeBytes return the total sum in bytes of all the valid transactions in the
  128. // mempool. It is thread-safe.
  129. func (txmp *TxMempool) SizeBytes() int64 {
  130. return atomic.LoadInt64(&txmp.sizeBytes)
  131. }
  132. // FlushAppConn executes FlushSync on the mempool's proxyAppConn.
  133. //
  134. // NOTE: The caller must obtain a write-lock via Lock() prior to execution.
  135. func (txmp *TxMempool) FlushAppConn() error {
  136. return txmp.proxyAppConn.FlushSync(context.Background())
  137. }
  138. // WaitForNextTx returns a blocking channel that will be closed when the next
  139. // valid transaction is available to gossip. It is thread-safe.
  140. func (txmp *TxMempool) WaitForNextTx() <-chan struct{} {
  141. return txmp.gossipIndex.WaitChan()
  142. }
  143. // NextGossipTx returns the next valid transaction to gossip. A caller must wait
  144. // for WaitForNextTx to signal a transaction is available to gossip first. It is
  145. // thread-safe.
  146. func (txmp *TxMempool) NextGossipTx() *WrappedTx {
  147. return txmp.gossipIndex.Front().Value.(*WrappedTx)
  148. }
  149. // EnableTxsAvailable enables the mempool to trigger events when transactions
  150. // are available on a block by block basis.
  151. func (txmp *TxMempool) EnableTxsAvailable() {
  152. txmp.mtx.Lock()
  153. defer txmp.mtx.Unlock()
  154. txmp.txsAvailable = make(chan struct{}, 1)
  155. }
  156. // TxsAvailable returns a channel which fires once for every height, and only
  157. // when transactions are available in the mempool. It is thread-safe.
  158. func (txmp *TxMempool) TxsAvailable() <-chan struct{} {
  159. return txmp.txsAvailable
  160. }
  161. // CheckTx executes the ABCI CheckTx method for a given transaction. It acquires
  162. // a read-lock attempts to execute the application's CheckTx ABCI method via
  163. // CheckTxAsync. We return an error if any of the following happen:
  164. //
  165. // - The CheckTxAsync execution fails.
  166. // - The transaction already exists in the cache and we've already received the
  167. // transaction from the peer. Otherwise, if it solely exists in the cache, we
  168. // return nil.
  169. // - The transaction size exceeds the maximum transaction size as defined by the
  170. // configuration provided to the mempool.
  171. // - The transaction fails Pre-Check (if it is defined).
  172. // - The proxyAppConn fails, e.g. the buffer is full.
  173. //
  174. // If the mempool is full, we still execute CheckTx and attempt to find a lower
  175. // priority transaction to evict. If such a transaction exists, we remove the
  176. // lower priority transaction and add the new one with higher priority.
  177. //
  178. // NOTE:
  179. // - The applications' CheckTx implementation may panic.
  180. // - The caller is not to explicitly require any locks for executing CheckTx.
  181. func (txmp *TxMempool) CheckTx(
  182. ctx context.Context,
  183. tx types.Tx,
  184. cb func(*abci.Response),
  185. txInfo mempool.TxInfo,
  186. ) error {
  187. txmp.mtx.RLock()
  188. defer txmp.mtx.RUnlock()
  189. txSize := len(tx)
  190. if txSize > txmp.config.MaxTxBytes {
  191. return mempool.ErrTxTooLarge{
  192. Max: txmp.config.MaxTxBytes,
  193. Actual: txSize,
  194. }
  195. }
  196. if txmp.preCheck != nil {
  197. if err := txmp.preCheck(tx); err != nil {
  198. return mempool.ErrPreCheck{
  199. Reason: err,
  200. }
  201. }
  202. }
  203. if err := txmp.proxyAppConn.Error(); err != nil {
  204. return err
  205. }
  206. txHash := mempool.TxKey(tx)
  207. // We add the transaction to the mempool's cache and if the transaction already
  208. // exists, i.e. false is returned, then we check if we've seen this transaction
  209. // from the same sender and error if we have. Otherwise, we return nil.
  210. if !txmp.cache.Push(tx) {
  211. wtx, ok := txmp.txStore.GetOrSetPeerByTxHash(txHash, txInfo.SenderID)
  212. if wtx != nil && ok {
  213. // We already have the transaction stored and the we've already seen this
  214. // transaction from txInfo.SenderID.
  215. return mempool.ErrTxInCache
  216. }
  217. txmp.logger.Debug("tx exists already in cache", "tx_hash", tx.Hash())
  218. return nil
  219. }
  220. if ctx == nil {
  221. ctx = context.Background()
  222. }
  223. reqRes, err := txmp.proxyAppConn.CheckTxAsync(ctx, abci.RequestCheckTx{Tx: tx})
  224. if err != nil {
  225. txmp.cache.Remove(tx)
  226. return err
  227. }
  228. reqRes.SetCallback(func(res *abci.Response) {
  229. if txmp.recheckCursor != nil {
  230. panic("recheck cursor is non-nil in CheckTx callback")
  231. }
  232. wtx := &WrappedTx{
  233. tx: tx,
  234. hash: txHash,
  235. timestamp: time.Now().UTC(),
  236. }
  237. txmp.initTxCallback(wtx, res, txInfo)
  238. if cb != nil {
  239. cb(res)
  240. }
  241. })
  242. return nil
  243. }
  244. // Flush flushes out the mempool. It acquires a read-lock, fetches all the
  245. // transactions currently in the transaction store and removes each transaction
  246. // from the store and all indexes and finally resets the cache.
  247. //
  248. // NOTE:
  249. // - Flushing the mempool may leave the mempool in an inconsistent state.
  250. func (txmp *TxMempool) Flush() {
  251. txmp.mtx.RLock()
  252. defer txmp.mtx.RUnlock()
  253. for _, wtx := range txmp.txStore.GetAllTxs() {
  254. if !txmp.txStore.IsTxRemoved(wtx.hash) {
  255. txmp.txStore.RemoveTx(wtx)
  256. txmp.priorityIndex.RemoveTx(wtx)
  257. txmp.gossipIndex.Remove(wtx.gossipEl)
  258. wtx.gossipEl.DetachPrev()
  259. }
  260. }
  261. atomic.SwapInt64(&txmp.sizeBytes, 0)
  262. txmp.cache.Reset()
  263. }
  264. // ReapMaxBytesMaxGas returns a list of transactions within the provided size
  265. // and gas constraints. Transaction are retrieved in priority order.
  266. //
  267. // NOTE:
  268. // - A read-lock is acquired.
  269. // - Transactions returned are not actually removed from the mempool transaction
  270. // store or indexes.
  271. func (txmp *TxMempool) ReapMaxBytesMaxGas(maxBytes, maxGas int64) types.Txs {
  272. txmp.mtx.RLock()
  273. defer txmp.mtx.RUnlock()
  274. var (
  275. totalGas int64
  276. totalSize int64
  277. )
  278. // wTxs contains a list of *WrappedTx retrieved from the priority queue that
  279. // need to be re-enqueued prior to returning.
  280. wTxs := make([]*WrappedTx, 0, txmp.priorityIndex.NumTxs())
  281. defer func() {
  282. for _, wtx := range wTxs {
  283. txmp.priorityIndex.PushTx(wtx)
  284. }
  285. }()
  286. txs := make([]types.Tx, 0, txmp.priorityIndex.NumTxs())
  287. for txmp.priorityIndex.NumTxs() > 0 {
  288. wtx := txmp.priorityIndex.PopTx()
  289. txs = append(txs, wtx.tx)
  290. wTxs = append(wTxs, wtx)
  291. size := types.ComputeProtoSizeForTxs([]types.Tx{wtx.tx})
  292. // Ensure we have capacity for the transaction with respect to the
  293. // transaction size.
  294. if maxBytes > -1 && totalSize+size > maxBytes {
  295. return txs[:len(txs)-1]
  296. }
  297. totalSize += size
  298. // ensure we have capacity for the transaction with respect to total gas
  299. gas := totalGas + wtx.gasWanted
  300. if maxGas > -1 && gas > maxGas {
  301. return txs[:len(txs)-1]
  302. }
  303. totalGas = gas
  304. }
  305. return txs
  306. }
  307. // ReapMaxTxs returns a list of transactions within the provided number of
  308. // transactions bound. Transaction are retrieved in priority order.
  309. //
  310. // NOTE:
  311. // - A read-lock is acquired.
  312. // - Transactions returned are not actually removed from the mempool transaction
  313. // store or indexes.
  314. func (txmp *TxMempool) ReapMaxTxs(max int) types.Txs {
  315. txmp.mtx.RLock()
  316. defer txmp.mtx.RUnlock()
  317. numTxs := txmp.priorityIndex.NumTxs()
  318. if max < 0 {
  319. max = numTxs
  320. }
  321. cap := tmmath.MinInt(numTxs, max)
  322. // wTxs contains a list of *WrappedTx retrieved from the priority queue that
  323. // need to be re-enqueued prior to returning.
  324. wTxs := make([]*WrappedTx, 0, cap)
  325. defer func() {
  326. for _, wtx := range wTxs {
  327. txmp.priorityIndex.PushTx(wtx)
  328. }
  329. }()
  330. txs := make([]types.Tx, 0, cap)
  331. for txmp.priorityIndex.NumTxs() > 0 && len(txs) < max {
  332. wtx := txmp.priorityIndex.PopTx()
  333. txs = append(txs, wtx.tx)
  334. wTxs = append(wTxs, wtx)
  335. }
  336. return txs
  337. }
  338. // Update iterates over all the transactions provided by the caller, i.e. the
  339. // block producer, and removes them from the cache (if applicable) and removes
  340. // the transactions from the main transaction store and associated indexes.
  341. // Finally, if there are trainsactions remaining in the mempool, we initiate a
  342. // re-CheckTx for them (if applicable), otherwise, we notify the caller more
  343. // transactions are available.
  344. //
  345. // NOTE:
  346. // - The caller must explicitly acquire a write-lock via Lock().
  347. func (txmp *TxMempool) Update(
  348. blockHeight int64,
  349. blockTxs types.Txs,
  350. deliverTxResponses []*abci.ResponseDeliverTx,
  351. newPreFn mempool.PreCheckFunc,
  352. newPostFn mempool.PostCheckFunc,
  353. ) error {
  354. txmp.height = blockHeight
  355. txmp.notifiedTxsAvailable = false
  356. if newPreFn != nil {
  357. txmp.preCheck = newPreFn
  358. }
  359. if newPostFn != nil {
  360. txmp.postCheck = newPostFn
  361. }
  362. for i, tx := range blockTxs {
  363. if deliverTxResponses[i].Code == abci.CodeTypeOK {
  364. // add the valid committed transaction to the cache (if missing)
  365. _ = txmp.cache.Push(tx)
  366. } else if !txmp.config.KeepInvalidTxsInCache {
  367. // allow invalid transactions to be re-submitted
  368. txmp.cache.Remove(tx)
  369. }
  370. // remove the committed transaction from the transaction store and indexes
  371. if wtx := txmp.txStore.GetTxByHash(mempool.TxKey(tx)); wtx != nil {
  372. txmp.removeTx(wtx, false)
  373. }
  374. }
  375. // If there any uncommitted transactions left in the mempool, we either
  376. // initiate re-CheckTx per remaining transaction or notify that remaining
  377. // transactions are left.
  378. if txmp.Size() > 0 {
  379. if txmp.config.Recheck {
  380. txmp.logger.Debug(
  381. "executing re-CheckTx for all remaining transactions",
  382. "num_txs", txmp.Size(),
  383. "height", blockHeight,
  384. )
  385. txmp.updateReCheckTxs()
  386. } else {
  387. txmp.notifyTxsAvailable()
  388. }
  389. }
  390. txmp.metrics.Size.Set(float64(txmp.Size()))
  391. return nil
  392. }
  393. // initTxCallback performs the initial, i.e. the first, callback after CheckTx
  394. // has been executed by the ABCI application. In other words, initTxCallback is
  395. // called after executing CheckTx when we see a unique transaction for the first
  396. // time. CheckTx can be called again for the same transaction at a later point
  397. // in time when re-checking, however, this callback will not be called.
  398. //
  399. // After the ABCI application executes CheckTx, initTxCallback is called with
  400. // the ABCI *Response object and TxInfo. If postCheck is defined on the mempool,
  401. // we execute that first. If there is no error from postCheck (if defined) and
  402. // the ABCI CheckTx response code is OK, we attempt to insert the transaction.
  403. //
  404. // When attempting to insert the transaction, we first check if there is
  405. // sufficient capacity. If there is sufficient capacity, the transaction is
  406. // inserted into the txStore and indexed across all indexes. Otherwise, if the
  407. // mempool is full, we attempt to find a lower priority transaction to evict in
  408. // place of the new incoming transaction. If no such transaction exists, the
  409. // new incoming transaction is rejected.
  410. //
  411. // If the new incoming transaction fails CheckTx or postCheck fails, we reject
  412. // the new incoming transaction.
  413. //
  414. // NOTE:
  415. // - An explicit lock is NOT required.
  416. func (txmp *TxMempool) initTxCallback(wtx *WrappedTx, res *abci.Response, txInfo mempool.TxInfo) {
  417. checkTxRes, ok := res.Value.(*abci.Response_CheckTx)
  418. if ok {
  419. var err error
  420. if txmp.postCheck != nil {
  421. err = txmp.postCheck(wtx.tx, checkTxRes.CheckTx)
  422. }
  423. if checkTxRes.CheckTx.Code == abci.CodeTypeOK && err == nil {
  424. sender := checkTxRes.CheckTx.Sender
  425. priority := checkTxRes.CheckTx.Priority
  426. if len(sender) > 0 {
  427. if wtx := txmp.txStore.GetTxBySender(sender); wtx != nil {
  428. txmp.logger.Error(
  429. "rejected incoming good transaction; tx already exists for sender",
  430. "tx", fmt.Sprintf("%X", wtx.tx.Hash()),
  431. "sender", sender,
  432. )
  433. txmp.metrics.RejectedTxs.Add(1)
  434. return
  435. }
  436. }
  437. if err := txmp.canAddTx(wtx); err != nil {
  438. evictTxs := txmp.priorityIndex.GetEvictableTxs(
  439. priority,
  440. int64(wtx.Size()),
  441. txmp.SizeBytes(),
  442. txmp.config.MaxTxsBytes,
  443. )
  444. if len(evictTxs) == 0 {
  445. // No room for the new incoming transaction so we just remove it from
  446. // the cache.
  447. txmp.cache.Remove(wtx.tx)
  448. txmp.logger.Error(
  449. "rejected incoming good transaction; mempool full",
  450. "tx", fmt.Sprintf("%X", wtx.tx.Hash()),
  451. "err", err.Error(),
  452. )
  453. txmp.metrics.RejectedTxs.Add(1)
  454. return
  455. }
  456. // evict an existing transaction(s)
  457. //
  458. // NOTE:
  459. // - The transaction, toEvict, can be removed while a concurrent
  460. // reCheckTx callback is being executed for the same transaction.
  461. for _, toEvict := range evictTxs {
  462. txmp.removeTx(toEvict, true)
  463. txmp.logger.Debug(
  464. "evicted existing good transaction; mempool full",
  465. "old_tx", fmt.Sprintf("%X", toEvict.tx.Hash()),
  466. "old_priority", toEvict.priority,
  467. "new_tx", fmt.Sprintf("%X", wtx.tx.Hash()),
  468. "new_priority", wtx.priority,
  469. )
  470. txmp.metrics.EvictedTxs.Add(1)
  471. }
  472. }
  473. wtx.gasWanted = checkTxRes.CheckTx.GasWanted
  474. wtx.height = txmp.height
  475. wtx.priority = priority
  476. wtx.sender = sender
  477. wtx.peers = map[uint16]struct{}{
  478. txInfo.SenderID: {},
  479. }
  480. txmp.metrics.TxSizeBytes.Observe(float64(wtx.Size()))
  481. txmp.metrics.Size.Set(float64(txmp.Size()))
  482. txmp.insertTx(wtx)
  483. txmp.logger.Debug(
  484. "inserted good transaction",
  485. "priority", wtx.priority,
  486. "tx", fmt.Sprintf("%X", wtx.tx.Hash()),
  487. "height", txmp.height,
  488. "num_txs", txmp.Size(),
  489. )
  490. txmp.notifyTxsAvailable()
  491. } else {
  492. // ignore bad transactions
  493. txmp.logger.Info(
  494. "rejected bad transaction",
  495. "priority", wtx.priority,
  496. "tx", fmt.Sprintf("%X", wtx.tx.Hash()),
  497. "peer_id", txInfo.SenderNodeID,
  498. "code", checkTxRes.CheckTx.Code,
  499. "post_check_err", err,
  500. )
  501. txmp.metrics.FailedTxs.Add(1)
  502. if !txmp.config.KeepInvalidTxsInCache {
  503. txmp.cache.Remove(wtx.tx)
  504. }
  505. }
  506. }
  507. }
  508. // defaultTxCallback performs the default CheckTx application callback. This is
  509. // NOT executed when a transaction is first seen/received. Instead, this callback
  510. // is executed during re-checking transactions (if enabled). A caller, i.e a
  511. // block proposer, acquires a mempool write-lock via Lock() and when executing
  512. // Update(), if the mempool is non-empty and Recheck is enabled, then all
  513. // remaining transactions will be rechecked via CheckTxAsync. The order in which
  514. // they are rechecked must be the same order in which this callback is called
  515. // per transaction.
  516. func (txmp *TxMempool) defaultTxCallback(req *abci.Request, res *abci.Response) {
  517. if txmp.recheckCursor == nil {
  518. return
  519. }
  520. txmp.metrics.RecheckTimes.Add(1)
  521. checkTxRes, ok := res.Value.(*abci.Response_CheckTx)
  522. if ok {
  523. tx := req.GetCheckTx().Tx
  524. wtx := txmp.recheckCursor.Value.(*WrappedTx)
  525. if !bytes.Equal(tx, wtx.tx) {
  526. panic(fmt.Sprintf("re-CheckTx transaction mismatch; got: %X, expected: %X", wtx.tx.Hash(), mempool.TxKey(tx)))
  527. }
  528. // Only evaluate transactions that have not been removed. This can happen
  529. // if an existing transaction is evicted during CheckTx and while this
  530. // callback is being executed for the same evicted transaction.
  531. if !txmp.txStore.IsTxRemoved(wtx.hash) {
  532. var err error
  533. if txmp.postCheck != nil {
  534. err = txmp.postCheck(tx, checkTxRes.CheckTx)
  535. }
  536. if checkTxRes.CheckTx.Code == abci.CodeTypeOK && err == nil {
  537. wtx.priority = checkTxRes.CheckTx.Priority
  538. } else {
  539. txmp.logger.Debug(
  540. "existing transaction no longer valid; failed re-CheckTx callback",
  541. "priority", wtx.priority,
  542. "tx", fmt.Sprintf("%X", mempool.TxHashFromBytes(wtx.tx)),
  543. "err", err,
  544. "code", checkTxRes.CheckTx.Code,
  545. )
  546. if wtx.gossipEl != txmp.recheckCursor {
  547. panic("corrupted reCheckTx cursor")
  548. }
  549. txmp.removeTx(wtx, !txmp.config.KeepInvalidTxsInCache)
  550. }
  551. }
  552. // move reCheckTx cursor to next element
  553. if txmp.recheckCursor == txmp.recheckEnd {
  554. txmp.recheckCursor = nil
  555. } else {
  556. txmp.recheckCursor = txmp.recheckCursor.Next()
  557. }
  558. if txmp.recheckCursor == nil {
  559. txmp.logger.Debug("finished rechecking transactions")
  560. if txmp.Size() > 0 {
  561. txmp.notifyTxsAvailable()
  562. }
  563. }
  564. txmp.metrics.Size.Set(float64(txmp.Size()))
  565. }
  566. }
  567. // updateReCheckTxs updates the recheck cursors by using the gossipIndex. For
  568. // each transaction, it executes CheckTxAsync. The global callback defined on
  569. // the proxyAppConn will be executed for each transaction after CheckTx is
  570. // executed.
  571. //
  572. // NOTE:
  573. // - The caller must have a write-lock when executing updateReCheckTxs.
  574. func (txmp *TxMempool) updateReCheckTxs() {
  575. if txmp.Size() == 0 {
  576. panic("attempted to update re-CheckTx txs when mempool is empty")
  577. }
  578. txmp.recheckCursor = txmp.gossipIndex.Front()
  579. txmp.recheckEnd = txmp.gossipIndex.Back()
  580. ctx := context.Background()
  581. for e := txmp.gossipIndex.Front(); e != nil; e = e.Next() {
  582. wtx := e.Value.(*WrappedTx)
  583. // Only execute CheckTx if the transaction is not marked as removed which
  584. // could happen if the transaction was evicted.
  585. if !txmp.txStore.IsTxRemoved(wtx.hash) {
  586. _, err := txmp.proxyAppConn.CheckTxAsync(ctx, abci.RequestCheckTx{
  587. Tx: wtx.tx,
  588. Type: abci.CheckTxType_Recheck,
  589. })
  590. if err != nil {
  591. // no need in retrying since the tx will be rechecked after the next block
  592. txmp.logger.Error("failed to execute CheckTx during rechecking", "err", err)
  593. }
  594. }
  595. }
  596. if _, err := txmp.proxyAppConn.FlushAsync(ctx); err != nil {
  597. txmp.logger.Error("failed to flush transactions during rechecking", "err", err)
  598. }
  599. }
  600. // canAddTx returns an error if we cannot insert the provided *WrappedTx into
  601. // the mempool due to mempool configured constraints. Otherwise, nil is returned
  602. // and the transaction can be inserted into the mempool.
  603. func (txmp *TxMempool) canAddTx(wtx *WrappedTx) error {
  604. var (
  605. numTxs = txmp.Size()
  606. sizeBytes = txmp.SizeBytes()
  607. )
  608. if numTxs >= txmp.config.Size || int64(wtx.Size())+sizeBytes > txmp.config.MaxTxsBytes {
  609. return mempool.ErrMempoolIsFull{
  610. NumTxs: numTxs,
  611. MaxTxs: txmp.config.Size,
  612. TxsBytes: sizeBytes,
  613. MaxTxsBytes: txmp.config.MaxTxsBytes,
  614. }
  615. }
  616. return nil
  617. }
  618. func (txmp *TxMempool) insertTx(wtx *WrappedTx) {
  619. txmp.txStore.SetTx(wtx)
  620. txmp.priorityIndex.PushTx(wtx)
  621. // Insert the transaction into the gossip index and mark the reference to the
  622. // linked-list element, which will be needed at a later point when the
  623. // transaction is removed.
  624. gossipEl := txmp.gossipIndex.PushBack(wtx)
  625. wtx.gossipEl = gossipEl
  626. atomic.AddInt64(&txmp.sizeBytes, int64(wtx.Size()))
  627. }
  628. func (txmp *TxMempool) removeTx(wtx *WrappedTx, removeFromCache bool) {
  629. if txmp.txStore.IsTxRemoved(wtx.hash) {
  630. return
  631. }
  632. txmp.txStore.RemoveTx(wtx)
  633. txmp.priorityIndex.RemoveTx(wtx)
  634. // Remove the transaction from the gossip index and cleanup the linked-list
  635. // element so it can be garbage collected.
  636. txmp.gossipIndex.Remove(wtx.gossipEl)
  637. wtx.gossipEl.DetachPrev()
  638. atomic.AddInt64(&txmp.sizeBytes, int64(-wtx.Size()))
  639. if removeFromCache {
  640. txmp.cache.Remove(wtx.tx)
  641. }
  642. }
  643. func (txmp *TxMempool) notifyTxsAvailable() {
  644. if txmp.Size() == 0 {
  645. panic("attempt to notify txs available but mempool is empty!")
  646. }
  647. if txmp.txsAvailable != nil && !txmp.notifiedTxsAvailable {
  648. // channel cap is 1, so this will send once
  649. txmp.notifiedTxsAvailable = true
  650. select {
  651. case txmp.txsAvailable <- struct{}{}:
  652. default:
  653. }
  654. }
  655. }