4 "github.com/golang/groupcache/lru"
6 "github.com/vapor/crypto/sha3pool"
7 "github.com/vapor/mining/tensority/cgo_algorithm"
8 "github.com/vapor/mining/tensority/go_algorithm"
9 "github.com/vapor/protocol/bc"
12 const maxAIHashCached = 64
14 func calcCacheKey(hash, seed *bc.Hash) *bc.Hash {
16 sha3pool.Sum256(b32[:], append(hash.Bytes(), seed.Bytes()...))
17 key := bc.NewHash(b32)
21 // Cache is create for cache the tensority result
26 // NewCache create a cache struct
27 func NewCache() *Cache {
28 return &Cache{lruCache: lru.New(maxAIHashCached)}
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)
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)
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 {
49 return algorithm(hash, seed)
52 func algorithm(bh, seed *bc.Hash) *bc.Hash {
54 return cgo_algorithm.SimdAlgorithm(bh, seed)
56 return go_algorithm.LegacyAlgorithm(bh, seed)
61 AIHash = NewCache() // AIHash is created for let different package share same cache