forked from libp2p/go-libp2p-kad-dht
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dht_test.go
2426 lines (2007 loc) · 61.4 KB
/
dht_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package dht
import (
"bytes"
"context"
"encoding/binary"
"errors"
"fmt"
"math/rand"
"runtime"
"sort"
"strings"
"sync"
"testing"
"time"
"github.com/libp2p/go-libp2p-kad-dht/internal/net"
"github.com/libp2p/go-libp2p-kad-dht/providers"
"github.com/libp2p/go-libp2p/core/crypto"
"github.com/libp2p/go-libp2p/core/event"
"github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/libp2p/go-libp2p/core/peerstore"
"github.com/libp2p/go-libp2p/core/protocol"
"github.com/libp2p/go-libp2p/core/routing"
ma "github.com/multiformats/go-multiaddr"
manet "github.com/multiformats/go-multiaddr/net"
"github.com/multiformats/go-multihash"
"github.com/multiformats/go-multistream"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
test "github.com/libp2p/go-libp2p-kad-dht/internal/testing"
pb "github.com/libp2p/go-libp2p-kad-dht/pb"
u "github.com/ipfs/boxo/util"
"github.com/ipfs/go-cid"
detectrace "github.com/ipfs/go-detect-race"
kb "github.com/libp2p/go-libp2p-kbucket"
record "github.com/libp2p/go-libp2p-record"
bhost "github.com/libp2p/go-libp2p/p2p/host/basic"
swarmt "github.com/libp2p/go-libp2p/p2p/net/swarm/testing"
)
var testCaseCids []cid.Cid
func init() {
for i := 0; i < 100; i++ {
v := fmt.Sprintf("%d -- value", i)
var newCid cid.Cid
switch i % 3 {
case 0:
mhv := u.Hash([]byte(v))
newCid = cid.NewCidV0(mhv)
case 1:
mhv := u.Hash([]byte(v))
newCid = cid.NewCidV1(cid.DagCBOR, mhv)
case 2:
rawMh := make([]byte, 12)
binary.PutUvarint(rawMh, cid.Raw)
binary.PutUvarint(rawMh[1:], 10)
copy(rawMh[2:], []byte(v)[:10])
_, mhv, err := multihash.MHFromBytes(rawMh)
if err != nil {
panic(err)
}
newCid = cid.NewCidV1(cid.Raw, mhv)
}
testCaseCids = append(testCaseCids, newCid)
}
}
type blankValidator struct{}
func (blankValidator) Validate(_ string, _ []byte) error { return nil }
func (blankValidator) Select(_ string, _ [][]byte) (int, error) { return 0, nil }
type testAtomicPutValidator struct {
test.TestValidator
}
// selects the entry with the 'highest' last byte
func (testAtomicPutValidator) Select(_ string, bs [][]byte) (int, error) {
index := -1
max := uint8(0)
for i, b := range bs {
if bytes.Equal(b, []byte("valid")) {
if index == -1 {
index = i
}
continue
}
str := string(b)
n := str[len(str)-1]
if n > max {
max = n
index = i
}
}
if index == -1 {
return -1, errors.New("no rec found")
}
return index, nil
}
var testPrefix = ProtocolPrefix("/test")
func setupDHT(ctx context.Context, t *testing.T, client bool, options ...Option) *IpfsDHT {
baseOpts := []Option{
testPrefix,
NamespacedValidator("v", blankValidator{}),
DisableAutoRefresh(),
}
if client {
baseOpts = append(baseOpts, Mode(ModeClient))
} else {
baseOpts = append(baseOpts, Mode(ModeServer))
}
host, err := bhost.NewHost(swarmt.GenSwarm(t, swarmt.OptDisableReuseport), new(bhost.HostOpts))
require.NoError(t, err)
host.Start()
t.Cleanup(func() { host.Close() })
d, err := New(ctx, host, append(baseOpts, options...)...)
require.NoError(t, err)
t.Cleanup(func() { d.Close() })
return d
}
func setupDHTS(t *testing.T, ctx context.Context, n int, options ...Option) []*IpfsDHT {
addrs := make([]ma.Multiaddr, n)
dhts := make([]*IpfsDHT, n)
peers := make([]peer.ID, n)
sanityAddrsMap := make(map[string]struct{})
sanityPeersMap := make(map[string]struct{})
for i := 0; i < n; i++ {
dhts[i] = setupDHT(ctx, t, false, options...)
peers[i] = dhts[i].PeerID()
addrs[i] = dhts[i].host.Addrs()[0]
if _, lol := sanityAddrsMap[addrs[i].String()]; lol {
t.Fatal("While setting up DHTs address got duplicated.")
} else {
sanityAddrsMap[addrs[i].String()] = struct{}{}
}
if _, lol := sanityPeersMap[peers[i].String()]; lol {
t.Fatal("While setting up DHTs peerid got duplicated.")
} else {
sanityPeersMap[peers[i].String()] = struct{}{}
}
}
return dhts
}
func connectNoSync(t *testing.T, ctx context.Context, a, b *IpfsDHT) {
t.Helper()
idB := b.self
addrB := b.peerstore.Addrs(idB)
if len(addrB) == 0 {
t.Fatal("peers setup incorrectly: no local address")
}
if err := a.host.Connect(ctx, peer.AddrInfo{ID: idB, Addrs: addrB}); err != nil {
t.Fatal(err)
}
}
func wait(t *testing.T, ctx context.Context, a, b *IpfsDHT) {
t.Helper()
// loop until connection notification has been received.
// under high load, this may not happen as immediately as we would like.
for a.routingTable.Find(b.self) == "" {
select {
case <-ctx.Done():
t.Fatal(ctx.Err())
case <-time.After(time.Millisecond * 5):
}
}
}
func connect(t *testing.T, ctx context.Context, a, b *IpfsDHT) {
t.Helper()
connectNoSync(t, ctx, a, b)
wait(t, ctx, a, b)
wait(t, ctx, b, a)
}
func bootstrap(t *testing.T, ctx context.Context, dhts []*IpfsDHT) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
logger.Debugf("refreshing DHTs routing tables...")
// tried async. sequential fares much better. compare:
// 100 async https://gist.github.com/jbenet/56d12f0578d5f34810b2
// 100 sync https://gist.github.com/jbenet/6c59e7c15426e48aaedd
// probably because results compound
start := rand.Intn(len(dhts)) // randomize to decrease bias.
for i := range dhts {
dht := dhts[(start+i)%len(dhts)]
select {
case err := <-dht.RefreshRoutingTable():
if err != nil {
t.Error(err)
}
case <-ctx.Done():
return
}
}
}
// Check to make sure we always signal the RefreshRoutingTable channel.
func TestRefreshMultiple(t *testing.T) {
// TODO: What's with this test? How long should it take and why does RefreshRoutingTable not take a context?
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Second)
defer cancel()
dhts := setupDHTS(t, ctx, 5)
defer func() {
for _, dht := range dhts {
dht.Close()
defer dht.host.Close()
}
}()
for _, dht := range dhts[1:] {
connect(t, ctx, dhts[0], dht)
}
a := dhts[0].RefreshRoutingTable()
time.Sleep(time.Nanosecond)
b := dhts[0].RefreshRoutingTable()
time.Sleep(time.Nanosecond)
c := dhts[0].RefreshRoutingTable()
// make sure that all of these eventually return
select {
case <-a:
case <-ctx.Done():
t.Fatal("first channel didn't signal")
}
select {
case <-b:
case <-ctx.Done():
t.Fatal("second channel didn't signal")
}
select {
case <-c:
case <-ctx.Done():
t.Fatal("third channel didn't signal")
}
}
func TestValueGetSet(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var dhts [5]*IpfsDHT
for i := range dhts {
dhts[i] = setupDHT(ctx, t, false)
defer dhts[i].Close()
defer dhts[i].host.Close()
}
connect(t, ctx, dhts[0], dhts[1])
t.Log("adding value on: ", dhts[0].self)
ctxT, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()
err := dhts[0].PutValue(ctxT, "/v/hello", []byte("world"))
if err != nil {
t.Fatal(err)
}
t.Log("requesting value on dhts: ", dhts[1].self)
ctxT, cancel = context.WithTimeout(ctx, time.Second*2*60)
defer cancel()
val, err := dhts[1].GetValue(ctxT, "/v/hello")
if err != nil {
t.Fatal(err)
}
if string(val) != "world" {
t.Fatalf("Expected 'world' got '%s'", string(val))
}
connect(t, ctx, dhts[2], dhts[0])
connect(t, ctx, dhts[2], dhts[1])
t.Log("requesting value (offline) on dhts: ", dhts[2].self)
vala, err := dhts[2].GetValue(ctxT, "/v/hello", Quorum(0))
if err != nil {
t.Fatal(err)
}
if string(vala) != "world" {
t.Fatalf("Expected 'world' got '%s'", string(vala))
}
t.Log("requesting value (online) on dhts: ", dhts[2].self)
val, err = dhts[2].GetValue(ctxT, "/v/hello")
if err != nil {
t.Fatal(err)
}
if string(val) != "world" {
t.Fatalf("Expected 'world' got '%s'", string(val))
}
for _, d := range dhts[:3] {
connect(t, ctx, dhts[3], d)
}
connect(t, ctx, dhts[4], dhts[3])
t.Log("requesting value (requires peer routing) on dhts: ", dhts[4].self)
val, err = dhts[4].GetValue(ctxT, "/v/hello")
if err != nil {
t.Fatal(err)
}
if string(val) != "world" {
t.Fatalf("Expected 'world' got '%s'", string(val))
}
}
func TestValueSetInvalid(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
dhtA := setupDHT(ctx, t, false)
dhtB := setupDHT(ctx, t, false)
defer dhtA.Close()
defer dhtB.Close()
defer dhtA.host.Close()
defer dhtB.host.Close()
dhtA.Validator.(record.NamespacedValidator)["v"] = test.TestValidator{}
dhtB.Validator.(record.NamespacedValidator)["v"] = blankValidator{}
connect(t, ctx, dhtA, dhtB)
testSetGet := func(val string, failset bool, exp string, experr error) {
t.Helper()
ctxT, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()
err := dhtA.PutValue(ctxT, "/v/hello", []byte(val))
if failset {
if err == nil {
t.Error("expected set to fail")
}
} else {
if err != nil {
t.Error(err)
}
}
ctxT, cancel = context.WithTimeout(ctx, time.Second*2)
defer cancel()
valb, err := dhtB.GetValue(ctxT, "/v/hello")
if err != experr {
t.Errorf("Set/Get %v: Expected %v error but got %v", val, experr, err)
} else if err == nil && string(valb) != exp {
t.Errorf("Expected '%v' got '%s'", exp, string(valb))
}
}
// Expired records should not be set
testSetGet("expired", true, "", routing.ErrNotFound)
// Valid record should be returned
testSetGet("valid", false, "valid", nil)
// Newer record should supersede previous record
testSetGet("newer", false, "newer", nil)
// Attempt to set older record again should be ignored
testSetGet("valid", true, "newer", nil)
}
func TestContextShutDown(t *testing.T) {
t.Skip("This test is flaky, see https://github.com/libp2p/go-libp2p-kad-dht/issues/724.")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
dht := setupDHT(ctx, t, false)
// context is alive
select {
case <-dht.Context().Done():
t.Fatal("context should not be done")
default:
}
// shut down dht
require.NoError(t, dht.Close())
// now context should be done
select {
case <-dht.Context().Done():
default:
t.Fatal("context should be done")
}
}
func TestSearchValue(t *testing.T) {
t.Skip("This test is flaky, see https://github.com/libp2p/go-libp2p-kad-dht/issues/723.")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
dhtA := setupDHT(ctx, t, false)
dhtB := setupDHT(ctx, t, false)
defer dhtA.Close()
defer dhtB.Close()
defer dhtA.host.Close()
defer dhtB.host.Close()
connect(t, ctx, dhtA, dhtB)
dhtA.Validator.(record.NamespacedValidator)["v"] = test.TestValidator{}
dhtB.Validator.(record.NamespacedValidator)["v"] = test.TestValidator{}
ctxT, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()
err := dhtA.PutValue(ctxT, "/v/hello", []byte("valid"))
if err != nil {
t.Error(err)
}
ctxT, cancel = context.WithTimeout(ctx, time.Second*2)
defer cancel()
valCh, err := dhtA.SearchValue(ctxT, "/v/hello", Quorum(0))
if err != nil {
t.Fatal(err)
}
select {
case v := <-valCh:
if string(v) != "valid" {
t.Errorf("expected 'valid', got '%s'", string(v))
}
case <-ctxT.Done():
t.Fatal(ctxT.Err())
}
err = dhtB.PutValue(ctxT, "/v/hello", []byte("newer"))
if err != nil {
t.Error(err)
}
select {
case v := <-valCh:
if string(v) != "newer" {
t.Errorf("expected 'newer', got '%s'", string(v))
}
case <-ctxT.Done():
t.Fatal(ctxT.Err())
}
}
func TestValueGetInvalid(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
dhtA := setupDHT(ctx, t, false)
dhtB := setupDHT(ctx, t, false)
defer dhtA.Close()
defer dhtB.Close()
defer dhtA.host.Close()
defer dhtB.host.Close()
dhtA.Validator.(record.NamespacedValidator)["v"] = blankValidator{}
dhtB.Validator.(record.NamespacedValidator)["v"] = test.TestValidator{}
connect(t, ctx, dhtA, dhtB)
testSetGet := func(val string, exp string, experr error) {
t.Helper()
ctxT, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()
err := dhtA.PutValue(ctxT, "/v/hello", []byte(val))
if err != nil {
t.Error(err)
}
ctxT, cancel = context.WithTimeout(ctx, time.Second*2)
defer cancel()
valb, err := dhtB.GetValue(ctxT, "/v/hello")
if err != experr {
t.Errorf("Set/Get %v: Expected '%v' error but got '%v'", val, experr, err)
} else if err == nil && string(valb) != exp {
t.Errorf("Expected '%v' got '%s'", exp, string(valb))
}
}
// Expired records should not be returned
testSetGet("expired", "", routing.ErrNotFound)
// Valid record should be returned
testSetGet("valid", "valid", nil)
// Newer record should supersede previous record
testSetGet("newer", "newer", nil)
// Attempt to set older record again should be ignored
testSetGet("valid", "newer", nil)
}
func TestProvides(t *testing.T) {
// t.Skip("skipping test to debug another")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
dhts := setupDHTS(t, ctx, 4)
defer func() {
for i := 0; i < 4; i++ {
dhts[i].Close()
defer dhts[i].host.Close()
}
}()
connect(t, ctx, dhts[0], dhts[1])
connect(t, ctx, dhts[1], dhts[2])
connect(t, ctx, dhts[1], dhts[3])
for _, k := range testCaseCids {
logger.Debugf("announcing provider for %s", k)
if err := dhts[3].Provide(ctx, k, true); err != nil {
t.Fatal(err)
}
}
// what is this timeout for? was 60ms before.
time.Sleep(time.Millisecond * 6)
n := 0
for _, c := range testCaseCids {
n = (n + 1) % 3
logger.Debugf("getting providers for %s from %d", c, n)
ctxT, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()
provchan := dhts[n].FindProvidersAsync(ctxT, c, 1)
select {
case prov := <-provchan:
if prov.ID == "" {
t.Fatal("Got back nil provider")
}
if prov.ID != dhts[3].self {
t.Fatal("Got back wrong provider")
}
if len(prov.Addrs) == 0 {
t.Fatal("Got no addresses back")
}
case <-ctxT.Done():
t.Fatal("Did not get a provider back.")
}
}
}
type testMessageSender struct {
sendRequest func(ctx context.Context, p peer.ID, pmes *pb.Message) (*pb.Message, error)
sendMessage func(ctx context.Context, p peer.ID, pmes *pb.Message) error
}
var _ pb.MessageSender = (*testMessageSender)(nil)
func (t testMessageSender) SendRequest(ctx context.Context, p peer.ID, pmes *pb.Message) (*pb.Message, error) {
return t.sendRequest(ctx, p, pmes)
}
func (t testMessageSender) SendMessage(ctx context.Context, p peer.ID, pmes *pb.Message) error {
return t.sendMessage(ctx, p, pmes)
}
func TestProvideAddressFilter(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
dhts := setupDHTS(t, ctx, 2)
connect(t, ctx, dhts[0], dhts[1])
testMaddr := ma.StringCast("/ip4/99.99.99.99/tcp/9999")
done := make(chan struct{})
impl := net.NewMessageSenderImpl(dhts[0].host, dhts[0].protocols)
tms := &testMessageSender{
sendMessage: func(ctx context.Context, p peer.ID, pmes *pb.Message) error {
defer close(done)
assert.Equal(t, pmes.Type, pb.Message_ADD_PROVIDER)
assert.Len(t, pmes.ProviderPeers[0].Addrs, 1)
assert.True(t, pmes.ProviderPeers[0].Addresses()[0].Equal(testMaddr))
return impl.SendMessage(ctx, p, pmes)
},
sendRequest: func(ctx context.Context, p peer.ID, pmes *pb.Message) (*pb.Message, error) {
return impl.SendRequest(ctx, p, pmes)
},
}
pm, err := pb.NewProtocolMessenger(tms)
require.NoError(t, err)
dhts[0].protoMessenger = pm
dhts[0].addrFilter = func(multiaddrs []ma.Multiaddr) []ma.Multiaddr {
return []ma.Multiaddr{testMaddr}
}
if err := dhts[0].Provide(ctx, testCaseCids[0], true); err != nil {
t.Fatal(err)
}
select {
case <-done:
case <-time.After(5 * time.Second):
t.Fatal("timeout")
}
}
type testProviderManager struct {
addProvider func(ctx context.Context, key []byte, prov peer.AddrInfo) error
getProviders func(ctx context.Context, key []byte) ([]peer.AddrInfo, error)
close func() error
}
var _ providers.ProviderStore = (*testProviderManager)(nil)
func (t *testProviderManager) AddProvider(ctx context.Context, key []byte, prov peer.AddrInfo) error {
return t.addProvider(ctx, key, prov)
}
func (t *testProviderManager) GetProviders(ctx context.Context, key []byte) ([]peer.AddrInfo, error) {
return t.getProviders(ctx, key)
}
func (t *testProviderManager) Close() error {
return t.close()
}
func TestHandleAddProviderAddressFilter(t *testing.T) {
ctx := context.Background()
d := setupDHT(ctx, t, false)
provider := setupDHT(ctx, t, false)
testMaddr := ma.StringCast("/ip4/99.99.99.99/tcp/9999")
d.addrFilter = func(multiaddrs []ma.Multiaddr) []ma.Multiaddr {
return []ma.Multiaddr{testMaddr}
}
done := make(chan struct{})
d.providerStore = &testProviderManager{
addProvider: func(ctx context.Context, key []byte, prov peer.AddrInfo) error {
defer close(done)
assert.True(t, prov.Addrs[0].Equal(testMaddr))
return nil
},
close: func() error { return nil },
}
pmes := &pb.Message{
Type: pb.Message_ADD_PROVIDER,
Key: []byte("test-key"),
ProviderPeers: pb.RawPeerInfosToPBPeers([]peer.AddrInfo{{
ID: provider.self,
Addrs: []ma.Multiaddr{
ma.StringCast("/ip4/55.55.55.55/tcp/5555"),
ma.StringCast("/ip4/66.66.66.66/tcp/6666"),
},
}}),
}
_, err := d.handleAddProvider(ctx, provider.self, pmes)
require.NoError(t, err)
select {
case <-done:
case <-time.After(5 * time.Second):
t.Fatal("timeout")
}
}
func TestLocalProvides(t *testing.T) {
// t.Skip("skipping test to debug another")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
dhts := setupDHTS(t, ctx, 4)
defer func() {
for i := 0; i < 4; i++ {
dhts[i].Close()
defer dhts[i].host.Close()
}
}()
connect(t, ctx, dhts[0], dhts[1])
connect(t, ctx, dhts[1], dhts[2])
connect(t, ctx, dhts[1], dhts[3])
for _, k := range testCaseCids {
logger.Debugf("announcing provider for %s", k)
if err := dhts[3].Provide(ctx, k, false); err != nil {
t.Fatal(err)
}
}
time.Sleep(time.Millisecond * 10)
for _, c := range testCaseCids {
for i := 0; i < 3; i++ {
provs, _ := dhts[i].ProviderStore().GetProviders(ctx, c.Hash())
if len(provs) > 0 {
t.Fatal("shouldnt know this")
}
}
}
}
func TestAddressFilterProvide(t *testing.T) {
// t.Skip("skipping test to debug another")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
testMaddr := ma.StringCast("/ip4/99.99.99.99/tcp/9999")
d := setupDHT(ctx, t, false)
provider := setupDHT(ctx, t, false)
d.addrFilter = func(maddrs []ma.Multiaddr) []ma.Multiaddr {
return []ma.Multiaddr{
testMaddr,
}
}
_, err := d.handleAddProvider(ctx, provider.self, &pb.Message{
Type: pb.Message_ADD_PROVIDER,
Key: []byte("random-key"),
ProviderPeers: pb.PeerInfosToPBPeers(provider.host.Network(), []peer.AddrInfo{{
ID: provider.self,
Addrs: provider.host.Addrs(),
}}),
})
require.NoError(t, err)
// because of the identify protocol we add all
// addresses to the peerstore, although the addresses
// will be filtered in the above handleAddProvider call
d.peerstore.AddAddrs(provider.self, provider.host.Addrs(), time.Hour)
resp, err := d.handleGetProviders(ctx, d.self, &pb.Message{
Type: pb.Message_GET_PROVIDERS,
Key: []byte("random-key"),
})
require.NoError(t, err)
assert.True(t, resp.ProviderPeers[0].Addresses()[0].Equal(testMaddr))
assert.Len(t, resp.ProviderPeers[0].Addresses(), 1)
}
// if minPeers or avgPeers is 0, dont test for it.
func waitForWellFormedTables(t *testing.T, dhts []*IpfsDHT, minPeers, avgPeers int, timeout time.Duration) {
// test "well-formed-ness" (>= minPeers peers in every routing table)
t.Helper()
timeoutA := time.After(timeout)
for {
select {
case <-timeoutA:
t.Errorf("failed to reach well-formed routing tables after %s", timeout)
return
case <-time.After(5 * time.Millisecond):
if checkForWellFormedTablesOnce(t, dhts, minPeers, avgPeers) {
// succeeded
return
}
}
}
}
func checkForWellFormedTablesOnce(t *testing.T, dhts []*IpfsDHT, minPeers, avgPeers int) bool {
t.Helper()
totalPeers := 0
for _, dht := range dhts {
rtlen := dht.routingTable.Size()
totalPeers += rtlen
if minPeers > 0 && rtlen < minPeers {
// t.Logf("routing table for %s only has %d peers (should have >%d)", dht.self, rtlen, minPeers)
return false
}
}
actualAvgPeers := totalPeers / len(dhts)
t.Logf("avg rt size: %d", actualAvgPeers)
if avgPeers > 0 && actualAvgPeers < avgPeers {
t.Logf("avg rt size: %d < %d", actualAvgPeers, avgPeers)
return false
}
return true
}
func printRoutingTables(dhts []*IpfsDHT) {
// the routing tables should be full now. let's inspect them.
fmt.Printf("checking routing table of %d\n", len(dhts))
for _, dht := range dhts {
fmt.Printf("checking routing table of %s\n", dht.self)
dht.routingTable.Print()
fmt.Println("")
}
}
func TestRefresh(t *testing.T) {
if testing.Short() {
t.SkipNow()
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
nDHTs := 30
dhts := setupDHTS(t, ctx, nDHTs)
defer func() {
for i := 0; i < nDHTs; i++ {
dhts[i].Close()
defer dhts[i].host.Close()
}
}()
t.Logf("connecting %d dhts in a ring", nDHTs)
for i := 0; i < nDHTs; i++ {
connect(t, ctx, dhts[i], dhts[(i+1)%len(dhts)])
}
<-time.After(100 * time.Millisecond)
// bootstrap a few times until we get good tables.
t.Logf("bootstrapping them so they find each other %d", nDHTs)
for {
bootstrap(t, ctx, dhts)
if checkForWellFormedTablesOnce(t, dhts, 7, 10) {
break
}
time.Sleep(time.Microsecond * 50)
}
if u.Debug {
// the routing tables should be full now. let's inspect them.
printRoutingTables(dhts)
}
}
func TestRefreshBelowMinRTThreshold(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
host, err := bhost.NewHost(swarmt.GenSwarm(t, swarmt.OptDisableReuseport), new(bhost.HostOpts))
require.NoError(t, err)
host.Start()
// enable auto bootstrap on A
dhtA, err := New(
ctx,
host,
testPrefix,
Mode(ModeServer),
NamespacedValidator("v", blankValidator{}),
)
if err != nil {
t.Fatal(err)
}
dhtB := setupDHT(ctx, t, false)
dhtC := setupDHT(ctx, t, false)
defer func() {
dhtA.Close()
dhtA.host.Close()
dhtB.Close()
dhtB.host.Close()
dhtC.Close()
dhtC.host.Close()
}()
connect(t, ctx, dhtA, dhtB)
connect(t, ctx, dhtB, dhtC)
// we ONLY init bootstrap on A
dhtA.RefreshRoutingTable()
// and wait for one round to complete i.e. A should be connected to both B & C
waitForWellFormedTables(t, []*IpfsDHT{dhtA}, 2, 2, 20*time.Second)
// now we create two new peers
dhtD := setupDHT(ctx, t, false)
dhtE := setupDHT(ctx, t, false)
// connect them to each other
connect(t, ctx, dhtD, dhtE)
defer func() {
dhtD.Close()
dhtD.host.Close()
dhtE.Close()
dhtE.host.Close()
}()
// and then, on connecting the peer D to A, the min RT threshold gets triggered on A which leads to a bootstrap.
// since the default bootstrap scan interval is 30 mins - 1 hour, we can be sure that if bootstrap happens,
// it is because of the min RT threshold getting triggered (since default min value is 4 & we only have 2 peers in the RT when D gets connected)
connect(t, ctx, dhtA, dhtD)
// and because of the above bootstrap, A also discovers E !
waitForWellFormedTables(t, []*IpfsDHT{dhtA}, 4, 4, 10*time.Second)
time.Sleep(100 * time.Millisecond)
assert.Equal(t, dhtE.self, dhtA.routingTable.Find(dhtE.self), "A's routing table should have peer E!")
}
func TestQueryWithEmptyRTShouldNotPanic(t *testing.T) {
ctx := context.Background()
d := setupDHT(ctx, t, false)
// TODO This swallows the error for now, should we change it ?
// FindProviders
ps, _ := d.FindProviders(ctx, testCaseCids[0])
require.Empty(t, ps)
// GetClosestPeers
pc, err := d.GetClosestPeers(ctx, "key")
require.Nil(t, pc)
require.Equal(t, kb.ErrLookupFailure, err)
// GetValue
best, err := d.GetValue(ctx, "key")
require.Empty(t, best)
require.Error(t, err)
// SearchValue
bchan, err := d.SearchValue(ctx, "key")
require.Empty(t, bchan)
require.NoError(t, err)
// Provide
err = d.Provide(ctx, testCaseCids[0], true)
require.Equal(t, kb.ErrLookupFailure, err)
}
func TestPeriodicRefresh(t *testing.T) {
if testing.Short() {
t.SkipNow()
}
if runtime.GOOS == "windows" {
t.Skip("skipping due to #760")
}
if detectrace.WithRace() {
t.Skip("skipping due to race detector max goroutines")
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
nDHTs := 30
dhts := setupDHTS(t, ctx, nDHTs)
defer func() {
for i := 0; i < nDHTs; i++ {
dhts[i].Close()
defer dhts[i].host.Close()
}
}()
t.Logf("dhts are not connected. %d", nDHTs)
for _, dht := range dhts {
rtlen := dht.routingTable.Size()
if rtlen > 0 {
t.Errorf("routing table for %s should have 0 peers. has %d", dht.self, rtlen)
}
}
for i := 0; i < nDHTs; i++ {
connect(t, ctx, dhts[i], dhts[(i+1)%len(dhts)])
}
t.Logf("DHTs are now connected to 1-2 others. %d", nDHTs)
for _, dht := range dhts {
rtlen := dht.routingTable.Size()
if rtlen > 2 {
t.Errorf("routing table for %s should have at most 2 peers. has %d", dht.self, rtlen)