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.

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