github.com/turingchain2020/turingchain@v1.1.21/system/mempool/simplequeue.go (about) 1 // Copyright Turing Corp. 2018 All Rights Reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package mempool 6 7 import ( 8 "github.com/turingchain2020/turingchain/common/listmap" 9 "github.com/turingchain2020/turingchain/types" 10 ) 11 12 // SubConfig 配置信息 13 type SubConfig struct { 14 PoolCacheSize int64 `json:"poolCacheSize"` 15 ProperFee int64 `json:"properFee"` 16 } 17 18 //SimpleQueue 简单队列模式(默认提供一个队列,便于测试) 19 type SimpleQueue struct { 20 txList *listmap.ListMap 21 subConfig SubConfig 22 cacheBytes int64 23 } 24 25 //NewSimpleQueue 创建队列 26 func NewSimpleQueue(subConfig SubConfig) *SimpleQueue { 27 return &SimpleQueue{ 28 txList: listmap.New(), 29 subConfig: subConfig, 30 } 31 } 32 33 //Exist 是否存在 34 func (cache *SimpleQueue) Exist(hash string) bool { 35 return cache.txList.Exist(hash) 36 } 37 38 //GetItem 获取数据通过 key 39 func (cache *SimpleQueue) GetItem(hash string) (*Item, error) { 40 item, err := cache.txList.GetItem(hash) 41 if err != nil { 42 return nil, err 43 } 44 return item.(*Item), nil 45 } 46 47 // Push 把给定tx添加到SimpleQueue;如果tx已经存在SimpleQueue中或Mempool已满则返回对应error 48 func (cache *SimpleQueue) Push(tx *Item) error { 49 hash := tx.Value.Hash() 50 if cache.Exist(string(hash)) { 51 return types.ErrTxExist 52 } 53 if cache.txList.Size() >= int(cache.subConfig.PoolCacheSize) { 54 return types.ErrMemFull 55 } 56 cache.txList.Push(string(hash), tx) 57 cache.cacheBytes += int64(types.Size(tx.Value)) 58 return nil 59 } 60 61 // Remove 删除数据 62 func (cache *SimpleQueue) Remove(hash string) error { 63 item, err := cache.GetItem(hash) 64 if err != nil { 65 return err 66 } 67 cache.txList.Remove(hash) 68 cache.cacheBytes -= int64(types.Size(item.Value)) 69 return nil 70 } 71 72 // Size 数据总数 73 func (cache *SimpleQueue) Size() int { 74 return cache.txList.Size() 75 } 76 77 // Walk 遍历整个队列 78 func (cache *SimpleQueue) Walk(count int, cb func(value *Item) bool) { 79 i := 0 80 cache.txList.Walk(func(item interface{}) bool { 81 if !cb(item.(*Item)) { 82 return false 83 } 84 i++ 85 return i != count 86 }) 87 } 88 89 // GetProperFee 获取合适的手续费 90 func (cache *SimpleQueue) GetProperFee() int64 { 91 return cache.subConfig.ProperFee 92 } 93 94 // GetCacheBytes 获取缓存占用空间大小 95 func (cache *SimpleQueue) GetCacheBytes() int64 { 96 return cache.cacheBytes 97 }