/
validator_store.go
74 lines (61 loc) · 1.63 KB
/
validator_store.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
// Copyright (C) 2021 Aung Maw
// Licensed under the GNU General Public License v3.0
package core
import (
"math"
)
// ValidatorStore godoc
type ValidatorStore interface {
ValidatorCount() int
MajorityCount() int
IsValidator(pubKey *PublicKey) bool
GetValidator(idx int) *PublicKey
GetValidatorIndex(pubKey *PublicKey) int
}
type simpleValidatorStore struct {
validators []*PublicKey
vMap map[string]int
majority int
}
var _ ValidatorStore = (*simpleValidatorStore)(nil)
func NewValidatorStore(validators []*PublicKey) ValidatorStore {
store := &simpleValidatorStore{
validators: validators,
}
store.vMap = make(map[string]int, len(store.validators))
for i, v := range store.validators {
store.vMap[v.String()] = i
}
store.majority = MajorityCount(len(validators))
return store
}
func (store *simpleValidatorStore) ValidatorCount() int {
return len(store.validators)
}
func (store *simpleValidatorStore) MajorityCount() int {
return store.majority
}
func (store *simpleValidatorStore) IsValidator(pubKey *PublicKey) bool {
if pubKey == nil {
return false
}
_, ok := store.vMap[pubKey.String()]
return ok
}
func (store *simpleValidatorStore) GetValidator(idx int) *PublicKey {
if idx >= len(store.validators) || idx < 0 {
return nil
}
return store.validators[idx]
}
func (store *simpleValidatorStore) GetValidatorIndex(pubKey *PublicKey) int {
if pubKey == nil {
return 0
}
return store.vMap[pubKey.String()]
}
// MajorityCount returns 2f + 1 members
func MajorityCount(validatorCount int) int {
// n=3f+1 -> f=floor((n-1)3) -> m=n-f -> m=ceil((2n+1)/3)
return int(math.Ceil(float64(2*validatorCount+1) / 3))
}