github.com/turingchain2020/turingchain@v1.1.21/system/mempool/shorthashtx.go (about)

     1  package mempool
     2  
     3  import (
     4  	"github.com/turingchain2020/turingchain/common"
     5  	"github.com/turingchain2020/turingchain/common/listmap"
     6  	log "github.com/turingchain2020/turingchain/common/log/log15"
     7  	"github.com/turingchain2020/turingchain/types"
     8  )
     9  
    10  var shashlog = log.New("module", "mempool.shash")
    11  
    12  //SHashTxCache 通过shorthash缓存交易
    13  type SHashTxCache struct {
    14  	max int
    15  	l   *listmap.ListMap
    16  }
    17  
    18  //NewSHashTxCache 创建通过短hash交易的cache
    19  func NewSHashTxCache(size int) *SHashTxCache {
    20  	return &SHashTxCache{
    21  		max: size,
    22  		l:   listmap.New(),
    23  	}
    24  }
    25  
    26  //GetSHashTxCache 返回shorthash对应的tx交易信息
    27  func (cache *SHashTxCache) GetSHashTxCache(sHash string) *types.Transaction {
    28  	tx, err := cache.l.GetItem(sHash)
    29  	if err != nil {
    30  		return nil
    31  	}
    32  	return tx.(*types.Transaction)
    33  
    34  }
    35  
    36  //Remove remove tx of SHashTxCache
    37  func (cache *SHashTxCache) Remove(tx *types.Transaction) {
    38  	txhash := tx.Hash()
    39  	cache.l.Remove(types.CalcTxShortHash(txhash))
    40  	//shashlog.Debug("SHashTxCache:Remove", "shash", types.CalcTxShortHash(txhash), "txhash", common.ToHex(txhash))
    41  }
    42  
    43  //Push tx into SHashTxCache
    44  func (cache *SHashTxCache) Push(tx *types.Transaction) {
    45  	shash := types.CalcTxShortHash(tx.Hash())
    46  
    47  	if cache.Exist(shash) {
    48  		shashlog.Error("SHashTxCache:Push:Exist", "oldhash", common.ToHex(cache.GetSHashTxCache(shash).Hash()), "newhash", common.ToHex(tx.Hash()))
    49  		return
    50  	}
    51  	if cache.l.Size() >= cache.max {
    52  		shashlog.Error("SHashTxCache:Push:ErrMemFull", "cache.l.Size()", cache.l.Size(), "cache.max", cache.max)
    53  		return
    54  	}
    55  	cache.l.Push(shash, tx)
    56  	//shashlog.Debug("SHashTxCache:Push", "shash", shash, "txhash", common.ToHex(tx.Hash()))
    57  }
    58  
    59  //Exist 是否存在
    60  func (cache *SHashTxCache) Exist(shash string) bool {
    61  	return cache.l.Exist(shash)
    62  }