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.

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