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