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.

699 lines
20 KiB

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