-
Notifications
You must be signed in to change notification settings - Fork 669
/
nnary_snowflake.go
81 lines (63 loc) · 2.03 KB
/
nnary_snowflake.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
// 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 _ NnarySnowflake = (*nnarySnowflake)(nil)
// nnarySnowflake is the implementation of a snowflake instance with an
// unbounded number of choices
type nnarySnowflake struct {
// wrap the n-nary slush logic
nnarySlush
// betaVirtuous is the number of consecutive successful queries required for
// finalization on a virtuous instance.
betaVirtuous int
// betaRogue is the number of consecutive successful queries required for
// finalization on a rogue instance.
betaRogue int
// confidence tracks the number of successful polls in a row that have
// returned the preference
confidence int
// rogue tracks if this instance has multiple choices or only one
rogue bool
// finalized prevents the state from changing after the required number of
// consecutive polls has been reached
finalized bool
}
func (sf *nnarySnowflake) Initialize(betaVirtuous, betaRogue int, choice ids.ID) {
sf.nnarySlush.Initialize(choice)
sf.betaVirtuous = betaVirtuous
sf.betaRogue = betaRogue
}
func (sf *nnarySnowflake) Add(choice ids.ID) {
sf.rogue = sf.rogue || choice != sf.preference
}
func (sf *nnarySnowflake) RecordSuccessfulPoll(choice ids.ID) {
if sf.finalized {
return // This instance is already decided.
}
if preference := sf.Preference(); preference == choice {
sf.confidence++
} else {
// confidence is set to 1 because there has already been 1 successful
// poll, namely this poll.
sf.confidence = 1
}
sf.finalized = (!sf.rogue && sf.confidence >= sf.betaVirtuous) ||
sf.confidence >= sf.betaRogue
sf.nnarySlush.RecordSuccessfulPoll(choice)
}
func (sf *nnarySnowflake) RecordUnsuccessfulPoll() {
sf.confidence = 0
}
func (sf *nnarySnowflake) Finalized() bool {
return sf.finalized
}
func (sf *nnarySnowflake) String() string {
return fmt.Sprintf("SF(Confidence = %d, Finalized = %v, %s)",
sf.confidence,
sf.finalized,
&sf.nnarySlush)
}