-
Notifications
You must be signed in to change notification settings - Fork 211
/
committracker.go
87 lines (69 loc) · 2.12 KB
/
committracker.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
package hare
type commitTrackerProvider interface {
OnCommit(msg *Msg)
HasEnoughCommits() bool
BuildCertificate() *certificate
CommitCount() int
}
// commitTracker tracks commit messages and build the certificate according to the tracked messages.
type commitTracker struct {
seenSenders map[string]bool // tracks seen senders
commits []*Message // tracks Set->Commits
proposedSet *Set // follows the set who has max number of commits
threshold int // the number of required commits
}
func newCommitTracker(threshold int, expectedSize int, proposedSet *Set) *commitTracker {
ct := &commitTracker{}
ct.seenSenders = make(map[string]bool, expectedSize)
ct.commits = make([]*Message, 0, threshold)
ct.proposedSet = proposedSet
ct.threshold = threshold
return ct
}
// OnCommit tracks the given commit message
func (ct *commitTracker) OnCommit(msg *Msg) {
if ct.proposedSet == nil { // no valid proposed set
return
}
if ct.HasEnoughCommits() {
return
}
pub := msg.PubKey
if ct.seenSenders[pub.String()] {
return
}
ct.seenSenders[pub.String()] = true
s := NewSet(msg.InnerMsg.Values)
if !ct.proposedSet.Equals(s) { // ignore commit on different set
return
}
// add msg
ct.commits = append(ct.commits, msg.Message)
}
// HasEnoughCommits returns true if the tracker can build a certificate, false otherwise.
func (ct *commitTracker) HasEnoughCommits() bool {
if ct.proposedSet == nil {
return false
}
return len(ct.commits) >= ct.threshold
}
func (ct *commitTracker) CommitCount() int {
return len(ct.commits)
}
// BuildCertificate returns a certificate if there are enough commits, nil otherwise
// Returns the certificate if has enough commit Messages, nil otherwise
func (ct *commitTracker) BuildCertificate() *certificate {
if !ct.HasEnoughCommits() {
return nil
}
c := &certificate{}
c.Values = ct.proposedSet.ToSlice()
c.AggMsgs = &aggregatedMessages{}
c.AggMsgs.Messages = ct.commits[:ct.threshold]
// optimize msg size by setting Values to nil
for _, commit := range c.AggMsgs.Messages {
commit.InnerMsg.Values = nil
}
// TODO: set c.AggMsgs.AggSig
return c
}