-
Notifications
You must be signed in to change notification settings - Fork 662
/
nnary_snowball.go
64 lines (50 loc) · 1.91 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
// Copyright (C) 2019-2022, 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{}
// 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 successful polls.
// Ties are broken by switching choice lazily
preference ids.ID
// maxSuccessfulPolls maximum number of successful polls this instance has
// gotten for any choice
maxSuccessfulPolls int
// numSuccessfulPolls tracks the total number of successful network polls of
// the choices
numSuccessfulPolls map[ids.ID]int
}
func (sb *nnarySnowball) Initialize(betaVirtuous, betaRogue int, choice ids.ID) {
sb.nnarySnowflake.Initialize(betaVirtuous, betaRogue, choice)
sb.preference = choice
sb.numSuccessfulPolls = make(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) {
numSuccessfulPolls := sb.numSuccessfulPolls[choice] + 1
sb.numSuccessfulPolls[choice] = numSuccessfulPolls
if numSuccessfulPolls > sb.maxSuccessfulPolls {
sb.preference = choice
sb.maxSuccessfulPolls = numSuccessfulPolls
}
sb.nnarySnowflake.RecordSuccessfulPoll(choice)
}
func (sb *nnarySnowball) String() string {
return fmt.Sprintf("SB(Preference = %s, NumSuccessfulPolls = %d, %s)",
sb.preference, sb.maxSuccessfulPolls, &sb.nnarySnowflake)
}