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.

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