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.

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