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.

602 lines
17 KiB

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