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.

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