-
Notifications
You must be signed in to change notification settings - Fork 646
/
state_test.go
882 lines (773 loc) · 26.7 KB
/
state_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
// Copyright (C) 2019-2021, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package chain
import (
"bytes"
"errors"
"fmt"
"testing"
"github.com/prometheus/client_golang/prometheus"
"github.com/stretchr/testify/require"
"github.com/ava-labs/avalanchego/database"
"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/snow/choices"
"github.com/ava-labs/avalanchego/snow/consensus/snowman"
"github.com/ava-labs/avalanchego/utils/hashing"
)
var _ Block = &TestBlock{}
type TestBlock struct {
*snowman.TestBlock
}
// SetStatus sets the status of the Block.
func (b *TestBlock) SetStatus(status choices.Status) { b.TestBlock.TestDecidable.StatusV = status }
// NewTestBlock returns a new test block with height, bytes, and ID derived from [i]
// and using [parentID] as the parent block ID
func NewTestBlock(i uint64, parentID ids.ID) *TestBlock {
b := []byte{byte(i)}
id := hashing.ComputeHash256Array(b)
return &TestBlock{
TestBlock: &snowman.TestBlock{
TestDecidable: choices.TestDecidable{
IDV: id,
StatusV: choices.Unknown,
},
HeightV: i,
ParentV: parentID,
BytesV: b,
},
}
}
// NewTestBlocks generates [numBlocks] consecutive blocks
func NewTestBlocks(numBlocks uint64) []*TestBlock {
blks := make([]*TestBlock, 0, numBlocks)
parentID := ids.Empty
for i := uint64(0); i < numBlocks; i++ {
blks = append(blks, NewTestBlock(i, parentID))
parent := blks[len(blks)-1]
parentID = parent.ID()
}
return blks
}
func createInternalBlockFuncs(t *testing.T, blks []*TestBlock) (func(id ids.ID) (snowman.Block, error), func(b []byte) (snowman.Block, error), func(height uint64) (ids.ID, error)) {
blkMap := make(map[ids.ID]*TestBlock)
blkByteMap := make(map[byte]*TestBlock)
for _, blk := range blks {
blkMap[blk.ID()] = blk
blkBytes := blk.Bytes()
if len(blkBytes) != 1 {
t.Fatalf("Expected block bytes to be length 1, but found %d", len(blkBytes))
}
blkByteMap[blkBytes[0]] = blk
}
getBlock := func(id ids.ID) (snowman.Block, error) {
blk, ok := blkMap[id]
if !ok || !blk.Status().Fetched() {
return nil, database.ErrNotFound
}
return blk, nil
}
parseBlk := func(b []byte) (snowman.Block, error) {
if len(b) != 1 {
return nil, fmt.Errorf("expected block bytes to be length 1, but found %d", len(b))
}
blk, ok := blkByteMap[b[0]]
if !ok {
return nil, fmt.Errorf("parsed unexpected block with bytes %x", b)
}
if blk.Status() == choices.Unknown {
blk.SetStatus(choices.Processing)
}
blkMap[blk.ID()] = blk
return blk, nil
}
getAcceptedBlockIDAtHeight := func(height uint64) (ids.ID, error) {
for _, blk := range blks {
if blk.Height() != height {
continue
}
if blk.Status() == choices.Accepted {
return blk.ID(), nil
}
}
return ids.ID{}, database.ErrNotFound
}
return getBlock, parseBlk, getAcceptedBlockIDAtHeight
}
func cantBuildBlock() (snowman.Block, error) {
return nil, errors.New("can't build new block")
}
// checkProcessingBlock checks that [blk] is of the correct type and is
// correctly uniquified when calling GetBlock and ParseBlock.
func checkProcessingBlock(t *testing.T, s *State, blk snowman.Block) {
if _, ok := blk.(*BlockWrapper); !ok {
t.Fatalf("Expected block to be of type (*BlockWrapper)")
}
parsedBlk, err := s.ParseBlock(blk.Bytes())
if err != nil {
t.Fatalf("Failed to parse verified block due to %s", err)
}
if parsedBlk.ID() != blk.ID() {
t.Fatalf("Expected parsed block to have the same ID as the requested block")
}
if !bytes.Equal(parsedBlk.Bytes(), blk.Bytes()) {
t.Fatalf("Expected parsed block to have the same bytes as the requested block")
}
if status := parsedBlk.Status(); status != choices.Processing {
t.Fatalf("Expected parsed block to have status Processing, but found %s", status)
}
if parsedBlk != blk {
t.Fatalf("Expected parsed block to return a uniquified block")
}
getBlk, err := s.GetBlock(blk.ID())
if err != nil {
t.Fatalf("Unexpected error during GetBlock for processing block %s", err)
}
if getBlk != parsedBlk {
t.Fatalf("Expected GetBlock to return the same unique block as ParseBlock")
}
}
// checkDecidedBlock asserts that [blk] is returned with the correct status by ParseBlock
// and GetBlock.
func checkDecidedBlock(t *testing.T, s *State, blk snowman.Block, expectedStatus choices.Status, cached bool) {
if _, ok := blk.(*BlockWrapper); !ok {
t.Fatalf("Expected block to be of type (*BlockWrapper)")
}
parsedBlk, err := s.ParseBlock(blk.Bytes())
if err != nil {
t.Fatalf("Unexpected error parsing decided block %s", err)
}
if parsedBlk.ID() != blk.ID() {
t.Fatalf("ParseBlock returned block with unexpected ID %s, expected %s", parsedBlk.ID(), blk.ID())
}
if !bytes.Equal(parsedBlk.Bytes(), blk.Bytes()) {
t.Fatalf("Expected parsed block to have the same bytes as the requested block")
}
if status := parsedBlk.Status(); status != expectedStatus {
t.Fatalf("Expected parsed block to have status %s, but found %s", expectedStatus, status)
}
// If the block should be in the cache, assert that the returned block is identical to [blk]
if cached && parsedBlk != blk {
t.Fatalf("Expected parsed block to have been cached, but retrieved non-unique decided block")
}
getBlk, err := s.GetBlock(blk.ID())
if err != nil {
t.Fatalf("Unexpected error during GetBlock for decided block %s", err)
}
if getBlk.ID() != blk.ID() {
t.Fatalf("GetBlock returned block with unexpected ID %s, expected %s", getBlk.ID(), blk.ID())
}
if !bytes.Equal(getBlk.Bytes(), blk.Bytes()) {
t.Fatalf("Expected block from GetBlock to have the same bytes as the requested block")
}
if status := getBlk.Status(); status != expectedStatus {
t.Fatalf("Expected block from GetBlock to have status %s, but found %s", expectedStatus, status)
}
// Since ParseBlock should have triggered a cache hit, assert that the block is identical
// to the parsed block.
if getBlk != parsedBlk {
t.Fatalf("Expected block returned by GetBlock to have been cached, but retrieved non-unique decided block")
}
}
func checkAcceptedBlock(t *testing.T, s *State, blk snowman.Block, cached bool) {
checkDecidedBlock(t, s, blk, choices.Accepted, cached)
}
func checkRejectedBlock(t *testing.T, s *State, blk snowman.Block, cached bool) {
checkDecidedBlock(t, s, blk, choices.Rejected, cached)
}
func TestState(t *testing.T) {
testBlks := NewTestBlocks(3)
genesisBlock := testBlks[0]
genesisBlock.SetStatus(choices.Accepted)
blk1 := testBlks[1]
blk2 := testBlks[2]
// Need to create a block with a different bytes and hash here
// to generate a conflict with blk2
blk3Bytes := []byte{byte(3)}
blk3ID := hashing.ComputeHash256Array(blk3Bytes)
blk3 := &TestBlock{
TestBlock: &snowman.TestBlock{
TestDecidable: choices.TestDecidable{
IDV: blk3ID,
StatusV: choices.Processing,
},
HeightV: uint64(2),
BytesV: blk3Bytes,
ParentV: blk1.IDV,
},
}
testBlks = append(testBlks, blk3)
getBlock, parseBlock, getCanonicalBlockID := createInternalBlockFuncs(t, testBlks)
chainState := NewState(&Config{
DecidedCacheSize: 2,
MissingCacheSize: 2,
UnverifiedCacheSize: 2,
BytesToIDCacheSize: 2,
LastAcceptedBlock: genesisBlock,
GetBlock: getBlock,
UnmarshalBlock: parseBlock,
BuildBlock: cantBuildBlock,
GetBlockIDAtHeight: getCanonicalBlockID,
})
lastAccepted, err := chainState.LastAccepted()
if err != nil {
t.Fatal(err)
}
if lastAccepted != genesisBlock.ID() {
t.Fatal("Expected last accepted block to be the genesis block")
}
wrappedGenesisBlk, err := chainState.GetBlock(genesisBlock.ID())
if err != nil {
t.Fatalf("Failed to get genesis block due to: %s", err)
}
// Check that a cache miss on a block is handled correctly
if _, err := chainState.GetBlock(blk1.ID()); err == nil {
t.Fatal("expected GetBlock to return an error for blk1 before it's been parsed")
}
if _, err := chainState.GetBlock(blk1.ID()); err == nil {
t.Fatal("expected GetBlock to return an error for blk1 before it's been parsed")
}
// Parse and verify blk1 and blk2
parsedBlk1, err := chainState.ParseBlock(blk1.Bytes())
if err != nil {
t.Fatal("Failed to parse blk1 due to: %w", err)
}
if err := parsedBlk1.Verify(); err != nil {
t.Fatal("Parsed blk1 failed verification unexpectedly due to %w", err)
}
parsedBlk2, err := chainState.ParseBlock(blk2.Bytes())
if err != nil {
t.Fatalf("Failed to parse blk2 due to: %s", err)
}
if err := parsedBlk2.Verify(); err != nil {
t.Fatalf("Parsed blk2 failed verification unexpectedly due to %s", err)
}
// Check that the verified blocks have been placed in the processing map
if numProcessing := len(chainState.verifiedBlocks); numProcessing != 2 {
t.Fatalf("Expected chain state to have 2 processing blocks, but found: %d", numProcessing)
}
parsedBlk3, err := chainState.ParseBlock(blk3.Bytes())
if err != nil {
t.Fatalf("Failed to parse blk3 due to %s", err)
}
getBlk3, err := chainState.GetBlock(blk3.ID())
if err != nil {
t.Fatalf("Failed to get blk3 due to %s", err)
}
require.Equal(t, parsedBlk3.ID(), getBlk3.ID(), "State GetBlock returned the wrong block")
// Check that parsing blk3 does not add it to processing blocks since it has
// not been verified.
if numProcessing := len(chainState.verifiedBlocks); numProcessing != 2 {
t.Fatalf("Expected State to have 2 processing blocks, but found: %d", numProcessing)
}
if err := parsedBlk3.Verify(); err != nil {
t.Fatalf("Parsed blk3 failed verification unexpectedly due to %s", err)
}
// Check that blk3 has been added to processing blocks.
if numProcessing := len(chainState.verifiedBlocks); numProcessing != 3 {
t.Fatalf("Expected chain state to have 3 processing blocks, but found: %d", numProcessing)
}
// Decide the blocks and ensure they are removed from the processing blocks map
if err := parsedBlk1.Accept(); err != nil {
t.Fatal(err)
}
if err := parsedBlk2.Accept(); err != nil {
t.Fatal(err)
}
if err := parsedBlk3.Reject(); err != nil {
t.Fatal(err)
}
if numProcessing := len(chainState.verifiedBlocks); numProcessing != 0 {
t.Fatalf("Expected chain state to have 0 processing blocks, but found: %d", numProcessing)
}
// Check that the last accepted block was updated correctly
lastAcceptedID, err := chainState.LastAccepted()
if err != nil {
t.Fatal(err)
}
if lastAcceptedID != blk2.ID() {
t.Fatal("Expected last accepted block to be blk2")
}
if lastAcceptedID := chainState.LastAcceptedBlock().ID(); lastAcceptedID != blk2.ID() {
t.Fatal("Expected last accepted block to be blk2")
}
// Flush the caches to ensure decided blocks are handled correctly on cache misses.
chainState.Flush()
checkAcceptedBlock(t, chainState, wrappedGenesisBlk, false)
checkAcceptedBlock(t, chainState, parsedBlk1, false)
checkAcceptedBlock(t, chainState, parsedBlk2, false)
checkRejectedBlock(t, chainState, parsedBlk3, false)
}
func TestBuildBlock(t *testing.T) {
testBlks := NewTestBlocks(2)
genesisBlock := testBlks[0]
genesisBlock.SetStatus(choices.Accepted)
blk1 := testBlks[1]
getBlock, parseBlock, getCanonicalBlockID := createInternalBlockFuncs(t, testBlks)
buildBlock := func() (snowman.Block, error) {
// Once the block is built, mark it as processing
blk1.SetStatus(choices.Processing)
return blk1, nil
}
chainState := NewState(&Config{
DecidedCacheSize: 2,
MissingCacheSize: 2,
UnverifiedCacheSize: 2,
BytesToIDCacheSize: 2,
LastAcceptedBlock: genesisBlock,
GetBlock: getBlock,
UnmarshalBlock: parseBlock,
BuildBlock: buildBlock,
GetBlockIDAtHeight: getCanonicalBlockID,
})
builtBlk, err := chainState.BuildBlock()
if err != nil {
t.Fatal(err)
}
require.Len(t, chainState.verifiedBlocks, 0)
if err := builtBlk.Verify(); err != nil {
t.Fatalf("Built block failed verification due to %s", err)
}
require.Len(t, chainState.verifiedBlocks, 1)
checkProcessingBlock(t, chainState, builtBlk)
if err := builtBlk.Accept(); err != nil {
t.Fatalf("Unexpected error while accepting built block %s", err)
}
checkAcceptedBlock(t, chainState, builtBlk, true)
}
func TestStateDecideBlock(t *testing.T) {
testBlks := NewTestBlocks(4)
genesisBlock := testBlks[0]
genesisBlock.SetStatus(choices.Accepted)
badAcceptBlk := testBlks[1]
badAcceptBlk.AcceptV = errors.New("this block should fail on Accept")
badVerifyBlk := testBlks[2]
badVerifyBlk.VerifyV = errors.New("this block should fail verification")
badRejectBlk := testBlks[3]
badRejectBlk.RejectV = errors.New("this block should fail on reject")
getBlock, parseBlock, getCanonicalBlockID := createInternalBlockFuncs(t, testBlks)
chainState := NewState(&Config{
DecidedCacheSize: 2,
MissingCacheSize: 2,
UnverifiedCacheSize: 2,
BytesToIDCacheSize: 2,
LastAcceptedBlock: genesisBlock,
GetBlock: getBlock,
UnmarshalBlock: parseBlock,
BuildBlock: cantBuildBlock,
GetBlockIDAtHeight: getCanonicalBlockID,
})
// Parse badVerifyBlk (which should fail verification)
badBlk, err := chainState.ParseBlock(badVerifyBlk.Bytes())
if err != nil {
t.Fatal(err)
}
if err := badBlk.Verify(); err == nil {
t.Fatal("Bad block should have failed verification")
}
// Ensure a block that fails verification is not marked as processing
require.Len(t, chainState.verifiedBlocks, 0)
// Ensure that an error during block acceptance is propagated correctly
badBlk, err = chainState.ParseBlock(badAcceptBlk.Bytes())
if err != nil {
t.Fatal(err)
}
if err := badBlk.Verify(); err != nil {
t.Fatal(err)
}
require.Len(t, chainState.verifiedBlocks, 1)
if err := badBlk.Accept(); err == nil {
t.Fatal("Block should have errored on Accept")
}
// Ensure that an error during block reject is propagated correctly
badBlk, err = chainState.ParseBlock(badRejectBlk.Bytes())
if err != nil {
t.Fatal(err)
}
if err := badBlk.Verify(); err != nil {
t.Fatal(err)
}
// Note: an error during block Accept/Reject is fatal, so it is undefined whether
// the block that failed on Accept should be removed from processing or not. We allow
// either case here to make this test more flexible.
if numProcessing := len(chainState.verifiedBlocks); numProcessing > 2 || numProcessing == 0 {
t.Fatalf("Expected number of processing blocks to be either 1 or 2, but found %d", numProcessing)
}
if err := badBlk.Reject(); err == nil {
t.Fatal("Block should have errored on Reject")
}
}
func TestStateParent(t *testing.T) {
testBlks := NewTestBlocks(3)
genesisBlock := testBlks[0]
genesisBlock.SetStatus(choices.Accepted)
blk1 := testBlks[1]
blk2 := testBlks[2]
getBlock, parseBlock, getCanonicalBlockID := createInternalBlockFuncs(t, testBlks)
chainState := NewState(&Config{
DecidedCacheSize: 2,
MissingCacheSize: 2,
UnverifiedCacheSize: 2,
BytesToIDCacheSize: 2,
LastAcceptedBlock: genesisBlock,
GetBlock: getBlock,
UnmarshalBlock: parseBlock,
BuildBlock: cantBuildBlock,
GetBlockIDAtHeight: getCanonicalBlockID,
})
parsedBlk2, err := chainState.ParseBlock(blk2.Bytes())
if err != nil {
t.Fatal(err)
}
missingBlk1ID := parsedBlk2.Parent()
if _, err := chainState.GetBlock(missingBlk1ID); err == nil {
t.Fatalf("Expected parent of blk2 to be not found")
}
parsedBlk1, err := chainState.ParseBlock(blk1.Bytes())
if err != nil {
t.Fatal(err)
}
genesisBlkParentID := parsedBlk1.Parent()
genesisBlkParent, err := chainState.GetBlock(genesisBlkParentID)
if err != nil {
t.Fatal(err)
}
checkAcceptedBlock(t, chainState, genesisBlkParent, true)
parentBlk1ID := parsedBlk2.Parent()
parentBlk1, err := chainState.GetBlock(parentBlk1ID)
if err != nil {
t.Fatal(err)
}
checkProcessingBlock(t, chainState, parentBlk1)
}
func TestGetBlockInternal(t *testing.T) {
testBlks := NewTestBlocks(1)
genesisBlock := testBlks[0]
genesisBlock.SetStatus(choices.Accepted)
getBlock, parseBlock, getCanonicalBlockID := createInternalBlockFuncs(t, testBlks)
chainState := NewState(&Config{
DecidedCacheSize: 2,
MissingCacheSize: 2,
UnverifiedCacheSize: 2,
BytesToIDCacheSize: 2,
LastAcceptedBlock: genesisBlock,
GetBlock: getBlock,
UnmarshalBlock: parseBlock,
BuildBlock: cantBuildBlock,
GetBlockIDAtHeight: getCanonicalBlockID,
})
genesisBlockInternal := chainState.LastAcceptedBlockInternal()
if _, ok := genesisBlockInternal.(*TestBlock); !ok {
t.Fatalf("Expected LastAcceptedBlockInternal to return a block of type *snowman.TestBlock, but found %T", genesisBlockInternal)
}
if genesisBlockInternal.ID() != genesisBlock.ID() {
t.Fatalf("Expected LastAcceptedBlockInternal to be blk %s, but found %s", genesisBlock.ID(), genesisBlockInternal.ID())
}
blk, err := chainState.GetBlockInternal(genesisBlock.ID())
if err != nil {
t.Fatal(err)
}
if _, ok := blk.(*TestBlock); !ok {
t.Fatalf("Expected retrieved block to return a block of type *snowman.TestBlock, but found %T", blk)
}
if blk.ID() != genesisBlock.ID() {
t.Fatalf("Expected GetBlock to be blk %s, but found %s", genesisBlock.ID(), blk.ID())
}
}
func TestGetBlockError(t *testing.T) {
testBlks := NewTestBlocks(2)
genesisBlock := testBlks[0]
genesisBlock.SetStatus(choices.Accepted)
blk1 := testBlks[1]
getBlock, parseBlock, getCanonicalBlockID := createInternalBlockFuncs(t, testBlks)
wrappedGetBlock := func(id ids.ID) (snowman.Block, error) {
blk, err := getBlock(id)
if err != nil {
return nil, fmt.Errorf("wrapping error to prevent caching miss: %w", err)
}
return blk, nil
}
chainState := NewState(&Config{
DecidedCacheSize: 2,
MissingCacheSize: 2,
UnverifiedCacheSize: 2,
BytesToIDCacheSize: 2,
LastAcceptedBlock: genesisBlock,
GetBlock: wrappedGetBlock,
UnmarshalBlock: parseBlock,
BuildBlock: cantBuildBlock,
GetBlockIDAtHeight: getCanonicalBlockID,
})
_, err := chainState.GetBlock(blk1.ID())
if err == nil {
t.Fatal("Expected GetBlock to return an error for unknown block")
}
// Update the status to Processing, so that it will be returned by the internal get block
// function.
blk1.SetStatus(choices.Processing)
blk, err := chainState.GetBlock(blk1.ID())
if err != nil {
t.Fatal(err)
}
if blk.ID() != blk1.ID() {
t.Fatalf("Expected GetBlock to retrieve %s, but found %s", blk1.ID(), blk.ID())
}
checkProcessingBlock(t, chainState, blk)
}
func TestParseBlockError(t *testing.T) {
testBlks := NewTestBlocks(1)
genesisBlock := testBlks[0]
genesisBlock.SetStatus(choices.Accepted)
getBlock, parseBlock, getCanonicalBlockID := createInternalBlockFuncs(t, testBlks)
chainState := NewState(&Config{
DecidedCacheSize: 2,
MissingCacheSize: 2,
UnverifiedCacheSize: 2,
BytesToIDCacheSize: 2,
LastAcceptedBlock: genesisBlock,
GetBlock: getBlock,
UnmarshalBlock: parseBlock,
BuildBlock: cantBuildBlock,
GetBlockIDAtHeight: getCanonicalBlockID,
})
blk, err := chainState.ParseBlock([]byte{255})
if err == nil {
t.Fatalf("Expected ParseBlock to return an error parsing an invalid block but found block of type %T", blk)
}
}
func TestBuildBlockError(t *testing.T) {
testBlks := NewTestBlocks(1)
genesisBlock := testBlks[0]
genesisBlock.SetStatus(choices.Accepted)
getBlock, parseBlock, getCanonicalBlockID := createInternalBlockFuncs(t, testBlks)
chainState := NewState(&Config{
DecidedCacheSize: 2,
MissingCacheSize: 2,
UnverifiedCacheSize: 2,
BytesToIDCacheSize: 2,
LastAcceptedBlock: genesisBlock,
GetBlock: getBlock,
UnmarshalBlock: parseBlock,
BuildBlock: cantBuildBlock,
GetBlockIDAtHeight: getCanonicalBlockID,
})
blk, err := chainState.BuildBlock()
if err == nil {
t.Fatalf("Expected BuildBlock to return an error but found block of type %T", blk)
}
}
func TestMeteredCache(t *testing.T) {
registry := prometheus.NewRegistry()
testBlks := NewTestBlocks(1)
genesisBlock := testBlks[0]
genesisBlock.SetStatus(choices.Accepted)
getBlock, parseBlock, getCanonicalBlockID := createInternalBlockFuncs(t, testBlks)
config := &Config{
DecidedCacheSize: 2,
MissingCacheSize: 2,
UnverifiedCacheSize: 2,
BytesToIDCacheSize: 2,
LastAcceptedBlock: genesisBlock,
GetBlock: getBlock,
UnmarshalBlock: parseBlock,
BuildBlock: cantBuildBlock,
GetBlockIDAtHeight: getCanonicalBlockID,
}
_, err := NewMeteredState(registry, config)
if err != nil {
t.Fatal(err)
}
_, err = NewMeteredState(registry, config)
if err == nil {
t.Fatal("Expected creating a second NewMeteredState to error due to a registry conflict")
}
}
// Test the bytesToIDCache
func TestStateBytesToIDCache(t *testing.T) {
testBlks := NewTestBlocks(3)
genesisBlock := testBlks[0]
genesisBlock.SetStatus(choices.Accepted)
blk1 := testBlks[1]
blk2 := testBlks[2]
getBlock, parseBlock, getCanonicalBlockID := createInternalBlockFuncs(t, testBlks)
buildBlock := func() (snowman.Block, error) {
t.Fatal("shouldn't have been called")
return nil, errors.New("")
}
chainState := NewState(&Config{
DecidedCacheSize: 0,
MissingCacheSize: 0,
UnverifiedCacheSize: 0,
BytesToIDCacheSize: 1,
LastAcceptedBlock: genesisBlock,
GetBlock: getBlock,
UnmarshalBlock: parseBlock,
BuildBlock: buildBlock,
GetBlockIDAtHeight: getCanonicalBlockID,
})
// Shouldn't have blk1 ID to start with
_, err := chainState.GetBlock(blk1.ID())
require.Error(t, err)
_, ok := chainState.bytesToIDCache.Get(string(blk1.Bytes()))
require.False(t, ok)
// Parse blk1 from bytes
_, err = chainState.ParseBlock(blk1.Bytes())
require.NoError(t, err)
// blk1 should be in cache now
_, ok = chainState.bytesToIDCache.Get(string(blk1.Bytes()))
require.True(t, ok)
// Parse another block
_, err = chainState.ParseBlock(blk2.Bytes())
require.NoError(t, err)
// Should have bumped blk1 from cache
_, ok = chainState.bytesToIDCache.Get(string(blk2.Bytes()))
require.True(t, ok)
_, ok = chainState.bytesToIDCache.Get(string(blk1.Bytes()))
require.False(t, ok)
}
// TestSetLastAcceptedBlock ensures chainState's last accepted block
// can be updated by calling [SetLastAcceptedBlock].
func TestSetLastAcceptedBlock(t *testing.T) {
testBlks := NewTestBlocks(1)
genesisBlock := testBlks[0]
genesisBlock.SetStatus(choices.Accepted)
postSetBlk1ParentID := hashing.ComputeHash256Array([]byte{byte(199)})
postSetBlk1Bytes := []byte{byte(200)}
postSetBlk2Bytes := []byte{byte(201)}
postSetBlk1 := &TestBlock{
TestBlock: &snowman.TestBlock{
TestDecidable: choices.TestDecidable{
IDV: hashing.ComputeHash256Array(postSetBlk1Bytes),
StatusV: choices.Accepted,
},
HeightV: uint64(200),
BytesV: postSetBlk1Bytes,
ParentV: postSetBlk1ParentID,
},
}
postSetBlk2 := &TestBlock{
TestBlock: &snowman.TestBlock{
TestDecidable: choices.TestDecidable{
IDV: hashing.ComputeHash256Array(postSetBlk2Bytes),
StatusV: choices.Processing,
},
HeightV: uint64(201),
BytesV: postSetBlk2Bytes,
ParentV: postSetBlk1.IDV,
},
}
// note we do not need to parse postSetBlk1 so it is omitted here
testBlks = append(testBlks, postSetBlk2)
getBlock, parseBlock, getCanonicalBlockID := createInternalBlockFuncs(t, testBlks)
chainState := NewState(&Config{
LastAcceptedBlock: genesisBlock,
GetBlock: getBlock,
UnmarshalBlock: parseBlock,
BuildBlock: cantBuildBlock,
GetBlockIDAtHeight: getCanonicalBlockID,
})
lastAcceptedID, err := chainState.LastAccepted()
if err != nil {
t.Fatal(err)
}
if lastAcceptedID != genesisBlock.ID() {
t.Fatal("Expected last accepted block to be the genesis block")
}
// call SetLastAcceptedBlock for postSetBlk1
if err := chainState.SetLastAcceptedBlock(postSetBlk1); err != nil {
t.Fatal(err)
}
lastAcceptedID, err = chainState.LastAccepted()
if err != nil {
t.Fatal(err)
}
if lastAcceptedID != postSetBlk1.ID() {
t.Fatal("Expected last accepted block to be postSetBlk1")
}
if lastAcceptedID = chainState.LastAcceptedBlock().ID(); lastAcceptedID != postSetBlk1.ID() {
t.Fatal("Expected last accepted block to be postSetBlk1")
}
// ensure further blocks can be accepted
parsedpostSetBlk2, err := chainState.ParseBlock(postSetBlk2.Bytes())
if err != nil {
t.Fatal("Failed to parse postSetBlk2 due to: %w", err)
}
if err := parsedpostSetBlk2.Verify(); err != nil {
t.Fatal("Parsed postSetBlk2 failed verification unexpectedly due to %w", err)
}
if err := parsedpostSetBlk2.Accept(); err != nil {
t.Fatal(err)
}
lastAcceptedID, err = chainState.LastAccepted()
if err != nil {
t.Fatal(err)
}
if lastAcceptedID != postSetBlk2.ID() {
t.Fatal("Expected last accepted block to be postSetBlk2")
}
if lastAcceptedID = chainState.LastAcceptedBlock().ID(); lastAcceptedID != postSetBlk2.ID() {
t.Fatal("Expected last accepted block to be postSetBlk2")
}
checkAcceptedBlock(t, chainState, parsedpostSetBlk2, false)
}
func TestSetLastAcceptedBlockWithProcessingBlocksErrors(t *testing.T) {
testBlks := NewTestBlocks(5)
genesisBlock := testBlks[0]
genesisBlock.SetStatus(choices.Accepted)
blk1 := testBlks[1]
resetBlk := testBlks[4]
getBlock, parseBlock, getCanonicalBlockID := createInternalBlockFuncs(t, testBlks)
buildBlock := func() (snowman.Block, error) {
// Once the block is built, mark it as processing
blk1.SetStatus(choices.Processing)
return blk1, nil
}
chainState := NewState(&Config{
DecidedCacheSize: 2,
MissingCacheSize: 2,
UnverifiedCacheSize: 2,
BytesToIDCacheSize: 2,
LastAcceptedBlock: genesisBlock,
GetBlock: getBlock,
UnmarshalBlock: parseBlock,
BuildBlock: buildBlock,
GetBlockIDAtHeight: getCanonicalBlockID,
})
builtBlk, err := chainState.BuildBlock()
if err != nil {
t.Fatal(err)
}
require.Len(t, chainState.verifiedBlocks, 0)
if err := builtBlk.Verify(); err != nil {
t.Fatalf("Built block failed verification due to %s", err)
}
require.Len(t, chainState.verifiedBlocks, 1)
checkProcessingBlock(t, chainState, builtBlk)
require.Error(t, chainState.SetLastAcceptedBlock(resetBlk), "should have errored resetting chain state with processing block")
}
func TestStateParseTransitivelyAcceptedBlock(t *testing.T) {
testBlks := NewTestBlocks(3)
genesisBlock := testBlks[0]
genesisBlock.SetStatus(choices.Accepted)
blk1 := testBlks[1]
blk2 := testBlks[2]
blk2.SetStatus(choices.Accepted)
getBlock, parseBlock, getCanonicalBlockID := createInternalBlockFuncs(t, testBlks)
chainState := NewState(&Config{
DecidedCacheSize: 2,
MissingCacheSize: 2,
UnverifiedCacheSize: 2,
BytesToIDCacheSize: 2,
LastAcceptedBlock: blk2,
GetBlock: getBlock,
UnmarshalBlock: parseBlock,
BuildBlock: cantBuildBlock,
GetBlockIDAtHeight: getCanonicalBlockID,
})
parsedBlk1, err := chainState.ParseBlock(blk1.Bytes())
if err != nil {
t.Fatalf("Failed to parse blk1 due to: %s", err)
}
if blk1.Height() != parsedBlk1.Height() {
t.Fatalf("Parsed blk1 reported incorrect height. Expected %d got %d", blk1.Height(), parsedBlk1.Height())
}
}