-
Notifications
You must be signed in to change notification settings - Fork 184
/
blockmanager_test.go
947 lines (805 loc) · 25.4 KB
/
blockmanager_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
package neutrino
import (
"encoding/binary"
"fmt"
"math/rand"
"reflect"
"strings"
"testing"
"time"
"github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcd/btcutil/gcs"
"github.com/btcsuite/btcd/btcutil/gcs/builder"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/integration/rpctest"
"github.com/btcsuite/btcd/peer"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcwallet/walletdb"
"github.com/lightninglabs/neutrino/banman"
"github.com/lightninglabs/neutrino/blockntfns"
"github.com/lightninglabs/neutrino/headerfs"
"github.com/lightninglabs/neutrino/query"
"github.com/stretchr/testify/require"
)
const (
// maxHeight is the height we will generate filter headers up to. We use
// an odd number of checkpoints to ensure we can test cases where the
// block manager is only able to fetch filter headers for one checkpoint
// interval rather than two.
maxHeight = 21 * uint32(wire.CFCheckptInterval)
dbOpenTimeout = time.Second * 10
)
// mockDispatcher implements the query.Dispatcher interface and allows us to
// set up a custom Query method during tests.
type mockDispatcher struct {
query.WorkManager
query func(requests []*query.Request,
options ...query.QueryOption) chan error
}
var _ query.Dispatcher = (*mockDispatcher)(nil)
func (m *mockDispatcher) Query(requests []*query.Request,
options ...query.QueryOption) chan error {
return m.query(requests, options...)
}
// setupBlockManager initialises a blockManager to be used in tests.
func setupBlockManager(t *testing.T) (*blockManager, headerfs.BlockHeaderStore,
*headerfs.FilterHeaderStore, error) {
// Set up the block and filter header stores.
tempDir := t.TempDir()
db, err := walletdb.Create(
"bdb", tempDir+"/weks.db", true, dbOpenTimeout,
)
if err != nil {
return nil, nil, nil, fmt.Errorf("error opening DB: %s", err)
}
t.Cleanup(func() {
require.NoError(t, db.Close())
})
hdrStore, err := headerfs.NewBlockHeaderStore(
tempDir, db, &chaincfg.SimNetParams,
)
if err != nil {
return nil, nil, nil, fmt.Errorf("error creating block "+
"header store: %s", err)
}
cfStore, err := headerfs.NewFilterHeaderStore(
tempDir, db, headerfs.RegularFilter, &chaincfg.SimNetParams,
nil,
)
if err != nil {
return nil, nil, nil, fmt.Errorf("error creating filter "+
"header store: %s", err)
}
// Set up a blockManager with the chain service we defined.
bm, err := newBlockManager(&blockManagerCfg{
ChainParams: chaincfg.SimNetParams,
BlockHeaders: hdrStore,
RegFilterHeaders: cfStore,
QueryDispatcher: &mockDispatcher{},
TimeSource: blockchain.NewMedianTime(),
BanPeer: func(string, banman.Reason) error {
return nil
},
})
if err != nil {
return nil, nil, nil, fmt.Errorf("unable to create "+
"blockmanager: %v", err)
}
return bm, hdrStore, cfStore, nil
}
// headers wraps the different headers and filters used throughout the tests.
type headers struct {
blockHeaders []headerfs.BlockHeader
cfHeaders []headerfs.FilterHeader
checkpoints []*chainhash.Hash
filterHashes []chainhash.Hash
}
// generateHeaders generates block headers, filter header and hashes, and
// checkpoints from the given genesis. The onCheckpoint method will be called
// with the current cf header on each checkpoint to modify the derivation of
// the next interval.
func generateHeaders(genesisBlockHeader *wire.BlockHeader,
genesisFilterHeader *chainhash.Hash,
onCheckpoint func(*chainhash.Hash)) (*headers, error) {
var blockHeaders []headerfs.BlockHeader
blockHeaders = append(blockHeaders, headerfs.BlockHeader{
BlockHeader: genesisBlockHeader,
Height: 0,
})
var cfHeaders []headerfs.FilterHeader
cfHeaders = append(cfHeaders, headerfs.FilterHeader{
HeaderHash: genesisBlockHeader.BlockHash(),
FilterHash: *genesisFilterHeader,
Height: 0,
})
// The filter hashes (not the filter headers!) will be sent as
// part of the CFHeaders response, so we also keep track of
// them.
genesisFilter, err := builder.BuildBasicFilter(
chaincfg.SimNetParams.GenesisBlock, nil,
)
if err != nil {
return nil, fmt.Errorf("unable to build genesis filter: %v",
err)
}
genesisFilterHash, err := builder.GetFilterHash(genesisFilter)
if err != nil {
return nil, fmt.Errorf("unable to get genesis filter hash: %v",
err)
}
var filterHashes []chainhash.Hash
filterHashes = append(filterHashes, genesisFilterHash)
// Also keep track of the current filter header. We use this to
// calculate the next filter header, as it commits to the
// previous.
currentCFHeader := *genesisFilterHeader
// checkpoints will be the checkpoints passed to
// getCheckpointedCFHeaders.
var checkpoints []*chainhash.Hash
for height := uint32(1); height <= maxHeight; height++ {
header := heightToHeader(height)
blockHeader := headerfs.BlockHeader{
BlockHeader: header,
Height: height,
}
blockHeaders = append(blockHeaders, blockHeader)
// It doesn't really matter what filter the filter
// header commit to, so just use the height as a nonce
// for the filters.
filterHash := chainhash.Hash{}
binary.BigEndian.PutUint32(filterHash[:], height)
filterHashes = append(filterHashes, filterHash)
// Calculate the current filter header, and add to our
// slice.
currentCFHeader = chainhash.DoubleHashH(
append(filterHash[:], currentCFHeader[:]...),
)
cfHeaders = append(cfHeaders, headerfs.FilterHeader{
HeaderHash: header.BlockHash(),
FilterHash: currentCFHeader,
Height: height,
})
// Each interval we must record a checkpoint.
if height%wire.CFCheckptInterval == 0 {
// We must make a copy of the current header to
// avoid mutation.
cfh := currentCFHeader
checkpoints = append(checkpoints, &cfh)
if onCheckpoint != nil {
onCheckpoint(¤tCFHeader)
}
}
}
return &headers{
blockHeaders: blockHeaders,
cfHeaders: cfHeaders,
checkpoints: checkpoints,
filterHashes: filterHashes,
}, nil
}
// generateResponses generates the MsgCFHeaders messages from the given queries
// and headers.
func generateResponses(msgs []wire.Message,
headers *headers) ([]*wire.MsgCFHeaders, error) {
// Craft a response for each message.
var responses []*wire.MsgCFHeaders
for _, msg := range msgs {
// Only GetCFHeaders expected.
q, ok := msg.(*wire.MsgGetCFHeaders)
if !ok {
return nil, fmt.Errorf("got unexpected message %T",
msg)
}
// The start height must be set to a checkpoint height+1.
if q.StartHeight%wire.CFCheckptInterval != 1 {
return nil, fmt.Errorf("unexpected start height %v",
q.StartHeight)
}
var prevFilterHeader chainhash.Hash
switch q.StartHeight {
// If the start height is 1 the prevFilterHeader is set to the
// genesis header.
case 1:
genesisFilterHeader := headers.cfHeaders[0].FilterHash
prevFilterHeader = genesisFilterHeader
// Otherwise we use one of the created checkpoints.
default:
j := q.StartHeight/wire.CFCheckptInterval - 1
prevFilterHeader = *headers.checkpoints[j]
}
resp := &wire.MsgCFHeaders{
FilterType: q.FilterType,
StopHash: q.StopHash,
PrevFilterHeader: prevFilterHeader,
}
// Keep adding filter hashes until we reach the stop hash.
for h := q.StartHeight; ; h++ {
resp.FilterHashes = append(
resp.FilterHashes, &headers.filterHashes[h],
)
blockHash := headers.blockHeaders[h].BlockHash()
if blockHash == q.StopHash {
break
}
}
responses = append(responses, resp)
}
return responses, nil
}
// TestBlockManagerInitialInterval tests that the block manager is able to
// handle checkpointed filter header query responses in out of order, and when
// a partial interval is already written to the store.
func TestBlockManagerInitialInterval(t *testing.T) {
t.Parallel()
type testCase struct {
// permute indicates whether responses should be permutated.
permute bool
// partialInterval indicates whether we should write parts of
// the first checkpoint interval to the filter header store
// before starting the test.
partialInterval bool
// repeat indicates whether responses should be repeated.
repeat bool
}
// Generate all combinations of testcases.
var testCases []testCase
b := []bool{false, true}
for _, perm := range b {
for _, part := range b {
for _, rep := range b {
testCases = append(testCases, testCase{
permute: perm,
partialInterval: part,
repeat: rep,
})
}
}
}
for _, test := range testCases {
test := test
testDesc := fmt.Sprintf("permute=%v, partial=%v, repeat=%v",
test.permute, test.partialInterval, test.repeat)
bm, hdrStore, cfStore, err := setupBlockManager(t)
if err != nil {
t.Fatalf("unable to set up ChainService: %v", err)
}
// Keep track of the filter headers and block headers. Since
// the genesis headers are written automatically when the store
// is created, we query it to add to the slices.
genesisBlockHeader, _, err := hdrStore.ChainTip()
require.NoError(t, err)
genesisFilterHeader, _, err := cfStore.ChainTip()
require.NoError(t, err)
headers, err := generateHeaders(
genesisBlockHeader, genesisFilterHeader, nil,
)
require.NoError(t, err)
// Write all block headers but the genesis, since it is already
// in the store.
err = hdrStore.WriteHeaders(headers.blockHeaders[1:]...)
require.NoError(t, err)
// We emulate the case where a few filter headers are already
// written to the store by writing 1/3 of the first interval.
if test.partialInterval {
err = cfStore.WriteHeaders(
headers.cfHeaders[1 : wire.CFCheckptInterval/3]...,
)
require.NoError(t, err)
}
// We set up a custom query batch method for this test, as we
// will use this to feed the blockmanager with our crafted
// responses.
bm.cfg.QueryDispatcher.(*mockDispatcher).query = func(
requests []*query.Request,
options ...query.QueryOption) chan error {
var msgs []wire.Message
for _, q := range requests {
msgs = append(msgs, q.Req)
}
responses, err := generateResponses(msgs, headers)
require.NoError(t, err)
// We permute the response order if the test signals
// that.
perm := rand.Perm(len(responses))
errChan := make(chan error, 1)
go func() {
for i, v := range perm {
index := i
if test.permute {
index = v
}
// Before handling the response we take
// copies of the message, as we cannot
// guarantee that it won't be modified.
resp := *responses[index]
resp2 := *responses[index]
// Let the blockmanager handle the
// message.
progress := requests[index].HandleResp(
msgs[index], &resp, "",
)
if !progress.Finished {
errChan <- fmt.Errorf("got "+
"response false on "+
"send of index %d: %v",
index, testDesc)
return
}
// If we are not testing repeated
// responses, go on to the next
// response.
if !test.repeat {
continue
}
// Otherwise resend the response we
// just sent.
progress = requests[index].HandleResp(
msgs[index], &resp2, "",
)
if !progress.Finished {
errChan <- fmt.Errorf("got "+
"response false on "+
"resend of index %d: "+
"%v", index, testDesc)
return
}
}
errChan <- nil
}()
return errChan
}
// We should expect to see notifications for each new filter
// header being connected.
startHeight := uint32(1)
if test.partialInterval {
startHeight = wire.CFCheckptInterval / 3
}
go func() {
for i := startHeight; i <= maxHeight; i++ {
ntfn := <-bm.blockNtfnChan
if _, ok := ntfn.(*blockntfns.Connected); !ok {
t.Error("expected block connected " +
"notification")
return
}
}
}()
// Call the get checkpointed cf headers method with the
// checkpoints we created to start the test.
bm.getCheckpointedCFHeaders(
headers.checkpoints, cfStore, wire.GCSFilterRegular,
)
// Finally make sure the filter header tip is what we expect.
tip, tipHeight, err := cfStore.ChainTip()
require.NoError(t, err)
require.Equal(t, maxHeight, tipHeight, "tip height")
lastCheckpoint := headers.checkpoints[len(headers.checkpoints)-1]
require.Equal(t, *lastCheckpoint, *tip, "tip")
}
}
// TestBlockManagerInvalidInterval tests that the block manager is able to
// determine it is receiving corrupt checkpoints and filter headers.
func TestBlockManagerInvalidInterval(t *testing.T) {
t.Parallel()
type testCase struct {
// wrongGenesis indicates whether we should start deriving the
// filters from a wrong genesis.
wrongGenesis bool
// intervalMisaligned indicates whether each interval prev hash
// should not line up with the previous checkpoint.
intervalMisaligned bool
// invalidPrevHash indicates whether the interval responses
// should have a prev hash that doesn't mathc that interval.
invalidPrevHash bool
// partialInterval indicates whether we should write parts of
// the first checkpoint interval to the filter header store
// before starting the test.
partialInterval bool
// firstInvalid is the first interval response we expect the
// blockmanager to determine is invalid.
firstInvalid int
}
testCases := []testCase{
// With a set of checkpoints and filter headers calculated from
// the wrong genesis, the block manager should be able to
// determine that the first interval doesn't line up.
{
wrongGenesis: true,
firstInvalid: 0,
},
// With checkpoints calculated from the wrong genesis, and a
// partial set of filter headers already written, the first
// interval response should be considered invalid.
{
wrongGenesis: true,
partialInterval: true,
firstInvalid: 0,
},
// With intervals not lining up, the second interval response
// should be determined invalid.
{
intervalMisaligned: true,
firstInvalid: 0,
},
// With misaligned intervals and a partial interval written, the
// second interval response should be considered invalid.
{
intervalMisaligned: true,
partialInterval: true,
firstInvalid: 0,
},
// With responses having invalid prev hashes, the second
// interval response should be deemed invalid.
{
invalidPrevHash: true,
firstInvalid: 1,
},
}
for _, test := range testCases {
test := test
bm, hdrStore, cfStore, err := setupBlockManager(t)
require.NoError(t, err)
// Create a mock peer to prevent panics when attempting to ban
// a peer that served an invalid filter header.
mockPeer := NewServerPeer(&ChainService{}, false)
mockPeer.Peer, err = peer.NewOutboundPeer(
NewPeerConfig(mockPeer), "127.0.0.1:8333",
)
require.NoError(t, err)
// Keep track of the filter headers and block headers. Since
// the genesis headers are written automatically when the store
// is created, we query it to add to the slices.
genesisBlockHeader, _, err := hdrStore.ChainTip()
require.NoError(t, err)
genesisFilterHeader, _, err := cfStore.ChainTip()
require.NoError(t, err)
// To emulate a full node serving us filter headers derived
// from different genesis than what we have, we flip a bit in
// the genesis filter header.
if test.wrongGenesis {
genesisFilterHeader[0] ^= 1
}
headers, err := generateHeaders(
genesisBlockHeader, genesisFilterHeader,
func(currentCFHeader *chainhash.Hash) {
// If we are testing that each interval doesn't
// line up properly with the previous, we flip
// a bit in the current header before
// calculating the next interval checkpoint.
if test.intervalMisaligned {
currentCFHeader[0] ^= 1
}
},
)
require.NoError(t, err)
// Write all block headers but the genesis, since it is already
// in the store.
err = hdrStore.WriteHeaders(headers.blockHeaders[1:]...)
require.NoError(t, err)
// We emulate the case where a few filter headers are already
// written to the store by writing 1/3 of the first interval.
if test.partialInterval {
err = cfStore.WriteHeaders(
headers.cfHeaders[1 : wire.CFCheckptInterval/3]...,
)
require.NoError(t, err)
}
bm.cfg.QueryDispatcher.(*mockDispatcher).query = func(
requests []*query.Request,
options ...query.QueryOption) chan error {
var msgs []wire.Message
for _, q := range requests {
msgs = append(msgs, q.Req)
}
responses, err := generateResponses(msgs, headers)
require.NoError(t, err)
// Since we used the generated checkpoints when
// creating the responses, we must flip the
// PrevFilterHeader bit back before sending them if we
// are checking for misaligned intervals. This to
// ensure we don't hit the invalid prev hash case.
if test.intervalMisaligned {
for i := range responses {
if i == 0 {
continue
}
responses[i].PrevFilterHeader[0] ^= 1
}
}
// If we are testing for intervals with invalid prev
// hashes, we flip a bit to corrupt them, regardless of
// whether we are testing misaligned intervals.
if test.invalidPrevHash {
for i := range responses {
if i == 0 {
continue
}
responses[i].PrevFilterHeader[1] ^= 1
}
}
errChan := make(chan error, 1)
go func() {
// Check that the success of the callback match what we
// expect.
for i := range responses {
progress := requests[i].HandleResp(
msgs[i], responses[i], "",
)
if i == test.firstInvalid {
if progress.Finished {
t.Errorf("expected interval "+
"%d to be invalid", i)
return
}
errChan <- fmt.Errorf("invalid interval")
break
}
if !progress.Finished {
t.Errorf("expected interval %d to be "+
"valid", i)
return
}
}
errChan <- nil
}()
return errChan
}
// We should expect to see notifications for each new filter
// header being connected.
startHeight := uint32(1)
if test.partialInterval {
startHeight = wire.CFCheckptInterval / 3
}
go func() {
for i := startHeight; i <= maxHeight; i++ {
ntfn := <-bm.blockNtfnChan
if _, ok := ntfn.(*blockntfns.Connected); !ok {
t.Error("expected block connected " +
"notification")
return
}
}
}()
// Start the test by calling the get checkpointed cf headers
// method with the checkpoints we created.
bm.getCheckpointedCFHeaders(
headers.checkpoints, cfStore, wire.GCSFilterRegular,
)
}
}
// buildNonPushScriptFilter creates a CFilter with all output scripts except all
// OP_RETURNS with push-only scripts.
//
// NOTE: this is not a valid filter, only for tests.
func buildNonPushScriptFilter(block *wire.MsgBlock) (*gcs.Filter, error) {
blockHash := block.BlockHash()
b := builder.WithKeyHash(&blockHash)
for _, tx := range block.Transactions {
for _, txOut := range tx.TxOut {
// The old version of BIP-158 skipped OP_RETURNs that
// had a push-only script.
if txOut.PkScript[0] == txscript.OP_RETURN &&
txscript.IsPushOnlyScript(txOut.PkScript[1:]) {
continue
}
b.AddEntry(txOut.PkScript)
}
}
return b.Build()
}
// buildAllPkScriptsFilter creates a CFilter with all output scripts, including
// OP_RETURNS.
//
// NOTE: this is not a valid filter, only for tests.
func buildAllPkScriptsFilter(block *wire.MsgBlock) (*gcs.Filter, error) {
blockHash := block.BlockHash()
b := builder.WithKeyHash(&blockHash)
for _, tx := range block.Transactions {
for _, txOut := range tx.TxOut {
// An old version of BIP-158 included all output
// scripts.
b.AddEntry(txOut.PkScript)
}
}
return b.Build()
}
func assertBadPeers(expBad map[string]struct{}, badPeers []string) error {
remBad := make(map[string]struct{})
for p := range expBad {
remBad[p] = struct{}{}
}
for _, p := range badPeers {
_, ok := remBad[p]
if !ok {
return fmt.Errorf("did not expect %v to be bad", p)
}
delete(remBad, p)
}
if len(remBad) != 0 {
return fmt.Errorf("did expect more bad peers")
}
return nil
}
// TestBlockManagerDetectBadPeers checks that we detect bad peers, like peers
// not responding to our filter query, serving inconsistent filters etc.
func TestBlockManagerDetectBadPeers(t *testing.T) {
t.Parallel()
var (
stopHash = chainhash.Hash{}
prev = chainhash.Hash{}
startHeight = uint32(100)
badIndex = uint32(5)
targetIndex = startHeight + badIndex
fType = wire.GCSFilterRegular
filterBytes, _ = correctFilter.NBytes()
filterHash, _ = builder.GetFilterHash(correctFilter)
blockHeader = wire.BlockHeader{}
targetBlockHash = block.BlockHash()
peers = []string{"good1:1", "good2:1", "bad:1", "good3:1"}
expBad = map[string]struct{}{
"bad:1": {},
}
)
testCases := []struct {
// filterAnswers is used by each testcase to set the anwers we
// want each peer to respond with on filter queries.
filterAnswers func(string, map[string]wire.Message)
}{
{
// We let the "bad" peers not respond to the filter
// query. They should be marked bad because they are
// unresponsive. We do this to ensure peers cannot
// only respond to us with headers, and stall our sync
// by not responding to filter requests.
filterAnswers: func(p string,
answers map[string]wire.Message) {
if strings.Contains(p, "bad") {
return
}
answers[p] = wire.NewMsgCFilter(
fType, &targetBlockHash, filterBytes,
)
},
},
{
// We let the "bad" peers serve filters that don't hash
// to the filter headers they have sent.
filterAnswers: func(p string,
answers map[string]wire.Message) {
filterData := filterBytes
if strings.Contains(p, "bad") {
filterData, _ = fakeFilter1.NBytes()
}
answers[p] = wire.NewMsgCFilter(
fType, &targetBlockHash, filterData,
)
},
},
}
for _, test := range testCases {
// Create a mock block header store. We only need to be able to
// serve a header for the target index.
blockHeaders := newMockBlockHeaderStore()
blockHeaders.heights[targetIndex] = blockHeader
// We set up the mock queryAllPeers to only respond according to
// the active testcase.
answers := make(map[string]wire.Message)
queryAllPeers := func(
queryMsg wire.Message,
checkResponse func(sp *ServerPeer, resp wire.Message,
quit chan<- struct{}, peerQuit chan<- struct{}),
options ...QueryOption) {
for p, resp := range answers {
pp, err := peer.NewOutboundPeer(
&peer.Config{}, p,
)
if err != nil {
panic(err)
}
sp := &ServerPeer{
Peer: pp,
}
checkResponse(
sp, resp, make(chan struct{}),
make(chan struct{}),
)
}
}
for _, p := range peers {
test.filterAnswers(p, answers)
}
// For the CFHeaders, we pretend all peers responded with the same
// filter headers.
msg := &wire.MsgCFHeaders{
FilterType: fType,
StopHash: stopHash,
PrevFilterHeader: prev,
}
for i := uint32(0); i < 2*badIndex; i++ {
_ = msg.AddCFHash(&filterHash)
}
headers := make(map[string]*wire.MsgCFHeaders)
for _, p := range peers {
headers[p] = msg
}
bm := &blockManager{
cfg: &blockManagerCfg{
BlockHeaders: blockHeaders,
queryAllPeers: queryAllPeers,
},
}
// Now trying to detect which peers are bad, we should detect the
// bad ones.
badPeers, err := bm.detectBadPeers(
headers, targetIndex, badIndex, fType,
)
require.NoError(t, err)
err = assertBadPeers(expBad, badPeers)
require.NoError(t, err)
}
}
// TestHandleHeaders checks that we handle headers correctly, and that we
// disconnect peers that serve us bad headers (headers that don't connect to
// each other properly).
func TestHandleHeaders(t *testing.T) {
t.Parallel()
// First, we set up a block manager and a fake peer that will act as the
// test's remote peer.
bm, _, _, err := setupBlockManager(t)
require.NoError(t, err)
fakePeer, err := peer.NewOutboundPeer(&peer.Config{}, "fake:123")
require.NoError(t, err)
assertPeerDisconnected := func(shouldBeDisconnected bool) {
// This is quite hacky but works: We expect the peer to be
// disconnected, which sets the unexported "disconnected" field
// to 1.
refValue := reflect.ValueOf(fakePeer).Elem()
foo := refValue.FieldByName("disconnect").Int()
if shouldBeDisconnected {
require.EqualValues(t, 1, foo)
} else {
require.EqualValues(t, 0, foo)
}
}
// We'll want to use actual, real blocks, so we take a miner harness
// that we can use to generate some.
harness, err := rpctest.New(
&chaincfg.SimNetParams, nil, []string{"--txindex"}, "",
)
require.NoError(t, err)
t.Cleanup(func() {
require.NoError(t, harness.TearDown())
})
err = harness.SetUp(false, 0)
require.NoError(t, err)
// Generate 200 valid blocks that we then feed to the block manager.
blockHashes, err := harness.Client.Generate(200)
require.NoError(t, err)
hmsg := &headersMsg{
headers: &wire.MsgHeaders{
Headers: make([]*wire.BlockHeader, len(blockHashes)),
},
peer: &ServerPeer{
Peer: fakePeer,
},
}
for i := range blockHashes {
header, err := harness.Client.GetBlockHeader(blockHashes[i])
require.NoError(t, err)
hmsg.headers.Headers[i] = header
}
// Let's feed in the correct headers. This should work fine and the peer
// should not be disconnected.
bm.handleHeadersMsg(hmsg)
assertPeerDisconnected(false)
// Now scramble the headers and feed them in again. This should cause
// the peer to be disconnected.
rand.Shuffle(len(hmsg.headers.Headers), func(i, j int) {
hmsg.headers.Headers[i], hmsg.headers.Headers[j] =
hmsg.headers.Headers[j], hmsg.headers.Headers[i]
})
bm.handleHeadersMsg(hmsg)
assertPeerDisconnected(true)
}