github.com/Bytom/bytom@v1.1.2-0.20210127130405-ae40204c0b09/mining/tensority/ai_hash.go (about)

     1  package tensority
     2  
     3  import (
     4  	"github.com/golang/groupcache/lru"
     5  
     6  	"github.com/bytom/bytom/crypto/sha3pool"
     7  	"github.com/bytom/bytom/mining/tensority/cgo_algorithm"
     8  	"github.com/bytom/bytom/mining/tensority/go_algorithm"
     9  	"github.com/bytom/bytom/protocol/bc"
    10  )
    11  
    12  const maxAIHashCached = 64
    13  
    14  func calcCacheKey(hash, seed *bc.Hash) *bc.Hash {
    15  	var b32 [32]byte
    16  	sha3pool.Sum256(b32[:], append(hash.Bytes(), seed.Bytes()...))
    17  	key := bc.NewHash(b32)
    18  	return &key
    19  }
    20  
    21  // Cache is create for cache the tensority result
    22  type Cache struct {
    23  	lruCache *lru.Cache
    24  }
    25  
    26  // NewCache create a cache struct
    27  func NewCache() *Cache {
    28  	return &Cache{lruCache: lru.New(maxAIHashCached)}
    29  }
    30  
    31  // AddCache is used for add tensority calculate result
    32  func (a *Cache) AddCache(hash, seed, result *bc.Hash) {
    33  	key := calcCacheKey(hash, seed)
    34  	a.lruCache.Add(*key, result)
    35  }
    36  
    37  // RemoveCache clean the cached result
    38  func (a *Cache) RemoveCache(hash, seed *bc.Hash) {
    39  	key := calcCacheKey(hash, seed)
    40  	a.lruCache.Remove(key)
    41  }
    42  
    43  // Hash is the real entry for call tensority algorithm
    44  func (a *Cache) Hash(hash, seed *bc.Hash) *bc.Hash {
    45  	key := calcCacheKey(hash, seed)
    46  	if v, ok := a.lruCache.Get(*key); ok {
    47  		return v.(*bc.Hash)
    48  	}
    49  	return algorithm(hash, seed)
    50  }
    51  
    52  func algorithm(bh, seed *bc.Hash) *bc.Hash {
    53  	if UseSIMD {
    54  		return cgo_algorithm.SimdAlgorithm(bh, seed)
    55  	} else {
    56  		return go_algorithm.LegacyAlgorithm(bh, seed)
    57  	}
    58  }
    59  
    60  var (
    61  	AIHash  = NewCache() // AIHash is created for let different package share same cache
    62  	UseSIMD = false
    63  )