/
bhcache.go
89 lines (78 loc) · 1.66 KB
/
bhcache.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package dman
import (
"strconv"
"sync"
"github.com/alicenet/alicenet/consensus/objs"
"github.com/alicenet/alicenet/utils"
)
type bHCache struct {
sync.Mutex
cache map[uint32]string
}
func (bhc *bHCache) Init() error {
bhc.cache = make(map[uint32]string)
return nil
}
func (bhc *bHCache) Add(bh *objs.BlockHeader) error {
bhc.Lock()
defer bhc.Unlock()
bhBytes, err := bh.MarshalBinary()
if err != nil {
return err
}
bhc.cache[bh.BClaims.Height] = string(bhBytes)
return nil
}
func (bhc *bHCache) Contains(height uint32) bool {
bhc.Lock()
defer bhc.Unlock()
if _, ok := bhc.getInternal(height); ok {
return true
}
return false
}
func (bhc *bHCache) Get(height uint32) (*objs.BlockHeader, bool) {
bhc.Lock()
defer bhc.Unlock()
return bhc.getInternal(height)
}
func (bhc *bHCache) getInternal(height uint32) (*objs.BlockHeader, bool) {
bhIf, ok := bhc.cache[height]
if ok {
bhString := bhIf
bhBytes := []byte(bhString)
bhCopy := utils.CopySlice(bhBytes)
bh := &objs.BlockHeader{}
err := bh.UnmarshalBinary(bhCopy)
if err != nil {
bhc.delInternal(height)
return nil, false
}
return bh, true
}
return nil, false
}
func (bhc *bHCache) Del(height uint32) {
bhc.Lock()
defer bhc.Unlock()
bhc.delInternal(height)
}
func (bhc *bHCache) delInternal(height uint32) {
delete(bhc.cache, height)
}
func (bhc *bHCache) DropBeforeHeight(dropHeight uint32) []string {
out := []string{}
if dropHeight-256 > dropHeight {
return out
}
bhc.Lock()
defer bhc.Unlock()
for height := range bhc.cache {
height := height
if height <= uint32(dropHeight) {
out = append(out, strconv.Itoa(int(height)))
bhc.delInternal(height)
}
}
return out
}