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.

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