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.

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