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.

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