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.

278 lines
7.5 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. "github.com/tendermint/tendermint/proxy"
  11. "github.com/tendermint/tendermint/types"
  12. tmsp "github.com/tendermint/tmsp/types"
  13. )
  14. /*
  15. The mempool pushes new txs onto the proxyAppConn.
  16. It gets a stream of (req, res) tuples from the proxy.
  17. The memool stores good txs in a concurrent linked-list.
  18. Multiple concurrent go-routines can traverse this linked-list
  19. safely by calling .NextWait() on each element.
  20. So we have several go-routines:
  21. 1. Consensus calling Update() and Reap() synchronously
  22. 2. Many mempool reactor's peer routines calling CheckTx()
  23. 3. Many mempool reactor's peer routines traversing the txs linked list
  24. 4. Another goroutine calling GarbageCollectTxs() periodically
  25. To manage these goroutines, there are three methods of locking.
  26. 1. Mutations to the linked-list is protected by an internal mtx (CList is goroutine-safe)
  27. 2. Mutations to the linked-list elements are atomic
  28. 3. CheckTx() calls can be paused upon Update() and Reap(), protected by .proxyMtx
  29. Garbage collection of old elements from mempool.txs is handlde via
  30. the DetachPrev() call, which makes old elements not reachable by
  31. peer broadcastTxRoutine() automatically garbage collected.
  32. TODO: Better handle tmsp client errors. (make it automatically handle connection errors)
  33. */
  34. const cacheSize = 100000
  35. type Mempool struct {
  36. proxyMtx sync.Mutex
  37. proxyAppConn proxy.AppConn
  38. txs *clist.CList // concurrent linked-list of good txs
  39. counter int64 // simple incrementing counter
  40. height int // the last block Update()'d to
  41. rechecking int32 // for re-checking filtered txs on Update()
  42. recheckCursor *clist.CElement // next expected response
  43. recheckEnd *clist.CElement // re-checking stops here
  44. // Keep a cache of already-seen txs.
  45. // This reduces the pressure on the proxyApp.
  46. cacheMap map[string]struct{}
  47. cacheList *list.List
  48. }
  49. func NewMempool(proxyAppConn proxy.AppConn) *Mempool {
  50. mempool := &Mempool{
  51. proxyAppConn: proxyAppConn,
  52. txs: clist.New(),
  53. counter: 0,
  54. height: 0,
  55. rechecking: 0,
  56. recheckCursor: nil,
  57. recheckEnd: nil,
  58. cacheMap: make(map[string]struct{}, cacheSize),
  59. cacheList: list.New(),
  60. }
  61. proxyAppConn.SetResponseCallback(mempool.resCb)
  62. return mempool
  63. }
  64. // Return the first element of mem.txs for peer goroutines to call .NextWait() on.
  65. // Blocks until txs has elements.
  66. func (mem *Mempool) TxsFrontWait() *clist.CElement {
  67. return mem.txs.FrontWait()
  68. }
  69. // Try a new transaction in the mempool.
  70. // Potentially blocking if we're blocking on Update() or Reap().
  71. // cb: A callback from the CheckTx command.
  72. // It gets called from another goroutine.
  73. // CONTRACT: Either cb will get called, or err returned.
  74. func (mem *Mempool) CheckTx(tx types.Tx, cb func(*tmsp.Response)) (err error) {
  75. mem.proxyMtx.Lock()
  76. defer mem.proxyMtx.Unlock()
  77. // CACHE
  78. if _, exists := mem.cacheMap[string(tx)]; exists {
  79. if cb != nil {
  80. cb(&tmsp.Response{
  81. Code: tmsp.CodeType_BadNonce, // TODO or duplicate tx
  82. Log: "Duplicate transaction (ignored)",
  83. })
  84. }
  85. return nil
  86. }
  87. if mem.cacheList.Len() >= cacheSize {
  88. popped := mem.cacheList.Front()
  89. poppedTx := popped.Value.(types.Tx)
  90. delete(mem.cacheMap, string(poppedTx))
  91. mem.cacheList.Remove(popped)
  92. }
  93. mem.cacheMap[string(tx)] = struct{}{}
  94. mem.cacheList.PushBack(tx)
  95. // END CACHE
  96. // NOTE: proxyAppConn may error if tx buffer is full
  97. if err = mem.proxyAppConn.Error(); err != nil {
  98. return err
  99. }
  100. reqRes := mem.proxyAppConn.CheckTxAsync(tx)
  101. if cb != nil {
  102. reqRes.SetCallback(cb)
  103. }
  104. return nil
  105. }
  106. // TMSP callback function
  107. func (mem *Mempool) resCb(req *tmsp.Request, res *tmsp.Response) {
  108. if mem.recheckCursor == nil {
  109. mem.resCbNormal(req, res)
  110. } else {
  111. mem.resCbRecheck(req, res)
  112. }
  113. }
  114. func (mem *Mempool) resCbNormal(req *tmsp.Request, res *tmsp.Response) {
  115. switch res.Type {
  116. case tmsp.MessageType_CheckTx:
  117. if res.Code == tmsp.CodeType_OK {
  118. mem.counter++
  119. memTx := &mempoolTx{
  120. counter: mem.counter,
  121. height: int64(mem.height),
  122. tx: req.Data,
  123. }
  124. mem.txs.PushBack(memTx)
  125. } else {
  126. // ignore bad transaction
  127. // TODO: handle other retcodes
  128. }
  129. default:
  130. // ignore other messages
  131. }
  132. }
  133. func (mem *Mempool) resCbRecheck(req *tmsp.Request, res *tmsp.Response) {
  134. switch res.Type {
  135. case tmsp.MessageType_CheckTx:
  136. memTx := mem.recheckCursor.Value.(*mempoolTx)
  137. if !bytes.Equal(req.Data, memTx.tx) {
  138. PanicSanity(Fmt("Unexpected tx response from proxy during recheck\n"+
  139. "Expected %X, got %X", req.Data, memTx.tx))
  140. }
  141. if res.Code == tmsp.CodeType_OK {
  142. // Good, nothing to do.
  143. } else {
  144. // Tx became invalidated due to newly committed block.
  145. mem.txs.Remove(mem.recheckCursor)
  146. mem.recheckCursor.DetachPrev()
  147. }
  148. if mem.recheckCursor == mem.recheckEnd {
  149. mem.recheckCursor = nil
  150. } else {
  151. mem.recheckCursor = mem.recheckCursor.Next()
  152. }
  153. if mem.recheckCursor == nil {
  154. // Done!
  155. atomic.StoreInt32(&mem.rechecking, 0)
  156. }
  157. default:
  158. // ignore other messages
  159. }
  160. }
  161. // Get the valid transactions remaining
  162. func (mem *Mempool) Reap() []types.Tx {
  163. mem.proxyMtx.Lock()
  164. defer mem.proxyMtx.Unlock()
  165. for atomic.LoadInt32(&mem.rechecking) > 0 {
  166. // TODO: Something better?
  167. time.Sleep(time.Millisecond * 10)
  168. }
  169. txs := mem.collectTxs()
  170. return txs
  171. }
  172. func (mem *Mempool) collectTxs() []types.Tx {
  173. txs := make([]types.Tx, 0, mem.txs.Len())
  174. for e := mem.txs.Front(); e != nil; e = e.Next() {
  175. memTx := e.Value.(*mempoolTx)
  176. txs = append(txs, memTx.tx)
  177. }
  178. return txs
  179. }
  180. // Tell mempool that these txs were committed.
  181. // Mempool will discard these txs.
  182. // NOTE: this should be called *after* block is committed by consensus.
  183. func (mem *Mempool) Update(height int, txs []types.Tx) {
  184. mem.proxyMtx.Lock()
  185. defer mem.proxyMtx.Unlock()
  186. // First, create a lookup map of txns in new txs.
  187. txsMap := make(map[string]struct{})
  188. for _, tx := range txs {
  189. txsMap[string(tx)] = struct{}{}
  190. }
  191. // Set height
  192. mem.height = height
  193. // Remove transactions that are already in txs.
  194. goodTxs := mem.filterTxs(txsMap)
  195. // Recheck mempool txs
  196. // TODO: make optional
  197. mem.recheckTxs(goodTxs)
  198. // At this point, mem.txs are being rechecked.
  199. // mem.recheckCursor re-scans mem.txs and possibly removes some txs.
  200. // Before mem.Reap(), we should wait for mem.recheckCursor to be nil.
  201. }
  202. func (mem *Mempool) filterTxs(blockTxsMap map[string]struct{}) []types.Tx {
  203. goodTxs := make([]types.Tx, 0, mem.txs.Len())
  204. for e := mem.txs.Front(); e != nil; e = e.Next() {
  205. memTx := e.Value.(*mempoolTx)
  206. if _, ok := blockTxsMap[string(memTx.tx)]; ok {
  207. // Remove the tx since already in block.
  208. mem.txs.Remove(e)
  209. e.DetachPrev()
  210. continue
  211. }
  212. // Good tx!
  213. goodTxs = append(goodTxs, memTx.tx)
  214. }
  215. return goodTxs
  216. }
  217. // NOTE: pass in goodTxs because mem.txs can mutate concurrently.
  218. func (mem *Mempool) recheckTxs(goodTxs []types.Tx) {
  219. if len(goodTxs) == 0 {
  220. return
  221. }
  222. atomic.StoreInt32(&mem.rechecking, 1)
  223. mem.recheckCursor = mem.txs.Front()
  224. mem.recheckEnd = mem.txs.Back()
  225. // Push txs to proxyAppConn
  226. // NOTE: resCb() may be called concurrently.
  227. for _, tx := range goodTxs {
  228. mem.proxyAppConn.CheckTxAsync(tx)
  229. }
  230. mem.proxyAppConn.FlushAsync()
  231. }
  232. //--------------------------------------------------------------------------------
  233. // A transaction that successfully ran
  234. type mempoolTx struct {
  235. counter int64 // a simple incrementing counter
  236. height int64 // height that this tx had been validated in
  237. tx types.Tx //
  238. }
  239. func (memTx *mempoolTx) Height() int {
  240. return int(atomic.LoadInt64(&memTx.height))
  241. }