forked from onflow/flow-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dkg_test.go
834 lines (749 loc) · 26.6 KB
/
dkg_test.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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
//go:build relic
// +build relic
package crypto
import (
crand "crypto/rand"
"fmt"
mrand "math/rand"
"sync"
"testing"
"time"
log "github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
var gt *testing.T
func TestDKG(t *testing.T) {
t.Run("FeldmanVSSSimple", testFeldmanVSSSimple)
t.Run("FeldmanVSSQual", testFeldmanVSSQual)
t.Run("JointFeldman", testJointFeldman)
}
// optimal threshold (t) to allow the largest number of malicious participants (m)
// assuming the protocol requires:
//
// m<=t for unforgeability
// n-m>=t+1 for robustness
func optimalThreshold(size int) int {
return (size - 1) / 2
}
// Testing the happy path of Feldman VSS by simulating a network of n participants
func testFeldmanVSSSimple(t *testing.T) {
log.SetLevel(log.ErrorLevel)
n := 4
for threshold := MinimumThreshold; threshold < n; threshold++ {
t.Run(fmt.Sprintf("FeldmanVSS (n,t)=(%d,%d)", n, threshold), func(t *testing.T) {
dkgCommonTest(t, feldmanVSS, n, threshold, happyPath)
})
}
}
type testCase int
const (
happyPath testCase = iota
invalidShares
invalidVector
invalidComplaint
invalidComplaintAnswer
duplicatedMessages
)
type behavior int
const (
honest behavior = iota
manyInvalidShares
fewInvalidShares
invalidVectorBroadcast
invalidComplaintBroadcast
timeoutedComplaintBroadcast
invalidSharesComplainTrigger
invalidComplaintAnswerBroadcast
duplicatedSendAndBroadcast
)
// Testing Feldman VSS with the qualification system by simulating a network of n participants
func testFeldmanVSSQual(t *testing.T) {
log.SetLevel(log.ErrorLevel)
n := 4
// happy path, test multiple values of thresold
for threshold := MinimumThreshold; threshold < n; threshold++ {
t.Run(fmt.Sprintf("FeldmanVSSQual_(n,t)=(%d,%d)", n, threshold), func(t *testing.T) {
dkgCommonTest(t, feldmanVSSQual, n, threshold, happyPath)
})
}
// unhappy path, with focus on the optimal threshold value
n = 5
threshold := optimalThreshold(n)
// unhappy path, with invalid shares
t.Run(fmt.Sprintf("FeldmanVSSQual_InvalidShares_(n,t)=(%d,%d)", n, threshold), func(t *testing.T) {
dkgCommonTest(t, feldmanVSSQual, n, threshold, invalidShares)
})
// unhappy path, with invalid vector
t.Run(fmt.Sprintf("FeldmanVSSQual_InvalidVector_(n,t)=(%d,%d)", n, threshold), func(t *testing.T) {
dkgCommonTest(t, feldmanVSSQual, n, threshold, invalidVector)
})
// unhappy paths with invalid complaints and complaint answers
// are only tested within joint feldman.
}
// Testing JointFeldman by simulating a network of n participants
func testJointFeldman(t *testing.T) {
log.SetLevel(log.ErrorLevel)
n := 4
var threshold int
// happy path, test multiple values of thresold
for threshold = MinimumThreshold; threshold < n; threshold++ {
t.Run(fmt.Sprintf("JointFeldman_(n,t)=(%d,%d)", n, threshold), func(t *testing.T) {
dkgCommonTest(t, jointFeldman, n, threshold, happyPath)
})
}
// unhappy path, with focus on the optimal threshold value
n = 5
threshold = optimalThreshold(n)
// unhappy path, with invalid shares
t.Run(fmt.Sprintf("JointFeldman_InvalidShares_(n,t)=(%d,%d)", n, threshold), func(t *testing.T) {
dkgCommonTest(t, jointFeldman, n, threshold, invalidShares)
})
// unhappy path, with invalid vector
t.Run(fmt.Sprintf("JointFeldman_InvalidVector_(n,t)=(%d,%d)", n, threshold), func(t *testing.T) {
dkgCommonTest(t, jointFeldman, n, threshold, invalidVector)
})
// unhappy path, with invalid complaints
t.Run(fmt.Sprintf("JointFeldman_InvalidComplaints_(n,t)=(%d,%d)", n, threshold), func(t *testing.T) {
dkgCommonTest(t, jointFeldman, n, threshold, invalidComplaint)
})
// unhappy path, with invalid complaint answers
t.Run(fmt.Sprintf("JointFeldman_InvalidComplaintAnswers_(n,t)=(%d,%d)", n, threshold), func(t *testing.T) {
dkgCommonTest(t, jointFeldman, n, threshold, invalidComplaintAnswer)
})
// unhappy path, with duplicated messages (all types)
t.Run(fmt.Sprintf("JointFeldman_DuplicatedMessages_(n,t)=(%d,%d)", n, threshold), func(t *testing.T) {
dkgCommonTest(t, jointFeldman, n, threshold, duplicatedMessages)
})
}
// Supported Key Generation protocols
const (
feldmanVSS = iota
feldmanVSSQual
jointFeldman
)
func newDKG(dkg int, size int, threshold int, myIndex int,
processor DKGProcessor, dealerIndex int) (DKGState, error) {
switch dkg {
case feldmanVSS:
return NewFeldmanVSS(size, threshold, myIndex, processor, dealerIndex)
case feldmanVSSQual:
return NewFeldmanVSSQual(size, threshold, myIndex, processor, dealerIndex)
case jointFeldman:
return NewJointFeldman(size, threshold, myIndex, processor)
default:
return nil, fmt.Errorf("non supported protocol")
}
}
func dkgCommonTest(t *testing.T, dkg int, n int, threshold int, test testCase) {
gt = t
log.Info("DKG protocol set up")
// create the participant channels
chans := make([]chan *message, n)
lateChansTimeout1 := make([]chan *message, n)
lateChansTimeout2 := make([]chan *message, n)
for i := 0; i < n; i++ {
chans[i] = make(chan *message, 5*n)
lateChansTimeout1[i] = make(chan *message, 5*n)
lateChansTimeout2[i] = make(chan *message, 5*n)
}
// number of dealers in the protocol
var dealers int
if dkg == jointFeldman {
dealers = n
} else {
dealers = 1
}
// create n processors for all participants
processors := make([]testDKGProcessor, 0, n)
for current := 0; current < n; current++ {
list := make([]bool, dealers)
processors = append(processors, testDKGProcessor{
current: current,
chans: chans,
lateChansTimeout1: lateChansTimeout1,
lateChansTimeout2: lateChansTimeout2,
protocol: dkgType,
malicious: honest,
disqualified: list,
})
}
// Update processors depending on the test
//
// r1 and r2 is the number of malicious participants, each group with a slight diffrent behavior.
// - r1 participants of indices 0 to r1-1 behave maliciously and will get disqualified by honest participants.
// - r2 participants of indices r1 to r1+r2-1 will behave maliciously at first but will recover and won't be
// disqualified by honest participants. The r2 participants may or may not obtain correct protocol results.
var r1, r2 int
// h is the index of the first honest participant. All participant with indices greater than or equal to h are honest.
// Checking the final protocol results is done for honest participants only.
// Whether the r2 participants belong to the honest participants or not depend on the malicious behavior (detailed below).
var h int
switch test {
case happyPath:
// r1 = r2 = 0
case invalidShares:
r1 = mrand.Intn(dealers + 1) // dealers with invalid shares and will get disqualified
r2 = mrand.Intn(dealers - r1 + 1) // dealers with invalid shares but will recover
h = r1
var i int
for i = 0; i < r1; i++ {
processors[i].malicious = manyInvalidShares
}
for ; i < r1+r2; i++ {
processors[i].malicious = fewInvalidShares
}
t.Logf("%d participants will be disqualified, %d other participants will recover\n", r1, r2)
case invalidVector:
r1 = 1 + mrand.Intn(dealers) // dealers with invalid vector and will get disqualified
h = r1
// in this case r2 = 0
for i := 0; i < r1; i++ {
processors[i].malicious = invalidVectorBroadcast
}
t.Logf("%d participants will be disqualified\n", r1)
case invalidComplaint:
r1 = 1 + mrand.Intn(dealers-1) // participants with invalid complaints and will get disqualified.
// r1>= 1 to have at least one malicious dealer, and r1<leadrers-1 to leave space for the trigger dealer below.
r2 = mrand.Intn(dealers - r1) // participants with timeouted complaints: they are considered qualified by honest participants
// but their results are invalid
h = r1 + r2 // r2 shouldn't be verified for protocol correctness
for i := 0; i < r1; i++ {
processors[i].malicious = invalidComplaintBroadcast
}
for i := r1; i < r1+r2; i++ {
processors[i].malicious = timeoutedComplaintBroadcast
}
// The participant (r1+r2) will send wrong shares and cause the 0..r1+r2-1 dealers to send complaints.
// This participant doesn't risk getting disqualified as the complaints against them
// are invalid and won't count. The participant doesn't even answer the complaint.
processors[r1+r2].malicious = invalidSharesComplainTrigger
t.Logf("%d participants will be disqualified, %d other participants won't be disqualified.\n", r1, r2)
case invalidComplaintAnswer:
r1 = 1 + mrand.Intn(dealers-1) // participants with invalid complaint answers and will get disqualified.
// r1>= 1 to have at least one malicious dealer, and r1<leadrers-1 to leave space for the complaint sender.
h = r1
// the 0..r1-1 dealers will send invalid shares to n-1 to trigger complaints.
for i := 0; i < r1; i++ {
processors[i].malicious = invalidComplaintAnswerBroadcast
}
t.Logf("%d participants will be disqualified\n", r1)
case duplicatedMessages:
// r1 = r2 = 0
// participant 0 will send duplicated shares, verif vector and complaint to all participants
processors[0].malicious = duplicatedSendAndBroadcast
// participant 1 is a complaint trigger, it sents a wrong share to 0 to trigger a complaint.
// it also sends duplicated complaint answers.
processors[1].malicious = invalidSharesComplainTrigger
default:
panic("test case not supported")
}
// number of participants to test
lead := 0
var sync sync.WaitGroup
// create DKG in all participants
for current := 0; current < n; current++ {
var err error
processors[current].dkg, err = newDKG(dkg, n, threshold,
current, &processors[current], lead)
require.NoError(t, err)
}
phase := 0
if dkg == feldmanVSS { // jump to the last phase since there is only one phase for feldmanVSS
phase = 2
}
// start DKG in all participants
// start listening on the channels
seed := make([]byte, SeedMinLenDKG)
sync.Add(n)
log.Info("DKG protocol starts")
for current := 0; current < n; current++ {
processors[current].startSync.Add(1)
go dkgRunChan(&processors[current], &sync, t, phase)
}
for current := 0; current < n; current++ {
// start dkg in parallel
// ( one common PRG is used internally for all instances which causes a race
// in generating randoms and leads to non-deterministic keys. If deterministic keys
// are required, switch to sequential calls to dkg.Start() )
go func(current int) {
_, err := crand.Read(seed)
require.NoError(t, err)
err = processors[current].dkg.Start(seed)
require.Nil(t, err)
processors[current].startSync.Done() // avoids reading messages when a dkg instance hasn't started yet
}(current)
}
phase++
// sync the two timeouts and start the next phase
for ; phase <= 2; phase++ {
sync.Wait()
// post processing required for timeout edge case tests
go timeoutPostProcess(processors, t, phase)
sync.Add(n)
for current := 0; current < n; current++ {
go dkgRunChan(&processors[current], &sync, t, phase)
}
}
// synchronize the main thread to end all DKGs
sync.Wait()
// assertions and results:
// check the disqualified list for all non-disqualified participants
expected := make([]bool, dealers)
for i := 0; i < r1; i++ {
expected[i] = true
}
for i := h; i < n; i++ {
t.Logf("participant %d is not disqualified, its disqualified list is:\n", i)
t.Log(processors[i].disqualified)
assert.Equal(t, expected, processors[i].disqualified)
}
// check if DKG is successful
if (dkg == jointFeldman && (r1 > threshold || (n-r1) <= threshold)) ||
(dkg == feldmanVSSQual && r1 == 1) { // case of a single dealer
t.Logf("dkg failed, there are %d disqualified participants\n", r1)
// DKG failed, check for final errors
for i := r1; i < n; i++ {
err := processors[i].finalError
assert.Error(t, err)
assert.True(t, IsDKGFailureError(err))
}
} else {
t.Logf("dkg succeeded, there are %d disqualified participants\n", r1)
// DKG has succeeded, check for final errors
for i := h; i < n; i++ {
assert.NoError(t, processors[i].finalError)
}
// DKG has succeeded, check the final keys
for i := h; i < n; i++ {
assert.True(t, processors[h].pk.Equals(processors[i].pk),
"2 group public keys are mismatching")
}
}
}
// time after which a silent channel causes switching to the next dkg phase
const phaseSwitchTimeout = 200 * time.Millisecond
// This is a testing function
// It simulates processing incoming messages by a participant
// it assumes proc.dkg is already running
func dkgRunChan(proc *testDKGProcessor,
sync *sync.WaitGroup, t *testing.T, phase int) {
for {
select {
// if a message is received, handle it
case newMsg := <-proc.chans[proc.current]:
proc.startSync.Wait() // avoids reading a message when the receiving dkg instance
// hasn't started yet.
if newMsg.channel == private {
err := proc.dkg.HandlePrivateMsg(newMsg.orig, newMsg.data)
require.Nil(t, err)
} else {
err := proc.dkg.HandleBroadcastMsg(newMsg.orig, newMsg.data)
require.Nil(t, err)
}
// if no message is received by the channel, call the DKG timeout
case <-time.After(phaseSwitchTimeout):
proc.startSync.Wait() // avoids racing when starting isn't over yet
switch phase {
case 0:
log.Infof("%d shares phase ended\n", proc.current)
err := proc.dkg.NextTimeout()
require.Nil(t, err)
case 1:
log.Infof("%d complaints phase ended \n", proc.current)
err := proc.dkg.NextTimeout()
require.Nil(t, err)
case 2:
log.Infof("%d dkg ended \n", proc.current)
_, pk, _, err := proc.dkg.End()
proc.finalError = err
proc.pk = pk
}
sync.Done()
return
}
}
}
// post processing required for some edge case tests
func timeoutPostProcess(processors []testDKGProcessor, t *testing.T, phase int) {
switch phase {
case 1:
for i := 0; i < len(processors); i++ {
go func(i int) {
for len(processors[0].lateChansTimeout1[i]) != 0 {
// to test timeouted messages, late messages are copied to the main channels
msg := <-processors[0].lateChansTimeout1[i]
processors[0].chans[i] <- msg
}
}(i)
}
case 2:
for i := 0; i < len(processors); i++ {
go func(i int) {
for len(processors[0].lateChansTimeout2[i]) != 0 {
// to test timeouted messages, late messages are copied to the main channels
msg := <-processors[0].lateChansTimeout2[i]
processors[0].chans[i] <- msg
}
}(i)
}
}
}
// implements DKGProcessor interface
type testDKGProcessor struct {
// instnce of DKG
dkg DKGState
// index of the current participant in the protocol
current int
// group public key, output of DKG
pk PublicKey
// final disqualified list
disqualified []bool
// final output error of the DKG
finalError error
// type of malicious behavior
malicious behavior
// start DKG syncer
startSync sync.WaitGroup
// main message channels
chans []chan *message
// extra channels for late messges with regards to the first timeout, and second timeout
lateChansTimeout1 []chan *message
lateChansTimeout2 []chan *message
// type of the protocol
protocol int
// only used when testing the threshold signature stateful api
ts *blsThresholdSignatureParticipant
keys *statelessKeys
}
const (
dkgType int = iota
tsType
)
const (
broadcast int = iota
private
)
type message struct {
orig int
protocol int
channel int
data []byte
}
func (proc *testDKGProcessor) Disqualify(participant int, logInfo string) {
gt.Logf("%d disqualifies %d, %s\n", proc.current, participant, logInfo)
proc.disqualified[participant] = true
}
func (proc *testDKGProcessor) FlagMisbehavior(participant int, logInfo string) {
gt.Logf("%d flags a misbehavior from %d: %s", proc.current, participant, logInfo)
}
// This is a testing function
// it simulates sending a message from one participant to another
func (proc *testDKGProcessor) PrivateSend(dest int, data []byte) {
go func() {
log.Infof("%d sending to %d", proc.current, dest)
if proc.malicious == fewInvalidShares || proc.malicious == manyInvalidShares ||
proc.malicious == invalidSharesComplainTrigger || proc.malicious == invalidComplaintAnswerBroadcast ||
proc.malicious == duplicatedSendAndBroadcast {
proc.invalidShareSend(dest, data)
return
}
proc.honestSend(dest, data)
}()
}
// This is a testing function
// it simulates sending a honest message from one participant to another
func (proc *testDKGProcessor) honestSend(dest int, data []byte) {
gt.Logf("%d honestly sending to %d:\n%x\n", proc.current, dest, data)
newMsg := &message{proc.current, proc.protocol, private, data}
proc.chans[dest] <- newMsg
}
// This is a testing function
// it simulates sending a malicious message from one participant to another
// This function simulates the behavior of a malicious participant.
func (proc *testDKGProcessor) invalidShareSend(dest int, data []byte) {
// check the behavior
var recipients int // number of recipients to send invalid shares to
switch proc.malicious {
case manyInvalidShares:
recipients = proc.dkg.Threshold() + 1 // t < recipients <= n
case fewInvalidShares:
recipients = proc.dkg.Threshold() // 0 <= recipients <= t
case invalidSharesComplainTrigger:
recipients = proc.current // equal to r1+r2, which causes all r1+r2 to complain
case invalidComplaintAnswerBroadcast:
recipients = 0 // treat this case separately as the complaint trigger is the participant n-1
case duplicatedSendAndBroadcast:
proc.honestSend(dest, data)
proc.honestSend(dest, data)
return
default:
panic("invalid share send not supported")
}
// copy of data
newData := make([]byte, len(data))
copy(newData, data)
newMsg := &message{proc.current, proc.protocol, private, newData}
originalMsg := &message{proc.current, proc.protocol, private, data}
// check destination
if (dest < recipients) || (proc.current < recipients && dest < recipients+1) ||
(proc.malicious == invalidComplaintAnswerBroadcast && dest == proc.dkg.Size()-1) {
// choose a random reason for an invalid share
coin := mrand.Intn(7)
gt.Logf("%d maliciously sending to %d, coin is %d\n", proc.current, dest, coin)
switch coin {
case 0:
// value doesn't match the verification vector
newMsg.data[8]++
proc.chans[dest] <- newMsg
case 1:
// empty message
newMsg.data = newMsg.data[:0]
proc.chans[dest] <- newMsg
case 2:
// valid message length but invalid share length
newMsg.data = newMsg.data[:1]
proc.chans[dest] <- newMsg
case 3:
// invalid value
for i := 0; i < len(newMsg.data); i++ {
newMsg.data[i] = 0xFF
}
proc.chans[dest] <- newMsg
case 4:
// do not send the share at all
return
case 5:
// wrong header: will cause a complaint
newMsg.data[0] = byte(feldmanVSSVerifVec)
proc.chans[dest] <- newMsg
case 6:
// message will be sent after the shares timeout and will be considered late
// by the receiver. All late messages go into a separate channel and will be sent to
// the main channel after the shares timeout.
proc.lateChansTimeout1[dest] <- newMsg
return
}
} else {
gt.Logf("turns out to be a honest send\n%x\n", data)
}
// honest send case: this is the only message sent
// malicious send case: this is a second correct send, to test the second message gets ignored
// by the receiver (sender has been tagged malicious after the first send)
proc.chans[dest] <- originalMsg
}
// This is a testing function
// it simulates broadcasting a message from one participant to all participants
func (proc *testDKGProcessor) Broadcast(data []byte) {
go func() {
log.Infof("%d Broadcasting:", proc.current)
if data[0] == byte(feldmanVSSVerifVec) && proc.malicious == invalidVectorBroadcast {
proc.invalidVectorBroadcast(data)
} else if data[0] == byte(feldmanVSSComplaint) &&
(proc.malicious == invalidComplaintBroadcast || proc.malicious == timeoutedComplaintBroadcast) {
proc.invalidComplaintBroadcast(data)
} else if data[0] == byte(feldmanVSSComplaintAnswer) && proc.malicious == invalidComplaintAnswerBroadcast {
proc.invalidComplaintAnswerBroadcast(data)
} else if proc.malicious == duplicatedSendAndBroadcast ||
(data[0] == byte(feldmanVSSComplaintAnswer) && proc.malicious == invalidSharesComplainTrigger) {
// the complaint trigger also sends duplicated complaint answers
proc.honestBroadcast(data)
proc.honestBroadcast(data)
} else {
proc.honestBroadcast(data)
}
}()
}
func (proc *testDKGProcessor) honestBroadcast(data []byte) {
gt.Logf("%d honestly broadcasting:\n%x\n", proc.current, data)
newMsg := &message{proc.current, proc.protocol, broadcast, data}
for i := 0; i < len(proc.chans); i++ {
if i != proc.current {
proc.chans[i] <- newMsg
}
}
}
func (proc *testDKGProcessor) invalidVectorBroadcast(data []byte) {
newMsg := &message{proc.current, proc.protocol, broadcast, data}
// choose a random reason of an invalid vector
coin := mrand.Intn(5)
gt.Logf("%d malicious vector broadcast, coin is %d\n", proc.current, coin)
switch coin {
case 0:
// invalid point serialization
newMsg.data[1] = 0xFF
case 1:
// invalid length
newMsg.data = newMsg.data[:5]
case 2:
// do not send the vector at all
return
case 3:
// wrong header
newMsg.data[0] = byte(feldmanVSSShare)
case 4:
// send the vector after the first timeout, equivalent to not sending at all
// as the vector should be ignored.
for i := 0; i < proc.dkg.Size(); i++ {
if i != proc.current {
proc.lateChansTimeout1[i] <- newMsg
}
}
return
}
gt.Logf("%x\n", newMsg.data)
for i := 0; i < proc.dkg.Size(); i++ {
if i != proc.current {
proc.chans[i] <- newMsg
}
}
}
func (proc *testDKGProcessor) invalidComplaintBroadcast(data []byte) {
newMsg := &message{proc.current, proc.protocol, broadcast, data}
if proc.malicious == invalidComplaintBroadcast {
// choose a random reason for an invalid complaint
coin := mrand.Intn(2)
gt.Logf("%d malicious complaint broadcast, coin is %d\n", proc.current, coin)
switch coin {
case 0:
// invalid complainee
newMsg.data[1] = byte(proc.dkg.Size() + 1)
case 1:
// invalid length
newMsg.data = make([]byte, complaintSize+5)
copy(newMsg.data, data)
}
gt.Logf("%x\n", newMsg.data)
for i := 0; i < len(proc.chans); i++ {
if i != proc.current {
proc.chans[i] <- newMsg
}
}
} else if proc.malicious == timeoutedComplaintBroadcast {
gt.Logf("%d timeouted complaint broadcast\n", proc.current)
// send the complaint after the second timeout, equivalent to not sending at all
// as the complaint should be ignored.
for i := 0; i < len(proc.chans); i++ {
if i != proc.current {
proc.lateChansTimeout2[i] <- newMsg
}
}
return
}
}
func (proc *testDKGProcessor) invalidComplaintAnswerBroadcast(data []byte) {
newMsg := &message{proc.current, proc.protocol, broadcast, data}
// choose a random reason for an invalid complaint
coin := mrand.Intn(3)
gt.Logf("%d malicious complaint answer broadcast, coin is %d\n", proc.current, coin)
switch coin {
case 0:
// invalid complainee
newMsg.data[1] = byte(proc.dkg.Size() + 1)
case 1:
// invalid length
newMsg.data = make([]byte, complaintAnswerSize+5)
copy(newMsg.data, data)
case 2:
// no answer at all
return
}
//gt.Logf("%x\n", newMsg.data)
for i := 0; i < len(proc.chans); i++ {
if i != proc.current {
proc.chans[i] <- newMsg
}
}
}
// implements a dummy DKGProcessor
type dummyTestDKGProcessor struct {
}
func (proc dummyTestDKGProcessor) PrivateSend(int, []byte) {}
func (proc dummyTestDKGProcessor) Broadcast([]byte) {}
func (proc dummyTestDKGProcessor) Disqualify(int, string) {}
func (proc dummyTestDKGProcessor) FlagMisbehavior(int, string) {}
func TestDKGErrorTypes(t *testing.T) {
t.Run("dkgFailureError sanity", func(t *testing.T) {
failureError := dkgFailureErrorf("some error")
invInpError := invalidInputsErrorf("")
otherError := fmt.Errorf("some error")
assert.True(t, IsDKGFailureError(failureError))
assert.False(t, IsDKGFailureError(otherError))
assert.False(t, IsDKGFailureError(invInpError))
assert.False(t, IsDKGFailureError(nil))
assert.False(t, IsInvalidInputsError(failureError))
})
t.Run("dkgInvalidStateTransitionError sanity", func(t *testing.T) {
failureError := dkgInvalidStateTransitionErrorf("some error")
invInpError := invalidInputsErrorf("")
otherError := fmt.Errorf("some error")
assert.True(t, IsDKGInvalidStateTransitionError(failureError))
assert.False(t, IsInvalidInputsError(failureError))
assert.False(t, IsDKGInvalidStateTransitionError(invInpError))
assert.False(t, IsDKGInvalidStateTransitionError(otherError))
assert.False(t, IsDKGInvalidStateTransitionError(nil))
})
}
func TestDKGTransitionErrors(t *testing.T) {
n := 5
threshold := 3
myIndex := 0
dealer := 1
seed := make([]byte, SeedMinLenDKG)
t.Run("feldman VSS", func(t *testing.T) {
state, err := NewFeldmanVSS(n, threshold, myIndex, dummyTestDKGProcessor{}, dealer)
require.NoError(t, err)
// calls before start
err = state.ForceDisqualify(1)
assert.True(t, IsDKGInvalidStateTransitionError(err))
err = state.HandlePrivateMsg(1, []byte{})
assert.True(t, IsDKGInvalidStateTransitionError(err))
err = state.HandleBroadcastMsg(1, []byte{})
assert.True(t, IsDKGInvalidStateTransitionError(err))
_, _, _, err = state.End()
assert.True(t, IsDKGInvalidStateTransitionError(err))
})
t.Run("Feldman VSS Qualif and joint-Feldman ", func(t *testing.T) {
stateFVSSQ, err := NewFeldmanVSSQual(n, threshold, myIndex, dummyTestDKGProcessor{}, dealer)
require.NoError(t, err)
stateJF, err := NewJointFeldman(n, threshold, myIndex, dummyTestDKGProcessor{})
require.NoError(t, err)
for _, state := range []DKGState{stateFVSSQ, stateJF} {
// calls before start
err = state.ForceDisqualify(1)
assert.True(t, IsDKGInvalidStateTransitionError(err))
err = state.HandlePrivateMsg(1, []byte{})
assert.True(t, IsDKGInvalidStateTransitionError(err))
err = state.HandleBroadcastMsg(1, []byte{})
assert.True(t, IsDKGInvalidStateTransitionError(err))
_, _, _, err = state.End()
assert.True(t, IsDKGInvalidStateTransitionError(err))
err = state.NextTimeout()
assert.True(t, IsDKGInvalidStateTransitionError(err))
// after start
err = state.Start(seed)
require.NoError(t, err)
_, _, _, err = state.End()
assert.True(t, IsDKGInvalidStateTransitionError(err))
// after first timeout
err = state.NextTimeout()
require.NoError(t, err)
err = state.Start(seed)
assert.True(t, IsDKGInvalidStateTransitionError(err))
_, _, _, err = state.End()
assert.True(t, IsDKGInvalidStateTransitionError(err))
// after second timeout
err = state.NextTimeout()
require.NoError(t, err)
err = state.Start(seed)
assert.True(t, IsDKGInvalidStateTransitionError(err))
err = state.NextTimeout()
assert.True(t, IsDKGInvalidStateTransitionError(err))
// after end
_, _, _, err = state.End()
require.True(t, IsDKGFailureError(err))
err = state.NextTimeout()
assert.True(t, IsDKGInvalidStateTransitionError(err))
}
})
}