-
Notifications
You must be signed in to change notification settings - Fork 669
/
nnary_snowball.go
73 lines (58 loc) · 2.21 KB
/
nnary_snowball.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
// Copyright (C) 2019-2023, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package snowball
import (
"fmt"
"github.com/ava-labs/avalanchego/ids"
)
var _ NnarySnowball = (*nnarySnowball)(nil)
func newNnarySnowball(betaVirtuous, betaRogue int, choice ids.ID) nnarySnowball {
return nnarySnowball{
nnarySnowflake: newNnarySnowflake(betaVirtuous, betaRogue, choice),
preference: choice,
preferenceStrength: make(map[ids.ID]int),
}
}
// nnarySnowball is a naive implementation of a multi-color snowball instance
type nnarySnowball struct {
// wrap the n-nary snowflake logic
nnarySnowflake
// preference is the choice with the largest number of polls which preferred
// it. Ties are broken by switching choice lazily
preference ids.ID
// maxPreferenceStrength is the maximum value stored in [preferenceStrength]
maxPreferenceStrength int
// preferenceStrength tracks the total number of network polls which
// preferred that choice
preferenceStrength map[ids.ID]int
}
func (sb *nnarySnowball) Preference() ids.ID {
// It is possible, with low probability, that the snowflake preference is
// not equal to the snowball preference when snowflake finalizes. However,
// this case is handled for completion. Therefore, if snowflake is
// finalized, then our finalized snowflake choice should be preferred.
if sb.Finalized() {
return sb.nnarySnowflake.Preference()
}
return sb.preference
}
func (sb *nnarySnowball) RecordSuccessfulPoll(choice ids.ID) {
sb.increasePreferenceStrength(choice)
sb.nnarySnowflake.RecordSuccessfulPoll(choice)
}
func (sb *nnarySnowball) RecordPollPreference(choice ids.ID) {
sb.increasePreferenceStrength(choice)
sb.nnarySnowflake.RecordPollPreference(choice)
}
func (sb *nnarySnowball) String() string {
return fmt.Sprintf("SB(Preference = %s, PreferenceStrength = %d, %s)",
sb.preference, sb.maxPreferenceStrength, &sb.nnarySnowflake)
}
func (sb *nnarySnowball) increasePreferenceStrength(choice ids.ID) {
preferenceStrength := sb.preferenceStrength[choice] + 1
sb.preferenceStrength[choice] = preferenceStrength
if preferenceStrength > sb.maxPreferenceStrength {
sb.preference = choice
sb.maxPreferenceStrength = preferenceStrength
}
}