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
8 years ago
8 years ago
9 years ago
8 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
8 years ago
9 years ago
9 years ago
8 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. const cacheSize = 100000
  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 int // 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 int // 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 int) *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(cacheSize),
  76. }
  77. mempool.initWAL()
  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 int, 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. // Flush removes all transactions from the mempool and cache
  135. func (mem *Mempool) Flush() {
  136. mem.proxyMtx.Lock()
  137. defer mem.proxyMtx.Unlock()
  138. mem.cache.Reset()
  139. for e := mem.txs.Front(); e != nil; e = e.Next() {
  140. mem.txs.Remove(e)
  141. e.DetachPrev()
  142. }
  143. }
  144. // TxsFrontWait returns the first transaction in the ordered list for peer goroutines to call .NextWait() on.
  145. // It blocks until the mempool is not empty (ie. until the internal `mem.txs` has at least one element)
  146. func (mem *Mempool) TxsFrontWait() *clist.CElement {
  147. return mem.txs.FrontWait()
  148. }
  149. // CheckTx executes a new transaction against the application to determine its validity
  150. // and whether it should be added to the mempool.
  151. // It blocks if we're waiting on Update() or Reap().
  152. // cb: A callback from the CheckTx command.
  153. // It gets called from another goroutine.
  154. // CONTRACT: Either cb will get called, or err returned.
  155. func (mem *Mempool) CheckTx(tx types.Tx, cb func(*abci.Response)) (err error) {
  156. mem.proxyMtx.Lock()
  157. defer mem.proxyMtx.Unlock()
  158. // CACHE
  159. if mem.cache.Exists(tx) {
  160. if cb != nil {
  161. cb(&abci.Response{
  162. Value: &abci.Response_CheckTx{
  163. &abci.ResponseCheckTx{
  164. Code: abci.CodeType_BadNonce, // TODO or duplicate tx
  165. Log: "Duplicate transaction (ignored)",
  166. },
  167. },
  168. })
  169. }
  170. return nil // TODO: return an error (?)
  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.CodeType_OK {
  210. mem.counter++
  211. memTx := &mempoolTx{
  212. counter: mem.counter,
  213. height: int64(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.CodeType_OK {
  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 int {
  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 int, txs types.Txs) error {
  310. if err := mem.proxyAppConn.FlushSync(); err != nil { // To flush async resCb calls e.g. from CheckTx
  311. return err
  312. }
  313. // First, create a lookup map of txns in new txs.
  314. txsMap := make(map[string]struct{})
  315. for _, tx := range txs {
  316. txsMap[string(tx)] = struct{}{}
  317. }
  318. // Set height
  319. mem.height = height
  320. mem.notifiedTxsAvailable = false
  321. // Remove transactions that are already in txs.
  322. goodTxs := mem.filterTxs(txsMap)
  323. // Recheck mempool txs if any txs were committed in the block
  324. // NOTE/XXX: in some apps a tx could be invalidated due to EndBlock,
  325. // so we really still do need to recheck, but this is for debugging
  326. if mem.config.Recheck && (mem.config.RecheckEmpty || len(txs) > 0) {
  327. mem.logger.Info("Recheck txs", "numtxs", len(goodTxs), "height", height)
  328. mem.recheckTxs(goodTxs)
  329. // At this point, mem.txs are being rechecked.
  330. // mem.recheckCursor re-scans mem.txs and possibly removes some txs.
  331. // Before mem.Reap(), we should wait for mem.recheckCursor to be nil.
  332. }
  333. return nil
  334. }
  335. func (mem *Mempool) filterTxs(blockTxsMap map[string]struct{}) []types.Tx {
  336. goodTxs := make([]types.Tx, 0, mem.txs.Len())
  337. for e := mem.txs.Front(); e != nil; e = e.Next() {
  338. memTx := e.Value.(*mempoolTx)
  339. // Remove the tx if it's alredy in a block.
  340. if _, ok := blockTxsMap[string(memTx.tx)]; ok {
  341. // remove from clist
  342. mem.txs.Remove(e)
  343. e.DetachPrev()
  344. // NOTE: we don't remove committed txs from the cache.
  345. continue
  346. }
  347. // Good tx!
  348. goodTxs = append(goodTxs, memTx.tx)
  349. }
  350. return goodTxs
  351. }
  352. // NOTE: pass in goodTxs because mem.txs can mutate concurrently.
  353. func (mem *Mempool) recheckTxs(goodTxs []types.Tx) {
  354. if len(goodTxs) == 0 {
  355. return
  356. }
  357. atomic.StoreInt32(&mem.rechecking, 1)
  358. mem.recheckCursor = mem.txs.Front()
  359. mem.recheckEnd = mem.txs.Back()
  360. // Push txs to proxyAppConn
  361. // NOTE: resCb() may be called concurrently.
  362. for _, tx := range goodTxs {
  363. mem.proxyAppConn.CheckTxAsync(tx)
  364. }
  365. mem.proxyAppConn.FlushAsync()
  366. }
  367. //--------------------------------------------------------------------------------
  368. // mempoolTx is a transaction that successfully ran
  369. type mempoolTx struct {
  370. counter int64 // a simple incrementing counter
  371. height int64 // height that this tx had been validated in
  372. tx types.Tx //
  373. }
  374. // Height returns the height for this transaction
  375. func (memTx *mempoolTx) Height() int {
  376. return int(atomic.LoadInt64(&memTx.height))
  377. }
  378. //--------------------------------------------------------------------------------
  379. // txCache maintains a cache of transactions.
  380. type txCache struct {
  381. mtx sync.Mutex
  382. size int
  383. map_ map[string]struct{}
  384. list *list.List // to remove oldest tx when cache gets too big
  385. }
  386. // newTxCache returns a new txCache.
  387. func newTxCache(cacheSize int) *txCache {
  388. return &txCache{
  389. size: cacheSize,
  390. map_: make(map[string]struct{}, cacheSize),
  391. list: list.New(),
  392. }
  393. }
  394. // Reset resets the txCache to empty.
  395. func (cache *txCache) Reset() {
  396. cache.mtx.Lock()
  397. cache.map_ = make(map[string]struct{}, cacheSize)
  398. cache.list.Init()
  399. cache.mtx.Unlock()
  400. }
  401. // Exists returns true if the given tx is cached.
  402. func (cache *txCache) Exists(tx types.Tx) bool {
  403. cache.mtx.Lock()
  404. _, exists := cache.map_[string(tx)]
  405. cache.mtx.Unlock()
  406. return exists
  407. }
  408. // Push adds the given tx to the txCache. It returns false if tx is already in the cache.
  409. func (cache *txCache) Push(tx types.Tx) bool {
  410. cache.mtx.Lock()
  411. defer cache.mtx.Unlock()
  412. if _, exists := cache.map_[string(tx)]; exists {
  413. return false
  414. }
  415. if cache.list.Len() >= cache.size {
  416. popped := cache.list.Front()
  417. poppedTx := popped.Value.(types.Tx)
  418. // NOTE: the tx may have already been removed from the map
  419. // but deleting a non-existent element is fine
  420. delete(cache.map_, string(poppedTx))
  421. cache.list.Remove(popped)
  422. }
  423. cache.map_[string(tx)] = struct{}{}
  424. cache.list.PushBack(tx)
  425. return true
  426. }
  427. // Remove removes the given tx from the cache.
  428. func (cache *txCache) Remove(tx types.Tx) {
  429. cache.mtx.Lock()
  430. delete(cache.map_, string(tx))
  431. cache.mtx.Unlock()
  432. }