forked from filecoin-project/lotus
-
Notifications
You must be signed in to change notification settings - Fork 14
/
block_receipt_tracker.go
72 lines (57 loc) · 1.31 KB
/
block_receipt_tracker.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
package chain
import (
"sort"
"sync"
"time"
"github.com/EpiK-Protocol/go-epik/build"
"github.com/EpiK-Protocol/go-epik/chain/types"
lru "github.com/hashicorp/golang-lru"
"github.com/libp2p/go-libp2p-core/peer"
)
type blockReceiptTracker struct {
lk sync.Mutex
// using an LRU cache because i don't want to handle all the edge cases for
// manual cleanup and maintenance of a fixed size set
cache *lru.Cache
}
type peerSet struct {
peers map[peer.ID]time.Time
}
func newBlockReceiptTracker() *blockReceiptTracker {
c, _ := lru.New(512)
return &blockReceiptTracker{
cache: c,
}
}
func (brt *blockReceiptTracker) Add(p peer.ID, ts *types.TipSet) {
brt.lk.Lock()
defer brt.lk.Unlock()
val, ok := brt.cache.Get(ts.Key())
if !ok {
pset := &peerSet{
peers: map[peer.ID]time.Time{
p: build.Clock.Now(),
},
}
brt.cache.Add(ts.Key(), pset)
return
}
val.(*peerSet).peers[p] = build.Clock.Now()
}
func (brt *blockReceiptTracker) GetPeers(ts *types.TipSet) []peer.ID {
brt.lk.Lock()
defer brt.lk.Unlock()
val, ok := brt.cache.Get(ts.Key())
if !ok {
return nil
}
ps := val.(*peerSet)
out := make([]peer.ID, 0, len(ps.peers))
for p := range ps.peers {
out = append(out, p)
}
sort.Slice(out, func(i, j int) bool {
return ps.peers[out[i]].Before(ps.peers[out[j]])
})
return out
}