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.

283 lines
7.7 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
  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. // If maxTxs is 0, there is no cap.
  163. func (mem *Mempool) Reap(maxTxs int) []types.Tx {
  164. mem.proxyMtx.Lock()
  165. defer mem.proxyMtx.Unlock()
  166. for atomic.LoadInt32(&mem.rechecking) > 0 {
  167. // TODO: Something better?
  168. time.Sleep(time.Millisecond * 10)
  169. }
  170. txs := mem.collectTxs(maxTxs)
  171. return txs
  172. }
  173. // maxTxs: 0 means uncapped
  174. func (mem *Mempool) collectTxs(maxTxs int) []types.Tx {
  175. if maxTxs == 0 {
  176. maxTxs = mem.txs.Len()
  177. }
  178. txs := make([]types.Tx, 0, MinInt(mem.txs.Len(), maxTxs))
  179. for e := mem.txs.Front(); e != nil && len(txs) < maxTxs; e = e.Next() {
  180. memTx := e.Value.(*mempoolTx)
  181. txs = append(txs, memTx.tx)
  182. }
  183. return txs
  184. }
  185. // Tell mempool that these txs were committed.
  186. // Mempool will discard these txs.
  187. // NOTE: this should be called *after* block is committed by consensus.
  188. func (mem *Mempool) Update(height int, txs []types.Tx) {
  189. mem.proxyMtx.Lock()
  190. defer mem.proxyMtx.Unlock()
  191. // First, create a lookup map of txns in new txs.
  192. txsMap := make(map[string]struct{})
  193. for _, tx := range txs {
  194. txsMap[string(tx)] = struct{}{}
  195. }
  196. // Set height
  197. mem.height = height
  198. // Remove transactions that are already in txs.
  199. goodTxs := mem.filterTxs(txsMap)
  200. // Recheck mempool txs
  201. if config.GetBool("mempool_recheck") {
  202. mem.recheckTxs(goodTxs)
  203. // At this point, mem.txs are being rechecked.
  204. // mem.recheckCursor re-scans mem.txs and possibly removes some txs.
  205. // Before mem.Reap(), we should wait for mem.recheckCursor to be nil.
  206. }
  207. }
  208. func (mem *Mempool) filterTxs(blockTxsMap map[string]struct{}) []types.Tx {
  209. goodTxs := make([]types.Tx, 0, mem.txs.Len())
  210. for e := mem.txs.Front(); e != nil; e = e.Next() {
  211. memTx := e.Value.(*mempoolTx)
  212. if _, ok := blockTxsMap[string(memTx.tx)]; ok {
  213. // Remove the tx since already in block.
  214. mem.txs.Remove(e)
  215. e.DetachPrev()
  216. continue
  217. }
  218. // Good tx!
  219. goodTxs = append(goodTxs, memTx.tx)
  220. }
  221. return goodTxs
  222. }
  223. // NOTE: pass in goodTxs because mem.txs can mutate concurrently.
  224. func (mem *Mempool) recheckTxs(goodTxs []types.Tx) {
  225. if len(goodTxs) == 0 {
  226. return
  227. }
  228. atomic.StoreInt32(&mem.rechecking, 1)
  229. mem.recheckCursor = mem.txs.Front()
  230. mem.recheckEnd = mem.txs.Back()
  231. // Push txs to proxyAppConn
  232. // NOTE: resCb() may be called concurrently.
  233. for _, tx := range goodTxs {
  234. mem.proxyAppConn.CheckTxAsync(tx)
  235. }
  236. mem.proxyAppConn.FlushAsync()
  237. }
  238. //--------------------------------------------------------------------------------
  239. // A transaction that successfully ran
  240. type mempoolTx struct {
  241. counter int64 // a simple incrementing counter
  242. height int64 // height that this tx had been validated in
  243. tx types.Tx //
  244. }
  245. func (memTx *mempoolTx) Height() int {
  246. return int(atomic.LoadInt64(&memTx.height))
  247. }