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.

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