tendermint/mempool/mempool.go

303 lines
8.2 KiB
Go
Raw Normal View History

package mempool
import (
2016-02-14 17:00:33 -08:00
"bytes"
"container/list"
"sync"
2015-12-01 20:12:01 -08:00
"sync/atomic"
2016-02-14 17:00:33 -08:00
"time"
2015-12-01 20:12:01 -08:00
"github.com/tendermint/go-clist"
. "github.com/tendermint/go-common"
"github.com/tendermint/tendermint/proxy"
2015-04-01 17:30:16 -07:00
"github.com/tendermint/tendermint/types"
2015-12-01 20:12:01 -08:00
tmsp "github.com/tendermint/tmsp/types"
)
2014-09-10 02:43:16 -07:00
2015-12-01 20:12:01 -08:00
/*
The mempool pushes new txs onto the proxyAppConn.
2015-12-01 20:12:01 -08:00
It gets a stream of (req, res) tuples from the proxy.
The memool stores good txs in a concurrent linked-list.
Multiple concurrent go-routines can traverse this linked-list
safely by calling .NextWait() on each element.
So we have several go-routines:
1. Consensus calling Update() and Reap() synchronously
2. Many mempool reactor's peer routines calling CheckTx()
2015-12-01 20:12:01 -08:00
3. Many mempool reactor's peer routines traversing the txs linked list
4. Another goroutine calling GarbageCollectTxs() periodically
To manage these goroutines, there are three methods of locking.
1. Mutations to the linked-list is protected by an internal mtx (CList is goroutine-safe)
2. Mutations to the linked-list elements are atomic
3. CheckTx() calls can be paused upon Update() and Reap(), protected by .proxyMtx
2015-12-01 20:12:01 -08:00
Garbage collection of old elements from mempool.txs is handlde via
the DetachPrev() call, which makes old elements not reachable by
peer broadcastTxRoutine() automatically garbage collected.
2016-02-14 17:00:33 -08:00
TODO: Better handle tmsp client errors. (make it automatically handle connection errors)
2015-12-01 20:12:01 -08:00
*/
const cacheSize = 100000
2014-09-10 02:43:16 -07:00
type Mempool struct {
2016-02-14 17:00:33 -08:00
proxyMtx sync.Mutex
proxyAppConn proxy.AppConn
txs *clist.CList // concurrent linked-list of good txs
counter int64 // simple incrementing counter
height int // the last block Update()'d to
rechecking int32 // for re-checking filtered txs on Update()
recheckCursor *clist.CElement // next expected response
recheckEnd *clist.CElement // re-checking stops here
// Keep a cache of already-seen txs.
// This reduces the pressure on the proxyApp.
cacheMap map[string]struct{}
cacheList *list.List
2014-09-10 02:43:16 -07:00
}
func NewMempool(proxyAppConn proxy.AppConn) *Mempool {
2015-12-01 20:12:01 -08:00
mempool := &Mempool{
2016-02-14 17:00:33 -08:00
proxyAppConn: proxyAppConn,
txs: clist.New(),
counter: 0,
height: 0,
rechecking: 0,
recheckCursor: nil,
recheckEnd: nil,
cacheMap: make(map[string]struct{}, cacheSize),
cacheList: list.New(),
2014-09-10 02:43:16 -07:00
}
proxyAppConn.SetResponseCallback(mempool.resCb)
2015-12-01 20:12:01 -08:00
return mempool
2014-09-10 02:43:16 -07:00
}
func (mem *Mempool) Lock() {
mem.proxyMtx.Lock()
}
func (mem *Mempool) Unlock() {
mem.proxyMtx.Unlock()
}
2016-03-07 15:38:05 -08:00
func (mem *Mempool) Size() int {
return mem.txs.Len()
}
2015-12-01 20:12:01 -08:00
// Return the first element of mem.txs for peer goroutines to call .NextWait() on.
// Blocks until txs has elements.
func (mem *Mempool) TxsFrontWait() *clist.CElement {
return mem.txs.FrontWait()
2015-03-21 13:31:17 -07:00
}
2015-12-01 20:12:01 -08:00
// Try a new transaction in the mempool.
// Potentially blocking if we're blocking on Update() or Reap().
2016-02-08 00:48:58 -08:00
// cb: A callback from the CheckTx command.
// It gets called from another goroutine.
// CONTRACT: Either cb will get called, or err returned.
2016-02-08 00:48:58 -08:00
func (mem *Mempool) CheckTx(tx types.Tx, cb func(*tmsp.Response)) (err error) {
2015-12-01 20:12:01 -08:00
mem.proxyMtx.Lock()
defer mem.proxyMtx.Unlock()
2015-09-29 08:36:52 -07:00
// CACHE
if _, exists := mem.cacheMap[string(tx)]; exists {
if cb != nil {
cb(&tmsp.Response{
Code: tmsp.CodeType_BadNonce, // TODO or duplicate tx
Log: "Duplicate transaction (ignored)",
})
}
return nil
}
if mem.cacheList.Len() >= cacheSize {
popped := mem.cacheList.Front()
poppedTx := popped.Value.(types.Tx)
delete(mem.cacheMap, string(poppedTx))
mem.cacheList.Remove(popped)
}
mem.cacheMap[string(tx)] = struct{}{}
mem.cacheList.PushBack(tx)
// END CACHE
2016-02-14 17:00:33 -08:00
// NOTE: proxyAppConn may error if tx buffer is full
if err = mem.proxyAppConn.Error(); err != nil {
return err
2014-09-10 02:43:16 -07:00
}
2016-02-08 00:48:58 -08:00
reqRes := mem.proxyAppConn.CheckTxAsync(tx)
if cb != nil {
reqRes.SetCallback(cb)
}
2015-12-01 20:12:01 -08:00
return nil
2014-09-10 02:43:16 -07:00
}
2015-12-01 20:12:01 -08:00
// TMSP callback function
2016-01-31 08:11:50 -08:00
func (mem *Mempool) resCb(req *tmsp.Request, res *tmsp.Response) {
2016-02-14 17:00:33 -08:00
if mem.recheckCursor == nil {
mem.resCbNormal(req, res)
} else {
mem.resCbRecheck(req, res)
}
}
func (mem *Mempool) resCbNormal(req *tmsp.Request, res *tmsp.Response) {
2016-01-31 08:11:50 -08:00
switch res.Type {
2016-01-31 19:55:23 -08:00
case tmsp.MessageType_CheckTx:
2016-02-04 18:40:02 -08:00
if res.Code == tmsp.CodeType_OK {
mem.counter++
memTx := &mempoolTx{
counter: mem.counter,
height: int64(mem.height),
2016-01-31 08:11:50 -08:00
tx: req.Data,
2015-12-01 20:12:01 -08:00
}
mem.txs.PushBack(memTx)
} else {
2016-04-12 07:38:54 -07:00
log.Info("Bad Transaction", "res", res)
// ignore bad transaction
// TODO: handle other retcodes
2015-12-01 20:12:01 -08:00
}
default:
// ignore other messages
}
}
2016-02-14 17:00:33 -08:00
func (mem *Mempool) resCbRecheck(req *tmsp.Request, res *tmsp.Response) {
switch res.Type {
case tmsp.MessageType_CheckTx:
memTx := mem.recheckCursor.Value.(*mempoolTx)
if !bytes.Equal(req.Data, memTx.tx) {
PanicSanity(Fmt("Unexpected tx response from proxy during recheck\n"+
"Expected %X, got %X", req.Data, memTx.tx))
}
if res.Code == tmsp.CodeType_OK {
// Good, nothing to do.
} else {
// Tx became invalidated due to newly committed block.
mem.txs.Remove(mem.recheckCursor)
mem.recheckCursor.DetachPrev()
}
if mem.recheckCursor == mem.recheckEnd {
mem.recheckCursor = nil
} else {
mem.recheckCursor = mem.recheckCursor.Next()
}
if mem.recheckCursor == nil {
// Done!
atomic.StoreInt32(&mem.rechecking, 0)
2016-04-12 07:38:54 -07:00
log.Info("Done rechecking txs")
2016-02-14 17:00:33 -08:00
}
default:
// ignore other messages
}
}
// Get the valid transactions remaining
2016-03-06 15:08:32 -08:00
// If maxTxs is 0, there is no cap.
func (mem *Mempool) Reap(maxTxs int) []types.Tx {
2015-12-01 20:12:01 -08:00
mem.proxyMtx.Lock()
defer mem.proxyMtx.Unlock()
2016-02-14 17:00:33 -08:00
for atomic.LoadInt32(&mem.rechecking) > 0 {
// TODO: Something better?
time.Sleep(time.Millisecond * 10)
}
2015-12-01 20:12:01 -08:00
2016-03-06 15:08:32 -08:00
txs := mem.collectTxs(maxTxs)
2016-02-14 17:00:33 -08:00
return txs
2015-09-25 09:55:59 -07:00
}
2016-04-26 19:17:13 -07:00
// maxTxs: -1 means uncapped, 0 means none
2016-03-06 15:08:32 -08:00
func (mem *Mempool) collectTxs(maxTxs int) []types.Tx {
if maxTxs == 0 {
2016-03-07 21:43:39 -08:00
return []types.Tx{}
2016-04-26 19:17:13 -07:00
} else if maxTxs < 0 {
maxTxs = mem.txs.Len()
2016-03-06 15:08:32 -08:00
}
txs := make([]types.Tx, 0, MinInt(mem.txs.Len(), maxTxs))
for e := mem.txs.Front(); e != nil && len(txs) < maxTxs; e = e.Next() {
2015-12-01 20:12:01 -08:00
memTx := e.Value.(*mempoolTx)
txs = append(txs, memTx.tx)
}
return txs
2015-09-25 09:55:59 -07:00
}
// Tell mempool that these txs were committed.
// Mempool will discard these txs.
2015-12-01 20:12:01 -08:00
// NOTE: this should be called *after* block is committed by consensus.
// NOTE: unsafe; Lock/Unlock must be managed by caller
2016-02-14 17:00:33 -08:00
func (mem *Mempool) Update(height int, txs []types.Tx) {
// mem.proxyMtx.Lock()
// defer mem.proxyMtx.Unlock()
2016-03-25 08:29:03 -07:00
mem.proxyAppConn.FlushSync() // To flush async resCb calls e.g. from CheckTx
2015-12-01 20:12:01 -08:00
// First, create a lookup map of txns in new txs.
txsMap := make(map[string]struct{})
for _, tx := range txs {
txsMap[string(tx)] = struct{}{}
2015-12-01 20:12:01 -08:00
}
// Set height
mem.height = height
// Remove transactions that are already in txs.
2016-02-14 17:00:33 -08:00
goodTxs := mem.filterTxs(txsMap)
// Recheck mempool txs
if config.GetBool("mempool_recheck") {
2016-04-12 07:38:54 -07:00
log.Info("Recheck txs", "numtxs", len(goodTxs))
mem.recheckTxs(goodTxs)
// At this point, mem.txs are being rechecked.
// mem.recheckCursor re-scans mem.txs and possibly removes some txs.
// Before mem.Reap(), we should wait for mem.recheckCursor to be nil.
}
2015-09-25 09:55:59 -07:00
}
func (mem *Mempool) filterTxs(blockTxsMap map[string]struct{}) []types.Tx {
2015-12-01 20:12:01 -08:00
goodTxs := make([]types.Tx, 0, mem.txs.Len())
for e := mem.txs.Front(); e != nil; e = e.Next() {
memTx := e.Value.(*mempoolTx)
if _, ok := blockTxsMap[string(memTx.tx)]; ok {
// Remove the tx since already in block.
mem.txs.Remove(e)
e.DetachPrev()
continue
}
// Good tx!
goodTxs = append(goodTxs, memTx.tx)
2015-09-25 09:55:59 -07:00
}
2015-12-01 20:12:01 -08:00
return goodTxs
2015-09-25 09:55:59 -07:00
}
2016-02-14 17:00:33 -08:00
// NOTE: pass in goodTxs because mem.txs can mutate concurrently.
func (mem *Mempool) recheckTxs(goodTxs []types.Tx) {
if len(goodTxs) == 0 {
return
}
atomic.StoreInt32(&mem.rechecking, 1)
mem.recheckCursor = mem.txs.Front()
mem.recheckEnd = mem.txs.Back()
// Push txs to proxyAppConn
// NOTE: resCb() may be called concurrently.
for _, tx := range goodTxs {
mem.proxyAppConn.CheckTxAsync(tx)
}
mem.proxyAppConn.FlushAsync()
}
2015-12-01 20:12:01 -08:00
//--------------------------------------------------------------------------------
// A transaction that successfully ran
type mempoolTx struct {
counter int64 // a simple incrementing counter
height int64 // height that this tx had been validated in
tx types.Tx //
}
func (memTx *mempoolTx) Height() int {
return int(atomic.LoadInt64(&memTx.height))
}