-
Notifications
You must be signed in to change notification settings - Fork 49
/
Copy pathqualification.go
375 lines (326 loc) · 9.74 KB
/
qualification.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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
package ceremony
import (
mapset "github.com/deckarep/golang-set"
"github.com/idena-network/idena-go/blockchain/attachments"
"github.com/idena-network/idena-go/blockchain/types"
"github.com/idena-network/idena-go/common"
"github.com/idena-network/idena-go/common/math"
"github.com/idena-network/idena-go/config"
"github.com/idena-network/idena-go/crypto"
"github.com/idena-network/idena-go/crypto/vrf"
"github.com/idena-network/idena-go/database"
"github.com/idena-network/idena-go/log"
statsTypes "github.com/idena-network/idena-go/stats/types"
math2 "math"
"sync"
)
type qualification struct {
config *config.Config
shortAnswers map[common.Address][]byte
longAnswers map[common.Address][]byte
epochDb *database.EpochDb
log log.Logger
hasNewAnswers bool
lock sync.RWMutex
}
func NewQualification(config *config.Config, epochDb *database.EpochDb) *qualification {
return &qualification{
config: config,
epochDb: epochDb,
log: log.New(),
shortAnswers: make(map[common.Address][]byte),
longAnswers: make(map[common.Address][]byte),
}
}
func (q *qualification) addAnswers(short bool, sender common.Address, txPayload []byte) {
var m map[common.Address][]byte
if short {
m = q.shortAnswers
} else {
m = q.longAnswers
}
q.lock.Lock()
defer q.lock.Unlock()
if _, ok := m[sender]; ok {
return
}
m[sender] = txPayload
q.hasNewAnswers = true
}
func (q *qualification) persist() {
if !q.hasNewAnswers {
return
}
q.lock.RLock()
defer q.lock.RUnlock()
var short, long []database.DbAnswer
for k, v := range q.shortAnswers {
short = append(short, database.DbAnswer{
Addr: k,
Ans: v,
})
}
for k, v := range q.longAnswers {
long = append(long, database.DbAnswer{
Addr: k,
Ans: v,
})
}
q.epochDb.WriteAnswers(short, long)
q.hasNewAnswers = false
}
func (q *qualification) restore() {
short, long := q.epochDb.ReadAnswers()
q.lock.Lock()
defer q.lock.Unlock()
for _, item := range short {
q.shortAnswers[item.Addr] = item.Ans
}
for _, item := range long {
q.longAnswers[item.Addr] = item.Ans
}
}
func (q *qualification) qualifyFlips(totalFlipsCount uint, candidates []*candidate, flipsPerCandidate [][]int) ([]FlipQualification, *reportersToReward) {
q.lock.RLock()
defer q.lock.RUnlock()
data := make([]struct {
answers []types.Answer
totalGrade int
gradesCount int
}, totalFlipsCount)
reportersToReward := newReportersToReward()
for candidateIdx := 0; candidateIdx < len(flipsPerCandidate); candidateIdx++ {
candidate := candidates[candidateIdx]
flips := flipsPerCandidate[candidateIdx]
answerBytes := q.longAnswers[candidate.Address]
attachment := attachments.ParseLongAnswerBytesAttachment(answerBytes)
// candidate didn't send long answers
if attachment == nil || len(attachment.Answers) == 0 {
continue
}
flipsCount := len(flips)
answers := types.NewAnswersFromBits(uint(flipsCount), attachment.Answers)
for j := uint(0); j < uint(flipsCount); j++ {
answer, grade := answers.Answer(j)
flipIdx := flips[j]
data[flipIdx].answers = append(data[flipIdx].answers, answer)
if grade == types.GradeReported {
reportersToReward.addReport(flipIdx, candidate.Address)
} else if grade != types.GradeNone {
data[flipIdx].totalGrade += int(grade)
data[flipIdx].gradesCount++
}
}
if flipsCount > 0 {
ignoreReports := float32(reportersToReward.getReportedFlipsCountByReporter(candidate.Address))/float32(flipsCount) >= 0.34
if ignoreReports {
reportersToReward.deleteReporter(candidate.Address)
}
}
}
result := make([]FlipQualification, totalFlipsCount)
for flipIdx := 0; flipIdx < len(data); flipIdx++ {
result[flipIdx] = q.qualifyOneFlip(data[flipIdx].answers, reportersToReward.getFlipReportsCount(flipIdx), data[flipIdx].totalGrade, data[flipIdx].gradesCount)
if result[flipIdx].grade != types.GradeReported {
reportersToReward.deleteFlip(flipIdx)
}
}
return result, reportersToReward
}
func (q *qualification) qualifyCandidate(candidate common.Address, flipQualificationMap map[int]FlipQualification,
flipsToSolve []int, shortSession bool, notApprovedFlips mapset.Set) (point float32, qualifiedFlipsCount uint32, flipAnswers map[int]statsTypes.FlipAnswerStats, noQual bool, noAnswer bool) {
q.lock.RLock()
var answerBytes []byte
if shortSession {
answerBytes = q.shortAnswers[candidate]
} else {
answerBytes = q.longAnswers[candidate]
}
q.lock.RUnlock()
// candidate didn't send answers
if answerBytes == nil {
return 0, 0, nil, false, true
}
if shortSession {
attachment := attachments.ParseShortAnswerBytesAttachment(answerBytes)
flipsCount := uint32(math.MinInt(int(common.ShortSessionFlipsCount()), len(flipsToSolve)))
// can't parse
if attachment == nil {
return 0, flipsCount, nil, false, false
}
answerBytes = attachment.Answers
} else {
attachment := attachments.ParseLongAnswerBytesAttachment(answerBytes)
flipsCount := uint32(len(flipsToSolve))
// can't parse
if attachment == nil {
return 0, flipsCount, nil, false, false
}
answerBytes = attachment.Answers
hash := q.epochDb.GetAnswerHash(candidate)
shortAttachment := attachments.ParseShortAnswerBytesAttachment(q.shortAnswers[candidate])
h, _ := vrf.HashFromProof(attachment.Proof)
if shortAttachment == nil || hash != crypto.Hash(append(shortAttachment.Answers, attachment.Salt...)) || getWordsRnd(h) != shortAttachment.Rnd {
return 0, flipsCount, nil, false, false
}
}
answers := types.NewAnswersFromBits(uint(len(flipsToSolve)), answerBytes)
availableExtraFlips := 0
if shortSession {
for i := 0; i < int(common.ShortSessionFlipsCount()) && i < len(flipsToSolve) && availableExtraFlips < int(common.ShortSessionExtraFlipsCount()); i++ {
answer, _ := answers.Answer(uint(i))
if notApprovedFlips.Contains(flipsToSolve[i]) && answer == types.None {
availableExtraFlips++
}
}
}
flipAnswers = make(map[int]statsTypes.FlipAnswerStats, len(flipsToSolve)+availableExtraFlips)
for i, flipIdx := range flipsToSolve {
qual := flipQualificationMap[flipIdx]
status := getFlipStatusForCandidate(flipIdx, i, qual.status, notApprovedFlips, answers, shortSession)
answer, grade := answers.Answer(uint(i))
//extra flip
if shortSession && i >= int(common.ShortSessionFlipsCount()) {
if availableExtraFlips > 0 && answer != types.None {
availableExtraFlips -= 1
} else {
continue
}
}
var answerPoint float32
if !shortSession || qual.grade != types.GradeReported {
switch status {
case Qualified:
if qual.answer == answer {
answerPoint = 1
}
qualifiedFlipsCount += 1
case WeaklyQualified:
switch {
case qual.answer == answer:
answerPoint = 1
qualifiedFlipsCount += 1
break
case answer == types.None:
qualifiedFlipsCount += 1
break
default:
answerPoint = 0.5
qualifiedFlipsCount += 1
}
}
point += answerPoint
}
flipAnswers[flipIdx] = statsTypes.FlipAnswerStats{
Respondent: candidate,
Answer: answer,
Point: answerPoint,
Grade: grade,
}
}
return point, qualifiedFlipsCount, flipAnswers, qualifiedFlipsCount == 0, false
}
func (q *qualification) GetWordsRnd(addr common.Address) uint64 {
q.lock.RLock()
defer q.lock.RUnlock()
attachment := attachments.ParseShortAnswerBytesAttachment(q.shortAnswers[addr])
if attachment == nil {
return 0
}
return attachment.Rnd
}
func getFlipStatusForCandidate(flipIdx int, flipsToSolveIdx int, baseStatus FlipStatus, notApprovedFlips mapset.Set,
answers *types.Answers, shortSession bool) FlipStatus {
if !shortSession || baseStatus == NotQualified || !notApprovedFlips.Contains(flipIdx) || baseStatus == QualifiedByNone {
return baseStatus
}
shortAnswer, _ := answers.Answer(uint(flipsToSolveIdx))
if shortAnswer == types.None {
return NotQualified
}
return baseStatus
}
func getAnswersCount(a []types.Answer) (left uint, right uint, none uint) {
for k := 0; k < len(a); k++ {
if a[k] == types.Left {
left++
}
if a[k] == types.Right {
right++
}
if a[k] == types.None {
none++
}
}
return left, right, none
}
func (q *qualification) qualifyOneFlip(answers []types.Answer, reportsCount int, totalGrade int, gradesCount int) FlipQualification {
left, right, none := getAnswersCount(answers)
totalAnswersCount := float32(len(answers))
reported := float32(reportsCount)/float32(len(answers)) > 0.5
if q.config.Consensus.FixSmallReportCommittee {
reported = false
switch len(answers) {
case 1, 2, 3:
reported = reportsCount >= len(answers)
case 4:
reported = reportsCount >= 3
case 5:
reported = reportsCount >= 4
default:
reported = float32(reportsCount)/float32(len(answers)) > 0.5
}
}
graded := float32(gradesCount)/float32(len(answers)) > 0.33
var grade types.Grade
switch {
case reported:
grade = types.GradeReported
break
case graded:
grade = types.Grade(math2.Round(float64(totalGrade) / float64(gradesCount)))
break
default:
grade = types.GradeD
}
if float32(left)/totalAnswersCount >= 0.75 {
return FlipQualification{
answer: types.Left,
status: Qualified,
grade: grade,
}
}
if float32(right)/totalAnswersCount >= 0.75 {
return FlipQualification{
answer: types.Right,
status: Qualified,
grade: grade,
}
}
if float32(left)/totalAnswersCount >= 0.66 {
return FlipQualification{
answer: types.Left,
status: WeaklyQualified,
grade: grade,
}
}
if float32(right)/totalAnswersCount >= 0.66 {
return FlipQualification{
answer: types.Right,
status: WeaklyQualified,
grade: grade,
}
}
if float32(none)/totalAnswersCount >= 0.66 {
return FlipQualification{
answer: types.None,
status: QualifiedByNone,
grade: grade,
}
}
return FlipQualification{
answer: types.None,
status: NotQualified,
grade: grade,
}
}