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.

193 lines
5.1 KiB

9 years ago
  1. package mempool
  2. import (
  3. "container/list"
  4. "sync"
  5. "sync/atomic"
  6. "github.com/tendermint/go-clist"
  7. . "github.com/tendermint/go-common"
  8. "github.com/tendermint/tendermint/proxy"
  9. "github.com/tendermint/tendermint/types"
  10. tmsp "github.com/tendermint/tmsp/types"
  11. )
  12. /*
  13. The mempool pushes new txs onto the proxyAppConn.
  14. It gets a stream of (req, res) tuples from the proxy.
  15. The memool stores good txs in a concurrent linked-list.
  16. Multiple concurrent go-routines can traverse this linked-list
  17. safely by calling .NextWait() on each element.
  18. So we have several go-routines:
  19. 1. Consensus calling Update() and Reap() synchronously
  20. 2. Many mempool reactor's peer routines calling CheckTx()
  21. 3. Many mempool reactor's peer routines traversing the txs linked list
  22. 4. Another goroutine calling GarbageCollectTxs() periodically
  23. To manage these goroutines, there are three methods of locking.
  24. 1. Mutations to the linked-list is protected by an internal mtx (CList is goroutine-safe)
  25. 2. Mutations to the linked-list elements are atomic
  26. 3. CheckTx() calls can be paused upon Update() and Reap(), protected by .proxyMtx
  27. Garbage collection of old elements from mempool.txs is handlde via
  28. the DetachPrev() call, which makes old elements not reachable by
  29. peer broadcastTxRoutine() automatically garbage collected.
  30. */
  31. const cacheSize = 100000
  32. type Mempool struct {
  33. proxyMtx sync.Mutex
  34. proxyAppConn proxy.AppConn
  35. txs *clist.CList // concurrent linked-list of good txs
  36. counter int64 // simple incrementing counter
  37. height int // the last block Update()'d to
  38. // Keep a cache of already-seen txs.
  39. // This reduces the pressure on the proxyApp.
  40. cacheMap map[string]struct{}
  41. cacheList *list.List
  42. }
  43. func NewMempool(proxyAppConn proxy.AppConn) *Mempool {
  44. mempool := &Mempool{
  45. proxyAppConn: proxyAppConn,
  46. txs: clist.New(),
  47. counter: 0,
  48. height: 0,
  49. cacheMap: make(map[string]struct{}, cacheSize),
  50. cacheList: list.New(),
  51. }
  52. proxyAppConn.SetResponseCallback(mempool.resCb)
  53. return mempool
  54. }
  55. // Return the first element of mem.txs for peer goroutines to call .NextWait() on.
  56. // Blocks until txs has elements.
  57. func (mem *Mempool) TxsFrontWait() *clist.CElement {
  58. return mem.txs.FrontWait()
  59. }
  60. // Try a new transaction in the mempool.
  61. // Potentially blocking if we're blocking on Update() or Reap().
  62. func (mem *Mempool) CheckTx(tx types.Tx) (err error) {
  63. mem.proxyMtx.Lock()
  64. defer mem.proxyMtx.Unlock()
  65. // CACHE
  66. if _, exists := mem.cacheMap[string(tx)]; exists {
  67. return nil
  68. }
  69. if mem.cacheList.Len() >= cacheSize {
  70. popped := mem.cacheList.Front()
  71. poppedTx := popped.Value.(types.Tx)
  72. delete(mem.cacheMap, string(poppedTx))
  73. mem.cacheList.Remove(popped)
  74. }
  75. mem.cacheMap[string(tx)] = struct{}{}
  76. mem.cacheList.PushBack(tx)
  77. // END CACHE
  78. if err = mem.proxyAppConn.Error(); err != nil {
  79. return err
  80. }
  81. mem.proxyAppConn.CheckTxAsync(tx)
  82. return nil
  83. }
  84. // TMSP callback function
  85. func (mem *Mempool) resCb(req tmsp.Request, res tmsp.Response) {
  86. switch res := res.(type) {
  87. case tmsp.ResponseCheckTx:
  88. reqCheckTx := req.(tmsp.RequestCheckTx)
  89. if res.RetCode == tmsp.RetCodeOK {
  90. mem.counter++
  91. memTx := &mempoolTx{
  92. counter: mem.counter,
  93. height: int64(mem.height),
  94. tx: reqCheckTx.TxBytes,
  95. }
  96. mem.txs.PushBack(memTx)
  97. } else {
  98. // ignore bad transaction
  99. // TODO: handle other retcodes
  100. }
  101. default:
  102. // ignore other messages
  103. }
  104. }
  105. // Get the valid transactions remaining
  106. func (mem *Mempool) Reap() ([]types.Tx, error) {
  107. mem.proxyMtx.Lock()
  108. defer mem.proxyMtx.Unlock()
  109. txs := mem.collectTxs()
  110. return txs, nil
  111. }
  112. func (mem *Mempool) collectTxs() []types.Tx {
  113. txs := make([]types.Tx, 0, mem.txs.Len())
  114. for e := mem.txs.Front(); e != nil; e = e.Next() {
  115. memTx := e.Value.(*mempoolTx)
  116. txs = append(txs, memTx.tx)
  117. }
  118. return txs
  119. }
  120. // Tell mempool that these txs were committed.
  121. // Mempool will discard these txs.
  122. // NOTE: this should be called *after* block is committed by consensus.
  123. func (mem *Mempool) Update(height int, txs []types.Tx) error {
  124. mem.proxyMtx.Lock()
  125. defer mem.proxyMtx.Unlock()
  126. // First, create a lookup map of txns in new txs.
  127. txsMap := make(map[string]struct{})
  128. for _, tx := range txs {
  129. txsMap[string(tx)] = struct{}{}
  130. }
  131. // Set height
  132. mem.height = height
  133. // Remove transactions that are already in txs.
  134. mem.filterTxs(txsMap)
  135. return nil
  136. }
  137. func (mem *Mempool) filterTxs(blockTxsMap map[string]struct{}) []types.Tx {
  138. goodTxs := make([]types.Tx, 0, mem.txs.Len())
  139. for e := mem.txs.Front(); e != nil; e = e.Next() {
  140. memTx := e.Value.(*mempoolTx)
  141. if _, ok := blockTxsMap[string(memTx.tx)]; ok {
  142. // Remove the tx since already in block.
  143. mem.txs.Remove(e)
  144. e.DetachPrev()
  145. continue
  146. }
  147. // Good tx!
  148. goodTxs = append(goodTxs, memTx.tx)
  149. }
  150. return goodTxs
  151. }
  152. //--------------------------------------------------------------------------------
  153. // A transaction that successfully ran
  154. type mempoolTx struct {
  155. counter int64 // a simple incrementing counter
  156. height int64 // height that this tx had been validated in
  157. tx types.Tx //
  158. }
  159. func (memTx *mempoolTx) Height() int {
  160. return int(atomic.LoadInt64(&memTx.height))
  161. }