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.

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