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.

767 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/internal/mempool"
  13. "github.com/tendermint/tendermint/libs/log"
  14. tmmath "github.com/tendermint/tendermint/libs/math"
  15. pubmempool "github.com/tendermint/tendermint/pkg/mempool"
  16. "github.com/tendermint/tendermint/proxy"
  17. "github.com/tendermint/tendermint/types"
  18. )
  19. var _ mempool.Mempool = (*TxMempool)(nil)
  20. // TxMempoolOption sets an optional parameter on the TxMempool.
  21. type TxMempoolOption func(*TxMempool)
  22. // TxMempool defines a prioritized mempool data structure used by the v1 mempool
  23. // reactor. It keeps a thread-safe priority queue of transactions that is used
  24. // when a block proposer constructs a block and a thread-safe linked-list that
  25. // is used to gossip transactions to peers in a FIFO manner.
  26. type TxMempool struct {
  27. logger log.Logger
  28. metrics *mempool.Metrics
  29. config *config.MempoolConfig
  30. proxyAppConn proxy.AppConnMempool
  31. // txsAvailable fires once for each height when the mempool is not empty
  32. txsAvailable chan struct{}
  33. notifiedTxsAvailable bool
  34. // height defines the last block height process during Update()
  35. height int64
  36. // sizeBytes defines the total size of the mempool (sum of all tx bytes)
  37. sizeBytes int64
  38. // cache defines a fixed-size cache of already seen transactions as this
  39. // reduces pressure on the proxyApp.
  40. cache mempool.TxCache
  41. // txStore defines the main storage of valid transactions. Indexes are built
  42. // on top of this store.
  43. txStore *TxStore
  44. // gossipIndex defines the gossiping index of valid transactions via a
  45. // thread-safe linked-list. We also use the gossip index as a cursor for
  46. // rechecking transactions already in the mempool.
  47. gossipIndex *clist.CList
  48. // recheckCursor and recheckEnd are used as cursors based on the gossip index
  49. // to recheck transactions that are already in the mempool. Iteration is not
  50. // thread-safe and transaction may be mutated in serial order.
  51. //
  52. // XXX/TODO: It might be somewhat of a codesmell to use the gossip index for
  53. // iterator and cursor management when rechecking transactions. If the gossip
  54. // index changes or is removed in a future refactor, this will have to be
  55. // refactored. Instead, we should consider just keeping a slice of a snapshot
  56. // of the mempool's current transactions during Update and an integer cursor
  57. // into that slice. This, however, requires additional O(n) space complexity.
  58. recheckCursor *clist.CElement // next expected response
  59. recheckEnd *clist.CElement // re-checking stops here
  60. // priorityIndex defines the priority index of valid transactions via a
  61. // thread-safe priority queue.
  62. priorityIndex *TxPriorityQueue
  63. // A read/write lock is used to safe guard updates, insertions and deletions
  64. // from the mempool. A read-lock is implicitly acquired when executing CheckTx,
  65. // however, a caller must explicitly grab a write-lock via Lock when updating
  66. // the mempool via Update().
  67. mtx tmsync.RWMutex
  68. preCheck mempool.PreCheckFunc
  69. postCheck mempool.PostCheckFunc
  70. }
  71. func NewTxMempool(
  72. logger log.Logger,
  73. cfg *config.MempoolConfig,
  74. proxyAppConn proxy.AppConnMempool,
  75. height int64,
  76. options ...TxMempoolOption,
  77. ) *TxMempool {
  78. txmp := &TxMempool{
  79. logger: logger,
  80. config: cfg,
  81. proxyAppConn: proxyAppConn,
  82. height: height,
  83. cache: mempool.NopTxCache{},
  84. metrics: mempool.NopMetrics(),
  85. txStore: NewTxStore(),
  86. gossipIndex: clist.New(),
  87. priorityIndex: NewTxPriorityQueue(),
  88. }
  89. if cfg.CacheSize > 0 {
  90. txmp.cache = mempool.NewLRUTxCache(cfg.CacheSize)
  91. }
  92. proxyAppConn.SetResponseCallback(txmp.defaultTxCallback)
  93. for _, opt := range options {
  94. opt(txmp)
  95. }
  96. return txmp
  97. }
  98. // WithPreCheck sets a filter for the mempool to reject a transaction if f(tx)
  99. // returns an error. This is executed before CheckTx. It only applies to the
  100. // first created block. After that, Update() overwrites the existing value.
  101. func WithPreCheck(f mempool.PreCheckFunc) TxMempoolOption {
  102. return func(txmp *TxMempool) { txmp.preCheck = f }
  103. }
  104. // WithPostCheck sets a filter for the mempool to reject a transaction if
  105. // f(tx, resp) returns an error. This is executed after CheckTx. It only applies
  106. // to the first created block. After that, Update overwrites the existing value.
  107. func WithPostCheck(f mempool.PostCheckFunc) TxMempoolOption {
  108. return func(txmp *TxMempool) { txmp.postCheck = f }
  109. }
  110. // WithMetrics sets the mempool's metrics collector.
  111. func WithMetrics(metrics *mempool.Metrics) TxMempoolOption {
  112. return func(txmp *TxMempool) { txmp.metrics = metrics }
  113. }
  114. // Lock obtains a write-lock on the mempool. A caller must be sure to explicitly
  115. // release the lock when finished.
  116. func (txmp *TxMempool) Lock() {
  117. txmp.mtx.Lock()
  118. }
  119. // Unlock releases a write-lock on the mempool.
  120. func (txmp *TxMempool) Unlock() {
  121. txmp.mtx.Unlock()
  122. }
  123. // Size returns the number of valid transactions in the mempool. It is
  124. // thread-safe.
  125. func (txmp *TxMempool) Size() int {
  126. return txmp.txStore.Size()
  127. }
  128. // SizeBytes return the total sum in bytes of all the valid transactions in the
  129. // mempool. It is thread-safe.
  130. func (txmp *TxMempool) SizeBytes() int64 {
  131. return atomic.LoadInt64(&txmp.sizeBytes)
  132. }
  133. // FlushAppConn executes FlushSync on the mempool's proxyAppConn.
  134. //
  135. // NOTE: The caller must obtain a write-lock via Lock() prior to execution.
  136. func (txmp *TxMempool) FlushAppConn() error {
  137. return txmp.proxyAppConn.FlushSync(context.Background())
  138. }
  139. // WaitForNextTx returns a blocking channel that will be closed when the next
  140. // valid transaction is available to gossip. It is thread-safe.
  141. func (txmp *TxMempool) WaitForNextTx() <-chan struct{} {
  142. return txmp.gossipIndex.WaitChan()
  143. }
  144. // NextGossipTx returns the next valid transaction to gossip. A caller must wait
  145. // for WaitForNextTx to signal a transaction is available to gossip first. It is
  146. // thread-safe.
  147. func (txmp *TxMempool) NextGossipTx() *WrappedTx {
  148. return txmp.gossipIndex.Front().Value.(*WrappedTx)
  149. }
  150. // EnableTxsAvailable enables the mempool to trigger events when transactions
  151. // are available on a block by block basis.
  152. func (txmp *TxMempool) EnableTxsAvailable() {
  153. txmp.mtx.Lock()
  154. defer txmp.mtx.Unlock()
  155. txmp.txsAvailable = make(chan struct{}, 1)
  156. }
  157. // TxsAvailable returns a channel which fires once for every height, and only
  158. // when transactions are available in the mempool. It is thread-safe.
  159. func (txmp *TxMempool) TxsAvailable() <-chan struct{} {
  160. return txmp.txsAvailable
  161. }
  162. // CheckTx executes the ABCI CheckTx method for a given transaction. It acquires
  163. // a read-lock attempts to execute the application's CheckTx ABCI method via
  164. // CheckTxAsync. We return an error if any of the following happen:
  165. //
  166. // - The CheckTxAsync execution fails.
  167. // - The transaction already exists in the cache and we've already received the
  168. // transaction from the peer. Otherwise, if it solely exists in the cache, we
  169. // return nil.
  170. // - The transaction size exceeds the maximum transaction size as defined by the
  171. // configuration provided to the mempool.
  172. // - The transaction fails Pre-Check (if it is defined).
  173. // - The proxyAppConn fails, e.g. the buffer is full.
  174. //
  175. // If the mempool is full, we still execute CheckTx and attempt to find a lower
  176. // priority transaction to evict. If such a transaction exists, we remove the
  177. // lower priority transaction and add the new one with higher priority.
  178. //
  179. // NOTE:
  180. // - The applications' CheckTx implementation may panic.
  181. // - The caller is not to explicitly require any locks for executing CheckTx.
  182. func (txmp *TxMempool) CheckTx(
  183. ctx context.Context,
  184. tx types.Tx,
  185. cb func(*abci.Response),
  186. txInfo mempool.TxInfo,
  187. ) error {
  188. txmp.mtx.RLock()
  189. defer txmp.mtx.RUnlock()
  190. txSize := len(tx)
  191. if txSize > txmp.config.MaxTxBytes {
  192. return pubmempool.ErrTxTooLarge{
  193. Max: txmp.config.MaxTxBytes,
  194. Actual: txSize,
  195. }
  196. }
  197. if txmp.preCheck != nil {
  198. if err := txmp.preCheck(tx); err != nil {
  199. return pubmempool.ErrPreCheck{
  200. Reason: err,
  201. }
  202. }
  203. }
  204. if err := txmp.proxyAppConn.Error(); err != nil {
  205. return err
  206. }
  207. txHash := mempool.TxKey(tx)
  208. // We add the transaction to the mempool's cache and if the transaction already
  209. // exists, i.e. false is returned, then we check if we've seen this transaction
  210. // from the same sender and error if we have. Otherwise, we return nil.
  211. if !txmp.cache.Push(tx) {
  212. wtx, ok := txmp.txStore.GetOrSetPeerByTxHash(txHash, txInfo.SenderID)
  213. if wtx != nil && ok {
  214. // We already have the transaction stored and the we've already seen this
  215. // transaction from txInfo.SenderID.
  216. return pubmempool.ErrTxInCache
  217. }
  218. txmp.logger.Debug("tx exists already in cache", "tx_hash", tx.Hash())
  219. return nil
  220. }
  221. if ctx == nil {
  222. ctx = context.Background()
  223. }
  224. reqRes, err := txmp.proxyAppConn.CheckTxAsync(ctx, abci.RequestCheckTx{Tx: tx})
  225. if err != nil {
  226. txmp.cache.Remove(tx)
  227. return err
  228. }
  229. reqRes.SetCallback(func(res *abci.Response) {
  230. if txmp.recheckCursor != nil {
  231. panic("recheck cursor is non-nil in CheckTx callback")
  232. }
  233. wtx := &WrappedTx{
  234. tx: tx,
  235. hash: txHash,
  236. timestamp: time.Now().UTC(),
  237. }
  238. txmp.initTxCallback(wtx, res, txInfo)
  239. if cb != nil {
  240. cb(res)
  241. }
  242. })
  243. return nil
  244. }
  245. // Flush flushes out the mempool. It acquires a read-lock, fetches all the
  246. // transactions currently in the transaction store and removes each transaction
  247. // from the store and all indexes and finally resets the cache.
  248. //
  249. // NOTE:
  250. // - Flushing the mempool may leave the mempool in an inconsistent state.
  251. func (txmp *TxMempool) Flush() {
  252. txmp.mtx.RLock()
  253. defer txmp.mtx.RUnlock()
  254. for _, wtx := range txmp.txStore.GetAllTxs() {
  255. if !txmp.txStore.IsTxRemoved(wtx.hash) {
  256. txmp.txStore.RemoveTx(wtx)
  257. txmp.priorityIndex.RemoveTx(wtx)
  258. txmp.gossipIndex.Remove(wtx.gossipEl)
  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 pubmempool.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. atomic.AddInt64(&txmp.sizeBytes, int64(-wtx.Size()))
  638. if removeFromCache {
  639. txmp.cache.Remove(wtx.tx)
  640. }
  641. }
  642. func (txmp *TxMempool) notifyTxsAvailable() {
  643. if txmp.Size() == 0 {
  644. panic("attempt to notify txs available but mempool is empty!")
  645. }
  646. if txmp.txsAvailable != nil && !txmp.notifiedTxsAvailable {
  647. // channel cap is 1, so this will send once
  648. txmp.notifiedTxsAvailable = true
  649. select {
  650. case txmp.txsAvailable <- struct{}{}:
  651. default:
  652. }
  653. }
  654. }