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.

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