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.

477 lines
13 KiB

9 years ago
9 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 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
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
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
8 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. "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. // Keep a cache of already-seen txs.
  53. // This reduces the pressure on the proxyApp.
  54. cache *txCache
  55. // A log of mempool txs
  56. wal *auto.AutoFile
  57. // fires once for each height, when the mempool is not empty
  58. txsAvailable chan struct{}
  59. notifiedTxsAvailable bool
  60. logger log.Logger
  61. }
  62. // NewMempool returns a new Mempool with the given configuration and connection to an application.
  63. func NewMempool(config *cfg.MempoolConfig, proxyAppConn proxy.AppConnMempool) *Mempool {
  64. mempool := &Mempool{
  65. config: config,
  66. proxyAppConn: proxyAppConn,
  67. txs: clist.New(),
  68. counter: 0,
  69. height: 0,
  70. rechecking: 0,
  71. recheckCursor: nil,
  72. recheckEnd: nil,
  73. logger: log.NewNopLogger(),
  74. cache: newTxCache(cacheSize),
  75. }
  76. mempool.initWAL()
  77. proxyAppConn.SetResponseCallback(mempool.resCb)
  78. return mempool
  79. }
  80. // FireOnTxsAvailable initializes the TxsAvailable channel,
  81. // ensuring it will trigger once every height when transactions are available.
  82. func (mem *Mempool) FireOnTxsAvailable() {
  83. mem.txsAvailable = make(chan struct{}, 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.alertIfTxsAvailable()
  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.alertIfTxsAvailable()
  230. }
  231. default:
  232. // ignore other messages
  233. }
  234. }
  235. func (mem *Mempool) alertIfTxsAvailable() {
  236. if !mem.notifiedTxsAvailable && mem.Size() > 0 {
  237. mem.notifiedTxsAvailable = true
  238. mem.txsAvailable <- struct{}{}
  239. }
  240. }
  241. // TxsAvailable returns a channel which fires once for every height,
  242. // and only when transactions are available in the mempool.
  243. // XXX: Will panic if mem.FireOnTxsAvailable() has not been called.
  244. func (mem *Mempool) TxsAvailable() chan struct{} {
  245. if mem.txsAvailable == nil {
  246. panic("mem.txsAvailable is nil")
  247. }
  248. return mem.txsAvailable
  249. }
  250. func (mem *Mempool) alertIfTxsAvailable() {
  251. if mem.txsAvailable != nil &&
  252. !mem.notifiedTxsAvailable && mem.Size() > 0 {
  253. mem.notifiedTxsAvailable = true
  254. mem.txsAvailable <- struct{}{}
  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. }