forked from cometbft/cometbft
-
Notifications
You must be signed in to change notification settings - Fork 0
/
validator_set_test.go
1616 lines (1454 loc) · 46.1 KB
/
validator_set_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
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package types
import (
"bytes"
"fmt"
"math"
"sort"
"strings"
"testing"
"testing/quick"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
cmtproto "github.com/cometbft/cometbft/api/cometbft/types/v1"
"github.com/cometbft/cometbft/crypto"
"github.com/cometbft/cometbft/crypto/ed25519"
cmtrand "github.com/cometbft/cometbft/internal/rand"
cmtmath "github.com/cometbft/cometbft/libs/math"
)
func TestValidatorSetBasic(t *testing.T) {
// empty or nil validator lists are allowed,
// but attempting to IncrementProposerPriority on them will panic.
vset := NewValidatorSet([]*Validator{})
assert.Panics(t, func() { vset.IncrementProposerPriority(1) })
vset = NewValidatorSet(nil)
assert.Panics(t, func() { vset.IncrementProposerPriority(1) })
assert.EqualValues(t, vset, vset.Copy())
assert.False(t, vset.HasAddress([]byte("some val")))
idx, val := vset.GetByAddress([]byte("some val"))
assert.EqualValues(t, -1, idx)
assert.Nil(t, val)
addr, val := vset.GetByIndex(-100)
assert.Nil(t, addr)
assert.Nil(t, val)
addr, val = vset.GetByIndex(0)
assert.Nil(t, addr)
assert.Nil(t, val)
addr, val = vset.GetByIndex(100)
assert.Nil(t, addr)
assert.Nil(t, val)
assert.Zero(t, vset.Size())
assert.Equal(t, int64(0), vset.TotalVotingPower())
assert.Nil(t, vset.GetProposer())
assert.Equal(t, []byte{
0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4,
0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95,
0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55,
}, vset.Hash())
// add
val = randValidator(vset.TotalVotingPower())
require.NoError(t, vset.UpdateWithChangeSet([]*Validator{val}))
assert.True(t, vset.HasAddress(val.Address))
idx, _ = vset.GetByAddress(val.Address)
assert.EqualValues(t, 0, idx)
addr, _ = vset.GetByIndex(0)
assert.Equal(t, []byte(val.Address), addr)
assert.Equal(t, 1, vset.Size())
assert.Equal(t, val.VotingPower, vset.TotalVotingPower())
assert.NotNil(t, vset.Hash())
assert.NotPanics(t, func() { vset.IncrementProposerPriority(1) })
assert.Equal(t, val.Address, vset.GetProposer().Address)
// update
val = randValidator(vset.TotalVotingPower())
require.NoError(t, vset.UpdateWithChangeSet([]*Validator{val}))
_, val = vset.GetByAddress(val.Address)
val.VotingPower += 100
proposerPriority := val.ProposerPriority
val.ProposerPriority = 0
require.NoError(t, vset.UpdateWithChangeSet([]*Validator{val}))
_, val = vset.GetByAddress(val.Address)
assert.Equal(t, proposerPriority, val.ProposerPriority)
}
func TestValidatorSetValidateBasic(t *testing.T) {
val, _ := RandValidator(false, 1)
badVal := &Validator{}
testCases := []struct {
vals ValidatorSet
err bool
msg string
}{
{
vals: ValidatorSet{},
err: true,
msg: "validator set is nil or empty",
},
{
vals: ValidatorSet{
Validators: []*Validator{},
},
err: true,
msg: "validator set is nil or empty",
},
{
vals: ValidatorSet{
Validators: []*Validator{val},
},
err: true,
msg: "proposer failed validate basic, error: nil validator",
},
{
vals: ValidatorSet{
Validators: []*Validator{badVal},
},
err: true,
msg: "invalid validator #0: validator does not have a public key",
},
{
vals: ValidatorSet{
Validators: []*Validator{val},
Proposer: val,
},
err: false,
msg: "",
},
}
for _, tc := range testCases {
err := tc.vals.ValidateBasic()
if tc.err {
if assert.Error(t, err) { //nolint:testifylint // require.Error doesn't work with the conditional here
assert.Equal(t, tc.msg, err.Error())
}
} else {
require.NoError(t, err)
}
}
}
func TestCopy(t *testing.T) {
vset := randValidatorSet(10)
vsetHash := vset.Hash()
if len(vsetHash) == 0 {
t.Fatalf("ValidatorSet had unexpected zero hash")
}
vsetCopy := vset.Copy()
vsetCopyHash := vsetCopy.Hash()
if !bytes.Equal(vsetHash, vsetCopyHash) {
t.Fatalf("ValidatorSet copy had wrong hash. Orig: %X, Copy: %X", vsetHash, vsetCopyHash)
}
}
// Test that IncrementProposerPriority requires positive times.
func TestIncrementProposerPriorityPositiveTimes(t *testing.T) {
vset := NewValidatorSet([]*Validator{
newValidator([]byte("foo"), 1000),
newValidator([]byte("bar"), 300),
newValidator([]byte("baz"), 330),
})
assert.Panics(t, func() { vset.IncrementProposerPriority(-1) })
assert.Panics(t, func() { vset.IncrementProposerPriority(0) })
vset.IncrementProposerPriority(1)
}
func BenchmarkValidatorSetCopy(b *testing.B) {
b.StopTimer()
vset := NewValidatorSet([]*Validator{})
for i := 0; i < 1000; i++ {
privKey := ed25519.GenPrivKey()
pubKey := privKey.PubKey()
val := NewValidator(pubKey, 10)
err := vset.UpdateWithChangeSet([]*Validator{val})
if err != nil {
panic("Failed to add validator")
}
}
b.StartTimer()
for i := 0; i < b.N; i++ {
vset.Copy()
}
}
//-------------------------------------------------------------------
func TestProposerSelection1(t *testing.T) {
vset := NewValidatorSet([]*Validator{
newValidator([]byte("foo"), 1000),
newValidator([]byte("bar"), 300),
newValidator([]byte("baz"), 330),
})
var proposers []string
for i := 0; i < 99; i++ {
val := vset.GetProposer()
proposers = append(proposers, string(val.Address))
vset.IncrementProposerPriority(1)
}
expected := `foo baz foo bar foo foo baz foo bar foo foo baz foo foo bar foo baz foo foo bar` +
` foo foo baz foo bar foo foo baz foo bar foo foo baz foo foo bar foo baz foo foo bar` +
` foo baz foo foo bar foo baz foo foo bar foo baz foo foo foo baz bar foo foo foo baz` +
` foo bar foo foo baz foo bar foo foo baz foo bar foo foo baz foo bar foo foo baz foo` +
` foo bar foo baz foo foo bar foo baz foo foo bar foo baz foo foo`
if expected != strings.Join(proposers, " ") {
t.Errorf("expected sequence of proposers was\n%v\nbut got \n%v", expected, strings.Join(proposers, " "))
}
}
func TestProposerSelection2(t *testing.T) {
addr0 := []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
addr1 := []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}
addr2 := []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2}
// when all voting power is same, we go in order of addresses
val0, val1, val2 := newValidator(addr0, 100), newValidator(addr1, 100), newValidator(addr2, 100)
valList := []*Validator{val0, val1, val2}
vals := NewValidatorSet(valList)
for i := 0; i < len(valList)*5; i++ {
ii := (i) % len(valList)
prop := vals.GetProposer()
if !bytes.Equal(prop.Address, valList[ii].Address) {
t.Fatalf("(%d): Expected %X. Got %X", i, valList[ii].Address, prop.Address)
}
vals.IncrementProposerPriority(1)
}
// One validator has more than the others, but not enough to propose twice in a row
*val2 = *newValidator(addr2, 400)
vals = NewValidatorSet(valList)
// vals.IncrementProposerPriority(1)
prop := vals.GetProposer()
if !bytes.Equal(prop.Address, addr2) {
t.Fatalf("Expected address with highest voting power to be first proposer. Got %X", prop.Address)
}
vals.IncrementProposerPriority(1)
prop = vals.GetProposer()
if !bytes.Equal(prop.Address, addr0) {
t.Fatalf("Expected smallest address to be validator. Got %X", prop.Address)
}
// One validator has more than the others, and enough to be proposer twice in a row
*val2 = *newValidator(addr2, 401)
vals = NewValidatorSet(valList)
prop = vals.GetProposer()
if !bytes.Equal(prop.Address, addr2) {
t.Fatalf("Expected address with highest voting power to be first proposer. Got %X", prop.Address)
}
vals.IncrementProposerPriority(1)
prop = vals.GetProposer()
if !bytes.Equal(prop.Address, addr2) {
t.Fatalf("Expected address with highest voting power to be second proposer. Got %X", prop.Address)
}
vals.IncrementProposerPriority(1)
prop = vals.GetProposer()
if !bytes.Equal(prop.Address, addr0) {
t.Fatalf("Expected smallest address to be validator. Got %X", prop.Address)
}
// each validator should be the proposer a proportional number of times
val0, val1, val2 = newValidator(addr0, 4), newValidator(addr1, 5), newValidator(addr2, 3)
valList = []*Validator{val0, val1, val2}
propCount := make([]int, 3)
vals = NewValidatorSet(valList)
N := 1
for i := 0; i < 120*N; i++ {
prop := vals.GetProposer()
ii := prop.Address[19]
propCount[ii]++
vals.IncrementProposerPriority(1)
}
if propCount[0] != 40*N {
t.Fatalf(
"Expected prop count for validator with 4/12 of voting power to be %d/%d. Got %d/%d",
40*N,
120*N,
propCount[0],
120*N,
)
}
if propCount[1] != 50*N {
t.Fatalf(
"Expected prop count for validator with 5/12 of voting power to be %d/%d. Got %d/%d",
50*N,
120*N,
propCount[1],
120*N,
)
}
if propCount[2] != 30*N {
t.Fatalf(
"Expected prop count for validator with 3/12 of voting power to be %d/%d. Got %d/%d",
30*N,
120*N,
propCount[2],
120*N,
)
}
}
func TestProposerSelection3(t *testing.T) {
vals := []*Validator{
newValidator([]byte("avalidator_address12"), 1),
newValidator([]byte("bvalidator_address12"), 1),
newValidator([]byte("cvalidator_address12"), 1),
newValidator([]byte("dvalidator_address12"), 1),
}
for i := 0; i < 4; i++ {
pk := ed25519.GenPrivKey().PubKey()
vals[i].PubKey = pk
vals[i].Address = pk.Address()
}
sort.Sort(ValidatorsByAddress(vals))
vset := NewValidatorSet(vals)
proposerOrder := make([]*Validator, 4)
for i := 0; i < 4; i++ {
proposerOrder[i] = vset.GetProposer()
vset.IncrementProposerPriority(1)
}
// i for the loop
// j for the times
// we should go in order for ever, despite some IncrementProposerPriority with times > 1
var (
i int
j int32
)
for ; i < 10000; i++ {
got := vset.GetProposer().Address
expected := proposerOrder[j%4].Address
if !bytes.Equal(got, expected) {
t.Fatalf(fmt.Sprintf("vset.Proposer (%X) does not match expected proposer (%X) for (%d, %d)", got, expected, i, j))
}
// serialize, deserialize, check proposer
b := vset.toBytes()
vset = vset.fromBytes(b)
computed := vset.GetProposer() // findGetProposer()
if i != 0 {
if !bytes.Equal(got, computed.Address) {
t.Fatalf(
fmt.Sprintf(
"vset.Proposer (%X) does not match computed proposer (%X) for (%d, %d)",
got,
computed.Address,
i,
j,
),
)
}
}
// times is usually 1
times := int32(1)
mod := (cmtrand.Int() % 5) + 1
if cmtrand.Int()%mod > 0 {
// sometimes its up to 5
times = (cmtrand.Int31() % 4) + 1
}
vset.IncrementProposerPriority(times)
j += times
}
}
func newValidator(address []byte, power int64) *Validator {
return &Validator{Address: address, VotingPower: power}
}
func randPubKey() crypto.PubKey {
pubKey := make(ed25519.PubKey, ed25519.PubKeySize)
copy(pubKey, cmtrand.Bytes(32))
return ed25519.PubKey(cmtrand.Bytes(32))
}
func randValidator(totalVotingPower int64) *Validator {
// this modulo limits the ProposerPriority/VotingPower to stay in the
// bounds of MaxTotalVotingPower minus the already existing voting power:
val := NewValidator(randPubKey(), int64(cmtrand.Uint64()%uint64(MaxTotalVotingPower-totalVotingPower)))
val.ProposerPriority = cmtrand.Int64() % (MaxTotalVotingPower - totalVotingPower)
return val
}
func randValidatorSet(numValidators int) *ValidatorSet {
validators := make([]*Validator, numValidators)
totalVotingPower := int64(0)
for i := 0; i < numValidators; i++ {
validators[i] = randValidator(totalVotingPower)
totalVotingPower += validators[i].VotingPower
}
return NewValidatorSet(validators)
}
func (vals *ValidatorSet) toBytes() []byte {
pbvs, err := vals.ToProto()
if err != nil {
panic(err)
}
bz, err := pbvs.Marshal()
if err != nil {
panic(err)
}
return bz
}
func (vals *ValidatorSet) fromBytes(b []byte) *ValidatorSet {
pbvs := new(cmtproto.ValidatorSet)
err := pbvs.Unmarshal(b)
if err != nil {
// DATA HAS BEEN CORRUPTED OR THE SPEC HAS CHANGED
panic(err)
}
vs, err := ValidatorSetFromProto(pbvs)
if err != nil {
panic(err)
}
return vs
}
//-------------------------------------------------------------------
func TestValidatorSetTotalVotingPowerPanicsOnOverflow(t *testing.T) {
// NewValidatorSet calls IncrementProposerPriority which calls TotalVotingPower()
// which should panic on overflows:
shouldPanic := func() {
NewValidatorSet([]*Validator{
{Address: []byte("a"), VotingPower: math.MaxInt64, ProposerPriority: 0},
{Address: []byte("b"), VotingPower: math.MaxInt64, ProposerPriority: 0},
{Address: []byte("c"), VotingPower: math.MaxInt64, ProposerPriority: 0},
})
}
assert.Panics(t, shouldPanic)
}
func TestAvgProposerPriority(t *testing.T) {
// Create Validator set without calling IncrementProposerPriority:
tcs := []struct {
vs ValidatorSet
want int64
}{
0: {ValidatorSet{Validators: []*Validator{{ProposerPriority: 0}, {ProposerPriority: 0}, {ProposerPriority: 0}}}, 0},
1: {
ValidatorSet{
Validators: []*Validator{{ProposerPriority: math.MaxInt64}, {ProposerPriority: 0}, {ProposerPriority: 0}},
}, math.MaxInt64 / 3,
},
2: {
ValidatorSet{
Validators: []*Validator{{ProposerPriority: math.MaxInt64}, {ProposerPriority: 0}},
}, math.MaxInt64 / 2,
},
3: {
ValidatorSet{
Validators: []*Validator{{ProposerPriority: math.MaxInt64}, {ProposerPriority: math.MaxInt64}},
}, math.MaxInt64,
},
4: {
ValidatorSet{
Validators: []*Validator{{ProposerPriority: math.MinInt64}, {ProposerPriority: math.MinInt64}},
}, math.MinInt64,
},
}
for i, tc := range tcs {
got := tc.vs.computeAvgProposerPriority()
assert.Equal(t, tc.want, got, "test case: %v", i)
}
}
func TestAveragingInIncrementProposerPriority(t *testing.T) {
// Test that the averaging works as expected inside of IncrementProposerPriority.
// Each validator comes with zero voting power which simplifies reasoning about
// the expected ProposerPriority.
tcs := []struct {
vs ValidatorSet
times int32
avg int64
}{
0: {
ValidatorSet{
Validators: []*Validator{
{Address: []byte("a"), ProposerPriority: 1},
{Address: []byte("b"), ProposerPriority: 2},
{Address: []byte("c"), ProposerPriority: 3},
},
},
1, 2,
},
1: {
ValidatorSet{
Validators: []*Validator{
{Address: []byte("a"), ProposerPriority: 10},
{Address: []byte("b"), ProposerPriority: -10},
{Address: []byte("c"), ProposerPriority: 1},
},
},
// this should average twice but the average should be 0 after the first iteration
// (voting power is 0 -> no changes)
11,
0, // 1 / 3
},
2: {
ValidatorSet{
Validators: []*Validator{
{Address: []byte("a"), ProposerPriority: 100},
{Address: []byte("b"), ProposerPriority: -10},
{Address: []byte("c"), ProposerPriority: 1},
},
},
1, 91 / 3,
},
}
for i, tc := range tcs {
// work on copy to have the old ProposerPriorities:
newVset := tc.vs.CopyIncrementProposerPriority(tc.times)
for _, val := range tc.vs.Validators {
_, updatedVal := newVset.GetByAddress(val.Address)
assert.Equal(t, updatedVal.ProposerPriority, val.ProposerPriority-tc.avg, "test case: %v", i)
}
}
}
func TestAveragingInIncrementProposerPriorityWithVotingPower(t *testing.T) {
// Other than TestAveragingInIncrementProposerPriority this is a more complete test showing
// how each ProposerPriority changes in relation to the validator's voting power respectively.
// average is zero in each round:
vp0 := int64(10)
vp1 := int64(1)
vp2 := int64(1)
total := vp0 + vp1 + vp2
avg := (vp0 + vp1 + vp2 - total) / 3
vals := ValidatorSet{Validators: []*Validator{
{Address: []byte{0}, ProposerPriority: 0, VotingPower: vp0},
{Address: []byte{1}, ProposerPriority: 0, VotingPower: vp1},
{Address: []byte{2}, ProposerPriority: 0, VotingPower: vp2},
}}
tcs := []struct {
vals *ValidatorSet
wantProposerPrioritys []int64
times int32
wantProposer *Validator
}{
0: {
vals.Copy(),
[]int64{
// Acumm+VotingPower-Avg:
0 + vp0 - total - avg, // mostest will be subtracted by total voting power (12)
0 + vp1,
0 + vp2,
},
1,
vals.Validators[0],
},
1: {
vals.Copy(),
[]int64{
(0 + vp0 - total) + vp0 - total - avg, // this will be mostest on 2nd iter, too
(0 + vp1) + vp1,
(0 + vp2) + vp2,
},
2,
vals.Validators[0],
}, // increment twice -> expect average to be subtracted twice
2: {
vals.Copy(),
[]int64{
0 + 3*(vp0-total) - avg, // still mostest
0 + 3*vp1,
0 + 3*vp2,
},
3,
vals.Validators[0],
},
3: {
vals.Copy(),
[]int64{
0 + 4*(vp0-total), // still mostest
0 + 4*vp1,
0 + 4*vp2,
},
4,
vals.Validators[0],
},
4: {
vals.Copy(),
[]int64{
0 + 4*(vp0-total) + vp0, // 4 iters was mostest
0 + 5*vp1 - total, // now this val is mostest for the 1st time (hence -12==totalVotingPower)
0 + 5*vp2,
},
5,
vals.Validators[1],
},
5: {
vals.Copy(),
[]int64{
0 + 6*vp0 - 5*total, // mostest again
0 + 6*vp1 - total, // mostest once up to here
0 + 6*vp2,
},
6,
vals.Validators[0],
},
6: {
vals.Copy(),
[]int64{
0 + 7*vp0 - 6*total, // in 7 iters this val is mostest 6 times
0 + 7*vp1 - total, // in 7 iters this val is mostest 1 time
0 + 7*vp2,
},
7,
vals.Validators[0],
},
7: {
vals.Copy(),
[]int64{
0 + 8*vp0 - 7*total, // mostest again
0 + 8*vp1 - total,
0 + 8*vp2,
},
8,
vals.Validators[0],
},
8: {
vals.Copy(),
[]int64{
0 + 9*vp0 - 7*total,
0 + 9*vp1 - total,
0 + 9*vp2 - total,
}, // mostest
9,
vals.Validators[2],
},
9: {
vals.Copy(),
[]int64{
0 + 10*vp0 - 8*total, // after 10 iters this is mostest again
0 + 10*vp1 - total, // after 6 iters this val is "mostest" once and not in between
0 + 10*vp2 - total,
}, // in between 10 iters this val is "mostest" once
10,
vals.Validators[0],
},
10: {
vals.Copy(),
[]int64{
0 + 11*vp0 - 9*total,
0 + 11*vp1 - total, // after 6 iters this val is "mostest" once and not in between
0 + 11*vp2 - total,
}, // after 10 iters this val is "mostest" once
11,
vals.Validators[0],
},
}
for i, tc := range tcs {
tc.vals.IncrementProposerPriority(tc.times)
assert.Equal(t, tc.wantProposer.Address, tc.vals.GetProposer().Address,
"test case: %v",
i)
for valIdx, val := range tc.vals.Validators {
assert.Equal(t,
tc.wantProposerPrioritys[valIdx],
val.ProposerPriority,
"test case: %v, validator: %v",
i,
valIdx)
}
}
}
func TestSafeAdd(t *testing.T) {
f := func(a, b int64) bool {
c, overflow := safeAdd(a, b)
return overflow || (!overflow && c == a+b)
}
if err := quick.Check(f, nil); err != nil {
t.Error(err)
}
}
func TestSafeAddClip(t *testing.T) {
assert.EqualValues(t, math.MaxInt64, safeAddClip(math.MaxInt64, 10))
assert.EqualValues(t, math.MaxInt64, safeAddClip(math.MaxInt64, math.MaxInt64))
assert.EqualValues(t, math.MinInt64, safeAddClip(math.MinInt64, -10))
}
func TestSafeSubClip(t *testing.T) {
assert.EqualValues(t, math.MinInt64, safeSubClip(math.MinInt64, 10))
assert.EqualValues(t, 0, safeSubClip(math.MinInt64, math.MinInt64))
assert.EqualValues(t, math.MinInt64, safeSubClip(math.MinInt64, math.MaxInt64))
assert.EqualValues(t, math.MaxInt64, safeSubClip(math.MaxInt64, -10))
}
//-------------------------------------------------------------------
func TestEmptySet(t *testing.T) {
var valList []*Validator
valSet := NewValidatorSet(valList)
assert.Panics(t, func() { valSet.IncrementProposerPriority(1) })
assert.Panics(t, func() { valSet.RescalePriorities(100) })
assert.Panics(t, func() { valSet.shiftByAvgProposerPriority() })
assert.Panics(t, func() { assert.Zero(t, computeMaxMinPriorityDiff(valSet)) })
valSet.GetProposer()
// Add to empty set
v1 := newValidator([]byte("v1"), 100)
v2 := newValidator([]byte("v2"), 100)
valList = []*Validator{v1, v2}
require.NoError(t, valSet.UpdateWithChangeSet(valList))
verifyValidatorSet(t, valSet)
// Delete all validators from set
v1 = newValidator([]byte("v1"), 0)
v2 = newValidator([]byte("v2"), 0)
delList := []*Validator{v1, v2}
require.Error(t, valSet.UpdateWithChangeSet(delList))
// Attempt delete from empty set
require.Error(t, valSet.UpdateWithChangeSet(delList))
}
func TestUpdatesForNewValidatorSet(t *testing.T) {
v1 := newValidator([]byte("v1"), 100)
v2 := newValidator([]byte("v2"), 100)
valList := []*Validator{v1, v2}
valSet := NewValidatorSet(valList)
verifyValidatorSet(t, valSet)
// Verify duplicates are caught in NewValidatorSet() and it panics
v111 := newValidator([]byte("v1"), 100)
v112 := newValidator([]byte("v1"), 123)
v113 := newValidator([]byte("v1"), 234)
valList = []*Validator{v111, v112, v113}
assert.Panics(t, func() { NewValidatorSet(valList) })
// Verify set including validator with voting power 0 cannot be created
v1 = newValidator([]byte("v1"), 0)
v2 = newValidator([]byte("v2"), 22)
v3 := newValidator([]byte("v3"), 33)
valList = []*Validator{v1, v2, v3}
assert.Panics(t, func() { NewValidatorSet(valList) })
// Verify set including validator with negative voting power cannot be created
v1 = newValidator([]byte("v1"), 10)
v2 = newValidator([]byte("v2"), -20)
v3 = newValidator([]byte("v3"), 30)
valList = []*Validator{v1, v2, v3}
assert.Panics(t, func() { NewValidatorSet(valList) })
}
type testVal struct {
name string
power int64
}
func permutation(valList []testVal) []testVal {
if len(valList) == 0 {
return nil
}
permList := make([]testVal, len(valList))
perm := cmtrand.Perm(len(valList))
for i, v := range perm {
permList[v] = valList[i]
}
return permList
}
func createNewValidatorList(testValList []testVal) []*Validator {
valList := make([]*Validator, 0, len(testValList))
for _, val := range testValList {
valList = append(valList, newValidator([]byte(val.name), val.power))
}
return valList
}
func createNewValidatorSet(testValList []testVal) *ValidatorSet {
return NewValidatorSet(createNewValidatorList(testValList))
}
func valSetTotalProposerPriority(valSet *ValidatorSet) int64 {
sum := int64(0)
for _, val := range valSet.Validators {
// mind overflow
sum = safeAddClip(sum, val.ProposerPriority)
}
return sum
}
func verifyValidatorSet(t *testing.T, valSet *ValidatorSet) {
t.Helper()
// verify that the capacity and length of validators is the same
assert.Len(t, valSet.Validators, cap(valSet.Validators))
// verify that the set's total voting power has been updated
tvp := valSet.totalVotingPower
valSet.updateTotalVotingPower()
expectedTvp := valSet.TotalVotingPower()
assert.Equal(t, expectedTvp, tvp,
"expected TVP %d. Got %d, valSet=%s", expectedTvp, tvp, valSet)
// verify that validator priorities are centered
valsCount := int64(len(valSet.Validators))
tpp := valSetTotalProposerPriority(valSet)
assert.True(t, tpp < valsCount && tpp > -valsCount,
"expected total priority in (-%d, %d). Got %d", valsCount, valsCount, tpp)
// verify that priorities are scaled
dist := computeMaxMinPriorityDiff(valSet)
assert.LessOrEqual(t, dist, PriorityWindowSizeFactor*tvp,
"expected priority distance < %d. Got %d", PriorityWindowSizeFactor*tvp, dist)
}
func toTestValList(valList []*Validator) []testVal {
testList := make([]testVal, len(valList))
for i, val := range valList {
testList[i].name = string(val.Address)
testList[i].power = val.VotingPower
}
return testList
}
func testValSet(nVals int, power int64) []testVal {
vals := make([]testVal, nVals)
for i := 0; i < nVals; i++ {
vals[i] = testVal{fmt.Sprintf("v%d", i+1), power}
}
return vals
}
type valSetErrTestCase struct {
startVals []testVal
updateVals []testVal
}
func executeValSetErrTestCase(t *testing.T, idx int, tt valSetErrTestCase) {
t.Helper()
// create a new set and apply updates, keeping copies for the checks
valSet := createNewValidatorSet(tt.startVals)
valSetCopy := valSet.Copy()
valList := createNewValidatorList(tt.updateVals)
valListCopy := validatorListCopy(valList)
err := valSet.UpdateWithChangeSet(valList)
// for errors check the validator set has not been changed
require.Error(t, err, "test %d", idx)
assert.Equal(t, valSet, valSetCopy, "test %v", idx)
// check the parameter list has not changed
assert.Equal(t, valList, valListCopy, "test %v", idx)
}
func TestValSetUpdatesDuplicateEntries(t *testing.T) {
testCases := []valSetErrTestCase{
// Duplicate entries in changes
{ // first entry is duplicated change
testValSet(2, 10),
[]testVal{{"v1", 11}, {"v1", 22}},
},
{ // second entry is duplicated change
testValSet(2, 10),
[]testVal{{"v2", 11}, {"v2", 22}},
},
{ // change duplicates are separated by a valid change
testValSet(2, 10),
[]testVal{{"v1", 11}, {"v2", 22}, {"v1", 12}},
},
{ // change duplicates are separated by a valid change
testValSet(3, 10),
[]testVal{{"v1", 11}, {"v3", 22}, {"v1", 12}},
},
// Duplicate entries in remove
{ // first entry is duplicated remove
testValSet(2, 10),
[]testVal{{"v1", 0}, {"v1", 0}},
},
{ // second entry is duplicated remove
testValSet(2, 10),
[]testVal{{"v2", 0}, {"v2", 0}},
},
{ // remove duplicates are separated by a valid remove
testValSet(2, 10),
[]testVal{{"v1", 0}, {"v2", 0}, {"v1", 0}},
},
{ // remove duplicates are separated by a valid remove
testValSet(3, 10),
[]testVal{{"v1", 0}, {"v3", 0}, {"v1", 0}},
},
{ // remove and update same val
testValSet(2, 10),
[]testVal{{"v1", 0}, {"v2", 20}, {"v1", 30}},
},
{ // duplicate entries in removes + changes
testValSet(2, 10),
[]testVal{{"v1", 0}, {"v2", 20}, {"v2", 30}, {"v1", 0}},
},
{ // duplicate entries in removes + changes
testValSet(3, 10),
[]testVal{{"v1", 0}, {"v3", 5}, {"v2", 20}, {"v2", 30}, {"v1", 0}},
},
}
for i, tt := range testCases {
executeValSetErrTestCase(t, i, tt)
}
}
func TestValSetUpdatesOverflows(t *testing.T) {
maxVP := MaxTotalVotingPower
testCases := []valSetErrTestCase{
{ // single update leading to overflow
testValSet(2, 10),
[]testVal{{"v1", math.MaxInt64}},
},
{ // single update leading to overflow
testValSet(2, 10),
[]testVal{{"v2", math.MaxInt64}},
},
{ // add validator leading to overflow
testValSet(1, maxVP),
[]testVal{{"v2", math.MaxInt64}},
},
{ // add validator leading to exceed Max
testValSet(1, maxVP-1),
[]testVal{{"v2", 5}},
},
{ // add validator leading to exceed Max
testValSet(2, maxVP/3),
[]testVal{{"v3", maxVP / 2}},
},
{ // add validator leading to exceed Max
testValSet(1, maxVP),
[]testVal{{"v2", maxVP}},
},
}
for i, tt := range testCases {
executeValSetErrTestCase(t, i, tt)
}
}
func TestValSetUpdatesOtherErrors(t *testing.T) {
testCases := []valSetErrTestCase{
{ // update with negative voting power
testValSet(2, 10),
[]testVal{{"v1", -123}},
},
{ // update with negative voting power
testValSet(2, 10),
[]testVal{{"v2", -123}},
},
{ // remove non-existing validator
testValSet(2, 10),
[]testVal{{"v3", 0}},
},
{ // delete all validators
[]testVal{{"v1", 10}, {"v2", 20}, {"v3", 30}},
[]testVal{{"v1", 0}, {"v2", 0}, {"v3", 0}},
},
}
for i, tt := range testCases {
executeValSetErrTestCase(t, i, tt)
}
}
func TestValSetUpdatesBasicTestsExecute(t *testing.T) {
valSetUpdatesBasicTests := []struct {
startVals []testVal
updateVals []testVal
expectedVals []testVal
}{
{ // no changes
testValSet(2, 10),
[]testVal{},
testValSet(2, 10),
},
{ // voting power changes
testValSet(2, 10),
[]testVal{{"v2", 22}, {"v1", 11}},
[]testVal{{"v2", 22}, {"v1", 11}},
},
{ // add new validators
[]testVal{{"v2", 20}, {"v1", 10}},
[]testVal{{"v4", 40}, {"v3", 30}},
[]testVal{{"v4", 40}, {"v3", 30}, {"v2", 20}, {"v1", 10}},
},
{ // add new validator to middle
[]testVal{{"v3", 20}, {"v1", 10}},
[]testVal{{"v2", 30}},
[]testVal{{"v2", 30}, {"v3", 20}, {"v1", 10}},