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.

481 lines
14 KiB

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