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

     1  package mempool
     2  
     3  import (
     4  	"github.com/turingchain2020/turingchain/common/listmap"
     5  	"github.com/turingchain2020/turingchain/types"
     6  )
     7  
     8  //AccountTxIndex 账户和交易索引
     9  type AccountTxIndex struct {
    10  	maxperaccount int
    11  	accMap        map[string]*listmap.ListMap
    12  }
    13  
    14  //NewAccountTxIndex 创建一个新的索引
    15  func NewAccountTxIndex(maxperaccount int) *AccountTxIndex {
    16  	return &AccountTxIndex{
    17  		maxperaccount: maxperaccount,
    18  		accMap:        make(map[string]*listmap.ListMap),
    19  	}
    20  }
    21  
    22  // TxNumOfAccount 返回账户在Mempool中交易数量
    23  func (cache *AccountTxIndex) TxNumOfAccount(addr string) int {
    24  	if _, ok := cache.accMap[addr]; ok {
    25  		return cache.accMap[addr].Size()
    26  	}
    27  	return 0
    28  }
    29  
    30  // GetAccTxs 用来获取对应账户地址(列表)中的全部交易详细信息
    31  func (cache *AccountTxIndex) GetAccTxs(addrs *types.ReqAddrs) *types.TransactionDetails {
    32  	res := &types.TransactionDetails{}
    33  	for _, addr := range addrs.Addrs {
    34  		if value, ok := cache.accMap[addr]; ok {
    35  			value.Walk(func(val interface{}) bool {
    36  				v := val.(*types.Transaction)
    37  				txAmount, err := v.Amount()
    38  				if err != nil {
    39  					txAmount = 0
    40  				}
    41  				res.Txs = append(res.Txs,
    42  					&types.TransactionDetail{
    43  						Tx:         v,
    44  						Amount:     txAmount,
    45  						Fromaddr:   addr,
    46  						ActionName: v.ActionName(),
    47  					})
    48  				return true
    49  			})
    50  		}
    51  	}
    52  	return res
    53  }
    54  
    55  //Remove 根据交易哈希删除对应账户的对应交易
    56  func (cache *AccountTxIndex) Remove(tx *types.Transaction) {
    57  	addr := tx.From()
    58  	if lm, ok := cache.accMap[addr]; ok {
    59  		lm.Remove(string(tx.Hash()))
    60  		if lm.Size() == 0 {
    61  			delete(cache.accMap, addr)
    62  		}
    63  	}
    64  }
    65  
    66  // Push push transaction to AccountTxIndex
    67  func (cache *AccountTxIndex) Push(tx *types.Transaction) error {
    68  	addr := tx.From()
    69  	_, ok := cache.accMap[addr]
    70  	if !ok {
    71  		cache.accMap[addr] = listmap.New()
    72  	}
    73  	if cache.accMap[addr].Size() >= cache.maxperaccount {
    74  		return types.ErrManyTx
    75  	}
    76  	cache.accMap[addr].Push(string(tx.Hash()), tx)
    77  	return nil
    78  }
    79  
    80  //CanPush 是否可以push 进 account index
    81  func (cache *AccountTxIndex) CanPush(tx *types.Transaction) bool {
    82  	if item, ok := cache.accMap[tx.From()]; ok {
    83  		return item.Size() < cache.maxperaccount
    84  	}
    85  	return true
    86  }