This repository has been archived by the owner on Nov 2, 2020. It is now read-only.
/
epoch_context.go
221 lines (201 loc) · 6.68 KB
/
epoch_context.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
package dpos
import (
"encoding/binary"
"errors"
"fmt"
"math/big"
"math/rand"
"sort"
"github.com/meitu/go-ethereum/common"
"github.com/meitu/go-ethereum/core/state"
"github.com/meitu/go-ethereum/core/types"
"github.com/meitu/go-ethereum/crypto"
"github.com/meitu/go-ethereum/log"
"github.com/meitu/go-ethereum/trie"
)
type EpochContext struct {
TimeStamp int64
DposContext *types.DposContext
statedb *state.StateDB
}
// countVotes
func (ec *EpochContext) countVotes() (votes map[common.Address]*big.Int, err error) {
votes = map[common.Address]*big.Int{}
delegateTrie := ec.DposContext.DelegateTrie()
candidateTrie := ec.DposContext.CandidateTrie()
statedb := ec.statedb
iterCandidate := trie.NewIterator(candidateTrie.NodeIterator(nil))
existCandidate := iterCandidate.Next()
if !existCandidate {
return votes, errors.New("no candidates")
}
for existCandidate {
candidate := iterCandidate.Value
candidateAddr := common.BytesToAddress(candidate)
delegateIterator := trie.NewIterator(delegateTrie.PrefixIterator(candidate))
existDelegator := delegateIterator.Next()
if !existDelegator {
votes[candidateAddr] = new(big.Int)
existCandidate = iterCandidate.Next()
continue
}
for existDelegator {
delegator := delegateIterator.Value
score, ok := votes[candidateAddr]
if !ok {
score = new(big.Int)
}
delegatorAddr := common.BytesToAddress(delegator)
weight := statedb.GetBalance(delegatorAddr)
score.Add(score, weight)
votes[candidateAddr] = score
existDelegator = delegateIterator.Next()
}
existCandidate = iterCandidate.Next()
}
return votes, nil
}
func (ec *EpochContext) kickoutValidator(epoch int64) error {
validators, err := ec.DposContext.GetValidators()
if err != nil {
return fmt.Errorf("failed to get validator: %s", err)
}
if len(validators) == 0 {
return errors.New("no validator could be kickout")
}
epochDuration := epochInterval
// First epoch duration may lt epoch interval,
// while the first block time wouldn't always align with epoch interval,
// so caculate the first epoch duartion with first block time instead of epoch interval,
// prevent the validators were kickout incorrectly.
if ec.TimeStamp-timeOfFirstBlock < epochInterval {
epochDuration = ec.TimeStamp - timeOfFirstBlock
}
needKickoutValidators := sortableAddresses{}
for _, validator := range validators {
key := make([]byte, 8)
binary.BigEndian.PutUint64(key, uint64(epoch))
key = append(key, validator.Bytes()...)
cnt := int64(0)
if cntBytes := ec.DposContext.MintCntTrie().Get(key); cntBytes != nil {
cnt = int64(binary.BigEndian.Uint64(cntBytes))
}
if cnt < epochDuration/blockInterval/ maxValidatorSize /2 {
// not active validators need kickout
needKickoutValidators = append(needKickoutValidators, &sortableAddress{validator, big.NewInt(cnt)})
}
}
// no validators need kickout
needKickoutValidatorCnt := len(needKickoutValidators)
if needKickoutValidatorCnt <= 0 {
return nil
}
sort.Sort(sort.Reverse(needKickoutValidators))
candidateCount := 0
iter := trie.NewIterator(ec.DposContext.CandidateTrie().NodeIterator(nil))
for iter.Next() {
candidateCount++
if candidateCount >= needKickoutValidatorCnt+safeSize {
break
}
}
for i, validator := range needKickoutValidators {
// ensure candidate count greater than or equal to safeSize
if candidateCount <= safeSize {
log.Info("No more candidate can be kickout", "prevEpochID", epoch, "candidateCount", candidateCount, "needKickoutCount", len(needKickoutValidators)-i)
return nil
}
if err := ec.DposContext.KickoutCandidate(validator.address); err != nil {
return err
}
// if kickout success, candidateCount minus 1
candidateCount--
log.Info("Kickout candidate", "prevEpochID", epoch, "candidate", validator.address.String(), "mintCnt", validator.weight.String())
}
return nil
}
func (ec *EpochContext) lookupValidator(now int64) (validator common.Address, err error) {
validator = common.Address{}
offset := now % epochInterval
if offset%blockInterval != 0 {
return common.Address{}, ErrInvalidMintBlockTime
}
offset /= blockInterval
validators, err := ec.DposContext.GetValidators()
if err != nil {
return common.Address{}, err
}
validatorSize := len(validators)
if validatorSize == 0 {
return common.Address{}, errors.New("failed to lookup validator")
}
offset %= int64(validatorSize)
return validators[offset], nil
}
func (ec *EpochContext) tryElect(genesis, parent *types.Header) error {
genesisEpoch := genesis.Time.Int64() / epochInterval
prevEpoch := parent.Time.Int64() / epochInterval
currentEpoch := ec.TimeStamp / epochInterval
prevEpochIsGenesis := prevEpoch == genesisEpoch
if prevEpochIsGenesis && prevEpoch < currentEpoch {
prevEpoch = currentEpoch - 1
}
prevEpochBytes := make([]byte, 8)
binary.BigEndian.PutUint64(prevEpochBytes, uint64(prevEpoch))
iter := trie.NewIterator(ec.DposContext.MintCntTrie().PrefixIterator(prevEpochBytes))
for i := prevEpoch; i < currentEpoch; i++ {
// if prevEpoch is not genesis, kickout not active candidate
if !prevEpochIsGenesis && iter.Next() {
if err := ec.kickoutValidator(prevEpoch); err != nil {
return err
}
}
votes, err := ec.countVotes()
if err != nil {
return err
}
candidates := sortableAddresses{}
for candidate, cnt := range votes {
candidates = append(candidates, &sortableAddress{candidate, cnt})
}
if len(candidates) < safeSize {
return errors.New("too few candidates")
}
sort.Sort(candidates)
if len(candidates) > maxValidatorSize {
candidates = candidates[:maxValidatorSize]
}
// shuffle candidates
seed := int64(binary.LittleEndian.Uint32(crypto.Keccak512(parent.Hash().Bytes()))) + i
r := rand.New(rand.NewSource(seed))
for i := len(candidates) - 1; i > 0; i-- {
j := int(r.Int31n(int32(i + 1)))
candidates[i], candidates[j] = candidates[j], candidates[i]
}
sortedValidators := make([]common.Address, 0)
for _, candidate := range candidates {
sortedValidators = append(sortedValidators, candidate.address)
}
epochTrie, _ := types.NewEpochTrie(common.Hash{}, ec.DposContext.DB())
ec.DposContext.SetEpoch(epochTrie)
ec.DposContext.SetValidators(sortedValidators)
log.Info("Come to new epoch", "prevEpoch", i, "nextEpoch", i+1)
}
return nil
}
type sortableAddress struct {
address common.Address
weight *big.Int
}
type sortableAddresses []*sortableAddress
func (p sortableAddresses) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func (p sortableAddresses) Len() int { return len(p) }
func (p sortableAddresses) Less(i, j int) bool {
if p[i].weight.Cmp(p[j].weight) < 0 {
return false
} else if p[i].weight.Cmp(p[j].weight) > 0 {
return true
} else {
return p[i].address.String() < p[j].address.String()
}
}