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.

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