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.

412 lines
11 KiB

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