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
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.resCbRecheck(req, res)
  278. }
  279. mem.metrics.Size.Set(float64(mem.Size()))
  280. }
  281. func (mem *Mempool) resCbNormal(req *abci.Request, res *abci.Response) {
  282. switch r := res.Value.(type) {
  283. case *abci.Response_CheckTx:
  284. tx := req.GetCheckTx().Tx
  285. if (r.CheckTx.Code == abci.CodeTypeOK) &&
  286. mem.isPostCheckPass(tx, r.CheckTx) {
  287. mem.counter++
  288. memTx := &mempoolTx{
  289. counter: mem.counter,
  290. height: mem.height,
  291. gasWanted: r.CheckTx.GasWanted,
  292. tx: tx,
  293. }
  294. mem.txs.PushBack(memTx)
  295. mem.logger.Info("Added good transaction", "tx", TxID(tx), "res", r, "total", mem.Size())
  296. mem.notifyTxsAvailable()
  297. } else {
  298. // ignore bad transaction
  299. mem.logger.Info("Rejected bad transaction", "tx", TxID(tx), "res", r)
  300. // remove from cache (it might be good later)
  301. mem.cache.Remove(tx)
  302. }
  303. default:
  304. // ignore other messages
  305. }
  306. }
  307. func (mem *Mempool) resCbRecheck(req *abci.Request, res *abci.Response) {
  308. switch r := res.Value.(type) {
  309. case *abci.Response_CheckTx:
  310. memTx := mem.recheckCursor.Value.(*mempoolTx)
  311. if !bytes.Equal(req.GetCheckTx().Tx, memTx.tx) {
  312. cmn.PanicSanity(
  313. fmt.Sprintf(
  314. "Unexpected tx response from proxy during recheck\nExpected %X, got %X",
  315. r.CheckTx.Data,
  316. memTx.tx,
  317. ),
  318. )
  319. }
  320. if (r.CheckTx.Code == abci.CodeTypeOK) && mem.isPostCheckPass(memTx.tx, r.CheckTx) {
  321. // Good, nothing to do.
  322. } else {
  323. // Tx became invalidated due to newly committed block.
  324. mem.txs.Remove(mem.recheckCursor)
  325. mem.recheckCursor.DetachPrev()
  326. // remove from cache (it might be good later)
  327. mem.cache.Remove(req.GetCheckTx().Tx)
  328. }
  329. if mem.recheckCursor == mem.recheckEnd {
  330. mem.recheckCursor = nil
  331. } else {
  332. mem.recheckCursor = mem.recheckCursor.Next()
  333. }
  334. if mem.recheckCursor == nil {
  335. // Done!
  336. atomic.StoreInt32(&mem.rechecking, 0)
  337. mem.logger.Info("Done rechecking txs")
  338. // incase the recheck removed all txs
  339. if mem.Size() > 0 {
  340. mem.notifyTxsAvailable()
  341. }
  342. }
  343. default:
  344. // ignore other messages
  345. }
  346. }
  347. // TxsAvailable returns a channel which fires once for every height,
  348. // and only when transactions are available in the mempool.
  349. // NOTE: the returned channel may be nil if EnableTxsAvailable was not called.
  350. func (mem *Mempool) TxsAvailable() <-chan struct{} {
  351. return mem.txsAvailable
  352. }
  353. func (mem *Mempool) notifyTxsAvailable() {
  354. if mem.Size() == 0 {
  355. panic("notified txs available but mempool is empty!")
  356. }
  357. if mem.txsAvailable != nil && !mem.notifiedTxsAvailable {
  358. // channel cap is 1, so this will send once
  359. mem.notifiedTxsAvailable = true
  360. select {
  361. case mem.txsAvailable <- struct{}{}:
  362. default:
  363. }
  364. }
  365. }
  366. // ReapMaxBytesMaxGas reaps transactions from the mempool up to maxBytes bytes total
  367. // with the condition that the total gasWanted must be less than maxGas.
  368. // If both maxes are negative, there is no cap on the size of all returned
  369. // transactions (~ all available transactions).
  370. func (mem *Mempool) ReapMaxBytesMaxGas(maxBytes, maxGas int64) types.Txs {
  371. mem.proxyMtx.Lock()
  372. defer mem.proxyMtx.Unlock()
  373. for atomic.LoadInt32(&mem.rechecking) > 0 {
  374. // TODO: Something better?
  375. time.Sleep(time.Millisecond * 10)
  376. }
  377. var totalBytes int64
  378. var totalGas int64
  379. // TODO: we will get a performance boost if we have a good estimate of avg
  380. // size per tx, and set the initial capacity based off of that.
  381. // txs := make([]types.Tx, 0, cmn.MinInt(mem.txs.Len(), max/mem.avgTxSize))
  382. txs := make([]types.Tx, 0, mem.txs.Len())
  383. for e := mem.txs.Front(); e != nil; e = e.Next() {
  384. memTx := e.Value.(*mempoolTx)
  385. // Check total size requirement
  386. aminoOverhead := int64(amino.UvarintSize(uint64(len(memTx.tx))))
  387. if maxBytes > -1 && totalBytes+int64(len(memTx.tx))+aminoOverhead > maxBytes {
  388. return txs
  389. }
  390. totalBytes += int64(len(memTx.tx)) + aminoOverhead
  391. // Check total gas requirement
  392. if maxGas > -1 && totalGas+memTx.gasWanted > maxGas {
  393. return txs
  394. }
  395. totalGas += memTx.gasWanted
  396. txs = append(txs, memTx.tx)
  397. }
  398. return txs
  399. }
  400. // ReapMaxTxs reaps up to max transactions from the mempool.
  401. // If max is negative, there is no cap on the size of all returned
  402. // transactions (~ all available transactions).
  403. func (mem *Mempool) ReapMaxTxs(max int) types.Txs {
  404. mem.proxyMtx.Lock()
  405. defer mem.proxyMtx.Unlock()
  406. if max < 0 {
  407. max = mem.txs.Len()
  408. }
  409. for atomic.LoadInt32(&mem.rechecking) > 0 {
  410. // TODO: Something better?
  411. time.Sleep(time.Millisecond * 10)
  412. }
  413. txs := make([]types.Tx, 0, cmn.MinInt(mem.txs.Len(), max))
  414. for e := mem.txs.Front(); e != nil && len(txs) <= max; e = e.Next() {
  415. memTx := e.Value.(*mempoolTx)
  416. txs = append(txs, memTx.tx)
  417. }
  418. return txs
  419. }
  420. // Update informs the mempool that the given txs were committed and can be discarded.
  421. // NOTE: this should be called *after* block is committed by consensus.
  422. // NOTE: unsafe; Lock/Unlock must be managed by caller
  423. func (mem *Mempool) Update(
  424. height int64,
  425. txs types.Txs,
  426. preCheck PreCheckFunc,
  427. postCheck PostCheckFunc,
  428. ) error {
  429. // First, create a lookup map of txns in new txs.
  430. txsMap := make(map[string]struct{}, len(txs))
  431. for _, tx := range txs {
  432. txsMap[string(tx)] = struct{}{}
  433. }
  434. // Set height
  435. mem.height = height
  436. mem.notifiedTxsAvailable = false
  437. if preCheck != nil {
  438. mem.preCheck = preCheck
  439. }
  440. if postCheck != nil {
  441. mem.postCheck = postCheck
  442. }
  443. // Remove transactions that are already in txs.
  444. goodTxs := mem.filterTxs(txsMap)
  445. // Recheck mempool txs if any txs were committed in the block
  446. // NOTE/XXX: in some apps a tx could be invalidated due to EndBlock,
  447. // so we really still do need to recheck, but this is for debugging
  448. if mem.config.Recheck && (mem.config.RecheckEmpty || len(goodTxs) > 0) {
  449. mem.logger.Info("Recheck txs", "numtxs", len(goodTxs), "height", height)
  450. mem.recheckTxs(goodTxs)
  451. // At this point, mem.txs are being rechecked.
  452. // mem.recheckCursor re-scans mem.txs and possibly removes some txs.
  453. // Before mem.Reap(), we should wait for mem.recheckCursor to be nil.
  454. }
  455. // Update metrics
  456. mem.metrics.Size.Set(float64(mem.Size()))
  457. return nil
  458. }
  459. func (mem *Mempool) filterTxs(blockTxsMap map[string]struct{}) []types.Tx {
  460. goodTxs := make([]types.Tx, 0, mem.txs.Len())
  461. for e := mem.txs.Front(); e != nil; e = e.Next() {
  462. memTx := e.Value.(*mempoolTx)
  463. // Remove the tx if it's alredy in a block.
  464. if _, ok := blockTxsMap[string(memTx.tx)]; ok {
  465. // remove from clist
  466. mem.txs.Remove(e)
  467. e.DetachPrev()
  468. // NOTE: we don't remove committed txs from the cache.
  469. continue
  470. }
  471. // Good tx!
  472. goodTxs = append(goodTxs, memTx.tx)
  473. }
  474. return goodTxs
  475. }
  476. // NOTE: pass in goodTxs because mem.txs can mutate concurrently.
  477. func (mem *Mempool) recheckTxs(goodTxs []types.Tx) {
  478. if len(goodTxs) == 0 {
  479. return
  480. }
  481. atomic.StoreInt32(&mem.rechecking, 1)
  482. mem.recheckCursor = mem.txs.Front()
  483. mem.recheckEnd = mem.txs.Back()
  484. // Push txs to proxyAppConn
  485. // NOTE: resCb() may be called concurrently.
  486. for _, tx := range goodTxs {
  487. mem.proxyAppConn.CheckTxAsync(tx)
  488. }
  489. mem.proxyAppConn.FlushAsync()
  490. }
  491. func (mem *Mempool) isPostCheckPass(tx types.Tx, r *abci.ResponseCheckTx) bool {
  492. return mem.postCheck == nil || mem.postCheck(tx, r)
  493. }
  494. //--------------------------------------------------------------------------------
  495. // mempoolTx is a transaction that successfully ran
  496. type mempoolTx struct {
  497. counter int64 // a simple incrementing counter
  498. height int64 // height that this tx had been validated in
  499. gasWanted int64 // amount of gas this tx states it will require
  500. tx types.Tx //
  501. }
  502. // Height returns the height for this transaction
  503. func (memTx *mempoolTx) Height() int64 {
  504. return atomic.LoadInt64(&memTx.height)
  505. }
  506. //--------------------------------------------------------------------------------
  507. type txCache interface {
  508. Reset()
  509. Push(tx types.Tx) bool
  510. Remove(tx types.Tx)
  511. }
  512. // mapTxCache maintains a cache of transactions. This only stores
  513. // the hash of the tx, due to memory concerns.
  514. type mapTxCache struct {
  515. mtx sync.Mutex
  516. size int
  517. map_ map[[sha256.Size]byte]*list.Element
  518. list *list.List // to remove oldest tx when cache gets too big
  519. }
  520. var _ txCache = (*mapTxCache)(nil)
  521. // newMapTxCache returns a new mapTxCache.
  522. func newMapTxCache(cacheSize int) *mapTxCache {
  523. return &mapTxCache{
  524. size: cacheSize,
  525. map_: make(map[[sha256.Size]byte]*list.Element, cacheSize),
  526. list: list.New(),
  527. }
  528. }
  529. // Reset resets the cache to an empty state.
  530. func (cache *mapTxCache) Reset() {
  531. cache.mtx.Lock()
  532. cache.map_ = make(map[[sha256.Size]byte]*list.Element, cache.size)
  533. cache.list.Init()
  534. cache.mtx.Unlock()
  535. }
  536. // Push adds the given tx to the cache and returns true. It returns false if tx
  537. // is already in the cache.
  538. func (cache *mapTxCache) Push(tx types.Tx) bool {
  539. cache.mtx.Lock()
  540. defer cache.mtx.Unlock()
  541. // Use the tx hash in the cache
  542. txHash := sha256.Sum256(tx)
  543. if moved, exists := cache.map_[txHash]; exists {
  544. cache.list.MoveToFront(moved)
  545. return false
  546. }
  547. if cache.list.Len() >= cache.size {
  548. popped := cache.list.Front()
  549. poppedTxHash := popped.Value.([sha256.Size]byte)
  550. delete(cache.map_, poppedTxHash)
  551. if popped != nil {
  552. cache.list.Remove(popped)
  553. }
  554. }
  555. cache.list.PushBack(txHash)
  556. cache.map_[txHash] = cache.list.Back()
  557. return true
  558. }
  559. // Remove removes the given tx from the cache.
  560. func (cache *mapTxCache) Remove(tx types.Tx) {
  561. cache.mtx.Lock()
  562. txHash := sha256.Sum256(tx)
  563. popped := cache.map_[txHash]
  564. delete(cache.map_, txHash)
  565. if popped != nil {
  566. cache.list.Remove(popped)
  567. }
  568. cache.mtx.Unlock()
  569. }
  570. type nopTxCache struct{}
  571. var _ txCache = (*nopTxCache)(nil)
  572. func (nopTxCache) Reset() {}
  573. func (nopTxCache) Push(types.Tx) bool { return true }
  574. func (nopTxCache) Remove(types.Tx) {}