-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathinstance_test.go
More file actions
1575 lines (1358 loc) · 55 KB
/
Copy pathinstance_test.go
File metadata and controls
1575 lines (1358 loc) · 55 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
import (
"bytes"
"context"
"crypto/rand"
"crypto/sha256"
"encoding/asn1"
"encoding/binary"
"fmt"
"sort"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/ava-labs/simplex/avalanchego"
"github.com/ava-labs/simplex/common"
metadata "github.com/ava-labs/simplex/msm"
"github.com/ava-labs/simplex/simplex"
"github.com/ava-labs/simplex/testutil"
"github.com/ava-labs/simplex/wal"
"github.com/stretchr/testify/require"
"go.uber.org/zap/zapcore"
)
func TestInstanceMixedNodeType(t *testing.T) {
t.Skip("skipping until test instance refactor")
// One node is a validator at genesis, the other is a non-validator.
// After some blocks, the second (non-validator) node also becomes a validator.
// The test ensures that the second node tracks the chain while the first node expands the chain
// in the first epoch, and that both nodes move to the second epoch and then both are used for consensus together.
const (
basePChainHeight = uint64(1)
epochChangePChainHeight = uint64(100)
)
var id [20]byte
rand.Read(id[:])
firstNodeID := common.NodeID(id[:])
// The peer that joins the validator set in the last epoch. Its ID is chosen
// to differ from the (random) node under test.
var peerID [20]byte
rand.Read(peerID[:])
secondNodeID := common.NodeID(peerID[:])
// Epoch 1 is single-validator
// The last epoch is expanded to two validators.
validatorSetsAtHeight := map[uint64]metadata.NodeBLSMappings{
basePChainHeight: {
{NodeID: id, BLSKey: []byte{0xaa}, Weight: 1},
},
epochChangePChainHeight: {
{NodeID: id, BLSKey: []byte{0xaa}, Weight: 2},
{NodeID: peerID, BLSKey: []byte{0xbb}, Weight: 2},
},
}
pChain := newTestPlatformChain(basePChainHeight, validatorSetsAtHeight)
cops := &testCryptoOps{}
genesisBlock := &testInnerBlock{Height_: 0, TS: time.Now(), Payload: []byte("genesis")}
net := newInMemNetwork(t)
t.Cleanup(net.stop)
// Create the storage for the instances and append the genesis block to each
storage := newStorageWithGenesis(t, genesisBlock)
storage2 := newStorageWithGenesis(t, genesisBlock)
// Create the instances and register them to the network
firstInstance := newInstance(t, firstNodeID, storage, net, pChain, cops, genesisBlock)
secondInstance := newInstance(t, secondNodeID, storage2, net, pChain, cops, genesisBlock)
net.register(firstNodeID, firstInstance)
net.register(secondNodeID, secondInstance)
/// Start the instances
require.NoError(t, firstInstance.Start(t.Context()))
require.NoError(t, secondInstance.Start(t.Context()))
t.Cleanup(firstInstance.Stop)
t.Cleanup(secondInstance.Stop)
// Epoch 1: wait until the node has committed a series of normal blocks on its own.
const epoch1Target = uint64(5) // genesis(0) + zero block(1) + 3 normal blocks
waitForNumBlocks(t, storage, epoch1Target)
waitForNumBlocks(t, storage2, epoch1Target)
// The validator set in force is the one introduced by the most recent block
// that carries a BlockValidationDescriptor (the zero block in epoch 1).
require.Equal(t, firstInstance.Config.ID, latestValidatorID(t, storage))
require.Equal(t, firstInstance.Config.ID, latestValidatorID(t, storage2))
// Trigger the epoch change: the validator set changes at epochChangePChainHeight,
// growing from one validator to two.
pChain.advanceTo(epochChangePChainHeight)
approval := &common.ValidatorSetApproval{
NodeID: peerID,
PChainHeight: epochChangePChainHeight,
AuxInfoDigest: sha256.Sum256(nil),
Signature: []byte{1, 2, 3},
}
// The node seals the epoch once it has a quorum of approvals of the new
// (two-validator) set. With two validators the node's self-approval is no longer
// a quorum and the peer is not running yet, so waitForSealingBlock injects the
// peer's approval on each poll until the sealing block is committed.
// TODO: Implement this capability in production so we won't need to inject approvals in tests.
sealingBlockSeq := waitForSealingBlock(t, firstInstance, approval, storage.NumBlocks())
waitForNumBlocks(t, storage2, sealingBlockSeq) // Ensure the new validator has replicated the sealing block.
// With both validators live, the two-validator epoch commits more blocks.
const epoch2Extra = uint64(3)
waitForNumBlocks(t, storage, sealingBlockSeq+epoch2Extra)
// Confirm the second epoch has the second validator in the sealing block
require.Equal(t, secondInstance.Config.ID, latestValidatorID(t, storage))
}
// emptyVoteRecorder wraps a Broadcaster and signals the first time an empty vote is broadcast.
type emptyVoteRecorder struct {
Broadcaster
got chan struct{}
}
func (r *emptyVoteRecorder) Broadcast(msg *common.Message) {
if msg.EmptyVoteMessage != nil {
select {
case r.got <- struct{}{}:
default:
}
}
r.Broadcaster.Broadcast(msg)
}
func TestEpochInvokesMSMWaitForPendingBlock(t *testing.T) {
const basePChainHeight = uint64(1)
// Two validators, but only one is instantiated. Our node has the smaller ID so it sorts to
// index 0 and is a non-leader for round 1 (LeaderForRound picks index 1%2). The other
// validator is the round leader but is never created, so no block is ever proposed.
var ourID, leaderID [20]byte
ourID[0], leaderID[0] = 0x01, 0x02
ourNode := common.NodeID(ourID[:])
require.NotEqual(t, ourNode, simplex.LeaderForRound([]common.NodeID{ourNode, leaderID[:]}, 1)) // ensure the leader is not our node
validatorSetsAtHeight := map[uint64]metadata.NodeBLSMappings{
basePChainHeight: {
{NodeID: ourID, BLSKey: []byte{0xaa}, Weight: 1},
{NodeID: leaderID, BLSKey: []byte{0xbb}, Weight: 1},
},
}
pChain := newTestPlatformChain(basePChainHeight, validatorSetsAtHeight)
cops := &testCryptoOps{}
genesisBlock := &testInnerBlock{Height_: 0, TS: time.Now(), Payload: []byte("genesis")}
net := newInMemNetwork(t)
t.Cleanup(net.stop)
storage := newStorageWithGenesis(t, genesisBlock)
// A paused VM never has a pending block, so its WaitForPendingBlock blocks until its context
// is cancelled: the MSM must decide to build on its own for the round to make progress.
vm := newTestVM()
vm.pause()
inst := newInstanceWithVM(t, ourNode, storage, net, pChain, cops, genesisBlock, vm)
// Capture the empty vote the node broadcasts once it gives up waiting for the leader.
recorder := &emptyVoteRecorder{Broadcaster: inst.Config.Broadcaster, got: make(chan struct{}, 1)}
inst.Config.Broadcaster = recorder
require.NoError(t, inst.Start(t.Context()))
t.Cleanup(inst.Stop)
select {
case <-recorder.got:
case <-time.After(10 * time.Second):
require.FailNow(t, "node never broadcast an empty vote, so the Epoch did not drive the MSM's WaitForPendingBlock")
}
}
func TestInstanceNonValidatorBootstraps(t *testing.T) {
t.Skip("skipping until test instance refactor")
// One node is a validator and progresses the chain by building blocks,
// and its weight changes while the chain progresses in 3 different P-chain epoch heights.
// Then, we add another node which is a non-validator.
// The node should bootstrap the chain but without shutting down the non-validator instance.
// Later on, the non-validator becomes a validator.
const (
basePChainHeight = uint64(1)
secondEpochP = uint64(100)
thirdEpochP = uint64(200)
joinEpochP = uint64(300)
)
var id [20]byte
rand.Read(id[:])
validatorNodeID := common.NodeID(id[:])
// The node that joins later, first as a non-validator and eventually as a validator.
var nv [20]byte
rand.Read(nv[:])
nonValidatorNodeID := common.NodeID(nv[:])
// The lone validator's weight changes at three different P-chain heights, sealing an
// epoch on each change. Because it remains the sole validator throughout, its own
// approval is a quorum and every epoch seals without any other node's participation.
// The last checkpoint (joinEpochP) grows the set to two validators, admitting the peer.
validatorSetsAtHeight := map[uint64]metadata.NodeBLSMappings{
basePChainHeight: {
{NodeID: id, BLSKey: []byte{0xaa}, Weight: 1},
},
secondEpochP: {
{NodeID: id, BLSKey: []byte{0xaa}, Weight: 2},
},
thirdEpochP: {
{NodeID: id, BLSKey: []byte{0xaa}, Weight: 3},
},
joinEpochP: {
{NodeID: id, BLSKey: []byte{0xaa}, Weight: 3},
{NodeID: nv, BLSKey: []byte{0xbb}, Weight: 1},
},
}
pChain := newTestPlatformChain(basePChainHeight, validatorSetsAtHeight)
cops := &testCryptoOps{}
genesisBlock := &testInnerBlock{Height_: 0, TS: time.Now(), Payload: []byte("genesis")}
net := newInMemNetwork(t)
t.Cleanup(net.stop)
// Both storages start with only the genesis block.
storage := newStorageWithGenesis(t, genesisBlock)
storage2 := newStorageWithGenesis(t, genesisBlock)
validatorInstance := newInstance(t, validatorNodeID, storage, net, pChain, cops, genesisBlock)
nonValidatorInstance := newInstance(t, nonValidatorNodeID, storage2, net, pChain, cops, genesisBlock)
// transitioned is closed when the node starts a Simplex epoch, i.e. becomes a validator.
// The node only ever starts an epoch here as part of its non-validator -> validator
// transition.
transitioned := make(chan struct{})
nonValidatorInstance.Config.Logger.(*testutil.TestLogger).Intercept(func(entry zapcore.Entry) error {
if strings.Contains(entry.Message, "Starting Simplex Epoch") {
select {
case <-transitioned:
default:
close(transitioned)
}
}
return nil
})
// Only the validator is running at first; it builds and seals the chain on its own.
net.register(validatorNodeID, validatorInstance)
require.NoError(t, validatorInstance.Start(t.Context()))
t.Cleanup(validatorInstance.Stop)
// Epoch 1: wait until the validator has committed a series of blocks on its own.
waitForNumBlocks(t, storage, 5) // genesis(0) + zero block(1) + a few normal blocks
// Drive two more epoch transitions by changing the validator's weight. Each change seals
// an epoch (and produces a sealing block) without any other node, since the validator's
// own approval is a quorum of the single-node set. The counts below include the zero block,
// which carries a block validation descriptor as well.
pChain.advanceTo(secondEpochP)
waitForSealingBlockCount(t, storage, 2)
pChain.advanceTo(thirdEpochP)
waitForSealingBlockCount(t, storage, 3)
// Let the third epoch grow a few normal blocks before the non validator joins, so bootstrap has to
// replicate past the sealing blocks and into ordinary blocks.
waitForNumBlocks(t, storage, storage.NumBlocks()+3)
// The new node joins as a non-validator (it is absent from the validator set at the current
// P-chain tip) and bootstraps the chain from the validator.
net.register(nonValidatorNodeID, nonValidatorInstance)
require.NoError(t, nonValidatorInstance.Start(t.Context()))
t.Cleanup(nonValidatorInstance.Stop)
// The non-validator replicates every sealed epoch and stays a non-validator throughout.
bootstrapTarget := storage.NumBlocks()
waitForNumBlocks(t, storage2, bootstrapTarget)
// It replicated through the sealed epochs without becoming a validator.
select {
case <-transitioned:
t.Fatal("non-validator transitioned to validator before joining the set")
default:
}
// Now grow the validator set to include the peer at the P-chain tip.
pChain.advanceTo(joinEpochP)
approval := &common.ValidatorSetApproval{
NodeID: nv,
PChainHeight: joinEpochP,
AuxInfoDigest: sha256.Sum256(nil),
Signature: []byte{1, 2, 3},
}
// With two validators the validator's self-approval is no longer a quorum and the peer is
// still a non-validator, so we inject the peer's approval until the sealing block commits.
// TODO: Implement this capability in production so we won't need to inject approvals in tests.
sealingBlockSeq := waitForSealingBlock(t, validatorInstance, approval, storage.NumBlocks())
waitForNumBlocks(t, storage2, sealingBlockSeq)
// Once the non-validator replicates the sealing block that admits it, it detects that it is
// now a validator at the tip and transitions from non-validator to validator.
select {
case <-transitioned:
case <-time.After(20 * time.Second):
t.Fatal("non-validator did not transition to validator")
}
// The newly promoted validator now participates in extending the chain.
require.Equal(t, nonValidatorInstance.Config.ID, latestValidatorID(t, storage))
// With both validators live, the two-validator epoch keeps committing blocks, and both
// nodes replicate them together. This confirms the promoted node contributes to consensus
// rather than merely tracking the chain.
const twoValidatorExtra = uint64(3)
extendedTarget := sealingBlockSeq + twoValidatorExtra
waitForNumBlocks(t, storage, extendedTarget)
waitForNumBlocks(t, storage2, extendedTarget)
}
func TestInstanceRestartAcrossEpochs(t *testing.T) {
t.Skip("skipping until test instance refactor")
// Restart a single validator at three different points in its lifecycle so that,
// on each (re)start, constructEpochAndValidatorSet takes a different branch of
// its switch:
//
// - Cold boot, ledger holds only the genesis (non-Simplex) block -> "genesis" branch.
// - Restart when the tip is a sealing block -> "sealing block at tip" branch.
// - Restart mid-epoch, when the tip is an ordinary Simplex block -> "sealing block in storage" branch.
//
const (
basePChainHeight = uint64(1)
epochChangePChainHeight = uint64(100)
)
var id [20]byte
rand.Read(id[:])
nodeID := common.NodeID(id[:])
// The lone validator's weight changes at epochChangePChainHeight, which seals the first
// epoch.
validatorSetsAtHeight := map[uint64]metadata.NodeBLSMappings{
basePChainHeight: {
{NodeID: id, BLSKey: []byte{0xaa}, Weight: 1},
},
epochChangePChainHeight: {
{NodeID: id, BLSKey: []byte{0xaa}, Weight: 2},
},
}
pChain := newTestPlatformChain(basePChainHeight, validatorSetsAtHeight)
cops := &testCryptoOps{}
genesisBlock := &testInnerBlock{Height_: 0, TS: time.Now(), Payload: []byte("genesis")}
net := newInMemNetwork(t)
t.Cleanup(net.stop)
storage := newStorageWithGenesis(t, genesisBlock)
vm := newTestVM()
const (
logEpochFromGenesis = "Determined epoch and validator set from genesis (ledger holds only non-Simplex blocks)"
logEpochFromSealingTip = "Determined epoch and validator set from sealing block at tip"
logEpochFromSealingStorage = "Determined epoch and validator set from sealing block in storage"
)
// lastEpochBranch holds the full debug message constructEpochAndValidatorSet
// logs, identifying which branch of its switch the latest (re)start took. It is
// written synchronously during Start, but also from the epoch-change goroutine,
// so an atomic guards it.
var lastEpochBranch atomic.Pointer[string]
// start (re)creates an instance over the same storage/network/VM. The log
// interceptor, installed before Start, records which branch startup took.
start := func() *Instance {
inst := newInstanceWithVM(t, nodeID, storage, net, pChain, cops, genesisBlock, vm)
inst.Config.Logger.(*testutil.TestLogger).Intercept(func(entry zapcore.Entry) error {
switch entry.Message {
case logEpochFromGenesis, logEpochFromSealingTip, logEpochFromSealingStorage:
msg := entry.Message
lastEpochBranch.Store(&msg)
}
return nil
})
net.register(nodeID, inst)
require.NoError(t, inst.Start(t.Context()))
return inst
}
// Pause block production before the node even starts: only protocol blocks (the
// zero block, the epoch transition and its sealing block) get built, and the
// chain stops at the sealing block since no ordinary block can be built on top.
vm.pause()
// --- Case 1: cold boot, ledger holds only the genesis block. ---
inst := start()
require.Equal(t, logEpochFromGenesis, *lastEpochBranch.Load())
// --- Case 2: restart when the tip is a sealing block. ---
// Change the validator's weight to seal the first epoch.
// countSealingBlocks == 2: the zero block plus that epoch's sealing block. With the VM
// paused, the sealing block stays the tip because no ordinary block can be built on top.
pChain.advanceTo(epochChangePChainHeight)
waitForSealingBlockCount(t, storage, 2)
requireTipIsSealing(t, storage, true)
inst.Stop()
inst = start()
require.Equal(t, logEpochFromSealingTip, *lastEpochBranch.Load())
// --- Case 3: restart mid-epoch, tip is an ordinary Simplex block. ---
// Resume production; the node extends the new epoch with ordinary blocks.
vm.resume()
waitForNumBlocks(t, storage, storage.NumBlocks()+3)
requireTipIsSealing(t, storage, false)
inst.Stop()
inst = start()
t.Cleanup(inst.Stop)
require.Equal(t, logEpochFromSealingStorage, *lastEpochBranch.Load())
// The restarted node keeps extending the chain.
waitForNumBlocks(t, storage, storage.NumBlocks()+2)
}
func TestParseBlockSizeMatchesBytes(t *testing.T) {
// Case 1: Bytes() first, Size() second, size returns the cached length.
pb := &ParsedBlock{
StateMachineBlock: metadata.StateMachineBlock{
Metadata: metadata.StateMachineMetadata{
SimplexProtocolMetadata: common.ProtocolMetadata{
Version: 1,
Prev: common.Digest{},
Round: 1,
Epoch: 4,
Seq: 2,
},
SimplexBlacklist: common.Blacklist{
Updates: common.BlacklistUpdates{{NodeIndex: 1, Type: 1}},
NodeCount: 2,
},
PChainHeight: 6,
},
InnerBlock: &testInnerBlock{
Height_: 7,
TS: time.UnixMilli(8),
Payload: []byte("payload"),
},
},
}
bytes := pb.Bytes()
require.Equal(t, len(bytes), pb.Size())
// Case 2: Size() first on a non serialized block. it will
// compute the size and match a later Byte() call.
pb2 := &ParsedBlock{
StateMachineBlock: metadata.StateMachineBlock{
Metadata: metadata.StateMachineMetadata{
SimplexProtocolMetadata: common.ProtocolMetadata{
Version: 1,
Prev: common.Digest{},
Round: 1,
Epoch: 4,
Seq: 2,
},
SimplexBlacklist: common.Blacklist{
Updates: common.BlacklistUpdates{{NodeIndex: 1, Type: 1}},
NodeCount: 2,
},
PChainHeight: 6,
},
InnerBlock: &testInnerBlock{
Height_: 9,
TS: time.UnixMilli(10),
Payload: []byte("other payload"),
},
},
}
size := pb2.Size()
require.NotZero(t, size)
bytes2 := pb2.Bytes()
require.Equal(t, len(bytes2), size)
// case 3: cincurrent Size() calls on a block that was never serialized.
// the goroutines rase to compute the size, the lock must make this
// safe and every call must return the correct value
pb3 := &ParsedBlock{
StateMachineBlock: metadata.StateMachineBlock{
Metadata: metadata.StateMachineMetadata{
SimplexProtocolMetadata: common.ProtocolMetadata{
Version: 1,
Prev: common.Digest{},
Round: 1,
Epoch: 4,
Seq: 2,
},
SimplexBlacklist: common.Blacklist{
Updates: common.BlacklistUpdates{{NodeIndex: 1, Type: 1}},
NodeCount: 2,
},
PChainHeight: 6,
},
InnerBlock: &testInnerBlock{
Height_: 11,
TS: time.UnixMilli(12),
Payload: []byte("concurrent"),
},
},
}
var wg sync.WaitGroup
sizes := make([]int, 4)
for i := range sizes {
wg.Add(1)
go func() {
defer wg.Done()
sizes[i] = pb3.Size()
}()
}
wg.Wait()
bytes3 := pb3.Bytes()
for _, size := range sizes {
require.Equal(t, len(bytes3), size)
}
}
// TestInstanceZeroBlockUsesLastNonSimplexPChainHeight asserts that the first ever Simplex block
// references the P-chain height of the last non-Simplex block.
func TestInstanceZeroBlockUsesLastNonSimplexPChainHeight(t *testing.T) {
t.Skip("skipping until test instance refactor")
const basePChainHeight = uint64(7)
var id [20]byte
rand.Read(id[:])
nodeID := common.NodeID(id[:])
validatorSetsAtHeight := map[uint64]metadata.NodeBLSMappings{
basePChainHeight: {
{NodeID: id, BLSKey: []byte{0xaa}, Weight: 1},
},
}
pChain := newTestPlatformChain(basePChainHeight, validatorSetsAtHeight)
cops := &testCryptoOps{}
genesisBlock := &testInnerBlock{Height_: 0, TS: time.Now(), Payload: []byte("genesis")}
net := newInMemNetwork(t)
t.Cleanup(net.stop)
storage := newStorageWithGenesis(t, genesisBlock)
inst := newInstance(t, nodeID, storage, net, pChain, cops, genesisBlock)
net.register(nodeID, inst)
require.NoError(t, inst.Start(t.Context()))
t.Cleanup(inst.Stop)
waitForNumBlocks(t, storage, 2) // genesis(0) + the zero block(1)
zeroBlock, ok := storage.blockAt(1)
require.True(t, ok)
require.Equal(t, metadata.BlockTypeZero, zeroBlock.Type())
require.Equal(t, basePChainHeight, zeroBlock.Metadata.PChainHeight)
require.Equal(t, basePChainHeight, zeroBlock.Metadata.SimplexEpochInfo.PChainReferenceHeight)
}
func TestInstanceDoubleStartFails(t *testing.T) {
const basePChainHeight = uint64(1)
var id [20]byte
rand.Read(id[:])
nodeID := common.NodeID(id[:])
// Single-validator set including this node, so Start brings up a validator epoch.
validatorSetsAtHeight := map[uint64]metadata.NodeBLSMappings{
basePChainHeight: {
{NodeID: id, BLSKey: []byte{0xaa}, Weight: 1},
},
}
pChain := newTestPlatformChain(basePChainHeight, validatorSetsAtHeight)
cops := &testCryptoOps{}
genesisBlock := &testInnerBlock{Height_: 0, TS: time.Now(), Payload: []byte("genesis")}
net := newInMemNetwork(t)
t.Cleanup(net.stop)
storage := newStorageWithGenesis(t, genesisBlock)
inst := newInstance(t, nodeID, storage, net, pChain, cops, genesisBlock)
require.NoError(t, inst.Start(t.Context()))
t.Cleanup(inst.Stop)
require.ErrorIs(t, inst.Start(t.Context()), errAlreadyStarted)
}
func TestNonValidatorSkipsMSMVerification(t *testing.T) {
t.Skip("skipping until test instance refactor")
// This test proves that a non-validator doesn't use the MSM to verify blocks.
// It does so by forcing a non-validator ti commit a block whose MSM state machine
// transition is invalid.
const basePChainHeight = uint64(1)
var id [20]byte
rand.Read(id[:])
validatorNodeID := common.NodeID(id[:])
// The node under test. It is absent from the validator set, so it comes up as a non-validator.
var nv [20]byte
rand.Read(nv[:])
nonValidatorNodeID := common.NodeID(nv[:])
validatorSetsAtHeight := map[uint64]metadata.NodeBLSMappings{
basePChainHeight: {
{NodeID: id, BLSKey: []byte{0xaa}, Weight: 1},
},
}
pChain := newTestPlatformChain(basePChainHeight, validatorSetsAtHeight)
cops := &testCryptoOps{}
genesisBlock := &testInnerBlock{Height_: 0, TS: time.Now(), Payload: []byte("genesis")}
net := newInMemNetwork(t)
t.Cleanup(net.stop)
// The lone validator builds a chain on its own and then shuts down, so that from here on the
// only source of blocks is this test.
storage := newStorageWithGenesis(t, genesisBlock)
validatorInstance := newInstance(t, validatorNodeID, storage, net, pChain, cops, genesisBlock)
net.register(validatorNodeID, validatorInstance)
require.NoError(t, validatorInstance.Start(t.Context()))
t.Cleanup(validatorInstance.Stop)
waitForNumBlocks(t, storage, 7)
validatorInstance.Stop()
require.True(t, validatorInstance.isStopped())
replicatedSeq := storage.NumBlocks() - 1
replicated, ok := storage.blockAt(replicatedSeq)
require.True(t, ok)
parent, ok := storage.blockAt(replicatedSeq - 1)
require.True(t, ok)
// The non-validator holds the chain up to, but not including, that last block, and is wired to
// a network of its own where nobody answers: the replication response we hand it below is the
// only way it can ever learn about the block.
nonValidatorStorage := storage.cloneBelow(replicatedSeq)
require.Equal(t, replicatedSeq, nonValidatorStorage.NumBlocks())
_, ok = nonValidatorStorage.blockAt(replicatedSeq)
require.False(t, ok, "the non-validator already has the block it is meant to replicate")
nonValidatorInstance := newInstance(t, nonValidatorNodeID, nonValidatorStorage, newInMemNetwork(t), pChain, cops, genesisBlock)
require.NoError(t, nonValidatorInstance.Start(t.Context()))
t.Cleanup(nonValidatorInstance.Stop)
// The MSM that built the chain - the validator has stopped, so nothing else uses it - accepts
// the block, so we know the block is valid.
msm := validatorInstance.msm
// The block we feed the non-validator is that same block with a single defect: a timestamp
// that precedes its parent's. Everything else - round, sequence, epoch info, P-chain height,
// inner block - is left alone, so the only thing wrong with it is its state machine
// transition.
tampered := replicated.Clone()
tampered.Metadata.Timestamp = parent.Metadata.Timestamp - 1
// Wire the MSM that built the chain to the tampered block, so we can prove that the MSM would have rejected it.
tamperedBlock := &ParsedBlock{StateMachineBlock: tampered.Clone(), msm: msm}
_, err := tamperedBlock.Verify(context.Background())
require.ErrorContains(t, err, "proposed timestamp is before parent block's timestamp")
// Changing the timestamp made it a block the validator never built: no sequence of its ledger
// holds it.
for seq := uint64(0); seq < storage.NumBlocks(); seq++ {
stored, ok := storage.blockAt(seq)
require.True(t, ok)
require.NotEqual(t, tampered.Digest(), stored.Digest(), "the validator has the tampered block at seq %d", seq)
}
// Send precisely that block: the finalization we hand over is a quorum on its digest, not on
// the digest of the block the validator built.
block := &ParsedBlock{StateMachineBlock: tampered.Clone()}
finalization, _ := testutil.NewFinalizationRecord(t, &testutil.TestSignatureAggregator{N: 1}, block, []common.NodeID{validatorNodeID})
require.Equal(t, common.Digest(tampered.Digest()), finalization.Finalization.Digest)
require.NotEqual(t, common.Digest(replicated.Digest()), finalization.Finalization.Digest)
require.NoError(t, nonValidatorInstance.HandleMessage(&common.Message{
ReplicationResponse: &common.ReplicationResponse{
Data: []common.QuorumRound{{Block: block, Finalization: &finalization}},
},
}, validatorNodeID))
// It commits the block its state machine would have rejected...
waitForNumBlocks(t, nonValidatorStorage, replicatedSeq+1)
committed, ok := nonValidatorStorage.blockAt(replicatedSeq)
require.True(t, ok)
require.Equal(t, tampered.Digest(), committed.Digest())
// ... so the two ledgers are the same height but disagree on their last block: the
// non-validator committed a block that exists nowhere in the validator's storage.
require.Equal(t, storage.NumBlocks(), nonValidatorStorage.NumBlocks())
require.NotEqual(t, replicated.Digest(), committed.Digest())
}
func TestValidatorSkipsMSMVerificationWhenReplicating(t *testing.T) {
t.Skip("skipping until test instance refactor")
// This test ensures that validators that are lagging behind do not use the MSM
// to verify blocks they replicate through the replication path, as they have a QC.
// We check once for a notarized block and once for a finalized block.
for _, tt := range []struct {
name string
// quorumRound wraps the replicated block with a QC.
quorumRound func(t *testing.T, logger common.Logger, block *ParsedBlock, signers []common.NodeID) common.QuorumRound
// requireReplicated asserts the lagging node replicated the block.
requireReplicated func(t *testing.T, storage *MockStorage, block metadata.StateMachineBlock)
}{
{
name: "notarization",
quorumRound: func(t *testing.T, logger common.Logger, block *ParsedBlock, signers []common.NodeID) common.QuorumRound {
notarization, err := testutil.NewNotarization(logger, &testutil.TestSignatureAggregator{N: len(signers)}, block, signers)
require.NoError(t, err)
return common.QuorumRound{Block: block, Notarization: ¬arization}
},
// A notarized block is not committed but notarized: the node persists the
// notarization to its WAL, which it only reaches after the block verified.
requireReplicated: func(t *testing.T, storage *MockStorage, block metadata.StateMachineBlock) {
round := block.Metadata.SimplexProtocolMetadata.Round
require.Eventually(t, func() bool {
return storage.containsNotarization(round)
}, 20*time.Second, 100*time.Millisecond, "no notarization for round %d was persisted to the WAL", round)
require.Equal(t, block.Metadata.SimplexProtocolMetadata.Seq, storage.NumBlocks(), "a notarized block should not have been committed")
},
},
{
name: "finalization",
quorumRound: func(t *testing.T, _ common.Logger, block *ParsedBlock, signers []common.NodeID) common.QuorumRound {
finalization, _ := testutil.NewFinalizationRecord(t, &testutil.TestSignatureAggregator{N: len(signers)}, block, signers)
return common.QuorumRound{Block: block, Finalization: &finalization}
},
// A finalized block is committed.
requireReplicated: func(t *testing.T, storage *MockStorage, block metadata.StateMachineBlock) {
seq := block.Metadata.SimplexProtocolMetadata.Seq
waitForNumBlocks(t, storage, seq+1)
committed, ok := storage.blockAt(seq)
require.True(t, ok)
require.Equal(t, block.Digest(), committed.Digest())
},
},
} {
t.Run(tt.name, func(t *testing.T) {
const basePChainHeight = uint64(1)
var first, second [20]byte
rand.Read(first[:])
rand.Read(second[:])
firstNodeID := common.NodeID(first[:])
secondNodeID := common.NodeID(second[:])
// Two validators, so a quorum is both of them: once one of them is down, the other
// cannot commit a block, nor even empty notarize a round, on its own.
validatorSetsAtHeight := map[uint64]metadata.NodeBLSMappings{
basePChainHeight: {
{NodeID: first, BLSKey: []byte{0xaa}, Weight: 1},
{NodeID: second, BLSKey: []byte{0xbb}, Weight: 1},
},
}
pChain := newTestPlatformChain(basePChainHeight, validatorSetsAtHeight)
cops := &testCryptoOps{}
genesisBlock := &testInnerBlock{Height_: 0, TS: time.Now(), Payload: []byte("genesis")}
net := newInMemNetwork(t)
t.Cleanup(net.stop)
// The two validators build a chain together and then both shut down, so that from
// here on the only source of blocks is this test.
storage := newStorageWithGenesis(t, genesisBlock)
storage2 := newStorageWithGenesis(t, genesisBlock)
firstInstance := newInstance(t, firstNodeID, storage, net, pChain, cops, genesisBlock)
secondInstance := newInstance(t, secondNodeID, storage2, net, pChain, cops, genesisBlock)
net.register(firstNodeID, firstInstance)
net.register(secondNodeID, secondInstance)
require.NoError(t, firstInstance.Start(t.Context()))
require.NoError(t, secondInstance.Start(t.Context()))
t.Cleanup(firstInstance.Stop)
t.Cleanup(secondInstance.Stop)
waitForNumBlocks(t, storage, 7)
firstInstance.Stop()
secondInstance.Stop()
require.True(t, firstInstance.isStopped())
require.True(t, secondInstance.isStopped())
replicatedSeq := storage.NumBlocks() - 1
replicated, ok := storage.blockAt(replicatedSeq)
require.True(t, ok)
parent, ok := storage.blockAt(replicatedSeq - 1)
require.True(t, ok)
// The node restored at the parent below sits at the round following the parent's, and
// only processes a replicated round it has reached, so the block it is missing must be
// the one that directly follows its parent's round.
require.Equal(t, parent.Metadata.SimplexProtocolMetadata.Round+1, replicated.Metadata.SimplexProtocolMetadata.Round,
"the chain grew an empty round before its last block")
// The MSM that built the chain - the validator has stopped, so nothing else uses it -
// accepts the block, so we know the block is valid.
msm := firstInstance.msm
// The block we hand the node is that same block with a single defect: a timestamp preceding its parent's.
// Everything else - round, sequence, epoch info, P-chain height, inner block - is left alone,
// so the only thing wrong with it is its state machine transition, which is what the state
// machine rejects and what verifying only the inner block - what a node replicating a
// block does - accepts.
tampered := replicated.Clone()
tampered.Metadata.Timestamp = parent.Metadata.Timestamp - 1
// The MSM rejects the tampered block, so we know the block is invalid.
tamperedBlock := &ParsedBlock{StateMachineBlock: tampered.Clone(), msm: msm}
_, err := tamperedBlock.Verify(context.Background())
require.ErrorContains(t, err, "proposed timestamp is before parent block's timestamp")
_, err = tamperedBlock.Verify(context.Background(), common.OnlyVMVerifyOpt)
require.NoError(t, err)
// Changing the timestamp made it a block neither validator ever built: no sequence of
// either ledger holds it.
for seq := uint64(0); seq < storage.NumBlocks(); seq++ {
for _, ledger := range []*MockStorage{storage, storage2} {
stored, ok := ledger.blockAt(seq)
require.True(t, ok)
require.NotEqual(t, tampered.Digest(), stored.Digest(), "a validator has the tampered block at seq %d", seq)
}
}
// The first validator comes back up lagging the chain by that block, with a paused VM
// and on a network of its own where nobody answers. It can therefore neither build
// the block nor replicate it legitimately, and since its peer is down it cannot reach
// a quorum to empty notarize either: it sits at exactly the round of the block it is
// missing until we hand it one.
laggingStorage := storage.cloneBelow(replicatedSeq)
require.Equal(t, replicatedSeq, laggingStorage.NumBlocks())
_, ok = laggingStorage.blockAt(replicatedSeq)
require.False(t, ok, "the lagging validator already has the block it is meant to replicate")
vm := newTestVM()
vm.pause()
laggingInstance := newInstanceWithVM(t, firstNodeID, laggingStorage, newInMemNetwork(t), pChain, cops, genesisBlock, vm)
require.NoError(t, laggingInstance.Start(t.Context()))
t.Cleanup(laggingInstance.Stop)
// Send precisely that block: the quorum certificate we hand over is on its digest, not
// on the digest of the block the validators built.
block := &ParsedBlock{StateMachineBlock: tampered.Clone()}
quorumRound := tt.quorumRound(t, laggingInstance.Config.Logger, block, []common.NodeID{firstNodeID, secondNodeID})
require.Equal(t, common.Digest(tampered.Digest()), quorumRound.Block.BlockHeader().Digest)
require.NotEqual(t, common.Digest(replicated.Digest()), quorumRound.Block.BlockHeader().Digest)
require.NoError(t, laggingInstance.HandleMessage(&common.Message{
ReplicationResponse: &common.ReplicationResponse{Data: []common.QuorumRound{quorumRound}},
}, secondNodeID))
tt.requireReplicated(t, laggingStorage, tampered)
})
}
}
// requireTipIsSealing asserts whether the last block in storage is a sealing block.
func requireTipIsSealing(t *testing.T, storage *MockStorage, want bool) {
t.Helper()
num := storage.NumBlocks()
require.Positive(t, num)
block, ok := storage.blockAt(num - 1)
require.True(t, ok)
require.Equal(t, want, block.SealingBlockInfo() != nil)
}
// countSealingBlocks returns the number of sealing blocks (blocks carrying a
// BlockValidationDescriptor) currently in storage.
func countSealingBlocks(t *testing.T, storage *MockStorage) int {
t.Helper()
count := 0
num := storage.NumBlocks()
for seq := uint64(0); seq < num; seq++ {
block, ok := storage.blockAt(seq)
if !ok {
continue
}
if block.SealingBlockInfo() != nil {
count++
}
}
return count
}
// waitForSealingBlockCount waits until storage holds at least target sealing blocks.
func waitForSealingBlockCount(t *testing.T, storage *MockStorage, target int) {
t.Helper()
require.Eventually(t, func() bool {
return countSealingBlocks(t, storage) >= target
}, 20*time.Second, 100*time.Millisecond)
}
// newStorageWithGenesis returns storage holding only the genesis block, the ledger every node
// here starts from.
func newStorageWithGenesis(t *testing.T, genesisBlock *testInnerBlock) *MockStorage {
t.Helper()
storage := NewMockStorage(t)
genesis := &ParsedBlock{StateMachineBlock: metadata.StateMachineBlock{InnerBlock: genesisBlock}}
require.NoError(t, storage.Index(context.Background(), genesis, common.Finalization{}))
return storage
}
// newInstance builds an Instance sharing the common test dependencies but with its own ID,
// storage and VM.
func newInstance(t *testing.T, nodeID common.NodeID, storage *MockStorage, net *inMemNetwork, pChain *testPlatformChain, cops *testCryptoOps, genesisBlock *testInnerBlock) *Instance {
return newInstanceWithVM(t, nodeID, storage, net, pChain, cops, genesisBlock, newTestVM())
}
// newInstanceWithVM is like newInstance but uses a caller-supplied VM, so a test
// can share one controllable VM across restarts of the same node.
func newInstanceWithVM(t *testing.T, nodeID common.NodeID, storage *MockStorage, net *inMemNetwork, pChain *testPlatformChain, cops *testCryptoOps, genesisBlock *testInnerBlock, vm *testVM) *Instance {
comm := &networkSender{net: net, self: nodeID}
config := Config{
Logger: testutil.MakeLogger(t, int(nodeID[0])),
ID: nodeID,
VM: vm,
Storage: storage,
ICMETransition: vm.ComputeICMEpoch,
Sender: comm,
Broadcaster: comm,
PlatformChain: pChain,
CryptoOps: cops,
LastNonSimplexInnerBlock: genesisBlock,
WalCreator: storage.CreateWAL,
ParameterConfig: ParameterConfig{
MaxNetworkDelay: 500 * time.Millisecond,
MaxRoundWindow: 100,
WALMaxSizeBytes: 1024,
},
}
return NewInstance(config)
}
func latestValidatorID(t *testing.T, storage *MockStorage) common.NodeID {
t.Helper()
num := storage.NumBlocks()
// Iterate backwards and find the latest sealing block (a block with a block validation descriptor)
for seq := int64(num) - 1; seq >= 0; seq-- {
block, ok := storage.blockAt(uint64(seq))
if !ok {
continue
}
if info := block.SealingBlockInfo(); info != nil {
return info.ValidatorSet[len(info.ValidatorSet)-1].Id
}
}
t.Fatalf("no block with a BlockValidationDescriptor found in storage")
return nil
}
// waitForNumBlocks waits until the given storage has at least targetHeight blocks.
func waitForNumBlocks(t *testing.T, storage *MockStorage, targetHeight uint64) {
t.Helper()
require.Eventually(t, func() bool {
return storage.NumBlocks() >= targetHeight
}, 20*time.Second, 100*time.Millisecond, "storage did not commit %d blocks in time", targetHeight)
}
// waitForSealingBlock waits until a sealing block (a block carrying a BlockValidationDescriptor with the new weight)
// is committed at or after fromSeq. It periodically injects approvals into the given instance.
// Returns the seq of the sealing block.
func waitForSealingBlock(t *testing.T, inst *Instance, approval *common.ValidatorSetApproval, fromSeq uint64) uint64 {
t.Helper()
var result uint64
storage := inst.Config.Storage.(*MockStorage)
require.Eventually(t, func() bool {