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.

350 lines
9.8 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
  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.AppConn
  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. cacheMap map[string]struct{}
  49. cacheList *list.List // to remove oldest tx when cache gets too big
  50. }
  51. func NewMempool(config cfg.Config, proxyAppConn proxy.AppConn) *Mempool {
  52. mempool := &Mempool{
  53. config: config,
  54. proxyAppConn: proxyAppConn,
  55. txs: clist.New(),
  56. counter: 0,
  57. height: 0,
  58. rechecking: 0,
  59. recheckCursor: nil,
  60. recheckEnd: nil,
  61. cacheMap: make(map[string]struct{}, cacheSize),
  62. cacheList: list.New(),
  63. }
  64. proxyAppConn.SetResponseCallback(mempool.resCb)
  65. return mempool
  66. }
  67. // consensus must be able to hold lock to safely update
  68. func (mem *Mempool) Lock() {
  69. mem.proxyMtx.Lock()
  70. }
  71. func (mem *Mempool) Unlock() {
  72. mem.proxyMtx.Unlock()
  73. }
  74. // Number of transactions in the mempool clist
  75. func (mem *Mempool) Size() int {
  76. return mem.txs.Len()
  77. }
  78. // Remove all transactions from mempool and cache
  79. func (mem *Mempool) Flush() {
  80. mem.proxyMtx.Lock()
  81. defer mem.proxyMtx.Unlock()
  82. mem.cacheMap = make(map[string]struct{}, cacheSize)
  83. mem.cacheList.Init()
  84. for e := mem.txs.Front(); e != nil; e = e.Next() {
  85. mem.txs.Remove(e)
  86. e.DetachPrev()
  87. }
  88. }
  89. // Return the first element of mem.txs for peer goroutines to call .NextWait() on.
  90. // Blocks until txs has elements.
  91. func (mem *Mempool) TxsFrontWait() *clist.CElement {
  92. return mem.txs.FrontWait()
  93. }
  94. // Try a new transaction in the mempool.
  95. // Potentially blocking if we're blocking on Update() or Reap().
  96. // cb: A callback from the CheckTx command.
  97. // It gets called from another goroutine.
  98. // CONTRACT: Either cb will get called, or err returned.
  99. func (mem *Mempool) CheckTx(tx types.Tx, cb func(*tmsp.Response)) (err error) {
  100. mem.proxyMtx.Lock()
  101. defer mem.proxyMtx.Unlock()
  102. // CACHE
  103. if _, exists := mem.cacheMap[string(tx)]; exists {
  104. if cb != nil {
  105. cb(&tmsp.Response{
  106. Value: &tmsp.Response_CheckTx{
  107. &tmsp.ResponseCheckTx{
  108. Code: tmsp.CodeType_BadNonce, // TODO or duplicate tx
  109. Log: "Duplicate transaction (ignored)",
  110. },
  111. },
  112. })
  113. }
  114. return nil
  115. }
  116. if mem.cacheList.Len() >= cacheSize {
  117. popped := mem.cacheList.Front()
  118. poppedTx := popped.Value.(types.Tx)
  119. // NOTE: the tx may have already been removed from the map
  120. // but deleting a non-existant element is fine
  121. delete(mem.cacheMap, string(poppedTx))
  122. mem.cacheList.Remove(popped)
  123. }
  124. mem.cacheMap[string(tx)] = struct{}{}
  125. mem.cacheList.PushBack(tx)
  126. // END CACHE
  127. // NOTE: proxyAppConn may error if tx buffer is full
  128. if err = mem.proxyAppConn.Error(); err != nil {
  129. return err
  130. }
  131. reqRes := mem.proxyAppConn.CheckTxAsync(tx)
  132. if cb != nil {
  133. reqRes.SetCallback(cb)
  134. }
  135. return nil
  136. }
  137. func (mem *Mempool) removeTxFromCacheMap(tx []byte) {
  138. mem.proxyMtx.Lock()
  139. // NOTE tx not removed from cacheList
  140. delete(mem.cacheMap, string(tx))
  141. mem.proxyMtx.Unlock()
  142. }
  143. // TMSP callback function
  144. func (mem *Mempool) resCb(req *tmsp.Request, res *tmsp.Response) {
  145. if mem.recheckCursor == nil {
  146. mem.resCbNormal(req, res)
  147. } else {
  148. mem.resCbRecheck(req, res)
  149. }
  150. }
  151. func (mem *Mempool) resCbNormal(req *tmsp.Request, res *tmsp.Response) {
  152. switch r := res.Value.(type) {
  153. case *tmsp.Response_CheckTx:
  154. if r.CheckTx.Code == tmsp.CodeType_OK {
  155. mem.counter++
  156. memTx := &mempoolTx{
  157. counter: mem.counter,
  158. height: int64(mem.height),
  159. tx: req.GetCheckTx().Tx,
  160. }
  161. mem.txs.PushBack(memTx)
  162. } else {
  163. // ignore bad transaction
  164. log.Info("Bad Transaction", "res", r)
  165. // remove from cache (it might be good later)
  166. // note this is an async callback,
  167. // so we need to grab the lock in removeTxFromCacheMap
  168. mem.removeTxFromCacheMap(req.GetCheckTx().Tx)
  169. // TODO: handle other retcodes
  170. }
  171. default:
  172. // ignore other messages
  173. }
  174. }
  175. func (mem *Mempool) resCbRecheck(req *tmsp.Request, res *tmsp.Response) {
  176. switch r := res.Value.(type) {
  177. case *tmsp.Response_CheckTx:
  178. memTx := mem.recheckCursor.Value.(*mempoolTx)
  179. if !bytes.Equal(req.GetCheckTx().Tx, memTx.tx) {
  180. PanicSanity(Fmt("Unexpected tx response from proxy during recheck\n"+
  181. "Expected %X, got %X", r.CheckTx.Data, memTx.tx))
  182. }
  183. if r.CheckTx.Code == tmsp.CodeType_OK {
  184. // Good, nothing to do.
  185. } else {
  186. // Tx became invalidated due to newly committed block.
  187. mem.txs.Remove(mem.recheckCursor)
  188. mem.recheckCursor.DetachPrev()
  189. // remove from cache (it might be good later)
  190. mem.removeTxFromCacheMap(req.GetCheckTx().Tx)
  191. }
  192. if mem.recheckCursor == mem.recheckEnd {
  193. mem.recheckCursor = nil
  194. } else {
  195. mem.recheckCursor = mem.recheckCursor.Next()
  196. }
  197. if mem.recheckCursor == nil {
  198. // Done!
  199. atomic.StoreInt32(&mem.rechecking, 0)
  200. log.Info("Done rechecking txs")
  201. }
  202. default:
  203. // ignore other messages
  204. }
  205. }
  206. // Get the valid transactions remaining
  207. // If maxTxs is 0, there is no cap.
  208. func (mem *Mempool) Reap(maxTxs int) []types.Tx {
  209. mem.proxyMtx.Lock()
  210. defer mem.proxyMtx.Unlock()
  211. for atomic.LoadInt32(&mem.rechecking) > 0 {
  212. // TODO: Something better?
  213. time.Sleep(time.Millisecond * 10)
  214. }
  215. txs := mem.collectTxs(maxTxs)
  216. return txs
  217. }
  218. // maxTxs: -1 means uncapped, 0 means none
  219. func (mem *Mempool) collectTxs(maxTxs int) []types.Tx {
  220. if maxTxs == 0 {
  221. return []types.Tx{}
  222. } else if maxTxs < 0 {
  223. maxTxs = mem.txs.Len()
  224. }
  225. txs := make([]types.Tx, 0, MinInt(mem.txs.Len(), maxTxs))
  226. for e := mem.txs.Front(); e != nil && len(txs) < maxTxs; e = e.Next() {
  227. memTx := e.Value.(*mempoolTx)
  228. txs = append(txs, memTx.tx)
  229. }
  230. return txs
  231. }
  232. // Tell mempool that these txs were committed.
  233. // Mempool will discard these txs.
  234. // NOTE: this should be called *after* block is committed by consensus.
  235. // NOTE: unsafe; Lock/Unlock must be managed by caller
  236. func (mem *Mempool) Update(height int, txs []types.Tx) {
  237. // mem.proxyMtx.Lock()
  238. // defer mem.proxyMtx.Unlock()
  239. mem.proxyAppConn.FlushSync() // To flush async resCb calls e.g. from CheckTx
  240. // First, create a lookup map of txns in new txs.
  241. txsMap := make(map[string]struct{})
  242. for _, tx := range txs {
  243. txsMap[string(tx)] = struct{}{}
  244. }
  245. // Set height
  246. mem.height = height
  247. // Remove transactions that are already in txs.
  248. goodTxs := mem.filterTxs(txsMap)
  249. // Recheck mempool txs if any txs were committed in the block
  250. // NOTE/XXX: in some apps a tx could be invalidated due to EndBlock,
  251. // so we really still do need to recheck, but this is for debugging
  252. if mem.config.GetBool("mempool_recheck") &&
  253. (mem.config.GetBool("mempool_recheck_empty") || len(txs) > 0) {
  254. log.Info("Recheck txs", "numtxs", len(goodTxs))
  255. mem.recheckTxs(goodTxs)
  256. // At this point, mem.txs are being rechecked.
  257. // mem.recheckCursor re-scans mem.txs and possibly removes some txs.
  258. // Before mem.Reap(), we should wait for mem.recheckCursor to be nil.
  259. }
  260. }
  261. func (mem *Mempool) filterTxs(blockTxsMap map[string]struct{}) []types.Tx {
  262. goodTxs := make([]types.Tx, 0, mem.txs.Len())
  263. for e := mem.txs.Front(); e != nil; e = e.Next() {
  264. memTx := e.Value.(*mempoolTx)
  265. // Remove the tx if it's alredy in a block.
  266. if _, ok := blockTxsMap[string(memTx.tx)]; ok {
  267. // remove from clist
  268. mem.txs.Remove(e)
  269. e.DetachPrev()
  270. // NOTE: we don't remove committed txs from the cache.
  271. continue
  272. }
  273. // Good tx!
  274. goodTxs = append(goodTxs, memTx.tx)
  275. }
  276. return goodTxs
  277. }
  278. // NOTE: pass in goodTxs because mem.txs can mutate concurrently.
  279. func (mem *Mempool) recheckTxs(goodTxs []types.Tx) {
  280. if len(goodTxs) == 0 {
  281. return
  282. }
  283. atomic.StoreInt32(&mem.rechecking, 1)
  284. mem.recheckCursor = mem.txs.Front()
  285. mem.recheckEnd = mem.txs.Back()
  286. // Push txs to proxyAppConn
  287. // NOTE: resCb() may be called concurrently.
  288. for _, tx := range goodTxs {
  289. mem.proxyAppConn.CheckTxAsync(tx)
  290. }
  291. mem.proxyAppConn.FlushAsync()
  292. }
  293. //--------------------------------------------------------------------------------
  294. // A transaction that successfully ran
  295. type mempoolTx struct {
  296. counter int64 // a simple incrementing counter
  297. height int64 // height that this tx had been validated in
  298. tx types.Tx //
  299. }
  300. func (memTx *mempoolTx) Height() int {
  301. return int(atomic.LoadInt64(&memTx.height))
  302. }