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.

355 lines
10 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
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. cfg "github.com/tendermint/go-config"
  11. "github.com/tendermint/tendermint/proxy"
  12. "github.com/tendermint/tendermint/types"
  13. tmsp "github.com/tendermint/tmsp/types"
  14. )
  15. /*
  16. The mempool pushes new txs onto the proxyAppConn.
  17. It gets a stream of (req, res) tuples from the proxy.
  18. The memool stores good txs in a concurrent linked-list.
  19. Multiple concurrent go-routines can traverse this linked-list
  20. safely by calling .NextWait() on each element.
  21. So we have several go-routines:
  22. 1. Consensus calling Update() and Reap() synchronously
  23. 2. Many mempool reactor's peer routines calling CheckTx()
  24. 3. Many mempool reactor's peer routines traversing the txs linked list
  25. 4. Another goroutine calling GarbageCollectTxs() periodically
  26. To manage these goroutines, there are three methods of locking.
  27. 1. Mutations to the linked-list is protected by an internal mtx (CList is goroutine-safe)
  28. 2. Mutations to the linked-list elements are atomic
  29. 3. CheckTx() calls can be paused upon Update() and Reap(), protected by .proxyMtx
  30. Garbage collection of old elements from mempool.txs is handlde via
  31. the DetachPrev() call, which makes old elements not reachable by
  32. peer broadcastTxRoutine() automatically garbage collected.
  33. TODO: Better handle tmsp client errors. (make it automatically handle connection errors)
  34. */
  35. const cacheSize = 100000
  36. type Mempool struct {
  37. config cfg.Config
  38. proxyMtx sync.Mutex
  39. proxyAppConn proxy.AppConn
  40. txs *clist.CList // concurrent linked-list of good txs
  41. counter int64 // simple incrementing counter
  42. height int // the last block Update()'d to
  43. rechecking int32 // for re-checking filtered txs on Update()
  44. recheckCursor *clist.CElement // next expected response
  45. recheckEnd *clist.CElement // re-checking stops here
  46. // Keep a cache of already-seen txs.
  47. // This reduces the pressure on the proxyApp.
  48. cacheMap map[string]struct{}
  49. cacheList *list.List // to remove oldest tx when cache gets too big
  50. }
  51. func NewMempool(config cfg.Config, proxyAppConn proxy.AppConn) *Mempool {
  52. mempool := &Mempool{
  53. config: config,
  54. proxyAppConn: proxyAppConn,
  55. txs: clist.New(),
  56. counter: 0,
  57. height: 0,
  58. rechecking: 0,
  59. recheckCursor: nil,
  60. recheckEnd: nil,
  61. cacheMap: make(map[string]struct{}, cacheSize),
  62. cacheList: list.New(),
  63. }
  64. proxyAppConn.SetResponseCallback(mempool.resCb)
  65. return mempool
  66. }
  67. // consensus must be able to hold lock to safely update
  68. func (mem *Mempool) Lock() {
  69. mem.proxyMtx.Lock()
  70. }
  71. func (mem *Mempool) Unlock() {
  72. mem.proxyMtx.Unlock()
  73. }
  74. // Number of transactions in the mempool clist
  75. func (mem *Mempool) Size() int {
  76. return mem.txs.Len()
  77. }
  78. // Remove all transactions from mempool and cache
  79. func (mem *Mempool) Flush() {
  80. mem.proxyMtx.Lock()
  81. defer mem.proxyMtx.Unlock()
  82. mem.cacheMap = make(map[string]struct{}, cacheSize)
  83. mem.cacheList.Init()
  84. for e := mem.txs.Front(); e != nil; e = e.Next() {
  85. mem.txs.Remove(e)
  86. e.DetachPrev()
  87. }
  88. }
  89. // Return the first element of mem.txs for peer goroutines to call .NextWait() on.
  90. // Blocks until txs has elements.
  91. func (mem *Mempool) TxsFrontWait() *clist.CElement {
  92. return mem.txs.FrontWait()
  93. }
  94. // Try a new transaction in the mempool.
  95. // Potentially blocking if we're blocking on Update() or Reap().
  96. // cb: A callback from the CheckTx command.
  97. // It gets called from another goroutine.
  98. // CONTRACT: Either cb will get called, or err returned.
  99. func (mem *Mempool) CheckTx(tx types.Tx, cb func(*tmsp.Response)) (err error) {
  100. mem.proxyMtx.Lock()
  101. defer mem.proxyMtx.Unlock()
  102. // CACHE
  103. if _, exists := mem.cacheMap[string(tx)]; exists {
  104. if cb != nil {
  105. cb(&tmsp.Response{
  106. Value: &tmsp.Response_CheckTx{
  107. &tmsp.ResponseCheckTx{
  108. Code: tmsp.CodeType_BadNonce, // TODO or duplicate tx
  109. Log: "Duplicate transaction (ignored)",
  110. },
  111. },
  112. })
  113. }
  114. return nil
  115. }
  116. if mem.cacheList.Len() >= cacheSize {
  117. popped := mem.cacheList.Front()
  118. poppedTx := popped.Value.(types.Tx)
  119. // NOTE: the tx may have already been removed from the map
  120. // but deleting a non-existant element is fine
  121. delete(mem.cacheMap, string(poppedTx))
  122. mem.cacheList.Remove(popped)
  123. }
  124. mem.cacheMap[string(tx)] = struct{}{}
  125. mem.cacheList.PushBack(tx)
  126. // END CACHE
  127. // NOTE: proxyAppConn may error if tx buffer is full
  128. if err = mem.proxyAppConn.Error(); err != nil {
  129. return err
  130. }
  131. reqRes := mem.proxyAppConn.CheckTxAsync(tx)
  132. if cb != nil {
  133. reqRes.SetCallback(cb)
  134. }
  135. return nil
  136. }
  137. func (mem *Mempool) removeTxFromCacheMap(tx []byte) {
  138. mem.proxyMtx.Lock()
  139. // NOTE tx not removed from cacheList
  140. delete(mem.cacheMap, string(tx))
  141. mem.proxyMtx.Unlock()
  142. }
  143. // TMSP callback function
  144. func (mem *Mempool) resCb(req *tmsp.Request, res *tmsp.Response) {
  145. if mem.recheckCursor == nil {
  146. mem.resCbNormal(req, res)
  147. } else {
  148. mem.resCbRecheck(req, res)
  149. }
  150. }
  151. func (mem *Mempool) resCbNormal(req *tmsp.Request, res *tmsp.Response) {
  152. switch r := res.Value.(type) {
  153. case *tmsp.Response_CheckTx:
  154. if r.CheckTx.Code == tmsp.CodeType_OK {
  155. mem.counter++
  156. memTx := &mempoolTx{
  157. counter: mem.counter,
  158. height: int64(mem.height),
  159. tx: req.GetCheckTx().Tx,
  160. }
  161. mem.txs.PushBack(memTx)
  162. } else {
  163. // ignore bad transaction
  164. log.Info("Bad Transaction", "res", r)
  165. // remove from cache (it might be good later)
  166. mem.removeTxFromCacheMap(req.GetCheckTx().Tx)
  167. // TODO: handle other retcodes
  168. }
  169. default:
  170. // ignore other messages
  171. }
  172. }
  173. func (mem *Mempool) resCbRecheck(req *tmsp.Request, res *tmsp.Response) {
  174. switch r := res.Value.(type) {
  175. case *tmsp.Response_CheckTx:
  176. memTx := mem.recheckCursor.Value.(*mempoolTx)
  177. if !bytes.Equal(req.GetCheckTx().Tx, memTx.tx) {
  178. PanicSanity(Fmt("Unexpected tx response from proxy during recheck\n"+
  179. "Expected %X, got %X", r.CheckTx.Data, memTx.tx))
  180. }
  181. if r.CheckTx.Code == tmsp.CodeType_OK {
  182. // Good, nothing to do.
  183. } else {
  184. // Tx became invalidated due to newly committed block.
  185. mem.txs.Remove(mem.recheckCursor)
  186. mem.recheckCursor.DetachPrev()
  187. // remove from cache (it might be good later)
  188. mem.removeTxFromCacheMap(req.GetCheckTx().Tx)
  189. }
  190. if mem.recheckCursor == mem.recheckEnd {
  191. mem.recheckCursor = nil
  192. } else {
  193. mem.recheckCursor = mem.recheckCursor.Next()
  194. }
  195. if mem.recheckCursor == nil {
  196. // Done!
  197. atomic.StoreInt32(&mem.rechecking, 0)
  198. log.Info("Done rechecking txs")
  199. }
  200. default:
  201. // ignore other messages
  202. }
  203. }
  204. // Get the valid transactions remaining
  205. // If maxTxs is 0, there is no cap.
  206. func (mem *Mempool) Reap(maxTxs int) []types.Tx {
  207. mem.proxyMtx.Lock()
  208. defer mem.proxyMtx.Unlock()
  209. for atomic.LoadInt32(&mem.rechecking) > 0 {
  210. // TODO: Something better?
  211. time.Sleep(time.Millisecond * 10)
  212. }
  213. txs := mem.collectTxs(maxTxs)
  214. return txs
  215. }
  216. // maxTxs: -1 means uncapped, 0 means none
  217. func (mem *Mempool) collectTxs(maxTxs int) []types.Tx {
  218. if maxTxs == 0 {
  219. return []types.Tx{}
  220. } else if maxTxs < 0 {
  221. maxTxs = mem.txs.Len()
  222. }
  223. txs := make([]types.Tx, 0, MinInt(mem.txs.Len(), maxTxs))
  224. for e := mem.txs.Front(); e != nil && len(txs) < maxTxs; e = e.Next() {
  225. memTx := e.Value.(*mempoolTx)
  226. txs = append(txs, memTx.tx)
  227. }
  228. return txs
  229. }
  230. // Tell mempool that these txs were committed.
  231. // Mempool will discard these txs.
  232. // NOTE: this should be called *after* block is committed by consensus.
  233. // NOTE: unsafe; Lock/Unlock must be managed by caller
  234. func (mem *Mempool) Update(height int, txs []types.Tx) {
  235. // mem.proxyMtx.Lock()
  236. // defer mem.proxyMtx.Unlock()
  237. mem.proxyAppConn.FlushSync() // To flush async resCb calls e.g. from CheckTx
  238. // First, create a lookup map of txns in new txs.
  239. txsMap := make(map[string]struct{})
  240. for _, tx := range txs {
  241. txsMap[string(tx)] = struct{}{}
  242. }
  243. // Set height
  244. mem.height = height
  245. // Remove transactions that are already in txs.
  246. goodTxs := mem.filterTxs(txsMap)
  247. // Recheck mempool txs if any txs were committed in the block
  248. // NOTE/XXX: in some apps a tx could be invalidated due to EndBlock,
  249. // so we really still do need to recheck, but this is for debugging
  250. if mem.config.GetBool("mempool_recheck") &&
  251. (mem.config.GetBool("mempool_recheck_empty") || len(txs) > 0) {
  252. log.Info("Recheck txs", "numtxs", len(goodTxs))
  253. mem.recheckTxs(goodTxs)
  254. // At this point, mem.txs are being rechecked.
  255. // mem.recheckCursor re-scans mem.txs and possibly removes some txs.
  256. // Before mem.Reap(), we should wait for mem.recheckCursor to be nil.
  257. }
  258. }
  259. func (mem *Mempool) filterTxs(blockTxsMap map[string]struct{}) []types.Tx {
  260. goodTxs := make([]types.Tx, 0, mem.txs.Len())
  261. for e := mem.txs.Front(); e != nil; e = e.Next() {
  262. memTx := e.Value.(*mempoolTx)
  263. // Remove the tx if its alredy in a block.
  264. if _, ok := blockTxsMap[string(memTx.tx)]; ok {
  265. // remove from clist
  266. mem.txs.Remove(e)
  267. e.DetachPrev()
  268. // remove from mempool cache
  269. // we only enforce "at-least once" semantics and
  270. // leave it to the application to implement "only-once"
  271. // via eg. sequence numbers, utxos, etc.
  272. // NOTE: expects caller of filterTxs to hold the lock
  273. // (so we can't use mem.removeTxFromCacheMap)
  274. delete(mem.cacheMap, string(memTx.tx))
  275. continue
  276. }
  277. // Good tx!
  278. goodTxs = append(goodTxs, memTx.tx)
  279. }
  280. return goodTxs
  281. }
  282. // NOTE: pass in goodTxs because mem.txs can mutate concurrently.
  283. func (mem *Mempool) recheckTxs(goodTxs []types.Tx) {
  284. if len(goodTxs) == 0 {
  285. return
  286. }
  287. atomic.StoreInt32(&mem.rechecking, 1)
  288. mem.recheckCursor = mem.txs.Front()
  289. mem.recheckEnd = mem.txs.Back()
  290. // Push txs to proxyAppConn
  291. // NOTE: resCb() may be called concurrently.
  292. for _, tx := range goodTxs {
  293. mem.proxyAppConn.CheckTxAsync(tx)
  294. }
  295. mem.proxyAppConn.FlushAsync()
  296. }
  297. //--------------------------------------------------------------------------------
  298. // A transaction that successfully ran
  299. type mempoolTx struct {
  300. counter int64 // a simple incrementing counter
  301. height int64 // height that this tx had been validated in
  302. tx types.Tx //
  303. }
  304. func (memTx *mempoolTx) Height() int {
  305. return int(atomic.LoadInt64(&memTx.height))
  306. }