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.

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