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.

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