-
Notifications
You must be signed in to change notification settings - Fork 186
/
Copy pathpeer_rank.go
93 lines (77 loc) · 2 KB
/
peer_rank.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
90
91
92
93
package query
import (
"sort"
)
const (
// bestScore is the best score a peer can get after multiple rewards.
bestScore = 0
// defaultScore is the score given to a peer when it hasn't been
// rewarded or punished.
defaultScore = 4
// worstScore is the worst score a peer can get after multiple
// punishments.
worstScore = 8
)
// peerRanking is a struct that keeps history of peer's previous query success
// rate, and uses that to prioritise which peers to give the next queries to.
type peerRanking struct {
// rank keeps track of the current set of peers and their score. A
// lower score is better.
rank map[string]uint64
}
// A compile time check to ensure peerRanking satisfies the PeerRanking
// interface.
var _ PeerRanking = (*peerRanking)(nil)
// NewPeerRanking returns a new, empty ranking.
func NewPeerRanking() PeerRanking {
return &peerRanking{
rank: make(map[string]uint64),
}
}
// Order sorts the given slice of peers based on their current score. If a
// peer has no current score given, the default will be used.
func (p *peerRanking) Order(peers []string) {
sort.Slice(peers, func(i, j int) bool {
score1, ok := p.rank[peers[i]]
if !ok {
score1 = defaultScore
}
score2, ok := p.rank[peers[j]]
if !ok {
score2 = defaultScore
}
return score1 < score2
})
}
// AddPeer adds a new peer to the ranking, starting out with the default score.
func (p *peerRanking) AddPeer(peer string) {
if _, ok := p.rank[peer]; ok {
return
}
p.rank[peer] = defaultScore
}
// Punish increases the score of the given peer.
func (p *peerRanking) Punish(peer string) {
score, ok := p.rank[peer]
if !ok {
return
}
// Cannot punish more.
if score == worstScore {
return
}
p.rank[peer] = score + 1
}
// Reward decreases the score of the given peer.
// TODO(halseth): use actual response time when ranking peers.
func (p *peerRanking) Reward(peer string) {
score, ok := p.rank[peer]
if !ok {
return
}
// Cannot reward more.
if score == bestScore {
return
}
p.rank[peer] = score - 1
}