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.

560 lines
16 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
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. // Keep a cache of already-seen txs.
  67. // This reduces the pressure on the proxyApp.
  68. cache txCache
  69. // A log of mempool txs
  70. wal *auto.AutoFile
  71. logger log.Logger
  72. metrics *Metrics
  73. }
  74. // MempoolOption sets an optional parameter on the Mempool.
  75. type MempoolOption func(*Mempool)
  76. // NewMempool returns a new Mempool with the given configuration and connection to an application.
  77. func NewMempool(
  78. config *cfg.MempoolConfig,
  79. proxyAppConn proxy.AppConnMempool,
  80. height int64,
  81. options ...MempoolOption,
  82. ) *Mempool {
  83. mempool := &Mempool{
  84. config: config,
  85. proxyAppConn: proxyAppConn,
  86. txs: clist.New(),
  87. counter: 0,
  88. height: height,
  89. rechecking: 0,
  90. recheckCursor: nil,
  91. recheckEnd: nil,
  92. logger: log.NewNopLogger(),
  93. metrics: NopMetrics(),
  94. }
  95. if config.CacheSize > 0 {
  96. mempool.cache = newMapTxCache(config.CacheSize)
  97. } else {
  98. mempool.cache = nopTxCache{}
  99. }
  100. proxyAppConn.SetResponseCallback(mempool.resCb)
  101. for _, option := range options {
  102. option(mempool)
  103. }
  104. return mempool
  105. }
  106. // EnableTxsAvailable initializes the TxsAvailable channel,
  107. // ensuring it will trigger once every height when transactions are available.
  108. // NOTE: not thread safe - should only be called once, on startup
  109. func (mem *Mempool) EnableTxsAvailable() {
  110. mem.txsAvailable = make(chan struct{}, 1)
  111. }
  112. // SetLogger sets the Logger.
  113. func (mem *Mempool) SetLogger(l log.Logger) {
  114. mem.logger = l
  115. }
  116. // WithMetrics sets the metrics.
  117. func WithMetrics(metrics *Metrics) MempoolOption {
  118. return func(mem *Mempool) { mem.metrics = metrics }
  119. }
  120. // CloseWAL closes and discards the underlying WAL file.
  121. // Any further writes will not be relayed to disk.
  122. func (mem *Mempool) CloseWAL() bool {
  123. if mem == nil {
  124. return false
  125. }
  126. mem.proxyMtx.Lock()
  127. defer mem.proxyMtx.Unlock()
  128. if mem.wal == nil {
  129. return false
  130. }
  131. if err := mem.wal.Close(); err != nil && mem.logger != nil {
  132. mem.logger.Error("Mempool.CloseWAL", "err", err)
  133. }
  134. mem.wal = nil
  135. return true
  136. }
  137. func (mem *Mempool) InitWAL() {
  138. walDir := mem.config.WalDir()
  139. if walDir != "" {
  140. err := cmn.EnsureDir(walDir, 0700)
  141. if err != nil {
  142. cmn.PanicSanity(errors.Wrap(err, "Error ensuring Mempool wal dir"))
  143. }
  144. af, err := auto.OpenAutoFile(walDir + "/wal")
  145. if err != nil {
  146. cmn.PanicSanity(errors.Wrap(err, "Error opening Mempool wal file"))
  147. }
  148. mem.wal = af
  149. }
  150. }
  151. // Lock locks the mempool. The consensus must be able to hold lock to safely update.
  152. func (mem *Mempool) Lock() {
  153. mem.proxyMtx.Lock()
  154. }
  155. // Unlock unlocks the mempool.
  156. func (mem *Mempool) Unlock() {
  157. mem.proxyMtx.Unlock()
  158. }
  159. // Size returns the number of transactions in the mempool.
  160. func (mem *Mempool) Size() int {
  161. return mem.txs.Len()
  162. }
  163. // Flushes the mempool connection to ensure async resCb calls are done e.g.
  164. // from CheckTx.
  165. func (mem *Mempool) FlushAppConn() error {
  166. return mem.proxyAppConn.FlushSync()
  167. }
  168. // Flush removes all transactions from the mempool and cache
  169. func (mem *Mempool) Flush() {
  170. mem.proxyMtx.Lock()
  171. defer mem.proxyMtx.Unlock()
  172. mem.cache.Reset()
  173. for e := mem.txs.Front(); e != nil; e = e.Next() {
  174. mem.txs.Remove(e)
  175. e.DetachPrev()
  176. }
  177. }
  178. // TxsFront returns the first transaction in the ordered list for peer
  179. // goroutines to call .NextWait() on.
  180. func (mem *Mempool) TxsFront() *clist.CElement {
  181. return mem.txs.Front()
  182. }
  183. // TxsWaitChan returns a channel to wait on transactions. It will be closed
  184. // once the mempool is not empty (ie. the internal `mem.txs` has at least one
  185. // element)
  186. func (mem *Mempool) TxsWaitChan() <-chan struct{} {
  187. return mem.txs.WaitChan()
  188. }
  189. // CheckTx executes a new transaction against the application to determine its validity
  190. // and whether it should be added to the mempool.
  191. // It blocks if we're waiting on Update() or Reap().
  192. // cb: A callback from the CheckTx command.
  193. // It gets called from another goroutine.
  194. // CONTRACT: Either cb will get called, or err returned.
  195. func (mem *Mempool) CheckTx(tx types.Tx, cb func(*abci.Response)) (err error) {
  196. mem.proxyMtx.Lock()
  197. defer mem.proxyMtx.Unlock()
  198. if mem.Size() >= mem.config.Size {
  199. return ErrMempoolIsFull
  200. }
  201. // CACHE
  202. if !mem.cache.Push(tx) {
  203. return ErrTxInCache
  204. }
  205. // END CACHE
  206. // WAL
  207. if mem.wal != nil {
  208. // TODO: Notify administrators when WAL fails
  209. _, err := mem.wal.Write([]byte(tx))
  210. if err != nil {
  211. mem.logger.Error("Error writing to WAL", "err", err)
  212. }
  213. _, err = mem.wal.Write([]byte("\n"))
  214. if err != nil {
  215. mem.logger.Error("Error writing to WAL", "err", err)
  216. }
  217. }
  218. // END WAL
  219. // NOTE: proxyAppConn may error if tx buffer is full
  220. if err = mem.proxyAppConn.Error(); err != nil {
  221. return err
  222. }
  223. reqRes := mem.proxyAppConn.CheckTxAsync(tx)
  224. if cb != nil {
  225. reqRes.SetCallback(cb)
  226. }
  227. return nil
  228. }
  229. // ABCI callback function
  230. func (mem *Mempool) resCb(req *abci.Request, res *abci.Response) {
  231. if mem.recheckCursor == nil {
  232. mem.resCbNormal(req, res)
  233. } else {
  234. mem.resCbRecheck(req, res)
  235. }
  236. mem.metrics.Size.Set(float64(mem.Size()))
  237. }
  238. func (mem *Mempool) resCbNormal(req *abci.Request, res *abci.Response) {
  239. switch r := res.Value.(type) {
  240. case *abci.Response_CheckTx:
  241. tx := req.GetCheckTx().Tx
  242. if r.CheckTx.Code == abci.CodeTypeOK {
  243. mem.counter++
  244. memTx := &mempoolTx{
  245. counter: mem.counter,
  246. height: mem.height,
  247. tx: tx,
  248. }
  249. mem.txs.PushBack(memTx)
  250. mem.logger.Info("Added good transaction", "tx", TxID(tx), "res", r, "total", mem.Size())
  251. mem.notifyTxsAvailable()
  252. } else {
  253. // ignore bad transaction
  254. mem.logger.Info("Rejected bad transaction", "tx", TxID(tx), "res", r)
  255. // remove from cache (it might be good later)
  256. mem.cache.Remove(tx)
  257. }
  258. default:
  259. // ignore other messages
  260. }
  261. }
  262. func (mem *Mempool) resCbRecheck(req *abci.Request, res *abci.Response) {
  263. switch r := res.Value.(type) {
  264. case *abci.Response_CheckTx:
  265. memTx := mem.recheckCursor.Value.(*mempoolTx)
  266. if !bytes.Equal(req.GetCheckTx().Tx, memTx.tx) {
  267. cmn.PanicSanity(fmt.Sprintf("Unexpected tx response from proxy during recheck\n"+
  268. "Expected %X, got %X", r.CheckTx.Data, memTx.tx))
  269. }
  270. if r.CheckTx.Code == abci.CodeTypeOK {
  271. // Good, nothing to do.
  272. } else {
  273. // Tx became invalidated due to newly committed block.
  274. mem.txs.Remove(mem.recheckCursor)
  275. mem.recheckCursor.DetachPrev()
  276. // remove from cache (it might be good later)
  277. mem.cache.Remove(req.GetCheckTx().Tx)
  278. }
  279. if mem.recheckCursor == mem.recheckEnd {
  280. mem.recheckCursor = nil
  281. } else {
  282. mem.recheckCursor = mem.recheckCursor.Next()
  283. }
  284. if mem.recheckCursor == nil {
  285. // Done!
  286. atomic.StoreInt32(&mem.rechecking, 0)
  287. mem.logger.Info("Done rechecking txs")
  288. // incase the recheck removed all txs
  289. if mem.Size() > 0 {
  290. mem.notifyTxsAvailable()
  291. }
  292. }
  293. default:
  294. // ignore other messages
  295. }
  296. }
  297. // TxsAvailable returns a channel which fires once for every height,
  298. // and only when transactions are available in the mempool.
  299. // NOTE: the returned channel may be nil if EnableTxsAvailable was not called.
  300. func (mem *Mempool) TxsAvailable() <-chan struct{} {
  301. return mem.txsAvailable
  302. }
  303. func (mem *Mempool) notifyTxsAvailable() {
  304. if mem.Size() == 0 {
  305. panic("notified txs available but mempool is empty!")
  306. }
  307. if mem.txsAvailable != nil && !mem.notifiedTxsAvailable {
  308. // channel cap is 1, so this will send once
  309. mem.notifiedTxsAvailable = true
  310. select {
  311. case mem.txsAvailable <- struct{}{}:
  312. default:
  313. }
  314. }
  315. }
  316. // Reap returns a list of transactions currently in the mempool.
  317. // If maxTxs is -1, there is no cap on the number of returned transactions.
  318. func (mem *Mempool) Reap(maxTxs int) types.Txs {
  319. mem.proxyMtx.Lock()
  320. defer mem.proxyMtx.Unlock()
  321. for atomic.LoadInt32(&mem.rechecking) > 0 {
  322. // TODO: Something better?
  323. time.Sleep(time.Millisecond * 10)
  324. }
  325. txs := mem.collectTxs(maxTxs)
  326. return txs
  327. }
  328. // maxTxs: -1 means uncapped, 0 means none
  329. func (mem *Mempool) collectTxs(maxTxs int) types.Txs {
  330. if maxTxs == 0 {
  331. return []types.Tx{}
  332. } else if maxTxs < 0 {
  333. maxTxs = mem.txs.Len()
  334. }
  335. txs := make([]types.Tx, 0, cmn.MinInt(mem.txs.Len(), maxTxs))
  336. for e := mem.txs.Front(); e != nil && len(txs) < maxTxs; e = e.Next() {
  337. memTx := e.Value.(*mempoolTx)
  338. txs = append(txs, memTx.tx)
  339. }
  340. return txs
  341. }
  342. // Update informs the mempool that the given txs were committed and can be discarded.
  343. // NOTE: this should be called *after* block is committed by consensus.
  344. // NOTE: unsafe; Lock/Unlock must be managed by caller
  345. func (mem *Mempool) Update(height int64, txs types.Txs) error {
  346. // First, create a lookup map of txns in new txs.
  347. txsMap := make(map[string]struct{}, len(txs))
  348. for _, tx := range txs {
  349. txsMap[string(tx)] = struct{}{}
  350. }
  351. // Set height
  352. mem.height = height
  353. mem.notifiedTxsAvailable = false
  354. // Remove transactions that are already in txs.
  355. goodTxs := mem.filterTxs(txsMap)
  356. // Recheck mempool txs if any txs were committed in the block
  357. // NOTE/XXX: in some apps a tx could be invalidated due to EndBlock,
  358. // so we really still do need to recheck, but this is for debugging
  359. if mem.config.Recheck && (mem.config.RecheckEmpty || len(goodTxs) > 0) {
  360. mem.logger.Info("Recheck txs", "numtxs", len(goodTxs), "height", height)
  361. mem.recheckTxs(goodTxs)
  362. // At this point, mem.txs are being rechecked.
  363. // mem.recheckCursor re-scans mem.txs and possibly removes some txs.
  364. // Before mem.Reap(), we should wait for mem.recheckCursor to be nil.
  365. }
  366. mem.metrics.Size.Set(float64(mem.Size()))
  367. return nil
  368. }
  369. func (mem *Mempool) filterTxs(blockTxsMap map[string]struct{}) []types.Tx {
  370. goodTxs := make([]types.Tx, 0, mem.txs.Len())
  371. for e := mem.txs.Front(); e != nil; e = e.Next() {
  372. memTx := e.Value.(*mempoolTx)
  373. // Remove the tx if it's alredy in a block.
  374. if _, ok := blockTxsMap[string(memTx.tx)]; ok {
  375. // remove from clist
  376. mem.txs.Remove(e)
  377. e.DetachPrev()
  378. // NOTE: we don't remove committed txs from the cache.
  379. continue
  380. }
  381. // Good tx!
  382. goodTxs = append(goodTxs, memTx.tx)
  383. }
  384. return goodTxs
  385. }
  386. // NOTE: pass in goodTxs because mem.txs can mutate concurrently.
  387. func (mem *Mempool) recheckTxs(goodTxs []types.Tx) {
  388. if len(goodTxs) == 0 {
  389. return
  390. }
  391. atomic.StoreInt32(&mem.rechecking, 1)
  392. mem.recheckCursor = mem.txs.Front()
  393. mem.recheckEnd = mem.txs.Back()
  394. // Push txs to proxyAppConn
  395. // NOTE: resCb() may be called concurrently.
  396. for _, tx := range goodTxs {
  397. mem.proxyAppConn.CheckTxAsync(tx)
  398. }
  399. mem.proxyAppConn.FlushAsync()
  400. }
  401. //--------------------------------------------------------------------------------
  402. // mempoolTx is a transaction that successfully ran
  403. type mempoolTx struct {
  404. counter int64 // a simple incrementing counter
  405. height int64 // height that this tx had been validated in
  406. tx types.Tx //
  407. }
  408. // Height returns the height for this transaction
  409. func (memTx *mempoolTx) Height() int64 {
  410. return atomic.LoadInt64(&memTx.height)
  411. }
  412. //--------------------------------------------------------------------------------
  413. type txCache interface {
  414. Reset()
  415. Push(tx types.Tx) bool
  416. Remove(tx types.Tx)
  417. }
  418. // mapTxCache maintains a cache of transactions. This only stores
  419. // the hash of the tx, due to memory concerns.
  420. type mapTxCache struct {
  421. mtx sync.Mutex
  422. size int
  423. map_ map[[sha256.Size]byte]*list.Element
  424. list *list.List // to remove oldest tx when cache gets too big
  425. }
  426. var _ txCache = (*mapTxCache)(nil)
  427. // newMapTxCache returns a new mapTxCache.
  428. func newMapTxCache(cacheSize int) *mapTxCache {
  429. return &mapTxCache{
  430. size: cacheSize,
  431. map_: make(map[[sha256.Size]byte]*list.Element, cacheSize),
  432. list: list.New(),
  433. }
  434. }
  435. // Reset resets the cache to an empty state.
  436. func (cache *mapTxCache) Reset() {
  437. cache.mtx.Lock()
  438. cache.map_ = make(map[[sha256.Size]byte]*list.Element, cache.size)
  439. cache.list.Init()
  440. cache.mtx.Unlock()
  441. }
  442. // Push adds the given tx to the cache and returns true. It returns false if tx
  443. // is already in the cache.
  444. func (cache *mapTxCache) Push(tx types.Tx) bool {
  445. cache.mtx.Lock()
  446. defer cache.mtx.Unlock()
  447. // Use the tx hash in the cache
  448. txHash := sha256.Sum256(tx)
  449. if _, exists := cache.map_[txHash]; exists {
  450. return false
  451. }
  452. if cache.list.Len() >= cache.size {
  453. popped := cache.list.Front()
  454. poppedTxHash := popped.Value.([sha256.Size]byte)
  455. delete(cache.map_, poppedTxHash)
  456. if popped != nil {
  457. cache.list.Remove(popped)
  458. }
  459. }
  460. cache.list.PushBack(txHash)
  461. cache.map_[txHash] = cache.list.Back()
  462. return true
  463. }
  464. // Remove removes the given tx from the cache.
  465. func (cache *mapTxCache) Remove(tx types.Tx) {
  466. cache.mtx.Lock()
  467. txHash := sha256.Sum256(tx)
  468. popped := cache.map_[txHash]
  469. delete(cache.map_, txHash)
  470. if popped != nil {
  471. cache.list.Remove(popped)
  472. }
  473. cache.mtx.Unlock()
  474. }
  475. type nopTxCache struct{}
  476. var _ txCache = (*nopTxCache)(nil)
  477. func (nopTxCache) Reset() {}
  478. func (nopTxCache) Push(types.Tx) bool { return true }
  479. func (nopTxCache) Remove(types.Tx) {}