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.

388 lines
10 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 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/tendermint/go-clist"
  9. . "github.com/tendermint/go-common"
  10. cfg "github.com/tendermint/go-config"
  11. "github.com/tendermint/tendermint/proxy"
  12. "github.com/tendermint/tendermint/types"
  13. tmsp "github.com/tendermint/tmsp/types"
  14. )
  15. /*
  16. The mempool pushes new txs onto the proxyAppConn.
  17. It gets a stream of (req, res) tuples from the proxy.
  18. The memool stores good txs in a concurrent linked-list.
  19. Multiple concurrent go-routines can traverse this linked-list
  20. safely by calling .NextWait() on each element.
  21. So we have several go-routines:
  22. 1. Consensus calling Update() and Reap() synchronously
  23. 2. Many mempool reactor's peer routines calling CheckTx()
  24. 3. Many mempool reactor's peer routines traversing the txs linked list
  25. 4. Another goroutine calling GarbageCollectTxs() periodically
  26. To manage these goroutines, there are three methods of locking.
  27. 1. Mutations to the linked-list is protected by an internal mtx (CList is goroutine-safe)
  28. 2. Mutations to the linked-list elements are atomic
  29. 3. CheckTx() calls can be paused upon Update() and Reap(), protected by .proxyMtx
  30. Garbage collection of old elements from mempool.txs is handlde via
  31. the DetachPrev() call, which makes old elements not reachable by
  32. peer broadcastTxRoutine() automatically garbage collected.
  33. TODO: Better handle tmsp client errors. (make it automatically handle connection errors)
  34. */
  35. const cacheSize = 100000
  36. type Mempool struct {
  37. config cfg.Config
  38. proxyMtx sync.Mutex
  39. proxyAppConn proxy.AppConnMempool
  40. txs *clist.CList // concurrent linked-list of good txs
  41. counter int64 // simple incrementing counter
  42. height int // the last block Update()'d to
  43. rechecking int32 // for re-checking filtered txs on Update()
  44. recheckCursor *clist.CElement // next expected response
  45. recheckEnd *clist.CElement // re-checking stops here
  46. // Keep a cache of already-seen txs.
  47. // This reduces the pressure on the proxyApp.
  48. cache *txCache
  49. }
  50. func NewMempool(config cfg.Config, proxyAppConn proxy.AppConnMempool) *Mempool {
  51. mempool := &Mempool{
  52. config: config,
  53. proxyAppConn: proxyAppConn,
  54. txs: clist.New(),
  55. counter: 0,
  56. height: 0,
  57. rechecking: 0,
  58. recheckCursor: nil,
  59. recheckEnd: nil,
  60. cache: newTxCache(cacheSize),
  61. }
  62. proxyAppConn.SetResponseCallback(mempool.resCb)
  63. return mempool
  64. }
  65. // consensus must be able to hold lock to safely update
  66. func (mem *Mempool) Lock() {
  67. mem.proxyMtx.Lock()
  68. }
  69. func (mem *Mempool) Unlock() {
  70. mem.proxyMtx.Unlock()
  71. }
  72. // Number of transactions in the mempool clist
  73. func (mem *Mempool) Size() int {
  74. return mem.txs.Len()
  75. }
  76. // Remove all transactions from mempool and cache
  77. func (mem *Mempool) Flush() {
  78. mem.proxyMtx.Lock()
  79. defer mem.proxyMtx.Unlock()
  80. mem.cache.Reset()
  81. for e := mem.txs.Front(); e != nil; e = e.Next() {
  82. mem.txs.Remove(e)
  83. e.DetachPrev()
  84. }
  85. }
  86. // Return the first element of mem.txs for peer goroutines to call .NextWait() on.
  87. // Blocks until txs has elements.
  88. func (mem *Mempool) TxsFrontWait() *clist.CElement {
  89. return mem.txs.FrontWait()
  90. }
  91. // Try a new transaction in the mempool.
  92. // Potentially blocking if we're blocking on Update() or Reap().
  93. // cb: A callback from the CheckTx command.
  94. // It gets called from another goroutine.
  95. // CONTRACT: Either cb will get called, or err returned.
  96. func (mem *Mempool) CheckTx(tx types.Tx, cb func(*tmsp.Response)) (err error) {
  97. mem.proxyMtx.Lock()
  98. defer mem.proxyMtx.Unlock()
  99. // CACHE
  100. if mem.cache.Exists(tx) {
  101. if cb != nil {
  102. cb(&tmsp.Response{
  103. Value: &tmsp.Response_CheckTx{
  104. &tmsp.ResponseCheckTx{
  105. Code: tmsp.CodeType_BadNonce, // TODO or duplicate tx
  106. Log: "Duplicate transaction (ignored)",
  107. },
  108. },
  109. })
  110. }
  111. return nil
  112. }
  113. mem.cache.Push(tx)
  114. // END CACHE
  115. // NOTE: proxyAppConn may error if tx buffer is full
  116. if err = mem.proxyAppConn.Error(); err != nil {
  117. return err
  118. }
  119. reqRes := mem.proxyAppConn.CheckTxAsync(tx)
  120. if cb != nil {
  121. reqRes.SetCallback(cb)
  122. }
  123. return nil
  124. }
  125. // TMSP callback function
  126. func (mem *Mempool) resCb(req *tmsp.Request, res *tmsp.Response) {
  127. if mem.recheckCursor == nil {
  128. mem.resCbNormal(req, res)
  129. } else {
  130. mem.resCbRecheck(req, res)
  131. }
  132. }
  133. func (mem *Mempool) resCbNormal(req *tmsp.Request, res *tmsp.Response) {
  134. switch r := res.Value.(type) {
  135. case *tmsp.Response_CheckTx:
  136. if r.CheckTx.Code == tmsp.CodeType_OK {
  137. mem.counter++
  138. memTx := &mempoolTx{
  139. counter: mem.counter,
  140. height: int64(mem.height),
  141. tx: req.GetCheckTx().Tx,
  142. }
  143. mem.txs.PushBack(memTx)
  144. } else {
  145. // ignore bad transaction
  146. log.Info("Bad Transaction", "res", r)
  147. // remove from cache (it might be good later)
  148. mem.cache.Remove(req.GetCheckTx().Tx)
  149. // TODO: handle other retcodes
  150. }
  151. default:
  152. // ignore other messages
  153. }
  154. }
  155. func (mem *Mempool) resCbRecheck(req *tmsp.Request, res *tmsp.Response) {
  156. switch r := res.Value.(type) {
  157. case *tmsp.Response_CheckTx:
  158. memTx := mem.recheckCursor.Value.(*mempoolTx)
  159. if !bytes.Equal(req.GetCheckTx().Tx, memTx.tx) {
  160. PanicSanity(Fmt("Unexpected tx response from proxy during recheck\n"+
  161. "Expected %X, got %X", r.CheckTx.Data, memTx.tx))
  162. }
  163. if r.CheckTx.Code == tmsp.CodeType_OK {
  164. // Good, nothing to do.
  165. } else {
  166. // Tx became invalidated due to newly committed block.
  167. mem.txs.Remove(mem.recheckCursor)
  168. mem.recheckCursor.DetachPrev()
  169. // remove from cache (it might be good later)
  170. mem.cache.Remove(req.GetCheckTx().Tx)
  171. }
  172. if mem.recheckCursor == mem.recheckEnd {
  173. mem.recheckCursor = nil
  174. } else {
  175. mem.recheckCursor = mem.recheckCursor.Next()
  176. }
  177. if mem.recheckCursor == nil {
  178. // Done!
  179. atomic.StoreInt32(&mem.rechecking, 0)
  180. log.Info("Done rechecking txs")
  181. }
  182. default:
  183. // ignore other messages
  184. }
  185. }
  186. // Get the valid transactions remaining
  187. // If maxTxs is -1, there is no cap on returned transactions.
  188. func (mem *Mempool) Reap(maxTxs int) []types.Tx {
  189. mem.proxyMtx.Lock()
  190. defer mem.proxyMtx.Unlock()
  191. for atomic.LoadInt32(&mem.rechecking) > 0 {
  192. // TODO: Something better?
  193. time.Sleep(time.Millisecond * 10)
  194. }
  195. txs := mem.collectTxs(maxTxs)
  196. return txs
  197. }
  198. // maxTxs: -1 means uncapped, 0 means none
  199. func (mem *Mempool) collectTxs(maxTxs int) []types.Tx {
  200. if maxTxs == 0 {
  201. return []types.Tx{}
  202. } else if maxTxs < 0 {
  203. maxTxs = mem.txs.Len()
  204. }
  205. txs := make([]types.Tx, 0, MinInt(mem.txs.Len(), maxTxs))
  206. for e := mem.txs.Front(); e != nil && len(txs) < maxTxs; e = e.Next() {
  207. memTx := e.Value.(*mempoolTx)
  208. txs = append(txs, memTx.tx)
  209. }
  210. return txs
  211. }
  212. // Tell mempool that these txs were committed.
  213. // Mempool will discard these txs.
  214. // NOTE: this should be called *after* block is committed by consensus.
  215. // NOTE: unsafe; Lock/Unlock must be managed by caller
  216. func (mem *Mempool) Update(height int, txs []types.Tx) {
  217. // mem.proxyMtx.Lock()
  218. // defer mem.proxyMtx.Unlock()
  219. mem.proxyAppConn.FlushSync() // To flush async resCb calls e.g. from CheckTx
  220. // First, create a lookup map of txns in new txs.
  221. txsMap := make(map[string]struct{})
  222. for _, tx := range txs {
  223. txsMap[string(tx)] = struct{}{}
  224. }
  225. // Set height
  226. mem.height = height
  227. // Remove transactions that are already in txs.
  228. goodTxs := mem.filterTxs(txsMap)
  229. // Recheck mempool txs if any txs were committed in the block
  230. // NOTE/XXX: in some apps a tx could be invalidated due to EndBlock,
  231. // so we really still do need to recheck, but this is for debugging
  232. if mem.config.GetBool("mempool_recheck") &&
  233. (mem.config.GetBool("mempool_recheck_empty") || len(txs) > 0) {
  234. log.Info("Recheck txs", "numtxs", len(goodTxs))
  235. mem.recheckTxs(goodTxs)
  236. // At this point, mem.txs are being rechecked.
  237. // mem.recheckCursor re-scans mem.txs and possibly removes some txs.
  238. // Before mem.Reap(), we should wait for mem.recheckCursor to be nil.
  239. }
  240. }
  241. func (mem *Mempool) filterTxs(blockTxsMap map[string]struct{}) []types.Tx {
  242. goodTxs := make([]types.Tx, 0, mem.txs.Len())
  243. for e := mem.txs.Front(); e != nil; e = e.Next() {
  244. memTx := e.Value.(*mempoolTx)
  245. // Remove the tx if it's alredy in a block.
  246. if _, ok := blockTxsMap[string(memTx.tx)]; ok {
  247. // remove from clist
  248. mem.txs.Remove(e)
  249. e.DetachPrev()
  250. // NOTE: we don't remove committed txs from the cache.
  251. continue
  252. }
  253. // Good tx!
  254. goodTxs = append(goodTxs, memTx.tx)
  255. }
  256. return goodTxs
  257. }
  258. // NOTE: pass in goodTxs because mem.txs can mutate concurrently.
  259. func (mem *Mempool) recheckTxs(goodTxs []types.Tx) {
  260. if len(goodTxs) == 0 {
  261. return
  262. }
  263. atomic.StoreInt32(&mem.rechecking, 1)
  264. mem.recheckCursor = mem.txs.Front()
  265. mem.recheckEnd = mem.txs.Back()
  266. // Push txs to proxyAppConn
  267. // NOTE: resCb() may be called concurrently.
  268. for _, tx := range goodTxs {
  269. mem.proxyAppConn.CheckTxAsync(tx)
  270. }
  271. mem.proxyAppConn.FlushAsync()
  272. }
  273. //--------------------------------------------------------------------------------
  274. // A transaction that successfully ran
  275. type mempoolTx struct {
  276. counter int64 // a simple incrementing counter
  277. height int64 // height that this tx had been validated in
  278. tx types.Tx //
  279. }
  280. func (memTx *mempoolTx) Height() int {
  281. return int(atomic.LoadInt64(&memTx.height))
  282. }
  283. //--------------------------------------------------------------------------------
  284. type txCache struct {
  285. mtx sync.Mutex
  286. size int
  287. map_ map[string]struct{}
  288. list *list.List // to remove oldest tx when cache gets too big
  289. }
  290. func newTxCache(cacheSize int) *txCache {
  291. return &txCache{
  292. size: cacheSize,
  293. map_: make(map[string]struct{}, cacheSize),
  294. list: list.New(),
  295. }
  296. }
  297. func (cache *txCache) Reset() {
  298. cache.mtx.Lock()
  299. cache.map_ = make(map[string]struct{}, cacheSize)
  300. cache.list.Init()
  301. cache.mtx.Unlock()
  302. }
  303. func (cache *txCache) Exists(tx types.Tx) bool {
  304. cache.mtx.Lock()
  305. _, exists := cache.map_[string(tx)]
  306. cache.mtx.Unlock()
  307. return exists
  308. }
  309. // Returns false if tx is in cache.
  310. func (cache *txCache) Push(tx types.Tx) bool {
  311. cache.mtx.Lock()
  312. defer cache.mtx.Unlock()
  313. if _, exists := cache.map_[string(tx)]; exists {
  314. return false
  315. }
  316. if cache.list.Len() >= cache.size {
  317. popped := cache.list.Front()
  318. poppedTx := popped.Value.(types.Tx)
  319. // NOTE: the tx may have already been removed from the map
  320. // but deleting a non-existant element is fine
  321. delete(cache.map_, string(poppedTx))
  322. cache.list.Remove(popped)
  323. }
  324. cache.map_[string(tx)] = struct{}{}
  325. cache.list.PushBack(tx)
  326. return true
  327. }
  328. func (cache *txCache) Remove(tx types.Tx) {
  329. cache.mtx.Lock()
  330. delete(cache.map_, string(tx))
  331. cache.mtx.Unlock()
  332. }