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.

416 lines
11 KiB

9 years ago
9 years ago
8 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
8 years ago
8 years ago
9 years ago
8 years ago
8 years ago
9 years ago
8 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 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
  1. package mempool
  2. import (
  3. "bytes"
  4. "container/list"
  5. "sync"
  6. "sync/atomic"
  7. "time"
  8. abci "github.com/tendermint/abci/types"
  9. auto "github.com/tendermint/tmlibs/autofile"
  10. "github.com/tendermint/tmlibs/clist"
  11. cmn "github.com/tendermint/tmlibs/common"
  12. "github.com/tendermint/tendermint/proxy"
  13. "github.com/tendermint/tendermint/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 abci client errors. (make it automatically handle connection errors)
  34. */
  35. const cacheSize = 100000
  36. type Mempool struct {
  37. config *Config
  38. proxyMtx sync.Mutex
  39. proxyAppConn proxy.AppConnMempool
  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. cache *txCache
  49. // A log of mempool txs
  50. wal *auto.AutoFile
  51. }
  52. func NewMempool(config *Config, proxyAppConn proxy.AppConnMempool) *Mempool {
  53. mempool := &Mempool{
  54. config: config,
  55. proxyAppConn: proxyAppConn,
  56. txs: clist.New(),
  57. counter: 0,
  58. height: 0,
  59. rechecking: 0,
  60. recheckCursor: nil,
  61. recheckEnd: nil,
  62. cache: newTxCache(cacheSize),
  63. }
  64. mempool.initWAL()
  65. proxyAppConn.SetResponseCallback(mempool.resCb)
  66. return mempool
  67. }
  68. func (mem *Mempool) initWAL() {
  69. walDir := mem.config.WalDir
  70. if walDir != "" {
  71. err := cmn.EnsureDir(walDir, 0700)
  72. if err != nil {
  73. log.Error("Error ensuring Mempool wal dir", "error", err)
  74. cmn.PanicSanity(err)
  75. }
  76. af, err := auto.OpenAutoFile(walDir + "/wal")
  77. if err != nil {
  78. log.Error("Error opening Mempool wal file", "error", err)
  79. cmn.PanicSanity(err)
  80. }
  81. mem.wal = af
  82. }
  83. }
  84. // consensus must be able to hold lock to safely update
  85. func (mem *Mempool) Lock() {
  86. mem.proxyMtx.Lock()
  87. }
  88. func (mem *Mempool) Unlock() {
  89. mem.proxyMtx.Unlock()
  90. }
  91. // Number of transactions in the mempool clist
  92. func (mem *Mempool) Size() int {
  93. return mem.txs.Len()
  94. }
  95. // Remove all transactions from mempool and cache
  96. func (mem *Mempool) Flush() {
  97. mem.proxyMtx.Lock()
  98. defer mem.proxyMtx.Unlock()
  99. mem.cache.Reset()
  100. for e := mem.txs.Front(); e != nil; e = e.Next() {
  101. mem.txs.Remove(e)
  102. e.DetachPrev()
  103. }
  104. }
  105. // Return the first element of mem.txs for peer goroutines to call .NextWait() on.
  106. // Blocks until txs has elements.
  107. func (mem *Mempool) TxsFrontWait() *clist.CElement {
  108. return mem.txs.FrontWait()
  109. }
  110. // Try a new transaction in the mempool.
  111. // Potentially blocking if we're blocking on Update() or Reap().
  112. // cb: A callback from the CheckTx command.
  113. // It gets called from another goroutine.
  114. // CONTRACT: Either cb will get called, or err returned.
  115. func (mem *Mempool) CheckTx(tx types.Tx, cb func(*abci.Response)) (err error) {
  116. mem.proxyMtx.Lock()
  117. defer mem.proxyMtx.Unlock()
  118. // CACHE
  119. if mem.cache.Exists(tx) {
  120. if cb != nil {
  121. cb(&abci.Response{
  122. Value: &abci.Response_CheckTx{
  123. &abci.ResponseCheckTx{
  124. Code: abci.CodeType_BadNonce, // TODO or duplicate tx
  125. Log: "Duplicate transaction (ignored)",
  126. },
  127. },
  128. })
  129. }
  130. return nil
  131. }
  132. mem.cache.Push(tx)
  133. // END CACHE
  134. // WAL
  135. if mem.wal != nil {
  136. // TODO: Notify administrators when WAL fails
  137. mem.wal.Write([]byte(tx))
  138. mem.wal.Write([]byte("\n"))
  139. }
  140. // END WAL
  141. // NOTE: proxyAppConn may error if tx buffer is full
  142. if err = mem.proxyAppConn.Error(); err != nil {
  143. return err
  144. }
  145. reqRes := mem.proxyAppConn.CheckTxAsync(tx)
  146. if cb != nil {
  147. reqRes.SetCallback(cb)
  148. }
  149. return nil
  150. }
  151. // ABCI callback function
  152. func (mem *Mempool) resCb(req *abci.Request, res *abci.Response) {
  153. if mem.recheckCursor == nil {
  154. mem.resCbNormal(req, res)
  155. } else {
  156. mem.resCbRecheck(req, res)
  157. }
  158. }
  159. func (mem *Mempool) resCbNormal(req *abci.Request, res *abci.Response) {
  160. switch r := res.Value.(type) {
  161. case *abci.Response_CheckTx:
  162. if r.CheckTx.Code == abci.CodeType_OK {
  163. mem.counter++
  164. memTx := &mempoolTx{
  165. counter: mem.counter,
  166. height: int64(mem.height),
  167. tx: req.GetCheckTx().Tx,
  168. }
  169. mem.txs.PushBack(memTx)
  170. } else {
  171. // ignore bad transaction
  172. log.Info("Bad Transaction", "res", r)
  173. // remove from cache (it might be good later)
  174. mem.cache.Remove(req.GetCheckTx().Tx)
  175. // TODO: handle other retcodes
  176. }
  177. default:
  178. // ignore other messages
  179. }
  180. }
  181. func (mem *Mempool) resCbRecheck(req *abci.Request, res *abci.Response) {
  182. switch r := res.Value.(type) {
  183. case *abci.Response_CheckTx:
  184. memTx := mem.recheckCursor.Value.(*mempoolTx)
  185. if !bytes.Equal(req.GetCheckTx().Tx, memTx.tx) {
  186. cmn.PanicSanity(cmn.Fmt("Unexpected tx response from proxy during recheck\n"+
  187. "Expected %X, got %X", r.CheckTx.Data, memTx.tx))
  188. }
  189. if r.CheckTx.Code == abci.CodeType_OK {
  190. // Good, nothing to do.
  191. } else {
  192. // Tx became invalidated due to newly committed block.
  193. mem.txs.Remove(mem.recheckCursor)
  194. mem.recheckCursor.DetachPrev()
  195. // remove from cache (it might be good later)
  196. mem.cache.Remove(req.GetCheckTx().Tx)
  197. }
  198. if mem.recheckCursor == mem.recheckEnd {
  199. mem.recheckCursor = nil
  200. } else {
  201. mem.recheckCursor = mem.recheckCursor.Next()
  202. }
  203. if mem.recheckCursor == nil {
  204. // Done!
  205. atomic.StoreInt32(&mem.rechecking, 0)
  206. log.Info("Done rechecking txs")
  207. }
  208. default:
  209. // ignore other messages
  210. }
  211. }
  212. // Get the valid transactions remaining
  213. // If maxTxs is -1, there is no cap on returned transactions.
  214. func (mem *Mempool) Reap(maxTxs int) types.Txs {
  215. mem.proxyMtx.Lock()
  216. defer mem.proxyMtx.Unlock()
  217. for atomic.LoadInt32(&mem.rechecking) > 0 {
  218. // TODO: Something better?
  219. time.Sleep(time.Millisecond * 10)
  220. }
  221. txs := mem.collectTxs(maxTxs)
  222. return txs
  223. }
  224. // maxTxs: -1 means uncapped, 0 means none
  225. func (mem *Mempool) collectTxs(maxTxs int) types.Txs {
  226. if maxTxs == 0 {
  227. return []types.Tx{}
  228. } else if maxTxs < 0 {
  229. maxTxs = mem.txs.Len()
  230. }
  231. txs := make([]types.Tx, 0, cmn.MinInt(mem.txs.Len(), maxTxs))
  232. for e := mem.txs.Front(); e != nil && len(txs) < maxTxs; e = e.Next() {
  233. memTx := e.Value.(*mempoolTx)
  234. txs = append(txs, memTx.tx)
  235. }
  236. return txs
  237. }
  238. // Tell mempool that these txs were committed.
  239. // Mempool will discard these txs.
  240. // NOTE: this should be called *after* block is committed by consensus.
  241. // NOTE: unsafe; Lock/Unlock must be managed by caller
  242. func (mem *Mempool) Update(height int, txs types.Txs) {
  243. // TODO: check err ?
  244. mem.proxyAppConn.FlushSync() // To flush async resCb calls e.g. from CheckTx
  245. // First, create a lookup map of txns in new txs.
  246. txsMap := make(map[string]struct{})
  247. for _, tx := range txs {
  248. txsMap[string(tx)] = struct{}{}
  249. }
  250. // Set height
  251. mem.height = height
  252. // Remove transactions that are already in txs.
  253. goodTxs := mem.filterTxs(txsMap)
  254. // Recheck mempool txs if any txs were committed in the block
  255. // NOTE/XXX: in some apps a tx could be invalidated due to EndBlock,
  256. // so we really still do need to recheck, but this is for debugging
  257. if mem.config.Recheck && (mem.config.RecheckEmpty || len(txs) > 0) {
  258. log.Info("Recheck txs", "numtxs", len(goodTxs))
  259. mem.recheckTxs(goodTxs)
  260. // At this point, mem.txs are being rechecked.
  261. // mem.recheckCursor re-scans mem.txs and possibly removes some txs.
  262. // Before mem.Reap(), we should wait for mem.recheckCursor to be nil.
  263. }
  264. }
  265. func (mem *Mempool) filterTxs(blockTxsMap map[string]struct{}) []types.Tx {
  266. goodTxs := make([]types.Tx, 0, mem.txs.Len())
  267. for e := mem.txs.Front(); e != nil; e = e.Next() {
  268. memTx := e.Value.(*mempoolTx)
  269. // Remove the tx if it's alredy in a block.
  270. if _, ok := blockTxsMap[string(memTx.tx)]; ok {
  271. // remove from clist
  272. mem.txs.Remove(e)
  273. e.DetachPrev()
  274. // NOTE: we don't remove committed txs from the cache.
  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. }
  307. //--------------------------------------------------------------------------------
  308. type txCache struct {
  309. mtx sync.Mutex
  310. size int
  311. map_ map[string]struct{}
  312. list *list.List // to remove oldest tx when cache gets too big
  313. }
  314. func newTxCache(cacheSize int) *txCache {
  315. return &txCache{
  316. size: cacheSize,
  317. map_: make(map[string]struct{}, cacheSize),
  318. list: list.New(),
  319. }
  320. }
  321. func (cache *txCache) Reset() {
  322. cache.mtx.Lock()
  323. cache.map_ = make(map[string]struct{}, cacheSize)
  324. cache.list.Init()
  325. cache.mtx.Unlock()
  326. }
  327. func (cache *txCache) Exists(tx types.Tx) bool {
  328. cache.mtx.Lock()
  329. _, exists := cache.map_[string(tx)]
  330. cache.mtx.Unlock()
  331. return exists
  332. }
  333. // Returns false if tx is in cache.
  334. func (cache *txCache) Push(tx types.Tx) bool {
  335. cache.mtx.Lock()
  336. defer cache.mtx.Unlock()
  337. if _, exists := cache.map_[string(tx)]; exists {
  338. return false
  339. }
  340. if cache.list.Len() >= cache.size {
  341. popped := cache.list.Front()
  342. poppedTx := popped.Value.(types.Tx)
  343. // NOTE: the tx may have already been removed from the map
  344. // but deleting a non-existant element is fine
  345. delete(cache.map_, string(poppedTx))
  346. cache.list.Remove(popped)
  347. }
  348. cache.map_[string(tx)] = struct{}{}
  349. cache.list.PushBack(tx)
  350. return true
  351. }
  352. func (cache *txCache) Remove(tx types.Tx) {
  353. cache.mtx.Lock()
  354. delete(cache.map_, string(tx))
  355. cache.mtx.Unlock()
  356. }