This repository has been archived by the owner on Nov 2, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 442
/
peers_test.go
1166 lines (1095 loc) · 30.6 KB
/
peers_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 gateway
import (
"errors"
"fmt"
"net"
"strconv"
"strings"
"testing"
"time"
"github.com/NebulousLabs/Sia/build"
"github.com/NebulousLabs/Sia/encoding"
"github.com/NebulousLabs/Sia/modules"
"github.com/NebulousLabs/Sia/types"
"github.com/NebulousLabs/fastrand"
)
// dummyConn implements the net.Conn interface, but does not carry any actual
// data.
type dummyConn struct {
net.Conn
}
func (dc *dummyConn) Read(p []byte) (int, error) { return len(p), nil }
func (dc *dummyConn) Write(p []byte) (int, error) { return len(p), nil }
func (dc *dummyConn) Close() error { return nil }
func (dc *dummyConn) SetReadDeadline(time.Time) error { return nil }
func (dc *dummyConn) SetWriteDeadline(time.Time) error { return nil }
// TestAddPeer tries adding a peer to the gateway.
func TestAddPeer(t *testing.T) {
if testing.Short() {
t.SkipNow()
}
t.Parallel()
g := newTestingGateway(t)
defer g.Close()
g.mu.Lock()
defer g.mu.Unlock()
g.addPeer(&peer{
Peer: modules.Peer{
NetAddress: "foo.com:123",
},
sess: newClientStream(new(dummyConn), build.Version),
})
if len(g.peers) != 1 {
t.Fatal("gateway did not add peer")
}
}
// TestAcceptPeer tests that acceptPeer does't kick outbound or local peers.
func TestAcceptPeer(t *testing.T) {
if testing.Short() {
t.SkipNow()
}
t.Parallel()
g := newTestingGateway(t)
defer g.Close()
g.mu.Lock()
defer g.mu.Unlock()
// Add only unkickable peers.
var unkickablePeers []*peer
for i := 0; i < fullyConnectedThreshold+1; i++ {
addr := modules.NetAddress(fmt.Sprintf("1.2.3.%d", i))
p := &peer{
Peer: modules.Peer{
NetAddress: addr,
Inbound: false,
Local: false,
},
sess: newClientStream(new(dummyConn), build.Version),
}
unkickablePeers = append(unkickablePeers, p)
}
for i := 0; i < fullyConnectedThreshold+1; i++ {
addr := modules.NetAddress(fmt.Sprintf("127.0.0.1:%d", i))
p := &peer{
Peer: modules.Peer{
NetAddress: addr,
Inbound: true,
Local: true,
},
sess: newClientStream(new(dummyConn), build.Version),
}
unkickablePeers = append(unkickablePeers, p)
}
for _, p := range unkickablePeers {
g.addPeer(p)
}
// Test that accepting another peer doesn't kick any of the peers.
g.acceptPeer(&peer{
Peer: modules.Peer{
NetAddress: "9.9.9.9",
Inbound: true,
},
sess: newClientStream(new(dummyConn), build.Version),
})
for _, p := range unkickablePeers {
if _, exists := g.peers[p.NetAddress]; !exists {
t.Error("accept peer kicked an outbound or local peer")
}
}
// Add a kickable peer.
g.addPeer(&peer{
Peer: modules.Peer{
NetAddress: "9.9.9.9",
Inbound: true,
},
sess: newClientStream(new(dummyConn), build.Version),
})
// Test that accepting a local peer will kick a kickable peer.
g.acceptPeer(&peer{
Peer: modules.Peer{
NetAddress: "127.0.0.1:99",
Inbound: true,
Local: true,
},
sess: newClientStream(new(dummyConn), build.Version),
})
if _, exists := g.peers["9.9.9.9"]; exists {
t.Error("acceptPeer didn't kick a peer to make room for a local peer")
}
}
// TestRandomInbountPeer checks that randomOutboundPeer returns the correct
// peer.
func TestRandomOutboundPeer(t *testing.T) {
if testing.Short() {
t.SkipNow()
}
t.Parallel()
g := newTestingGateway(t)
defer g.Close()
g.mu.Lock()
defer g.mu.Unlock()
_, err := g.randomOutboundPeer()
if err != errNoPeers {
t.Fatal("expected errNoPeers, got", err)
}
g.addPeer(&peer{
Peer: modules.Peer{
NetAddress: "foo.com:123",
Inbound: false,
},
sess: newClientStream(new(dummyConn), build.Version),
})
if len(g.peers) != 1 {
t.Fatal("gateway did not add peer")
}
addr, err := g.randomOutboundPeer()
if err != nil || addr != "foo.com:123" {
t.Fatal("gateway did not select random peer")
}
}
// TestListen is a general test probling the connection listener.
func TestListen(t *testing.T) {
if testing.Short() {
t.SkipNow()
}
t.Parallel()
g := newTestingGateway(t)
defer g.Close()
// compliant connect with old version
conn, err := net.Dial("tcp", string(g.Address()))
if err != nil {
t.Fatal("dial failed:", err)
}
addr := modules.NetAddress(conn.LocalAddr().String())
ack, err := connectVersionHandshake(conn, "0.1")
if err != errPeerRejectedConn {
t.Fatal(err)
}
if ack != "" {
t.Fatal("gateway should have rejected old version")
}
for i := 0; i < 10; i++ {
g.mu.RLock()
_, ok := g.peers[addr]
g.mu.RUnlock()
if ok {
t.Fatal("gateway should not have added an old peer")
}
time.Sleep(20 * time.Millisecond)
}
// a simple 'conn.Close' would not obey the stream disconnect protocol
newClientStream(conn, build.Version).Close()
// compliant connect with invalid net address
conn, err = net.Dial("tcp", string(g.Address()))
if err != nil {
t.Fatal("dial failed:", err)
}
addr = modules.NetAddress(conn.LocalAddr().String())
ack, err = connectVersionHandshake(conn, build.Version)
if err != nil {
t.Fatal(err)
}
if ack != build.Version {
t.Fatal("gateway should have given ack")
}
header := sessionHeader{
GenesisID: types.GenesisID,
UniqueID: gatewayID{},
NetAddress: "fake",
}
err = exchangeOurHeader(conn, header)
if err == nil {
t.Fatal("expected error, got nil")
}
conn.Close()
// compliant connect
conn, err = net.Dial("tcp", string(g.Address()))
if err != nil {
t.Fatal("dial failed:", err)
}
addr = modules.NetAddress(conn.LocalAddr().String())
ack, err = connectVersionHandshake(conn, build.Version)
if err != nil {
t.Fatal(err)
}
if ack != build.Version {
t.Fatal("gateway should have given ack")
}
header.NetAddress = modules.NetAddress(conn.LocalAddr().String())
err = exchangeOurHeader(conn, header)
if err != nil {
t.Fatal(err)
}
_, err = exchangeRemoteHeader(conn, header)
if err != nil {
t.Fatal(err)
}
// g should add the peer
err = build.Retry(50, 100*time.Millisecond, func() error {
g.mu.RLock()
_, ok := g.peers[addr]
g.mu.RUnlock()
if !ok {
return errors.New("g should have added the peer")
}
return nil
})
if err != nil {
t.Fatal(err)
}
// Disconnect. Now that connection has been established, need to shutdown
// via the stream multiplexer.
newClientStream(conn, build.Version).Close()
// g should remove the peer
err = build.Retry(50, 100*time.Millisecond, func() error {
g.mu.RLock()
_, ok := g.peers[addr]
g.mu.RUnlock()
if ok {
return errors.New("g should have removed the peer")
}
return nil
})
if err != nil {
t.Fatal(err)
}
// uncompliant connect
conn, err = net.Dial("tcp", string(g.Address()))
if err != nil {
t.Fatal("dial failed:", err)
}
if _, err := conn.Write([]byte("missing length prefix")); err != nil {
t.Fatal("couldn't write malformed header")
}
// g should have closed the connection
if n, err := conn.Write([]byte("closed")); err != nil && n > 0 {
t.Error("write succeeded after closed connection")
}
}
// TestConnect verifies that connecting peers will add peer relationships to
// the gateway, and that certain edge cases are properly handled.
func TestConnect(t *testing.T) {
if testing.Short() {
t.SkipNow()
}
t.Parallel()
// create bootstrap peer
bootstrap := newNamedTestingGateway(t, "1")
defer bootstrap.Close()
// give it a node
bootstrap.mu.Lock()
bootstrap.addNode(dummyNode)
bootstrap.mu.Unlock()
// create peer who will connect to bootstrap
g := newNamedTestingGateway(t, "2")
defer g.Close()
// first simulate a "bad" connect, where bootstrap won't share its nodes
bootstrap.mu.Lock()
bootstrap.handlers[handlerName("ShareNodes")] = func(modules.PeerConn) error {
return nil
}
bootstrap.mu.Unlock()
// connect
err := g.Connect(bootstrap.Address())
if err != nil {
t.Fatal(err)
}
// g should not have the node
if g.removeNode(dummyNode) == nil {
t.Fatal("bootstrapper should not have received dummyNode:", g.nodes)
}
// split 'em up
g.Disconnect(bootstrap.Address())
bootstrap.Disconnect(g.Address())
// now restore the correct ShareNodes RPC and try again
bootstrap.mu.Lock()
bootstrap.handlers[handlerName("ShareNodes")] = bootstrap.shareNodes
bootstrap.mu.Unlock()
err = g.Connect(bootstrap.Address())
if err != nil {
t.Fatal(err)
}
// g should have the node
time.Sleep(200 * time.Millisecond)
g.mu.RLock()
if _, ok := g.nodes[dummyNode]; !ok {
g.mu.RUnlock() // Needed to prevent a deadlock if this error condition is reached.
t.Fatal("bootstrapper should have received dummyNode:", g.nodes)
}
g.mu.RUnlock()
}
// TestUnitAcceptableVersion tests that the acceptableVersion func returns an
// error for unacceptable versions.
func TestUnitAcceptableVersion(t *testing.T) {
invalidVersions := []string{
// ascii gibberish
"foobar",
"foobar.0",
"foobar.9",
"0.foobar",
"9.foobar",
"foobar.0.0",
"foobar.9.9",
"0.foobar.0",
"9.foobar.9",
"0.0.foobar",
"9.9.foobar",
// utf-8 gibberish
"世界",
"世界.0",
"世界.9",
"0.世界",
"9.世界",
"世界.0.0",
"世界.9.9",
"0.世界.0",
"9.世界.9",
"0.0.世界",
"9.9.世界",
// missing numbers
".",
"..",
"...",
"0.",
".1",
"2..",
".3.",
"..4",
"5.6.",
".7.8",
".9.0.",
}
for _, v := range invalidVersions {
err := acceptableVersion(v)
if _, ok := err.(invalidVersionError); err == nil || !ok {
t.Errorf("acceptableVersion returned %q for version %q, but expected invalidVersionError", err, v)
}
}
insufficientVersions := []string{
// random small versions
"0",
"00",
"0000000000",
"0.0",
"0000000000.0",
"0.0000000000",
"0.0.0.0.0.0.0.0",
"0.0.9",
"0.0.999",
"0.0.99999999999",
"0.1.2",
"0.1.2.3.4.5.6.7.8.9",
// pre-hardfork versions
"0.3.3",
"0.3.9.9.9.9.9.9.9.9.9.9",
"0.3.9999999999",
"1.3.0",
}
for _, v := range insufficientVersions {
err := acceptableVersion(v)
if _, ok := err.(insufficientVersionError); err == nil || !ok {
t.Errorf("acceptableVersion returned %q for version %q, but expected insufficientVersionError", err, v)
}
}
validVersions := []string{
minimumAcceptablePeerVersion,
"1.4.0",
"1.3.1",
"1.6.0",
"1.6.1",
"1.9",
"1.999",
"1.9999999999",
"2",
"2.0",
"2.0.0",
"9",
"9.0",
"9.0.0",
"9.9.9",
}
for _, v := range validVersions {
err := acceptableVersion(v)
if err != nil {
t.Errorf("acceptableVersion returned %q for version %q, but expected nil", err, v)
}
}
}
// TestConnectRejectsInvalidAddrs tests that Connect only connects to valid IP
// addresses.
func TestConnectRejectsInvalidAddrs(t *testing.T) {
if testing.Short() {
t.SkipNow()
}
t.Parallel()
g := newNamedTestingGateway(t, "1")
defer g.Close()
g2 := newNamedTestingGateway(t, "2")
defer g2.Close()
_, g2Port, err := net.SplitHostPort(string(g2.Address()))
if err != nil {
t.Fatal(err)
}
tests := []struct {
addr modules.NetAddress
wantErr bool
msg string
}{
{
addr: "127.0.0.1:123",
wantErr: true,
msg: "Connect should reject unreachable addresses",
},
{
addr: "111.111.111.111:0",
wantErr: true,
msg: "Connect should reject invalid NetAddresses",
},
{
addr: modules.NetAddress(net.JoinHostPort("localhost", g2Port)),
wantErr: true,
msg: "Connect should reject non-IP addresses",
},
{
addr: g2.Address(),
msg: "Connect failed to connect to another gateway",
},
{
addr: g2.Address(),
wantErr: true,
msg: "Connect should reject an address it's already connected to",
},
}
for _, tt := range tests {
err := g.Connect(tt.addr)
if tt.wantErr != (err != nil) {
t.Errorf("%v, wantErr: %v, err: %v", tt.msg, tt.wantErr, err)
}
}
}
// TestConnectRejectsVersions tests that Gateway.Connect only accepts peers
// with sufficient and valid versions.
func TestConnectRejectsVersions(t *testing.T) {
if testing.Short() {
t.SkipNow()
}
g := newTestingGateway(t)
defer g.Close()
// Setup a listener that mocks Gateway.acceptConn, but sends the
// version sent over mockVersionChan instead of build.Version.
listener, err := net.Listen("tcp", "localhost:0")
if err != nil {
t.Fatal(err)
}
defer listener.Close()
tests := []struct {
version string
errWant string
localErrWant string
invalidVersion bool
insufficientVersion bool
msg string
// version required for this test
versionRequired string
// 1.2.0 sessionHeader extension to handshake protocol
genesisID types.BlockID
uniqueID gatewayID
}{
// Test that Connect fails when the remote peer's version is "reject".
{
version: "reject",
errWant: errPeerRejectedConn.Error(),
msg: "Connect should fail when the remote peer rejects the connection",
},
// Test that Connect fails when the remote peer's version is ascii gibberish.
{
version: "foobar",
invalidVersion: true,
msg: "Connect should fail when the remote peer's version is ascii gibberish",
},
// Test that Connect fails when the remote peer's version is utf8 gibberish.
{
version: "世界",
invalidVersion: true,
msg: "Connect should fail when the remote peer's version is utf8 gibberish",
},
// Test that Connect fails when the remote peer's version is < 0.4.0 (0).
{
version: "0",
insufficientVersion: true,
msg: "Connect should fail when the remote peer's version is 0",
},
{
version: "0.0.0",
insufficientVersion: true,
msg: "Connect should fail when the remote peer's version is 0.0.0",
},
{
version: "0000.0000.0000",
insufficientVersion: true,
msg: "Connect should fail when the remote peer's version is 0000.0000.0000",
},
{
version: "0.3.9",
insufficientVersion: true,
msg: "Connect should fail when the remote peer's version is 0.3.9",
},
{
version: "0.3.9999",
insufficientVersion: true,
msg: "Connect should fail when the remote peer's version is 0.3.9999",
},
{
version: "0.3.9.9.9",
insufficientVersion: true,
msg: "Connect should fail when the remote peer's version is 0.3.9.9.9",
},
// Test that Connect succeeds when the remote peer's version is 0.4.0.
{
version: "0.4.0",
msg: "Connect should succeed when the remote peer's version is 0.4.0",
},
// Test that Connect succeeds when the remote peer's version is > 0.4.0.
{
version: "0.9.0",
msg: "Connect should succeed when the remote peer's version is 0.9.0",
},
// Test that Connect /could/ succeed when the remote peer's version is >= 1.3.0.
{
version: minimumAcceptablePeerVersion,
msg: "Connect should succeed when the remote peer's version is 1.3.0 and sessionHeader checks out",
uniqueID: func() (id gatewayID) { fastrand.Read(id[:]); return }(),
genesisID: types.GenesisID,
versionRequired: minimumAcceptablePeerVersion,
},
{
version: minimumAcceptablePeerVersion,
msg: "Connect should not succeed when peer is connecting to itself",
uniqueID: g.staticId,
genesisID: types.GenesisID,
errWant: errOurAddress.Error(),
localErrWant: errOurAddress.Error(),
versionRequired: minimumAcceptablePeerVersion,
},
}
for testIndex, tt := range tests {
if tt.versionRequired != "" && build.VersionCmp(build.Version, tt.versionRequired) < 0 {
continue // skip, as we do not meet the required version
}
// create the listener
doneChan := make(chan struct{})
go func() {
defer close(doneChan)
conn, err := listener.Accept()
if err != nil {
panic(fmt.Sprintf("test #%d failed: %s", testIndex, err))
}
remoteVersion, err := acceptVersionHandshake(conn, tt.version)
if err != nil {
panic(fmt.Sprintf("test #%d failed: %s", testIndex, err))
}
if remoteVersion != build.Version {
panic(fmt.Sprintf("test #%d failed: remoteVersion != build.Version", testIndex))
}
if build.VersionCmp(tt.version, minimumAcceptablePeerVersion) >= 0 {
ourHeader := sessionHeader{
GenesisID: tt.genesisID,
UniqueID: tt.uniqueID,
NetAddress: modules.NetAddress(conn.LocalAddr().String()),
}
_, err = exchangeRemoteHeader(conn, ourHeader)
exchangeOurHeader(conn, ourHeader)
} else if build.VersionCmp(tt.version, handshakeUpgradeVersion) >= 0 {
var dialbackPort string
err = encoding.ReadObject(conn, &dialbackPort, 13)
} else {
// no action taken for old peers
}
if (err == nil && tt.localErrWant != "") || (err != nil && !strings.Contains(err.Error(), tt.localErrWant)) {
panic(fmt.Sprintf("test #%d failed: %v != %v", testIndex, tt.localErrWant, err))
}
}()
err = g.Connect(modules.NetAddress(listener.Addr().String()))
switch {
case tt.invalidVersion:
// Check that the error is the expected type.
if _, ok := err.(invalidVersionError); !ok {
t.Fatalf("expected Connect to error with invalidVersionError: %s", tt.msg)
}
case tt.insufficientVersion:
// Check that the error is the expected type.
if _, ok := err.(insufficientVersionError); !ok {
t.Fatalf("expected Connect to error with insufficientVersionError: %s", tt.msg)
}
default:
// Check that the error is the expected error.
if (err == nil && tt.errWant != "") || (err != nil && !strings.Contains(err.Error(), tt.errWant)) {
t.Fatalf("expected Connect to error with '%v', but got '%v': %s", tt.errWant, err, tt.msg)
}
}
<-doneChan
g.Disconnect(modules.NetAddress(listener.Addr().String()))
}
}
// TestAcceptConnRejectsVersions tests that Gateway.acceptConn only accepts
// peers with sufficient and valid versions.
func TestAcceptConnRejectsVersions(t *testing.T) {
if testing.Short() {
t.SkipNow()
}
t.Parallel()
g := newTestingGateway(t)
defer g.Close()
tests := []struct {
remoteVersion string
versionResponseWant string
errWant error
msg string
}{
// Test that acceptConn fails when the remote peer's version is "reject".
{
remoteVersion: "reject",
versionResponseWant: "",
errWant: errPeerRejectedConn,
msg: "acceptConn shouldn't accept a remote peer whose version is \"reject\"",
},
// Test that acceptConn fails when the remote peer's version is ascii gibberish.
{
remoteVersion: "foobar",
versionResponseWant: "",
errWant: errPeerRejectedConn,
msg: "acceptConn shouldn't accept a remote peer whose version is ascii gibberish",
},
// Test that acceptConn fails when the remote peer's version is utf8 gibberish.
{
remoteVersion: "世界",
versionResponseWant: "",
errWant: errPeerRejectedConn,
msg: "acceptConn shouldn't accept a remote peer whose version is utf8 gibberish",
},
// Test that acceptConn fails when the remote peer's version is < 0.4.0 (0).
{
remoteVersion: "0",
versionResponseWant: "",
errWant: errPeerRejectedConn,
msg: "acceptConn shouldn't accept a remote peer whose version is 0",
},
{
remoteVersion: "0.0.0",
versionResponseWant: "",
errWant: errPeerRejectedConn,
msg: "acceptConn shouldn't accept a remote peer whose version is 0.0.0",
},
{
remoteVersion: "0000.0000.0000",
versionResponseWant: "",
errWant: errPeerRejectedConn,
msg: "acceptConn shouldn't accept a remote peer whose version is 0000.000.000",
},
{
remoteVersion: "0.3.9",
versionResponseWant: "",
errWant: errPeerRejectedConn,
msg: "acceptConn shouldn't accept a remote peer whose version is 0.3.9",
},
{
remoteVersion: "0.3.9999",
versionResponseWant: "",
errWant: errPeerRejectedConn,
msg: "acceptConn shouldn't accept a remote peer whose version is 0.3.9999",
},
{
remoteVersion: "0.3.9.9.9",
versionResponseWant: "",
errWant: errPeerRejectedConn,
msg: "acceptConn shouldn't accept a remote peer whose version is 0.3.9.9.9",
},
// Test that acceptConn succeeds when the remote peer's version is
// minAcceptableVersion
{
remoteVersion: minimumAcceptablePeerVersion,
versionResponseWant: build.Version,
msg: "acceptConn should accept a remote peer whose version is 0.4.0",
},
// Test that acceptConn succeeds when the remote peer's version is
// above minAcceptableVersion
{
remoteVersion: "9",
versionResponseWant: build.Version,
msg: "acceptConn should accept a remote peer whose version is 9",
},
{
remoteVersion: "9.9.9",
versionResponseWant: build.Version,
msg: "acceptConn should accept a remote peer whose version is 9.9.9",
},
{
remoteVersion: "9999.9999.9999",
versionResponseWant: build.Version,
msg: "acceptConn should accept a remote peer whose version is 9999.9999.9999",
},
}
for _, tt := range tests {
conn, err := net.DialTimeout("tcp", string(g.Address()), dialTimeout)
if err != nil {
t.Fatal(err)
}
remoteVersion, err := connectVersionHandshake(conn, tt.remoteVersion)
if err != tt.errWant {
t.Fatal(err)
}
if remoteVersion != tt.versionResponseWant {
t.Fatal(tt.msg)
}
conn.Close()
}
}
// TestDisconnect checks that calls to gateway.Disconnect correctly disconnect
// and remove peers from the gateway.
func TestDisconnect(t *testing.T) {
if testing.Short() {
t.SkipNow()
}
t.Parallel()
g := newTestingGateway(t)
defer g.Close()
g2 := newNamedTestingGateway(t, "2")
defer g2.Close()
// Try disconnecting from a peer that doesn't exist.
if err := g.Disconnect("bar.com:123"); err == nil {
t.Fatal("disconnect removed unconnected peer")
}
// Connect two peers to eachother.
err := g.Connect(g2.myAddr)
if err != nil {
t.Fatal(err)
}
g.mu.Lock()
_, exists := g.nodes[g2.myAddr]
if !exists {
t.Error("peer never made it into node list")
}
g.mu.Unlock()
// Disconnect the peer.
if err := g.Disconnect(g2.myAddr); err != nil {
t.Fatal("disconnect failed:", err)
}
g2.Disconnect(g.myAddr) // Prevents g2 from connecting back to g
peers := g.Peers()
for _, peer := range peers {
if peer.NetAddress == g2.myAddr {
t.Error("disconnect seems to have failed - still have this peer")
}
}
g.mu.Lock()
_, exists = g.nodes[g2.myAddr]
if exists {
t.Error("should be dropping peer from nodelist after disconnect")
}
g.mu.Unlock()
}
// TestPeerManager checks that the peer manager is properly spacing out peer
// connection requests.
func TestPeerManager(t *testing.T) {
if testing.Short() {
t.SkipNow()
}
t.Parallel()
g1 := newNamedTestingGateway(t, "1")
defer g1.Close()
// create a valid node to connect to
g2 := newNamedTestingGateway(t, "2")
defer g2.Close()
// g1's node list should only contain g2
g1.mu.Lock()
g1.nodes = map[modules.NetAddress]*node{}
g1.nodes[g2.Address()] = &node{NetAddress: g2.Address()}
g1.mu.Unlock()
// when peerManager wakes up, it should connect to g2.
time.Sleep(time.Second + noNodesDelay)
g1.mu.RLock()
defer g1.mu.RUnlock()
if len(g1.peers) != 1 || g1.peers[g2.Address()] == nil {
t.Fatal("gateway did not connect to g2:", g1.peers)
}
}
// TestOverloadedBootstrap creates a bunch of gateways and connects all of them
// to the first gateway, the bootstrap gateway. More gateways will be created
// than is allowed by the bootstrap for the total number of connections. After
// waiting, all peers should eventually get to the full number of outbound
// peers.
func TestOverloadedBootstrap(t *testing.T) {
if testing.Short() {
t.SkipNow()
}
t.Parallel()
// Create fullyConnectedThreshold*2 peers and connect them all to only the
// first node.
var gs []*Gateway
for i := 0; i < fullyConnectedThreshold*2; i++ {
gs = append(gs, newNamedTestingGateway(t, strconv.Itoa(i)))
// Connect this gateway to the first gateway.
if i == 0 {
continue
}
err := gs[i].Connect(gs[0].myAddr)
for j := 0; j < 100 && err != nil; j++ {
time.Sleep(time.Millisecond * 250)
err = gs[i].Connect(gs[0].myAddr)
}
if err != nil {
panic(err)
}
}
// Spin until all gateways have a complete number of outbound peers.
success := false
for i := 0; i < 100; i++ {
success = true
for _, g := range gs {
outboundPeers := 0
g.mu.RLock()
for _, p := range g.peers {
if !p.Inbound {
outboundPeers++
}
}
g.mu.RUnlock()
if outboundPeers < wellConnectedThreshold {
success = false
break
}
}
if !success {
time.Sleep(time.Second)
}
}
if !success {
for i, g := range gs {
outboundPeers := 0
g.mu.RLock()
for _, p := range g.peers {
if !p.Inbound {
outboundPeers++
}
}
g.mu.RUnlock()
t.Log("Gateway", i, ":", outboundPeers)
}
t.Fatal("after 100 seconds not all gateways able to become well connected")
}
// Randomly close many of the peers. For many peers, this should put them
// below the well connected threshold, but there are still enough nodes on
// the network that no partitions should occur.
var newGS []*Gateway
for _, i := range fastrand.Perm(len(gs)) {
newGS = append(newGS, gs[i])
}
cutSize := len(newGS) / 4
// Close the first many of the now-randomly-sorted gateways.
for _, g := range newGS[:cutSize] {
err := g.Close()
if err != nil {
t.Fatal(err)
}
}
// Set 'gs' equal to the remaining gateways.
gs = newGS[cutSize:]
// Spin until all gateways have a complete number of outbound peers. The
// test can fail if there are network partitions, however not a huge
// magnitude of nodes are being removed, and they all started with 4
// connections. A partition is unlikely.
success = false
for i := 0; i < 100; i++ {
success = true
for _, g := range gs {
outboundPeers := 0
g.mu.RLock()
for _, p := range g.peers {
if !p.Inbound {
outboundPeers++
}
}
g.mu.RUnlock()
if outboundPeers < wellConnectedThreshold {
success = false
break
}
}
if !success {
time.Sleep(time.Second)
}
}
if !success {
t.Fatal("after 100 seconds not all gateways able to become well connected")
}
// Close all remaining gateways.
for _, g := range gs {
err := g.Close()
if err != nil {
t.Error(err)
}
}
}
// TestPeerManagerPriority tests that the peer manager will prioritize
// connecting to previous outbound peers before inbound peers.
func TestPeerManagerPriority(t *testing.T) {
if testing.Short() {
t.SkipNow()
}
t.Parallel()
g1 := newNamedTestingGateway(t, "1")
defer g1.Close()