-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathreplication_test.go
More file actions
1738 lines (1446 loc) · 55.1 KB
/
replication_test.go
File metadata and controls
1738 lines (1446 loc) · 55.1 KB
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
// Copyright (C) 2019-2025, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package simplex_test
import (
"bytes"
"context"
"fmt"
"strings"
"sync"
"testing"
"time"
"github.com/ava-labs/simplex"
"github.com/stretchr/testify/require"
"go.uber.org/zap/zapcore"
"github.com/ava-labs/simplex/record"
"github.com/ava-labs/simplex/testutil"
. "github.com/ava-labs/simplex/testutil"
)
// TestReplication tests the replication process of a node that
// is behind the rest of the network by less than maxRoundWindow.
func TestBasicReplication(t *testing.T) {
nodes := []simplex.NodeID{{1}, {2}, {3}, []byte("lagging")}
for i := range 3 * simplex.DefaultMaxRoundWindow {
testName := fmt.Sprintf("Basic replication_of_%d_blocks", i)
// lagging node cannot be the leader after node disconnects
isLaggingNodeLeader := bytes.Equal(simplex.LeaderForRound(nodes, uint64(i)), nodes[3])
if isLaggingNodeLeader {
continue
}
t.Run(testName, func(t *testing.T) {
t.Parallel()
testReplication(t, uint64(i), nodes)
})
}
}
func testReplication(t *testing.T, startSeq uint64, nodes []simplex.NodeID) {
net := NewControlledNetwork(t, nodes)
// initiate a network with 4 nodes. one node is behind by startSeq blocks
storageData := createBlocks(t, nodes, startSeq)
testEpochConfig := &TestNodeConfig{
InitialStorage: storageData,
ReplicationEnabled: true,
}
normalNode1 := NewControlledSimplexNode(t, nodes[0], net, testEpochConfig)
normalNode2 := NewControlledSimplexNode(t, nodes[1], net, testEpochConfig)
normalNode3 := NewControlledSimplexNode(t, nodes[2], net, testEpochConfig)
laggingNode := NewControlledSimplexNode(t, nodes[3], net, &TestNodeConfig{
ReplicationEnabled: true,
})
require.Equal(t, startSeq, normalNode1.Storage.NumBlocks())
require.Equal(t, startSeq, normalNode2.Storage.NumBlocks())
require.Equal(t, startSeq, normalNode3.Storage.NumBlocks())
require.Equal(t, uint64(0), laggingNode.Storage.NumBlocks())
net.StartInstances()
defer net.StopInstances()
net.TriggerLeaderBlockBuilder(startSeq)
// all blocks except the lagging node start at round startSeq, seq startSeq.
// lagging node starts at round 0, seq 0.
// this asserts that the lagging node catches up to the latest round
for _, n := range net.Instances {
n.Storage.WaitForBlockCommit(startSeq)
}
}
// TestReplicationAdversarialNode tests the replication process of a node that
// has been sent a different block by one node, however the rest of the network
// notarizes a different block for the same round
func TestReplicationAdversarialNode(t *testing.T) {
nodes := []simplex.NodeID{{1}, {2}, {3}, []byte("lagging")}
quorum := simplex.Quorum(len(nodes))
net := NewControlledNetwork(t, nodes)
testEpochConfig := &TestNodeConfig{
ReplicationEnabled: true,
}
// doubleBlockProposalNode will propose two blocks for the same round
doubleBlockProposalNode := NewControlledSimplexNode(t, nodes[0], net, testEpochConfig)
normalNode2 := NewControlledSimplexNode(t, nodes[1], net, testEpochConfig)
normalNode3 := NewControlledSimplexNode(t, nodes[2], net, testEpochConfig)
laggingNode := NewControlledSimplexNode(t, nodes[3], net, &TestNodeConfig{
ReplicationEnabled: true,
})
require.Equal(t, uint64(0), doubleBlockProposalNode.Storage.NumBlocks())
require.Equal(t, uint64(0), normalNode2.Storage.NumBlocks())
require.Equal(t, uint64(0), normalNode3.Storage.NumBlocks())
require.Equal(t, uint64(0), laggingNode.Storage.NumBlocks())
net.StartInstances()
doubleBlock := NewTestBlock(doubleBlockProposalNode.E.Metadata(), emptyBlacklist)
doubleBlockVote, err := NewTestVote(doubleBlock, doubleBlockProposalNode.E.ID)
require.NoError(t, err)
msg := &simplex.Message{
BlockMessage: &simplex.BlockMessage{
Block: doubleBlock,
Vote: *doubleBlockVote,
},
}
laggingNode.E.HandleMessage(msg, doubleBlockProposalNode.E.ID)
net.Disconnect(laggingNode.E.ID)
blocks := []simplex.VerifiedBlock{}
for i := uint64(0); i < 2; i++ {
net.TriggerLeaderBlockBuilder(i)
for j, n := range net.Instances[:3] {
committed := n.Storage.WaitForBlockCommit(i)
if j == 0 {
blocks = append(blocks, committed)
}
}
}
// lagging node should not have committed the block
require.Equal(t, uint64(0), laggingNode.Storage.NumBlocks())
require.Equal(t, uint64(0), laggingNode.E.Metadata().Round)
net.Connect(laggingNode.E.ID)
finalization, _ := NewFinalizationRecord(t, laggingNode.E.Logger, laggingNode.E.SignatureAggregator, blocks[1], nodes[:quorum])
finalizationMsg := &simplex.Message{
Finalization: &finalization,
}
laggingNode.E.HandleMessage(finalizationMsg, doubleBlockProposalNode.E.ID)
for i := range 2 {
lagBlock := laggingNode.Storage.WaitForBlockCommit(uint64(i))
require.Equal(t, blocks[i], lagBlock)
}
}
// TestRebroadcastingWithReplication verifies that after network recovery,
// a lagging node and the rest of the network correctly propagate missing
// finalizations and index all blocks.
func TestRebroadcastingWithReplication(t *testing.T) {
nodes := []simplex.NodeID{{1}, {2}, {3}, {4}}
net := NewControlledNetwork(t, nodes)
newNodeConfig := func(from simplex.NodeID) *TestNodeConfig {
comm := NewTestComm(from, net.BasicInMemoryNetwork, AllowAllMessages)
return &TestNodeConfig{
Comm: comm,
ReplicationEnabled: true,
}
}
NewControlledSimplexNode(t, nodes[0], net, newNodeConfig(nodes[0]))
NewControlledSimplexNode(t, nodes[1], net, newNodeConfig(nodes[1]))
NewControlledSimplexNode(t, nodes[2], net, newNodeConfig(nodes[2]))
// we do not expect the lagging node to build any blocks
laggingNode := NewControlledSimplexNode(t, nodes[3], net, newNodeConfig(nodes[3]))
for _, n := range net.Instances {
require.Equal(t, uint64(0), n.Storage.NumBlocks())
}
net.StartInstances()
net.Disconnect(laggingNode.E.ID)
numNotarizations := uint64(9)
missedSeqs := uint64(0)
// finalization for the first block
net.TriggerLeaderBlockBuilder(0)
for _, n := range net.Instances {
if n.E.ID.Equals(laggingNode.E.ID) {
continue
}
n.Storage.WaitForBlockCommit(0)
}
net.SetAllNodesMessageFilter(denyFinalizationMessages)
// normal nodes continue to make progress
for i := uint64(1); i < numNotarizations; i++ {
emptyRound := bytes.Equal(simplex.LeaderForRound(nodes, i), laggingNode.E.ID)
if emptyRound {
net.AdvanceWithoutLeader(i, laggingNode.E.ID)
missedSeqs++
} else {
net.TriggerLeaderBlockBuilder(i)
for _, n := range net.Instances {
if n.E.ID.Equals(laggingNode.E.ID) {
continue
}
n.WAL.AssertNotarization(i)
}
}
}
for _, n := range net.Instances {
if n.E.ID.Equals(laggingNode.E.ID) {
require.Equal(t, uint64(0), n.Storage.NumBlocks())
require.Equal(t, uint64(0), n.E.Metadata().Round)
continue
}
// assert metadata
require.Equal(t, numNotarizations, n.E.Metadata().Round)
require.Equal(t, uint64(1), n.E.Storage.NumBlocks())
}
// the lagging node has been asleep, it should be notified blocks are available
laggingNode.BlockShouldBeBuilt()
net.SetAllNodesMessageFilter(AllowAllMessages)
net.Connect(laggingNode.E.ID)
net.TriggerLeaderBlockBuilder(numNotarizations)
timeout := time.NewTimer(30 * time.Second)
expectedSeq := numNotarizations - missedSeqs
for i := uint64(0); i <= expectedSeq; i++ {
for _, n := range net.Instances {
for {
committed := n.Storage.NumBlocks()
if committed > i {
break
}
// if we haven't indexed, advance the time to trigger rebroadcast/replication timeouts
select {
case <-time.After(time.Millisecond * 10):
for _, n := range net.Instances {
n.AdvanceTime(2 * simplex.DefaultMaxProposalWaitTime)
}
continue
case <-timeout.C:
require.Fail(t, "timed out waiting for event")
}
}
}
}
for _, n := range net.Instances {
require.Equal(t, expectedSeq+1, n.Storage.NumBlocks())
}
}
// TestReplicationEmptyNotarizations ensures a lagging node will properly replicate
// many empty notarizations in a row.
// This test sometimes takes > 30 sec
func TestReplicationEmptyNotarizations(t *testing.T) {
nodes := []simplex.NodeID{{1}, {2}, {3}, {4}, {5}, {6}}
for endRound := uint64(2); endRound <= 2*simplex.DefaultMaxRoundWindow; endRound++ {
isLaggingNodeLeader := bytes.Equal(simplex.LeaderForRound(nodes, endRound), nodes[5])
if isLaggingNodeLeader {
continue
}
testName := fmt.Sprintf("Empty_notarizations_end_round%d", endRound)
t.Run(testName, func(t *testing.T) {
t.Parallel()
testReplicationEmptyNotarizations(t, nodes, endRound)
})
}
}
func testReplicationEmptyNotarizations(t *testing.T, nodes []simplex.NodeID, endRound uint64) {
net := NewControlledNetwork(t, nodes)
newNodeConfig := func(from simplex.NodeID) *TestNodeConfig {
comm := NewTestComm(from, net.BasicInMemoryNetwork, AllowAllMessages)
return &TestNodeConfig{
Comm: comm,
ReplicationEnabled: true,
}
}
NewControlledSimplexNode(t, nodes[0], net, newNodeConfig(nodes[0]))
NewControlledSimplexNode(t, nodes[1], net, newNodeConfig(nodes[1]))
NewControlledSimplexNode(t, nodes[2], net, newNodeConfig(nodes[2]))
NewControlledSimplexNode(t, nodes[3], net, newNodeConfig(nodes[3]))
NewControlledSimplexNode(t, nodes[4], net, newNodeConfig(nodes[4]))
laggingNode := NewControlledSimplexNode(t, nodes[5], net, newNodeConfig(nodes[5]))
net.StartInstances()
net.Disconnect(laggingNode.E.ID)
net.TriggerLeaderBlockBuilder(0)
for _, n := range net.Instances {
if n.E.ID.Equals(laggingNode.E.ID) {
continue
}
n.Storage.WaitForBlockCommit(0)
}
net.SetAllNodesMessageFilter(onlyAllowEmptyRoundMessages)
// normal nodes continue to make progress
for i := uint64(1); i < endRound; i++ {
leader := simplex.LeaderForRound(nodes, i)
if !leader.Equals(laggingNode.E.ID) {
net.TriggerLeaderBlockBuilder(i)
}
net.AdvanceWithoutLeader(i, laggingNode.E.ID)
}
for _, n := range net.Instances {
if n.E.ID.Equals(laggingNode.E.ID) {
require.Equal(t, uint64(0), n.Storage.NumBlocks())
require.Equal(t, uint64(0), n.E.Metadata().Round)
continue
}
// assert metadata
require.Equal(t, uint64(endRound), n.E.Metadata().Round)
require.Equal(t, uint64(1), n.E.Metadata().Seq)
require.Equal(t, uint64(1), n.E.Storage.NumBlocks())
}
net.SetAllNodesMessageFilter(AllowAllMessages)
net.Connect(laggingNode.E.ID)
net.TriggerLeaderBlockBuilder(endRound)
for _, n := range net.Instances {
if n.E.ID.Equals(laggingNode.E.ID) {
// maybe lagging node has requested finalizations to a node without it, we may need to resend the request
for {
if n.Storage.NumBlocks() == 2 {
break
}
time.Sleep(10 * time.Millisecond)
n.AdvanceTime(2 * simplex.DefaultMaxProposalWaitTime)
}
continue
}
n.Storage.WaitForBlockCommit(1)
}
require.Equal(t, uint64(2), laggingNode.Storage.NumBlocks())
require.Equal(t, uint64(endRound+1), laggingNode.E.Metadata().Round)
require.Equal(t, uint64(2), laggingNode.E.Metadata().Seq)
}
// TestReplicationStartsBeforeCurrentRound tests the replication process of a node that
// starts replicating in the middle of the current round.
func TestReplicationStartsBeforeCurrentRound(t *testing.T) {
nodes := []simplex.NodeID{{1}, {2}, {3}, []byte("lagging")}
quorum := simplex.Quorum(len(nodes))
net := NewControlledNetwork(t, nodes)
startSeq := uint64(simplex.DefaultMaxRoundWindow + 3)
storageData := createBlocks(t, nodes, startSeq)
testEpochConfig := &TestNodeConfig{
InitialStorage: storageData,
ReplicationEnabled: true,
}
normalNode1 := NewControlledSimplexNode(t, nodes[0], net, testEpochConfig)
normalNode2 := NewControlledSimplexNode(t, nodes[1], net, testEpochConfig)
normalNode3 := NewControlledSimplexNode(t, nodes[2], net, testEpochConfig)
laggingNode := NewControlledSimplexNode(t, nodes[3], net, &TestNodeConfig{
ReplicationEnabled: true,
})
firstBlock := storageData[0].VerifiedBlock
fBytes, err := firstBlock.Bytes()
require.NoError(t, err)
record := simplex.BlockRecord(firstBlock.BlockHeader(), fBytes)
laggingNode.WAL.Append(record)
firstNotarizationRecord, err := NewNotarizationRecord(laggingNode.E.Logger, laggingNode.E.SignatureAggregator, firstBlock, nodes[0:quorum])
require.NoError(t, err)
laggingNode.WAL.Append(firstNotarizationRecord)
secondBlock := storageData[1].VerifiedBlock
sBytes, err := secondBlock.Bytes()
require.NoError(t, err)
record = simplex.BlockRecord(secondBlock.BlockHeader(), sBytes)
laggingNode.WAL.Append(record)
secondNotarizationRecord, err := NewNotarizationRecord(laggingNode.E.Logger, laggingNode.E.SignatureAggregator, secondBlock, nodes[0:quorum])
require.NoError(t, err)
laggingNode.WAL.Append(secondNotarizationRecord)
require.Equal(t, startSeq, normalNode1.Storage.NumBlocks())
require.Equal(t, startSeq, normalNode2.Storage.NumBlocks())
require.Equal(t, startSeq, normalNode3.Storage.NumBlocks())
require.Equal(t, uint64(0), laggingNode.Storage.NumBlocks())
net.StartInstances()
laggingNodeMd := laggingNode.E.Metadata()
require.Equal(t, uint64(2), laggingNodeMd.Round)
net.TriggerLeaderBlockBuilder(startSeq)
for i := uint64(0); i <= startSeq; i++ {
for _, n := range net.Instances {
n.Storage.WaitForBlockCommit(startSeq)
}
}
}
func TestReplicationFutureFinalization(t *testing.T) {
// send a block, then simultaneously send a finalization for the block
bb := testutil.NewTestBlockBuilder()
nodes := []simplex.NodeID{{1}, {2}, {3}, {4}}
quorum := simplex.Quorum(len(nodes))
conf, _, storage := DefaultTestNodeEpochConfig(t, nodes[1], NoopComm(nodes), bb)
e, err := simplex.NewEpoch(conf)
require.NoError(t, err)
require.NoError(t, e.Start())
md := e.Metadata()
_, ok := bb.BuildBlock(context.Background(), md, emptyBlacklist)
require.True(t, ok)
require.Equal(t, md.Round, md.Seq)
block := bb.GetBuiltBlock()
block.VerificationDelay = make(chan struct{}) // add a delay to the block verification
vote, err := NewTestVote(block, nodes[0])
require.NoError(t, err)
err = e.HandleMessage(&simplex.Message{
BlockMessage: &simplex.BlockMessage{
Vote: *vote,
Block: block,
},
}, nodes[0])
require.NoError(t, err)
finalization, _ := NewFinalizationRecord(t, e.Logger, e.SignatureAggregator, block, nodes[0:quorum])
// send finalization
err = e.HandleMessage(&simplex.Message{
Finalization: &finalization,
}, nodes[0])
require.NoError(t, err)
block.VerificationDelay <- struct{}{} // unblock the block verification
storedBlock := storage.WaitForBlockCommit(0)
require.Equal(t, uint64(1), storage.NumBlocks())
require.Equal(t, block, storedBlock)
}
// TestReplicationAfterNodeDisconnects tests the replication process of a node that
// disconnects from the network and reconnects after the rest of the network has made progress.
//
// All nodes make progress for `startDisconnect` blocks. The lagging node disconnects
// and the rest of the nodes continue to make progress for another `endDisconnect - startDisconnect` blocks.
// The lagging node reconnects and the after the next `finalization` is sent, the lagging node catches up to the latest height.
func TestReplicationAfterNodeDisconnects(t *testing.T) {
nodes := []simplex.NodeID{{1}, {2}, {3}, []byte("lagging")}
for startDisconnect := uint64(0); startDisconnect <= 5; startDisconnect++ {
for endDisconnect := uint64(10); endDisconnect <= 20; endDisconnect++ {
// lagging node cannot be the leader after node disconnects
isLaggingNodeLeader := bytes.Equal(simplex.LeaderForRound(nodes, endDisconnect), nodes[3])
if isLaggingNodeLeader {
continue
}
testName := fmt.Sprintf("Disconnect_%d_to_%d", startDisconnect, endDisconnect)
t.Run(testName, func(t *testing.T) {
t.Parallel()
testReplicationAfterNodeDisconnects(t, nodes, startDisconnect, endDisconnect)
})
}
}
}
func testReplicationAfterNodeDisconnects(t *testing.T, nodes []simplex.NodeID, startDisconnect, endDisconnect uint64) {
net := NewControlledNetwork(t, nodes)
testConfig := &TestNodeConfig{
ReplicationEnabled: true,
}
normalNode1 := NewControlledSimplexNode(t, nodes[0], net, testConfig)
normalNode2 := NewControlledSimplexNode(t, nodes[1], net, testConfig)
normalNode3 := NewControlledSimplexNode(t, nodes[2], net, testConfig)
laggingNode := NewControlledSimplexNode(t, nodes[3], net, testConfig)
require.Equal(t, uint64(0), normalNode1.Storage.NumBlocks())
require.Equal(t, uint64(0), normalNode2.Storage.NumBlocks())
require.Equal(t, uint64(0), normalNode3.Storage.NumBlocks())
require.Equal(t, uint64(0), laggingNode.Storage.NumBlocks())
net.StartInstances()
for i := uint64(0); i < startDisconnect; i++ {
net.TriggerLeaderBlockBuilder(i)
for _, n := range net.Instances {
n.Storage.WaitForBlockCommit(i)
}
}
// all nodes have committed `startDisconnect` blocks
for _, n := range net.Instances {
require.Equal(t, startDisconnect, n.Storage.NumBlocks())
}
// lagging node disconnects
net.Disconnect(laggingNode.E.ID)
isLaggingNodeLeader := bytes.Equal(simplex.LeaderForRound(nodes, startDisconnect), laggingNode.E.ID)
if isLaggingNodeLeader {
net.TriggerLeaderBlockBuilder(startDisconnect)
}
missedSeqs := uint64(0)
// normal nodes continue to make progress
for i := startDisconnect; i < endDisconnect; i++ {
emptyRound := bytes.Equal(simplex.LeaderForRound(nodes, i), nodes[3])
if emptyRound {
net.AdvanceWithoutLeader(i, laggingNode.E.ID)
missedSeqs++
} else {
net.TriggerLeaderBlockBuilder(i)
for _, n := range net.Instances[:3] {
n.Storage.WaitForBlockCommit(i - missedSeqs)
}
}
}
// all nodes except for lagging node have progressed and committed [endDisconnect - missedSeqs] blocks
for _, n := range net.Instances[:3] {
require.Equal(t, endDisconnect-missedSeqs, n.Storage.NumBlocks())
}
require.Equal(t, startDisconnect, laggingNode.Storage.NumBlocks())
require.Equal(t, startDisconnect, laggingNode.E.Metadata().Round)
// lagging node reconnects
net.Connect(laggingNode.E.ID)
net.TriggerLeaderBlockBuilder(endDisconnect)
var blacklist simplex.Blacklist
for _, n := range net.Instances {
block := n.Storage.WaitForBlockCommit(endDisconnect - missedSeqs)
blacklist = block.Blacklist()
}
for _, n := range net.Instances {
require.Equal(t, endDisconnect-missedSeqs, n.Storage.NumBlocks()-1)
}
if blacklist.IsNodeSuspected(3) {
t.Log("lagging node is blacklisted, cannot continue replication")
return
}
// the lagging node should build a block when triggered if its the leader
net.TriggerLeaderBlockBuilder(endDisconnect + 1)
for _, n := range net.Instances {
n.Storage.WaitForBlockCommit(endDisconnect - missedSeqs + 1)
}
}
// sendVotesToOneNode allows block messages to be sent to all nodes, and only
// passes vote messages to one node. This will allows that node to notarize the block,
// while the other blocks will timeout
func sendVotesToOneNode(filteredInNode simplex.NodeID) MessageFilter {
return func(msg *simplex.Message, _, to simplex.NodeID) bool {
if msg.VerifiedBlockMessage != nil || msg.BlockMessage != nil {
return true
}
if msg.VoteMessage != nil {
// this is the lagging node
if to.Equals(filteredInNode) {
return true
}
}
return false
}
}
func TestReplicationStuckInProposingBlock(t *testing.T) {
var aboutToBuildBlock sync.WaitGroup
aboutToBuildBlock.Add(2)
tbb := testutil.NewTestBlockBuilder()
bb := NewTestControlledBlockBuilder(t)
bb.TestBlockBuilder = *tbb
nodes := []simplex.NodeID{{1}, {2}, {3}, {4}}
blocks := createBlocks(t, nodes, 5)
quorum := simplex.Quorum(len(nodes))
sentMessages := make(chan *simplex.Message, 100)
conf, _, storage := DefaultTestNodeEpochConfig(t, nodes[0], &recordingComm{
Communication: NoopComm(nodes),
SentMessages: sentMessages,
}, bb)
conf.ReplicationEnabled = true
l := conf.Logger.(*TestLogger)
l.Intercept(func(entry zapcore.Entry) error {
if strings.Contains(entry.Message, "Scheduling block building") {
aboutToBuildBlock.Done()
}
return nil
})
e, err := simplex.NewEpoch(conf)
e.ReplicationEnabled = true
require.NoError(t, err)
require.NoError(t, e.Start())
bb.TriggerNewBlock()
notarizeAndFinalizeRoundWithMetadata(t, e, &bb.TestBlockBuilder, &blocks[0].Finalization.Finalization.ProtocolMetadata)
gb := storage.WaitForBlockCommit(0)
require.Equal(t, gb, blocks[0].VerifiedBlock.(*TestBlock))
highBlock, _ := blocks[3].VerifiedBlock.(*TestBlock)
highFinalization, _ := NewFinalizationRecord(t, e.Logger, e.SignatureAggregator, highBlock, nodes[0:quorum])
// Trigger the replication process to start by sending a finalization for a block we do not have
e.HandleMessage(&simplex.Message{
Finalization: &highFinalization,
}, nodes[1])
// Wait for the replication request to be sent
for {
msg := <-sentMessages
if msg.ReplicationRequest != nil {
break
}
}
// Drain the block builder channels
for len(bb.TestBlockBuilder.BlockShouldBeBuilt) > 0 {
select {
case <-bb.TestBlockBuilder.BlockShouldBeBuilt:
default:
}
}
// Prepare the quorum round answer to be sent as a response to the replication request
quorumRounds := make([]simplex.QuorumRound, 0, 4)
for i := uint64(1); i <= 4; i++ {
tb := blocks[i].VerifiedBlock.(*TestBlock)
finalization := blocks[i].Finalization
quorumRounds = append(quorumRounds, simplex.QuorumRound{
Block: tb,
Finalization: &finalization,
})
}
// Respond to the replication request with a block that has a notarization
replicationResponse := &simplex.ReplicationResponse{
LatestRound: &quorumRounds[2],
Data: quorumRounds[:3],
}
e.HandleMessage(&simplex.Message{
ReplicationResponse: replicationResponse,
}, nodes[1])
// Wait for the second block to be attempted to be built
aboutToBuildBlock.Wait()
// Trigger the replication process to start by sending a finalization for a block we do not have
e.HandleMessage(&simplex.Message{
Finalization: &blocks[4].Finalization,
}, nodes[1])
// Wait for the replication request to be sent
for {
msg := <-sentMessages
if msg.ReplicationRequest != nil {
break
}
}
replicationResponse = &simplex.ReplicationResponse{
LatestRound: &quorumRounds[3],
Data: quorumRounds[3:],
}
e.HandleMessage(&simplex.Message{
ReplicationResponse: replicationResponse,
}, nodes[1])
storage.WaitForBlockCommit(4)
}
// TestReplicationNodeDiverges tests that a node replicates blocks even if they
// have a stale notarization for a round(i.e. a node notarized a block but the rest of the network
// propagated an empty notarization).
func TestReplicationNodeDiverges(t *testing.T) {
nodes := []simplex.NodeID{{1}, {2}, {3}, {4}, {5}, {6}}
numBlocks := uint64(5)
net := NewControlledNetwork(t, nodes)
nodeConfig := func(from simplex.NodeID) *TestNodeConfig {
comm := NewTestComm(from, net.BasicInMemoryNetwork, sendVotesToOneNode(nodes[3]))
return &TestNodeConfig{
Comm: comm,
ReplicationEnabled: true,
}
}
NewControlledSimplexNode(t, nodes[0], net, nodeConfig(nodes[0]))
NewControlledSimplexNode(t, nodes[1], net, nodeConfig(nodes[1]))
NewControlledSimplexNode(t, nodes[2], net, nodeConfig(nodes[2]))
laggingNode := NewControlledSimplexNode(t, nodes[3], net, nodeConfig(nodes[3]))
// we need at least 6 nodes since the lagging node & leader will not timeout
NewControlledSimplexNode(t, nodes[4], net, nodeConfig(nodes[4]))
NewControlledSimplexNode(t, nodes[5], net, nodeConfig(nodes[5]))
net.StartInstances()
net.TriggerLeaderBlockBuilder(0)
// because of the message filter, the lagging one will be the only one to notarize the block
laggingNode.WAL.AssertNotarization(0)
for _, n := range net.Instances {
if n.E.ID.Equals(laggingNode.E.ID) {
continue
}
require.Equal(t, false, n.WAL.ContainsNotarization(0))
}
// we disconnect lagging node first so that it doesn't send the notarized block to any other nodes
net.Disconnect(laggingNode.E.ID)
net.SetAllNodesMessageFilter(
// block sending votes from round 0 to ensure all nodes will timeout
func(msg *simplex.Message, _, to simplex.NodeID) bool {
return !(msg.VoteMessage != nil && msg.VoteMessage.Vote.Round == 0)
},
)
// This function call ensures all nodes will timeout, and
// receive an empty notarization for round 0(except for lagging).
net.AdvanceWithoutLeader(0, laggingNode.E.ID)
for _, n := range net.Instances {
if n.E.ID.Equals(laggingNode.E.ID) {
require.Equal(t, uint64(1), n.E.Metadata().Round)
require.Equal(t, uint64(1), n.E.Metadata().Seq)
continue
}
require.Equal(t, uint64(0), n.E.Metadata().Seq)
require.Equal(t, uint64(1), n.E.Metadata().Round)
}
// advance [numBlocks] while the lagging node is disconnected
missedSeqs := uint64(1) // missed the first seq
for i := uint64(1); i < 1+numBlocks; i++ {
emptyRound := bytes.Equal(simplex.LeaderForRound(nodes, i), laggingNode.E.ID)
if emptyRound {
net.AdvanceWithoutLeader(i, laggingNode.E.ID)
missedSeqs++
} else {
net.TriggerLeaderBlockBuilder(i)
for _, n := range net.Instances {
if n.E.ID.Equals(laggingNode.E.ID) {
continue
}
n.Storage.WaitForBlockCommit(i - missedSeqs)
}
}
}
net.Connect(laggingNode.E.ID)
for _, n := range net.Instances {
// TODO: remove when replication can be initiated with empty notarizations
if n.E.ID.Equals(laggingNode.E.ID) {
continue
}
WaitToEnterRound(t, n.E, numBlocks+1)
}
// we are in round 6(which means node 1 should be leader(but it is blacklisted))
net.AdvanceWithoutLeader(1+numBlocks, laggingNode.E.ID)
net.TriggerLeaderBlockBuilder(numBlocks + 2)
for _, n := range net.Instances {
n.Storage.WaitForBlockCommit(numBlocks - missedSeqs + 1)
}
assertEqualLedgers(t, net)
}
func assertEqualLedgers(t *testing.T, net *ControlledInMemoryNetwork) {
expectedLedger := map[uint64][]byte{}
for seq := range net.Instances[0].Storage.NumBlocks() {
block, _, err := net.Instances[0].Storage.Retrieve(seq)
require.NoError(t, err)
bytes, err := block.Bytes()
require.NoError(t, err)
expectedLedger[seq] = bytes
}
for _, n := range net.Instances {
actualLedger := map[uint64][]byte{}
for seq := range n.Storage.NumBlocks() {
block, _, err := n.Storage.Retrieve(seq)
require.NoError(t, err)
bytes, err := block.Bytes()
require.NoError(t, err)
actualLedger[seq] = bytes
}
require.Equal(t, expectedLedger, actualLedger)
}
}
func TestReplicationNotarizationWithoutFinalizations(t *testing.T) {
nodes := []simplex.NodeID{{1}, {2}, {3}, {4}}
for numBlocks := uint64(1); numBlocks <= 3*simplex.DefaultMaxRoundWindow; numBlocks++ {
// lagging node cannot be the leader after node disconnects
isLaggingNodeLeader := bytes.Equal(simplex.LeaderForRound(nodes, numBlocks), nodes[3])
if isLaggingNodeLeader {
continue
}
testName := fmt.Sprintf("NotarizationWithoutFinalization_%d_blocks", numBlocks)
t.Run(testName, func(t *testing.T) {
t.Parallel()
testReplicationNotarizationWithoutFinalizations(t, numBlocks, nodes)
})
}
}
// TestReplicationNotarizationWithoutFinalizations tests that a lagging node will replicate
// blocks that have notarizations but no finalizations.
func testReplicationNotarizationWithoutFinalizations(t *testing.T, numBlocks uint64, nodes []simplex.NodeID) {
net := NewControlledNetwork(t, nodes)
onlyAllowBlockProposalsAndNotarizations := func(msg *simplex.Message, _, to simplex.NodeID) bool {
if to.Equals(nodes[3]) {
return (msg.BlockMessage != nil || msg.VerifiedBlockMessage != nil || msg.Notarization != nil)
}
return true
}
nodeConfig := func(from simplex.NodeID) *TestNodeConfig {
comm := NewTestComm(from, net.BasicInMemoryNetwork, onlyAllowBlockProposalsAndNotarizations)
return &TestNodeConfig{
Comm: comm,
ReplicationEnabled: true,
}
}
NewControlledSimplexNode(t, nodes[0], net, nodeConfig(nodes[0]))
NewControlledSimplexNode(t, nodes[1], net, nodeConfig(nodes[1]))
NewControlledSimplexNode(t, nodes[2], net, nodeConfig(nodes[2]))
laggingNode := NewControlledSimplexNode(t, nodes[3], net, nodeConfig(nodes[3]))
for _, n := range net.Instances {
require.Equal(t, uint64(0), n.Storage.NumBlocks())
}
net.StartInstances()
// normal nodes continue to make progress
for i := uint64(0); i < uint64(numBlocks); i++ {
net.TriggerLeaderBlockBuilder(i)
for _, n := range net.Instances[:3] {
n.Storage.WaitForBlockCommit(uint64(i))
}
}
laggingNode.WAL.AssertNotarization(numBlocks - 1)
require.Equal(t, uint64(0), laggingNode.Storage.NumBlocks())
require.Equal(t, uint64(numBlocks), laggingNode.E.Metadata().Round)
net.SetAllNodesMessageFilter(AllowAllMessages)
net.TriggerLeaderBlockBuilder(numBlocks)
for _, n := range net.Instances {
n.Storage.WaitForBlockCommit(uint64(numBlocks))
}
}
func createBlocks(t *testing.T, nodes []simplex.NodeID, seqCount uint64) []simplex.VerifiedFinalizedBlock {
bb := NewTestBlockBuilder()
logger := MakeLogger(t, int(0))
ctx := context.Background()
data := make([]simplex.VerifiedFinalizedBlock, 0, seqCount)
var prev simplex.Digest
for i := uint64(0); i < seqCount; i++ {
protocolMetadata := simplex.ProtocolMetadata{
Seq: i,
Round: i,
Prev: prev,
}
block, ok := bb.BuildBlock(ctx, protocolMetadata, emptyBlacklist)
require.True(t, ok)
prev = block.BlockHeader().Digest
finalization, _ := NewFinalizationRecord(t, logger, &TestSignatureAggregator{N: len(nodes)}, block, nodes)
data = append(data, simplex.VerifiedFinalizedBlock{
VerifiedBlock: block,
Finalization: finalization,
})
}
return data
}
func TestReplicationVerifyNotarization(t *testing.T) {
bb := testutil.NewTestBlockBuilder()
nodes := []simplex.NodeID{{1}, {2}, {3}, {4}}
// This function takes a QC and makes it that it is signed by only 2 out of 4 nodes,
// while still having a quorum of signatures.
corruptQC := func(qc simplex.QuorumCertificate) simplex.QuorumCertificate {
badQC := qc.(TestQC)
// Duplicate the last signature
badQC = append(badQC, badQC[len(badQC)-1])
// Remove the first signature
badQC = badQC[1:]
// Finalization should have 3 signers
require.Len(t, badQC.Signers(), 3)
// But all these signers are either the second and third node.
require.Contains(t, badQC.Signers(), nodes[1])
require.Contains(t, badQC.Signers(), nodes[2])
// Not the first or the fourth node.
require.NotContains(t, badQC.Signers(), nodes[0])
require.NotContains(t, badQC.Signers(), nodes[3])
return badQC
}
quorum := simplex.Quorum(len(nodes))
sentMessages := make(chan *simplex.Message, 100)
conf, wal, _ := DefaultTestNodeEpochConfig(t, nodes[1], &recordingComm{
Communication: NewNoopComm(nodes),
SentMessages: sentMessages,
}, bb)
conf.ReplicationEnabled = true
e, err := simplex.NewEpoch(conf)
require.NoError(t, err)
require.NoError(t, e.Start())
md := e.Metadata()
_, ok := bb.BuildBlock(context.Background(), md, emptyBlacklist)
require.True(t, ok)
require.Equal(t, md.Round, md.Seq)
block := bb.GetBuiltBlock()
finalization, _ := NewFinalizationRecord(t, e.Logger, e.SignatureAggregator, block, nodes[0:quorum])
// Trigger the replication process to start by sending a finalization for a block we do not have
e.HandleMessage(&simplex.Message{
Finalization: &finalization,
}, nodes[0])
// Wait for the replication request to be sent
for {
msg := <-sentMessages
if msg.ReplicationRequest != nil {
break
}
}
notarization, err := NewNotarization(e.Logger, e.SignatureAggregator, block, nodes[0:quorum])
require.NoError(t, err)
// Corrupt the QC
notarization.QC = corruptQC(notarization.QC)
// Respond to the replication request with a block that has a notarization
replicationResponse := &simplex.ReplicationResponse{
Data: []simplex.QuorumRound{
{
Block: block,
Notarization: ¬arization,
},
},
}
e.HandleMessage(&simplex.Message{
ReplicationResponse: replicationResponse,
}, nodes[0])
require.Never(t, func() bool {
return wal.ContainsNotarization(0)
}, time.Millisecond*500, time.Millisecond*10, "Did not expect block with a corrupt QC to be written to the WAL")