-
Notifications
You must be signed in to change notification settings - Fork 211
/
protocol.go
427 lines (397 loc) · 11.2 KB
/
protocol.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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
package hare3
import (
"sort"
"sync"
"go.uber.org/zap/zapcore"
"github.com/spacemeshos/go-spacemesh/common/types"
"github.com/spacemeshos/go-spacemesh/log"
)
type grade uint8
const (
grade0 grade = iota
grade1
grade2
grade3
grade4
grade5
)
func isSubset(s, v []types.ProposalID) bool {
set := map[types.ProposalID]struct{}{}
for _, id := range v {
set[id] = struct{}{}
}
for _, id := range s {
if _, exist := set[id]; !exist {
return false
}
}
return true
}
func toHash(proposals []types.ProposalID) types.Hash32 {
return types.CalcProposalHash32Presorted(proposals, nil)
}
type messageKey struct {
IterRound
Sender types.NodeID
}
type input struct {
*Message
atxgrade grade
malicious bool
msgHash types.Hash32
}
func (i *input) MarshalLogObject(encoder zapcore.ObjectEncoder) error {
if i.Message != nil {
i.Message.MarshalLogObject(encoder)
}
encoder.AddUint8("atxgrade", uint8(i.atxgrade))
encoder.AddBool("malicious", i.malicious)
encoder.AddString("hash", i.msgHash.ShortString())
return nil
}
type output struct {
coin *bool // set based on preround messages right after preround completes in 0 iter
result []types.ProposalID // set based on notify messages at the start of next iter
terminated bool // protocol participates in one more iteration after outputing result
message *Message
}
func (o *output) MarshalLogObject(encoder zapcore.ObjectEncoder) error {
encoder.AddBool("terminated", o.terminated)
if o.coin != nil {
encoder.AddBool("coin", *o.coin)
}
if o.result != nil {
encoder.AddArray("result", zapcore.ArrayMarshalerFunc(func(encoder log.ArrayEncoder) error {
for _, id := range o.result {
encoder.AppendString(types.Hash20(id).ShortString())
}
return nil
}))
}
if o.message != nil {
encoder.AddObject("msg", o.message)
}
return nil
}
func newProtocol(threshold uint16) *protocol {
return &protocol{
validProposals: map[types.Hash32][]types.ProposalID{},
gossip: gossip{threshold: threshold, state: map[messageKey]*gossipInput{}},
}
}
type protocol struct {
mu sync.Mutex
IterRound
coinout bool
coin *types.VrfSignature // smallest vrf from preround messages. not a part of paper
initial []types.ProposalID // Si
result *types.Hash32 // set after waiting for notify messages. Case 1
locked *types.Hash32 // Li
hardLocked bool
validProposals map[types.Hash32][]types.ProposalID // Ti
validValues [grade5 + 1][]types.ProposalID // Vi
gossip gossip
}
func (p *protocol) OnInitial(proposals []types.ProposalID) {
p.mu.Lock()
defer p.mu.Unlock()
p.initial = proposals
}
func (p *protocol) OnInput(msg *input) (bool, *types.HareProof) {
p.mu.Lock()
defer p.mu.Unlock()
gossip, equivocation := p.gossip.receive(p.IterRound, msg)
if !gossip {
return false, equivocation
}
if msg.Round == preround &&
(p.coin == nil || (p.coin != nil && msg.Eligibility.Proof.Cmp(p.coin) == -1)) {
p.coin = &msg.Eligibility.Proof
}
return gossip, equivocation
}
func (p *protocol) thresholdProposals(ir IterRound) (*types.Hash32, []types.ProposalID) {
for _, ref := range p.gossip.thresholdGossipRef(ir) {
valid, exist := p.validProposals[ref]
if exist {
return &ref, valid
}
}
return nil, nil
}
func (p *protocol) commitExists(iter uint8, match types.Hash32) bool {
for _, ref := range p.gossip.thresholdGossipRef(IterRound{Iter: iter, Round: commit}) {
if ref == match {
return true
}
}
return false
}
func (p *protocol) execution(out *output, active bool) {
// 4.3 Protocol Execution
if p.Iter == 0 && p.Round >= softlock && p.Round <= wait2 {
// -1 - skipped hardlock round in iter 0
// -1 - implementation rounds starts from 0
g := grade5 - grade(p.Round-2)
p.validValues[g] = p.gossip.thresholdGossip(IterRound{Round: preround})
}
if p.Round == preround && active {
out.message = &Message{Body: Body{
IterRound: p.IterRound,
Value: Value{Proposals: p.initial},
}}
} else if p.Round == hardlock && p.Iter > 0 {
if p.result != nil {
out.terminated = true
}
ref, values := p.thresholdProposals(IterRound{Iter: p.Iter - 1, Round: notify})
if ref != nil && p.result == nil {
p.result = ref
out.result = values
if values == nil {
// receiver expects non-nil result
out.result = []types.ProposalID{}
}
}
if ref, _ := p.thresholdProposals(IterRound{Iter: p.Iter - 1, Round: commit}); ref != nil {
p.locked = ref
p.hardLocked = true
} else {
p.locked = nil
p.hardLocked = false
}
} else if p.Round == softlock && p.Iter > 0 && !p.hardLocked {
if ref, _ := p.thresholdProposals(IterRound{Iter: p.Iter - 1, Round: commit}); ref != nil {
p.locked = ref
} else {
p.locked = nil
}
} else if p.Round == propose && active {
values := p.validValues[grade4]
if p.Iter > 0 {
ref, overwrite := p.thresholdProposals(IterRound{Iter: p.Iter - 1, Round: commit})
if ref != nil {
values = overwrite
}
}
out.message = &Message{Body: Body{
IterRound: p.IterRound,
Value: Value{Proposals: values},
}}
} else if p.Round == commit {
// condition (d) is realized by ordering proposals by vrf
proposed := p.gossip.gradecast(IterRound{Iter: p.Iter, Round: propose})
for _, graded := range proposed {
// condition (a) and (b)
if graded.grade < grade1 || !isSubset(graded.values, p.validValues[grade2]) {
continue
}
p.validProposals[toHash(graded.values)] = graded.values
}
if active {
var ref *types.Hash32
if p.hardLocked && p.locked != nil {
ref = p.locked
} else {
for _, graded := range proposed {
id := toHash(graded.values)
// condition (c)
if _, exist := p.validProposals[id]; !exist {
continue
}
// condition (e)
if graded.grade != grade2 {
continue
}
// condition (f)
if !isSubset(graded.values, p.validValues[grade3]) {
continue
}
// condition (g)
if !isSubset(p.validValues[grade5], graded.values) &&
!p.commitExists(p.Iter-1, id) {
continue
}
// condition (h)
if p.locked != nil && *p.locked != id {
continue
}
ref = &id
break
}
}
if ref != nil {
out.message = &Message{Body: Body{
IterRound: p.IterRound,
Value: Value{Reference: ref},
}}
}
}
} else if p.Round == notify && active {
ref := p.result
if ref == nil {
ref, _ = p.thresholdProposals(IterRound{Iter: p.Iter, Round: commit})
}
if ref != nil {
out.message = &Message{Body: Body{
IterRound: p.IterRound,
Value: Value{Reference: ref},
}}
}
}
}
func (p *protocol) Next(active bool) output {
p.mu.Lock()
defer p.mu.Unlock()
out := output{}
p.execution(&out, active)
if p.Round >= softlock && p.coin != nil && !p.coinout {
coin := p.coin.LSB() != 0
out.coin = &coin
p.coinout = true
}
if p.Round == preround && p.Iter == 0 {
// skips hardlock unlike softlock in the paper.
// this makes no practical difference from correctness.
// but allows to simplify assignment in validValues
p.Round = softlock
} else if p.Round == notify {
p.Round = hardlock
p.Iter++
} else {
p.Round++
}
return out
}
type gossipInput struct {
*input
received IterRound
otherReceived *IterRound
}
// Protocol 1. graded-gossip. page 10.
type gossip struct {
threshold uint16
state map[messageKey]*gossipInput
}
func (g *gossip) receive(current IterRound, input *input) (bool, *types.HareProof) {
// Case 1: will be discarded earlier
other, exist := g.state[input.key()]
if exist {
if other.msgHash != input.msgHash && !other.malicious {
// Protocol 3. thresh-gossip. keep one with the maximal grade.
if input.atxgrade > other.atxgrade {
input.malicious = true
g.state[input.key()] = &gossipInput{
input: input,
received: current,
otherReceived: &other.received,
}
} else {
// Case 3
other.malicious = true
other.otherReceived = ¤t
}
return true, &types.HareProof{Messages: [2]types.HareProofMsg{
other.ToMalfeasanceProof(), input.ToMalfeasanceProof(),
}}
}
// Case 2. but also we filter duplicates from p2p layer here
return false, nil
}
// Case 4
g.state[input.key()] = &gossipInput{input: input, received: current}
return true, nil
}
type gset struct {
values []types.ProposalID
grade grade
smallest types.VrfSignature
}
// Protocol 2. gradecast. page 13.
func (g *gossip) gradecast(target IterRound) []gset {
// unlike paper we use 5-graded gossip for gradecast as well
var rst []gset
for key, value := range g.state {
if key.IterRound == target && (!value.malicious || value.otherReceived != nil) {
g := grade0
if value.atxgrade == grade5 && value.received.Delay(target) <= 1 &&
// 2 (a)
(value.otherReceived == nil || value.otherReceived.Delay(target) > 3) {
// 2 (b)
g = grade2
} else if value.atxgrade >= grade4 && value.received.Delay(target) <= 2 &&
// 3 (a)
(value.otherReceived == nil || value.otherReceived.Delay(target) > 2) {
// 3 (b)
g = grade1
}
if g > grade0 {
rst = append(rst, gset{
grade: g,
values: value.Value.Proposals,
smallest: value.Eligibility.Proof,
})
}
}
}
// it satisfies p-Weak leader election
// inconsistent order of proposals may cause participants to commit on different proposals
sort.Slice(rst, func(i, j int) bool {
return rst[i].smallest.Cmp(&rst[j].smallest) == -1
})
return rst
}
// Protocol 3. thresh-gossip. Page 15.
// output returns union of sorted proposals received
// in the given round with minimal specified grade.
func (g *gossip) thresholdGossip(filter IterRound) []types.ProposalID {
rst := thresholdGossip(g.state, g.threshold, filter,
func(total map[types.ProposalID]uint16, valid map[types.ProposalID]struct{}, inp *gossipInput) {
for _, id := range inp.Value.Proposals {
total[id] += inp.Eligibility.Count
if !inp.malicious {
valid[id] = struct{}{}
}
}
})
return types.SortProposalIDs(rst)
}
// thresholdGossipRef returns all references to proposals in the given round with minimal grade.
func (g *gossip) thresholdGossipRef(filter IterRound) []types.Hash32 {
return thresholdGossip(g.state, g.threshold, filter,
func(total map[types.Hash32]uint16, valid map[types.Hash32]struct{}, inp *gossipInput) {
total[*inp.Value.Reference] += inp.Eligibility.Count
if !inp.malicious {
valid[*inp.Value.Reference] = struct{}{}
}
})
}
func thresholdGossip[T comparable](
state map[messageKey]*gossipInput, threshold uint16, filter IterRound,
tally func(all map[T]uint16, good map[T]struct{}, inp *gossipInput),
) []T {
total := map[T]uint16{}
valid := map[T]struct{}{}
min := grade5
// pick min atx grade from non equivocating identity.
for key, value := range state {
if key.IterRound == filter && value.atxgrade < min && !value.malicious {
min = value.atxgrade
}
}
// tally votes for valid and malicious messages
for key, value := range state {
if key.IterRound == filter && value.atxgrade >= min {
tally(total, valid, value)
}
}
rst := []T{}
// valid > 0 and total >= f
// atleast one non-equivocating vote and crossed committee/2 + 1
for id := range valid {
if total[id] >= threshold {
rst = append(rst, id)
}
}
return rst
}