forked from bitcoin/bitcoin
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathnet_tests.cpp
More file actions
1961 lines (1710 loc) · 84.8 KB
/
Copy pathnet_tests.cpp
File metadata and controls
1961 lines (1710 loc) · 84.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2012-2021 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <test/util/setup_common.h>
#include <chainparams.h>
#include <clientversion.h>
#include <compat/compat.h>
#include <net.h>
#include <net_processing.h>
#include <netaddress.h>
#include <netbase.h>
#include <netmessagemaker.h>
#include <serialize.h>
#include <span.h>
#include <streams.h>
#include <test/util/net.h>
#include <test/util/random.h>
#include <test/util/validation.h>
#include <timedata.h>
#include <util/strencodings.h>
#include <util/string.h>
#include <util/system.h>
#include <validation.h>
#include <version.h>
#include <boost/test/unit_test.hpp>
#include <algorithm>
#include <cstdint>
#include <ios>
#include <memory>
#include <optional>
#include <string>
using namespace std::literals;
BOOST_FIXTURE_TEST_SUITE(net_tests, RegTestingSetup)
namespace {
//! GetObjectInterval(MSG_CLSIG), the shortest of the per-type request intervals, and the grace that
//! follows it: RECENT_OBJECT_REQUEST_TTL_INTERVALS of them. Neither is reachable from a test, so the
//! arithmetic is spelled out here -- if either changes, the cases pinning this boundary should be
//! revisited rather than silently re-pointed at a different one.
constexpr auto CLSIG_REQUEST_INTERVAL{5s};
constexpr auto CLSIG_LATE_GRACE{2 * CLSIG_REQUEST_INTERVAL};
GetDataResponse ConsumeGetDataResponse(PeerManager& peerman, const CNode& peer, const CInv& inv)
{
return WITH_LOCK(::cs_main, return peerman.PeerConsumeGetDataResponse(peer.GetId(), inv));
}
void ProcessInv(PeerManager& peerman, CNode& peer, const CInv& inv)
EXCLUSIVE_LOCKS_REQUIRED(NetEventsInterface::g_msgproc_mutex)
{
CDataStream inv_stream{SER_NETWORK, PROTOCOL_VERSION};
inv_stream << std::vector<CInv>{inv};
std::atomic<bool> interrupt_dummy{false};
peerman.ProcessMessage(peer, NetMsgType::INV, inv_stream, GetTime<std::chrono::microseconds>(), interrupt_dummy);
}
} // namespace
BOOST_AUTO_TEST_CASE(cnode_listen_port)
{
// test default
uint16_t port{GetListenPort()};
BOOST_CHECK(port == Params().GetDefaultPort());
// test set port
uint16_t altPort = 12345;
BOOST_CHECK(gArgs.SoftSetArg("-port", ToString(altPort)));
port = GetListenPort();
BOOST_CHECK(port == altPort);
}
BOOST_AUTO_TEST_CASE(peer_requested_object_authorizes_and_erases_per_peer_state)
{
LOCK(NetEventsInterface::g_msgproc_mutex);
TestChainState& chainstate =
*static_cast<TestChainState*>(&m_node.chainman->ActiveChainstate());
chainstate.JumpOutOfIbd();
auto peer{MakeTestPeer(/*id=*/0)};
m_node.peerman->InitializeNode(*peer, NODE_NETWORK);
const CInv announced_inv{MSG_SPORK, uint256S("01")};
ProcessInv(*m_node.peerman, *peer, announced_inv);
// The announcement is queued for a GETDATA that hasn't been sent yet.
BOOST_CHECK_EQUAL(WITH_LOCK(::cs_main, return m_node.peerman->GetRequestedObjectCount(peer->GetId())), 1U);
// Consuming completes the peer's announcement and returns true exactly once.
BOOST_CHECK(WITH_LOCK(::cs_main, return m_node.peerman->PeerConsumeObjectRequest(peer->GetId(), announced_inv)));
BOOST_CHECK(!WITH_LOCK(::cs_main, return m_node.peerman->PeerConsumeObjectRequest(peer->GetId(), announced_inv)));
// A consumed announcement must not be requested by SendMessages.
SetMockTime(GetTime<std::chrono::seconds>() + 61s);
m_node.peerman->SendMessages(peer.get());
BOOST_CHECK_EQUAL(WITH_LOCK(::cs_main, return m_node.peerman->GetRequestedObjectCount(peer->GetId())), 0U);
// Not re-requested: consuming did not resurrect the announcement.
BOOST_CHECK(!WITH_LOCK(::cs_main, return m_node.peerman->PeerConsumeObjectRequest(peer->GetId(), announced_inv)));
// Authorization must also survive getdata scheduling. After SendMessages issues the
// GETDATA the announcement is in the requested state; PeerConsumeObjectRequest returns true
// for both announced and requested states, so this checks that a requested inv authorizes.
const CInv requested_inv{MSG_SPORK, uint256S("02")};
ProcessInv(*m_node.peerman, *peer, requested_inv);
SetMockTime(GetTime<std::chrono::seconds>() + 61s);
m_node.peerman->SendMessages(peer.get());
BOOST_CHECK(WITH_LOCK(::cs_main, return m_node.peerman->PeerConsumeObjectRequest(peer->GetId(), requested_inv)));
BOOST_CHECK(!WITH_LOCK(::cs_main, return m_node.peerman->PeerConsumeObjectRequest(peer->GetId(), requested_inv)));
const CInv unsolicited_inv{MSG_SPORK, uint256S("03")};
BOOST_CHECK(!WITH_LOCK(::cs_main, return m_node.peerman->PeerConsumeObjectRequest(peer->GetId(), unsolicited_inv)));
// A failed authorization check must leave no trace: a later legitimate announcement for the
// same hash must still be requested (GETDATA scheduled) and therefore authorize.
ProcessInv(*m_node.peerman, *peer, unsolicited_inv);
SetMockTime(GetTime<std::chrono::seconds>() + 61s);
m_node.peerman->SendMessages(peer.get());
BOOST_CHECK(WITH_LOCK(::cs_main, return m_node.peerman->PeerConsumeObjectRequest(peer->GetId(), unsolicited_inv)));
m_node.peerman->FinalizeNode(*peer);
chainstate.ResetIbd();
SetMockTime(0s);
}
// GETDATA-only object types use the stricter PeerConsumeGetDataResponse, which -- unlike
// PeerConsumeObjectRequest -- must reject a bare announcement. Otherwise a peer could authorise its
// own payload by sending INV immediately followed by the object, before SendMessages ever turned
// that announcement into a request.
BOOST_AUTO_TEST_CASE(peer_getdata_response_requires_an_inflight_request)
{
LOCK(NetEventsInterface::g_msgproc_mutex);
TestChainState& chainstate =
*static_cast<TestChainState*>(&m_node.chainman->ActiveChainstate());
chainstate.JumpOutOfIbd();
auto peer{MakeTestPeer(/*id=*/0)};
m_node.peerman->InitializeNode(*peer, NODE_NETWORK);
// MSG_SPORK is not a GETDATA-only type (see IsGetDataOnlyObject), so nothing here is ever
// softened to LATE and the strict in-flight requirement is visible on its own.
const CInv inv{MSG_SPORK, uint256S("04")};
ProcessInv(*m_node.peerman, *peer, inv);
// Announced but not yet requested: the looser check accepts this, the stricter one must not.
BOOST_CHECK(ConsumeGetDataResponse(*m_node.peerman, *peer, inv) == GetDataResponse::UNREQUESTED);
// The rejection left the candidate intact, so the GETDATA is still pending.
BOOST_CHECK_EQUAL(WITH_LOCK(::cs_main, return m_node.peerman->GetRequestedObjectCount(peer->GetId())), 1U);
// After SendMessages issues the GETDATA the announcement is REQUESTED and authorises once.
SetMockTime(GetTime<std::chrono::seconds>() + 61s);
m_node.peerman->SendMessages(peer.get());
BOOST_CHECK(ConsumeGetDataResponse(*m_node.peerman, *peer, inv) == GetDataResponse::REQUESTED);
BOOST_CHECK(ConsumeGetDataResponse(*m_node.peerman, *peer, inv) == GetDataResponse::UNREQUESTED);
// Never announced at all: rejected, and no trace left behind.
const CInv never_announced{MSG_SPORK, uint256S("05")};
BOOST_CHECK(ConsumeGetDataResponse(*m_node.peerman, *peer, never_announced) == GetDataResponse::UNREQUESTED);
BOOST_CHECK_EQUAL(WITH_LOCK(::cs_main, return m_node.peerman->GetRequestedObjectCount(peer->GetId())), 0U);
m_node.peerman->FinalizeNode(*peer);
chainstate.ResetIbd();
SetMockTime(0s);
}
// The tracker cannot answer "did we ever ask this peer?" on its own: an announcement is erased once
// it expires as the sole one for its hash. A peer that answers our GETDATA a little too slowly is
// then indistinguishable from one that was never asked -- unless we remember having asked. Without
// that memory an honest but slow peer accrues misbehaviour, and the score never decays within a
// connection.
BOOST_AUTO_TEST_CASE(expired_getdata_response_is_late_not_unrequested)
{
LOCK(NetEventsInterface::g_msgproc_mutex);
TestChainState& chainstate = *static_cast<TestChainState*>(&m_node.chainman->ActiveChainstate());
chainstate.JumpOutOfIbd();
auto peer{MakeTestPeer(/*id=*/0)};
m_node.peerman->InitializeNode(*peer, NODE_NETWORK);
// MSG_CLSIG is a GETDATA-only type, and its request interval is the shortest of them all.
const CInv inv{MSG_CLSIG, uint256S("06")};
ProcessInv(*m_node.peerman, *peer, inv);
// Nudge past the announcement's reqtime so SendMessages issues the GETDATA.
SetMockTime(GetTime<std::chrono::seconds>() + 2s);
m_node.peerman->SendMessages(peer.get());
BOOST_CHECK_EQUAL(WITH_LOCK(::cs_main, return m_node.peerman->GetRequestedObjectCount(peer->GetId())), 1U);
// Answer on the last moment of the grace: the request expired at CLSIG_REQUEST_INTERVAL, and
// this peer was the only announcer, so the tracker drops the record entirely rather than keeping
// a COMPLETED one -- there is nothing left for it to consult.
SetMockTime(GetTime<std::chrono::seconds>() + CLSIG_LATE_GRACE);
m_node.peerman->SendMessages(peer.get());
BOOST_CHECK_EQUAL(WITH_LOCK(::cs_main, return m_node.peerman->GetRequestedObjectCount(peer->GetId())), 0U);
// The answer is late, not unsolicited: it must not be scored.
BOOST_CHECK(ConsumeGetDataResponse(*m_node.peerman, *peer, inv) == GetDataResponse::LATE);
// One GETDATA buys exactly one answer. Without this a peer could induce a single request and
// then replay that payload forever, unscored -- which is the abuse the gate exists to stop.
BOOST_CHECK(ConsumeGetDataResponse(*m_node.peerman, *peer, inv) == GetDataResponse::UNREQUESTED);
// A hash we never asked this peer for is still unsolicited.
BOOST_CHECK(ConsumeGetDataResponse(*m_node.peerman, *peer, CInv{MSG_CLSIG, uint256S("07")}) ==
GetDataResponse::UNREQUESTED);
m_node.peerman->FinalizeNode(*peer);
chainstate.ResetIbd();
SetMockTime(0s);
}
// Accepting an object from any source erases every peer's announcement of it (ForgetTxHash), which
// likewise strands an in-flight request. Reachable in production whenever the object turns up
// locally -- a ChainLock we sign ourselves, or one submitted over RPC -- while a GETDATA is out.
BOOST_AUTO_TEST_CASE(forgotten_getdata_response_is_late_not_unrequested)
{
LOCK(NetEventsInterface::g_msgproc_mutex);
TestChainState& chainstate = *static_cast<TestChainState*>(&m_node.chainman->ActiveChainstate());
chainstate.JumpOutOfIbd();
auto peer{MakeTestPeer(/*id=*/0)};
m_node.peerman->InitializeNode(*peer, NODE_NETWORK);
const CInv inv{MSG_CLSIG, uint256S("08")};
ProcessInv(*m_node.peerman, *peer, inv);
SetMockTime(GetTime<std::chrono::seconds>() + 2s);
m_node.peerman->SendMessages(peer.get());
BOOST_CHECK_EQUAL(WITH_LOCK(::cs_main, return m_node.peerman->GetRequestedObjectCount(peer->GetId())), 1U);
// The object arrives from somewhere else while our GETDATA is still in flight.
WITH_LOCK(::cs_main, m_node.peerman->PeerForgetObjectRequest(inv));
BOOST_CHECK_EQUAL(WITH_LOCK(::cs_main, return m_node.peerman->GetRequestedObjectCount(peer->GetId())), 0U);
BOOST_CHECK(ConsumeGetDataResponse(*m_node.peerman, *peer, inv) == GetDataResponse::LATE);
BOOST_CHECK(ConsumeGetDataResponse(*m_node.peerman, *peer, inv) == GetDataResponse::UNREQUESTED);
m_node.peerman->FinalizeNode(*peer);
chainstate.ResetIbd();
SetMockTime(0s);
}
// The type in an INV is whatever the peer said it was, and is not bound to the payload until that
// payload arrives. So a peer can announce the hash of an object of one gated type under another --
// no hash collision needed, it picks the hash -- collect our GETDATA, and answer with the object it
// meant all along. The grace must be tied to the type we asked for, not the one we are handed, or
// the request authorises the substitute and lends it the wrong type's window as well.
BOOST_AUTO_TEST_CASE(getdata_response_grace_does_not_cross_inv_types)
{
LOCK(NetEventsInterface::g_msgproc_mutex);
TestChainState& chainstate = *static_cast<TestChainState*>(&m_node.chainman->ActiveChainstate());
chainstate.JumpOutOfIbd();
auto peer{MakeTestPeer(/*id=*/0)};
m_node.peerman->InitializeNode(*peer, NODE_NETWORK);
// Announced as a ChainLock, so that is what we ask for.
const uint256 hash{uint256S("0b")};
ProcessInv(*m_node.peerman, *peer, CInv{MSG_CLSIG, hash});
SetMockTime(GetTime<std::chrono::seconds>() + 2s);
m_node.peerman->SendMessages(peer.get());
// Strand the request so only the recorded grace is left to consult, then answer with a DKG
// message carrying that hash, inside the interval that type would have been given (120s) but
// outside the one the ChainLock request actually earned (10s).
WITH_LOCK(::cs_main, m_node.peerman->PeerForgetObjectRequest(CInv{MSG_CLSIG, hash}));
SetMockTime(GetTime<std::chrono::seconds>() + CLSIG_LATE_GRACE + 1s);
BOOST_CHECK(ConsumeGetDataResponse(*m_node.peerman, *peer, CInv{MSG_QUORUM_CONTRIB, hash}) ==
GetDataResponse::UNREQUESTED);
m_node.peerman->FinalizeNode(*peer);
chainstate.ResetIbd();
SetMockTime(0s);
}
// The grace is bounded in time, not just in count. Without that a peer could induce a GETDATA, never
// answer it, and spend the authorisation an arbitrarily long time later -- banking one per request.
BOOST_AUTO_TEST_CASE(getdata_response_grace_expires)
{
LOCK(NetEventsInterface::g_msgproc_mutex);
TestChainState& chainstate = *static_cast<TestChainState*>(&m_node.chainman->ActiveChainstate());
chainstate.JumpOutOfIbd();
auto peer{MakeTestPeer(/*id=*/0)};
m_node.peerman->InitializeNode(*peer, NODE_NETWORK);
const CInv inv{MSG_CLSIG, uint256S("0a")};
ProcessInv(*m_node.peerman, *peer, inv);
SetMockTime(GetTime<std::chrono::seconds>() + 2s);
m_node.peerman->SendMessages(peer.get());
// Exactly one second past the boundary that expired_getdata_response_is_late_not_unrequested
// sits on, so the two cases together pin it from both sides.
SetMockTime(GetTime<std::chrono::seconds>() + CLSIG_LATE_GRACE + 1s);
m_node.peerman->SendMessages(peer.get());
BOOST_CHECK_EQUAL(WITH_LOCK(::cs_main, return m_node.peerman->GetRequestedObjectCount(peer->GetId())), 0U);
BOOST_CHECK(ConsumeGetDataResponse(*m_node.peerman, *peer, inv) == GetDataResponse::UNREQUESTED);
m_node.peerman->FinalizeNode(*peer);
chainstate.ResetIbd();
SetMockTime(0s);
}
BOOST_AUTO_TEST_CASE(cnode_simple_test)
{
NodeId id = 0;
in_addr ipv4Addr;
ipv4Addr.s_addr = 0xa0b0c001;
CAddress addr = CAddress(CService(ipv4Addr, 7777), NODE_NETWORK);
std::string pszDest;
std::unique_ptr<CNode> pnode1 = std::make_unique<CNode>(id++,
/*sock=*/nullptr,
addr,
/*nKeyedNetGroupIn=*/0,
/*nLocalHostNonceIn=*/0,
CAddress(),
pszDest,
ConnectionType::OUTBOUND_FULL_RELAY,
/*inbound_onion=*/false);
BOOST_CHECK(pnode1->IsFullOutboundConn() == true);
BOOST_CHECK(pnode1->IsManualConn() == false);
BOOST_CHECK(pnode1->IsBlockOnlyConn() == false);
BOOST_CHECK(pnode1->IsFeelerConn() == false);
BOOST_CHECK(pnode1->IsAddrFetchConn() == false);
BOOST_CHECK(pnode1->IsInboundConn() == false);
BOOST_CHECK(pnode1->m_inbound_onion == false);
BOOST_CHECK_EQUAL(pnode1->ConnectedThroughNetwork(), Network::NET_IPV4);
std::unique_ptr<CNode> pnode2 = std::make_unique<CNode>(id++,
/*sock=*/nullptr,
addr,
/*nKeyedNetGroupIn=*/1,
/*nLocalHostNonceIn=*/1,
CAddress(),
pszDest,
ConnectionType::INBOUND,
/*inbound_onion=*/false);
BOOST_CHECK(pnode2->IsFullOutboundConn() == false);
BOOST_CHECK(pnode2->IsManualConn() == false);
BOOST_CHECK(pnode2->IsBlockOnlyConn() == false);
BOOST_CHECK(pnode2->IsFeelerConn() == false);
BOOST_CHECK(pnode2->IsAddrFetchConn() == false);
BOOST_CHECK(pnode2->IsInboundConn() == true);
BOOST_CHECK(pnode2->m_inbound_onion == false);
BOOST_CHECK_EQUAL(pnode2->ConnectedThroughNetwork(), Network::NET_IPV4);
std::unique_ptr<CNode> pnode3 = std::make_unique<CNode>(id++,
/*sock=*/nullptr,
addr,
/*nKeyedNetGroupIn=*/0,
/*nLocalHostNonceIn=*/0,
CAddress(),
pszDest,
ConnectionType::OUTBOUND_FULL_RELAY,
/*inbound_onion=*/false);
BOOST_CHECK(pnode3->IsFullOutboundConn() == true);
BOOST_CHECK(pnode3->IsManualConn() == false);
BOOST_CHECK(pnode3->IsBlockOnlyConn() == false);
BOOST_CHECK(pnode3->IsFeelerConn() == false);
BOOST_CHECK(pnode3->IsAddrFetchConn() == false);
BOOST_CHECK(pnode3->IsInboundConn() == false);
BOOST_CHECK(pnode3->m_inbound_onion == false);
BOOST_CHECK_EQUAL(pnode3->ConnectedThroughNetwork(), Network::NET_IPV4);
std::unique_ptr<CNode> pnode4 = std::make_unique<CNode>(id++,
/*sock=*/nullptr,
addr,
/*nKeyedNetGroupIn=*/1,
/*nLocalHostNonceIn=*/1,
CAddress(),
pszDest,
ConnectionType::INBOUND,
/*inbound_onion=*/true);
BOOST_CHECK(pnode4->IsFullOutboundConn() == false);
BOOST_CHECK(pnode4->IsManualConn() == false);
BOOST_CHECK(pnode4->IsBlockOnlyConn() == false);
BOOST_CHECK(pnode4->IsFeelerConn() == false);
BOOST_CHECK(pnode4->IsAddrFetchConn() == false);
BOOST_CHECK(pnode4->IsInboundConn() == true);
BOOST_CHECK(pnode4->m_inbound_onion == true);
BOOST_CHECK_EQUAL(pnode4->ConnectedThroughNetwork(), Network::NET_ONION);
}
BOOST_AUTO_TEST_CASE(cnetaddr_basic)
{
CNetAddr addr;
// IPv4, INADDR_ANY
addr = LookupHost("0.0.0.0", false).value();
BOOST_REQUIRE(!addr.IsValid());
BOOST_REQUIRE(addr.IsIPv4());
BOOST_CHECK(addr.IsBindAny());
BOOST_CHECK(addr.IsAddrV1Compatible());
BOOST_CHECK_EQUAL(addr.ToStringAddr(), "0.0.0.0");
// IPv4, INADDR_NONE
addr = LookupHost("255.255.255.255", false).value();
BOOST_REQUIRE(!addr.IsValid());
BOOST_REQUIRE(addr.IsIPv4());
BOOST_CHECK(!addr.IsBindAny());
BOOST_CHECK(addr.IsAddrV1Compatible());
BOOST_CHECK_EQUAL(addr.ToStringAddr(), "255.255.255.255");
// IPv4, casual
addr = LookupHost("12.34.56.78", false).value();
BOOST_REQUIRE(addr.IsValid());
BOOST_REQUIRE(addr.IsIPv4());
BOOST_CHECK(!addr.IsBindAny());
BOOST_CHECK(addr.IsAddrV1Compatible());
BOOST_CHECK_EQUAL(addr.ToStringAddr(), "12.34.56.78");
// IPv6, in6addr_any
addr = LookupHost("::", false).value();
BOOST_REQUIRE(!addr.IsValid());
BOOST_REQUIRE(addr.IsIPv6());
BOOST_CHECK(addr.IsBindAny());
BOOST_CHECK(addr.IsAddrV1Compatible());
BOOST_CHECK_EQUAL(addr.ToStringAddr(), "::");
// IPv6, casual
addr = LookupHost("1122:3344:5566:7788:9900:aabb:ccdd:eeff", false).value();
BOOST_REQUIRE(addr.IsValid());
BOOST_REQUIRE(addr.IsIPv6());
BOOST_CHECK(!addr.IsBindAny());
BOOST_CHECK(addr.IsAddrV1Compatible());
BOOST_CHECK_EQUAL(addr.ToStringAddr(), "1122:3344:5566:7788:9900:aabb:ccdd:eeff");
// IPv6, scoped/link-local. See https://tools.ietf.org/html/rfc4007
// We support non-negative decimal integers (uint32_t) as zone id indices.
// Normal link-local scoped address functionality is to append "%" plus the
// zone id, for example, given a link-local address of "fe80::1" and a zone
// id of "32", return the address as "fe80::1%32".
const std::string link_local{"fe80::1"};
const std::string scoped_addr{link_local + "%32"};
addr = LookupHost(scoped_addr, false).value();
BOOST_REQUIRE(addr.IsValid());
BOOST_REQUIRE(addr.IsIPv6());
BOOST_CHECK(!addr.IsBindAny());
BOOST_CHECK_EQUAL(addr.ToStringAddr(), scoped_addr);
// Test that the delimiter "%" and default zone id of 0 can be omitted for the default scope.
addr = LookupHost(link_local + "%0", false).value();
BOOST_REQUIRE(addr.IsValid());
BOOST_REQUIRE(addr.IsIPv6());
BOOST_CHECK(!addr.IsBindAny());
BOOST_CHECK_EQUAL(addr.ToStringAddr(), link_local);
// TORv2, no longer supported
BOOST_CHECK(!addr.SetSpecial("6hzph5hv6337r6p2.onion"));
// TORv3
const char* torv3_addr = "pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion";
BOOST_REQUIRE(addr.SetSpecial(torv3_addr));
BOOST_REQUIRE(addr.IsValid());
BOOST_REQUIRE(addr.IsTor());
BOOST_CHECK(!addr.IsI2P());
BOOST_CHECK(!addr.IsBindAny());
BOOST_CHECK(!addr.IsAddrV1Compatible());
BOOST_CHECK_EQUAL(addr.ToStringAddr(), torv3_addr);
// TORv3, broken, with wrong checksum
BOOST_CHECK(!addr.SetSpecial("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscsad.onion"));
// TORv3, broken, with wrong version
BOOST_CHECK(!addr.SetSpecial("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscrye.onion"));
// TORv3, malicious
BOOST_CHECK(!addr.SetSpecial(std::string{
"pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd\0wtf.onion", 66}));
// TOR, bogus length
BOOST_CHECK(!addr.SetSpecial(std::string{"mfrggzak.onion"}));
// TOR, invalid base32
BOOST_CHECK(!addr.SetSpecial(std::string{"mf*g zak.onion"}));
// I2P
const char* i2p_addr = "UDHDrtrcetjm5sxzskjyr5ztpeszydbh4dpl3pl4utgqqw2v4jna.b32.I2P";
BOOST_REQUIRE(addr.SetSpecial(i2p_addr));
BOOST_REQUIRE(addr.IsValid());
BOOST_REQUIRE(addr.IsI2P());
BOOST_CHECK(!addr.IsTor());
BOOST_CHECK(!addr.IsBindAny());
BOOST_CHECK(!addr.IsAddrV1Compatible());
BOOST_CHECK_EQUAL(addr.ToStringAddr(), ToLower(i2p_addr));
// I2P, correct length, but decodes to less than the expected number of bytes.
BOOST_CHECK(!addr.SetSpecial("udhdrtrcetjm5sxzskjyr5ztpeszydbh4dpl3pl4utgqqw2v4jn=.b32.i2p"));
// I2P, extra unnecessary padding
BOOST_CHECK(!addr.SetSpecial("udhdrtrcetjm5sxzskjyr5ztpeszydbh4dpl3pl4utgqqw2v4jna=.b32.i2p"));
// I2P, malicious
BOOST_CHECK(!addr.SetSpecial("udhdrtrcetjm5sxzskjyr5ztpeszydbh4dpl3pl4utgqqw2v\0wtf.b32.i2p"s));
// I2P, valid but unsupported (56 Base32 characters)
// See "Encrypted LS with Base 32 Addresses" in
// https://geti2p.net/spec/encryptedleaseset.txt
BOOST_CHECK(
!addr.SetSpecial("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscsad.b32.i2p"));
// I2P, invalid base32
BOOST_CHECK(!addr.SetSpecial(std::string{"tp*szydbh4dp.b32.i2p"}));
// Internal
addr.SetInternal("esffpp");
BOOST_REQUIRE(!addr.IsValid()); // "internal" is considered invalid
BOOST_REQUIRE(addr.IsInternal());
BOOST_CHECK(!addr.IsBindAny());
BOOST_CHECK(addr.IsAddrV1Compatible());
BOOST_CHECK_EQUAL(addr.ToStringAddr(), "esffpvrt3wpeaygy.internal");
// Totally bogus
BOOST_CHECK(!addr.SetSpecial("totally bogus"));
}
BOOST_AUTO_TEST_CASE(cnetaddr_tostring_canonical_ipv6)
{
// Test that CNetAddr::ToString formats IPv6 addresses with zero compression as described in
// RFC 5952 ("A Recommendation for IPv6 Address Text Representation").
const std::map<std::string, std::string> canonical_representations_ipv6{
{"0000:0000:0000:0000:0000:0000:0000:0000", "::"},
{"000:0000:000:00:0:00:000:0000", "::"},
{"000:000:000:000:000:000:000:000", "::"},
{"00:00:00:00:00:00:00:00", "::"},
{"0:0:0:0:0:0:0:0", "::"},
{"0:0:0:0:0:0:0:1", "::1"},
{"2001:0:0:1:0:0:0:1", "2001:0:0:1::1"},
{"2001:0db8:0:0:1:0:0:1", "2001:db8::1:0:0:1"},
{"2001:0db8:85a3:0000:0000:8a2e:0370:7334", "2001:db8:85a3::8a2e:370:7334"},
{"2001:0db8::0001", "2001:db8::1"},
{"2001:0db8::0001:0000", "2001:db8::1:0"},
{"2001:0db8::1:0:0:1", "2001:db8::1:0:0:1"},
{"2001:db8:0000:0:1::1", "2001:db8::1:0:0:1"},
{"2001:db8:0000:1:1:1:1:1", "2001:db8:0:1:1:1:1:1"},
{"2001:db8:0:0:0:0:2:1", "2001:db8::2:1"},
{"2001:db8:0:0:0::1", "2001:db8::1"},
{"2001:db8:0:0:1:0:0:1", "2001:db8::1:0:0:1"},
{"2001:db8:0:0:1::1", "2001:db8::1:0:0:1"},
{"2001:DB8:0:0:1::1", "2001:db8::1:0:0:1"},
{"2001:db8:0:0::1", "2001:db8::1"},
{"2001:db8:0:0:aaaa::1", "2001:db8::aaaa:0:0:1"},
{"2001:db8:0:1:1:1:1:1", "2001:db8:0:1:1:1:1:1"},
{"2001:db8:0::1", "2001:db8::1"},
{"2001:db8:85a3:0:0:8a2e:370:7334", "2001:db8:85a3::8a2e:370:7334"},
{"2001:db8::0:1", "2001:db8::1"},
{"2001:db8::0:1:0:0:1", "2001:db8::1:0:0:1"},
{"2001:DB8::1", "2001:db8::1"},
{"2001:db8::1", "2001:db8::1"},
{"2001:db8::1:0:0:1", "2001:db8::1:0:0:1"},
{"2001:db8::1:1:1:1:1", "2001:db8:0:1:1:1:1:1"},
{"2001:db8::aaaa:0:0:1", "2001:db8::aaaa:0:0:1"},
{"2001:db8:aaaa:bbbb:cccc:dddd:0:1", "2001:db8:aaaa:bbbb:cccc:dddd:0:1"},
{"2001:db8:aaaa:bbbb:cccc:dddd::1", "2001:db8:aaaa:bbbb:cccc:dddd:0:1"},
{"2001:db8:aaaa:bbbb:cccc:dddd:eeee:0001", "2001:db8:aaaa:bbbb:cccc:dddd:eeee:1"},
{"2001:db8:aaaa:bbbb:cccc:dddd:eeee:001", "2001:db8:aaaa:bbbb:cccc:dddd:eeee:1"},
{"2001:db8:aaaa:bbbb:cccc:dddd:eeee:01", "2001:db8:aaaa:bbbb:cccc:dddd:eeee:1"},
{"2001:db8:aaaa:bbbb:cccc:dddd:eeee:1", "2001:db8:aaaa:bbbb:cccc:dddd:eeee:1"},
{"2001:db8:aaaa:bbbb:cccc:dddd:eeee:aaaa", "2001:db8:aaaa:bbbb:cccc:dddd:eeee:aaaa"},
{"2001:db8:aaaa:bbbb:cccc:dddd:eeee:AAAA", "2001:db8:aaaa:bbbb:cccc:dddd:eeee:aaaa"},
{"2001:db8:aaaa:bbbb:cccc:dddd:eeee:AaAa", "2001:db8:aaaa:bbbb:cccc:dddd:eeee:aaaa"},
};
for (const auto& [input_address, expected_canonical_representation_output] : canonical_representations_ipv6) {
const std::optional<CNetAddr> net_addr{LookupHost(input_address, false)};
BOOST_REQUIRE(net_addr.value().IsIPv6());
BOOST_CHECK_EQUAL(net_addr.value().ToStringAddr(), expected_canonical_representation_output);
}
}
BOOST_AUTO_TEST_CASE(cnetaddr_serialize_v1)
{
CNetAddr addr;
CDataStream s(SER_NETWORK, PROTOCOL_VERSION);
s << addr;
BOOST_CHECK_EQUAL(HexStr(s), "00000000000000000000000000000000");
s.clear();
addr = LookupHost("1.2.3.4", false).value();
s << addr;
BOOST_CHECK_EQUAL(HexStr(s), "00000000000000000000ffff01020304");
s.clear();
addr = LookupHost("1a1b:2a2b:3a3b:4a4b:5a5b:6a6b:7a7b:8a8b", false).value();
s << addr;
BOOST_CHECK_EQUAL(HexStr(s), "1a1b2a2b3a3b4a4b5a5b6a6b7a7b8a8b");
s.clear();
// TORv2, no longer supported
BOOST_CHECK(!addr.SetSpecial("6hzph5hv6337r6p2.onion"));
BOOST_REQUIRE(addr.SetSpecial("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion"));
s << addr;
BOOST_CHECK_EQUAL(HexStr(s), "00000000000000000000000000000000");
s.clear();
addr.SetInternal("a");
s << addr;
BOOST_CHECK_EQUAL(HexStr(s), "fd6b88c08724ca978112ca1bbdcafac2");
s.clear();
}
BOOST_AUTO_TEST_CASE(cnetaddr_serialize_v2)
{
CNetAddr addr;
CDataStream s(SER_NETWORK, PROTOCOL_VERSION);
// Add ADDRV2_FORMAT to the version so that the CNetAddr
// serialize method produces an address in v2 format.
s.SetVersion(s.GetVersion() | ADDRV2_FORMAT);
s << addr;
BOOST_CHECK_EQUAL(HexStr(s), "021000000000000000000000000000000000");
s.clear();
addr = LookupHost("1.2.3.4", false).value();
s << addr;
BOOST_CHECK_EQUAL(HexStr(s), "010401020304");
s.clear();
addr = LookupHost("1a1b:2a2b:3a3b:4a4b:5a5b:6a6b:7a7b:8a8b", false).value();
s << addr;
BOOST_CHECK_EQUAL(HexStr(s), "02101a1b2a2b3a3b4a4b5a5b6a6b7a7b8a8b");
s.clear();
// TORv2, no longer supported
BOOST_CHECK(!addr.SetSpecial("6hzph5hv6337r6p2.onion"));
BOOST_REQUIRE(addr.SetSpecial("kpgvmscirrdqpekbqjsvw5teanhatztpp2gl6eee4zkowvwfxwenqaid.onion"));
s << addr;
BOOST_CHECK_EQUAL(HexStr(s), "042053cd5648488c4707914182655b7664034e09e66f7e8cbf1084e654eb56c5bd88");
s.clear();
BOOST_REQUIRE(addr.SetInternal("a"));
s << addr;
BOOST_CHECK_EQUAL(HexStr(s), "0210fd6b88c08724ca978112ca1bbdcafac2");
s.clear();
}
BOOST_AUTO_TEST_CASE(cnetaddr_unserialize_v2)
{
CNetAddr addr;
CDataStream s(SER_NETWORK, PROTOCOL_VERSION);
// Add ADDRV2_FORMAT to the version so that the CNetAddr
// unserialize method expects an address in v2 format.
s.SetVersion(s.GetVersion() | ADDRV2_FORMAT);
// Valid IPv4.
s << Span{ParseHex("01" // network type (IPv4)
"04" // address length
"01020304")}; // address
s >> addr;
BOOST_CHECK(addr.IsValid());
BOOST_CHECK(addr.IsIPv4());
BOOST_CHECK(addr.IsAddrV1Compatible());
BOOST_CHECK_EQUAL(addr.ToStringAddr(), "1.2.3.4");
BOOST_REQUIRE(s.empty());
// Invalid IPv4, valid length but address itself is shorter.
s << Span{ParseHex("01" // network type (IPv4)
"04" // address length
"0102")}; // address
BOOST_CHECK_EXCEPTION(s >> addr, std::ios_base::failure, HasReason("end of data"));
BOOST_REQUIRE(!s.empty()); // The stream is not consumed on invalid input.
s.clear();
// Invalid IPv4, with bogus length.
s << Span{ParseHex("01" // network type (IPv4)
"05" // address length
"01020304")}; // address
BOOST_CHECK_EXCEPTION(s >> addr, std::ios_base::failure,
HasReason("BIP155 IPv4 address with length 5 (should be 4)"));
BOOST_REQUIRE(!s.empty()); // The stream is not consumed on invalid input.
s.clear();
// Invalid IPv4, with extreme length.
s << Span{ParseHex("01" // network type (IPv4)
"fd0102" // address length (513 as CompactSize)
"01020304")}; // address
BOOST_CHECK_EXCEPTION(s >> addr, std::ios_base::failure,
HasReason("Address too long: 513 > 512"));
BOOST_REQUIRE(!s.empty()); // The stream is not consumed on invalid input.
s.clear();
// Valid IPv6.
s << Span{ParseHex("02" // network type (IPv6)
"10" // address length
"0102030405060708090a0b0c0d0e0f10")}; // address
s >> addr;
BOOST_CHECK(addr.IsValid());
BOOST_CHECK(addr.IsIPv6());
BOOST_CHECK(addr.IsAddrV1Compatible());
BOOST_CHECK_EQUAL(addr.ToStringAddr(), "102:304:506:708:90a:b0c:d0e:f10");
BOOST_REQUIRE(s.empty());
// Valid IPv6, contains embedded "internal".
s << Span{ParseHex(
"02" // network type (IPv6)
"10" // address length
"fd6b88c08724ca978112ca1bbdcafac2")}; // address: 0xfd + sha256("bitcoin")[0:5] +
// sha256(name)[0:10]
s >> addr;
BOOST_CHECK(addr.IsInternal());
BOOST_CHECK(addr.IsAddrV1Compatible());
BOOST_CHECK_EQUAL(addr.ToStringAddr(), "zklycewkdo64v6wc.internal");
BOOST_REQUIRE(s.empty());
// Invalid IPv6, with bogus length.
s << Span{ParseHex("02" // network type (IPv6)
"04" // address length
"00")}; // address
BOOST_CHECK_EXCEPTION(s >> addr, std::ios_base::failure,
HasReason("BIP155 IPv6 address with length 4 (should be 16)"));
BOOST_REQUIRE(!s.empty()); // The stream is not consumed on invalid input.
s.clear();
// Invalid IPv6, contains embedded IPv4.
s << Span{ParseHex("02" // network type (IPv6)
"10" // address length
"00000000000000000000ffff01020304")}; // address
s >> addr;
BOOST_CHECK(!addr.IsValid());
BOOST_REQUIRE(s.empty());
// Invalid IPv6, contains embedded TORv2.
s << Span{ParseHex("02" // network type (IPv6)
"10" // address length
"fd87d87eeb430102030405060708090a")}; // address
s >> addr;
BOOST_CHECK(!addr.IsValid());
BOOST_REQUIRE(s.empty());
// TORv2, no longer supported.
s << Span{ParseHex("03" // network type (TORv2)
"0a" // address length
"f1f2f3f4f5f6f7f8f9fa")}; // address
s >> addr;
BOOST_CHECK(!addr.IsValid());
BOOST_REQUIRE(s.empty());
// Valid TORv3.
s << Span{ParseHex("04" // network type (TORv3)
"20" // address length
"79bcc625184b05194975c28b66b66b04" // address
"69f7f6556fb1ac3189a79b40dda32f1f"
)};
s >> addr;
BOOST_CHECK(addr.IsValid());
BOOST_CHECK(addr.IsTor());
BOOST_CHECK(!addr.IsAddrV1Compatible());
BOOST_CHECK_EQUAL(addr.ToStringAddr(),
"pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion");
BOOST_REQUIRE(s.empty());
// Invalid TORv3, with bogus length.
s << Span{ParseHex("04" // network type (TORv3)
"00" // address length
"00" // address
)};
BOOST_CHECK_EXCEPTION(s >> addr, std::ios_base::failure,
HasReason("BIP155 TORv3 address with length 0 (should be 32)"));
BOOST_REQUIRE(!s.empty()); // The stream is not consumed on invalid input.
s.clear();
// Valid I2P.
s << Span{ParseHex("05" // network type (I2P)
"20" // address length
"a2894dabaec08c0051a481a6dac88b64" // address
"f98232ae42d4b6fd2fa81952dfe36a87")};
s >> addr;
BOOST_CHECK(addr.IsValid());
BOOST_CHECK(addr.IsI2P());
BOOST_CHECK(!addr.IsAddrV1Compatible());
BOOST_CHECK_EQUAL(addr.ToStringAddr(),
"ukeu3k5oycgaauneqgtnvselmt4yemvoilkln7jpvamvfx7dnkdq.b32.i2p");
BOOST_REQUIRE(s.empty());
// Invalid I2P, with bogus length.
s << Span{ParseHex("05" // network type (I2P)
"03" // address length
"00" // address
)};
BOOST_CHECK_EXCEPTION(s >> addr, std::ios_base::failure,
HasReason("BIP155 I2P address with length 3 (should be 32)"));
BOOST_REQUIRE(!s.empty()); // The stream is not consumed on invalid input.
s.clear();
// Valid CJDNS.
s << Span{ParseHex("06" // network type (CJDNS)
"10" // address length
"fc000001000200030004000500060007" // address
)};
s >> addr;
BOOST_CHECK(addr.IsValid());
BOOST_CHECK(addr.IsCJDNS());
BOOST_CHECK(!addr.IsAddrV1Compatible());
BOOST_CHECK_EQUAL(addr.ToStringAddr(), "fc00:1:2:3:4:5:6:7");
BOOST_REQUIRE(s.empty());
// Invalid CJDNS, wrong prefix.
s << Span{ParseHex("06" // network type (CJDNS)
"10" // address length
"aa000001000200030004000500060007" // address
)};
s >> addr;
BOOST_CHECK(addr.IsCJDNS());
BOOST_CHECK(!addr.IsValid());
BOOST_REQUIRE(s.empty());
// Invalid CJDNS, with bogus length.
s << Span{ParseHex("06" // network type (CJDNS)
"01" // address length
"00" // address
)};
BOOST_CHECK_EXCEPTION(s >> addr, std::ios_base::failure,
HasReason("BIP155 CJDNS address with length 1 (should be 16)"));
BOOST_REQUIRE(!s.empty()); // The stream is not consumed on invalid input.
s.clear();
// Unknown, with extreme length.
s << Span{ParseHex("aa" // network type (unknown)
"fe00000002" // address length (CompactSize's MAX_SIZE)
"01020304050607" // address
)};
BOOST_CHECK_EXCEPTION(s >> addr, std::ios_base::failure,
HasReason("Address too long: 33554432 > 512"));
BOOST_REQUIRE(!s.empty()); // The stream is not consumed on invalid input.
s.clear();
// Unknown, with reasonable length.
s << Span{ParseHex("aa" // network type (unknown)
"04" // address length
"01020304" // address
)};
s >> addr;
BOOST_CHECK(!addr.IsValid());
BOOST_REQUIRE(s.empty());
// Unknown, with zero length.
s << Span{ParseHex("aa" // network type (unknown)
"00" // address length
"" // address
)};
s >> addr;
BOOST_CHECK(!addr.IsValid());
BOOST_REQUIRE(s.empty());
}
// prior to PR #14728, this test triggers an undefined behavior
BOOST_AUTO_TEST_CASE(ipv4_peer_with_ipv6_addrMe_test)
{
// set up local addresses; all that's necessary to reproduce the bug is
// that a normal IPv4 address is among the entries, but if this address is
// !IsRoutable the undefined behavior is easier to trigger deterministically
in_addr raw_addr;
raw_addr.s_addr = htonl(0x7f000001);
const CNetAddr mapLocalHost_entry = CNetAddr(raw_addr);
{
LOCK(g_maplocalhost_mutex);
LocalServiceInfo lsi;
lsi.nScore = 23;
lsi.nPort = 42;
mapLocalHost[mapLocalHost_entry] = lsi;
}
// create a peer with an IPv4 address
in_addr ipv4AddrPeer;
ipv4AddrPeer.s_addr = 0xa0b0c001;
CAddress addr = CAddress(CService(ipv4AddrPeer, 7777), NODE_NETWORK);
std::unique_ptr<CNode> pnode = std::make_unique<CNode>(/*id=*/0,
/*sock=*/nullptr,
addr,
/*nKeyedNetGroupIn=*/0,
/*nLocalHostNonceIn=*/0,
CAddress{},
/*pszDest=*/std::string{},
ConnectionType::OUTBOUND_FULL_RELAY,
/*inbound_onion=*/false);
pnode->fSuccessfullyConnected.store(true);
// the peer claims to be reaching us via IPv6
in6_addr ipv6AddrLocal;
memset(ipv6AddrLocal.s6_addr, 0, 16);
ipv6AddrLocal.s6_addr[0] = 0xcc;
CAddress addrLocal = CAddress(CService(ipv6AddrLocal, 7777), NODE_NETWORK);
pnode->SetAddrLocal(addrLocal);
// before patch, this causes undefined behavior detectable with clang's -fsanitize=memory
GetLocalAddrForPeer(*pnode);
// suppress no-checks-run warning; if this test fails, it's by triggering a sanitizer
BOOST_CHECK(1);
// Cleanup, so that we don't confuse other tests.
{
LOCK(g_maplocalhost_mutex);
mapLocalHost.erase(mapLocalHost_entry);
}
}
BOOST_AUTO_TEST_CASE(get_local_addr_for_peer_port)
{
// Test that GetLocalAddrForPeer() properly selects the address to self-advertise:
//
// 1. GetLocalAddrForPeer() calls GetLocalAddress() which returns an address that is
// not routable.
// 2. GetLocalAddrForPeer() overrides the address with whatever the peer has told us
// he sees us as.
// 2.1. For inbound connections we must override both the address and the port.
// 2.2. For outbound connections we must override only the address.
// Pretend that we bound to this port.
const uint16_t bind_port = 20001;
m_node.args->ForceSetArg("-bind", strprintf("3.4.5.6:%u", bind_port));
// Our address:port as seen from the peer, completely different from the above.
in_addr peer_us_addr;
peer_us_addr.s_addr = htonl(0x02030405);
const CService peer_us{peer_us_addr, 20002};
// Create a peer with a routable IPv4 address (outbound).
in_addr peer_out_in_addr;
peer_out_in_addr.s_addr = htonl(0x01020304);
CNode peer_out{/*id=*/0,
/*sock=*/nullptr,
/*addrIn=*/CAddress{CService{peer_out_in_addr, 8333}, NODE_NETWORK},
/*nKeyedNetGroupIn=*/0,
/*nLocalHostNonceIn=*/0,
/*addrBindIn=*/CAddress{},
/*addrNameIn=*/std::string{},
/*conn_type_in=*/ConnectionType::OUTBOUND_FULL_RELAY,
/*inbound_onion=*/false};
peer_out.fSuccessfullyConnected = true;
peer_out.SetAddrLocal(peer_us);
// Without the fix peer_us:8333 is chosen instead of the proper peer_us:bind_port.
auto chosen_local_addr = GetLocalAddrForPeer(peer_out);
BOOST_REQUIRE(chosen_local_addr);
const CService expected{peer_us_addr, bind_port};
BOOST_CHECK(*chosen_local_addr == expected);
// Create a peer with a routable IPv4 address (inbound).
in_addr peer_in_in_addr;
peer_in_in_addr.s_addr = htonl(0x05060708);
CNode peer_in{/*id=*/0,
/*sock=*/nullptr,
/*addrIn=*/CAddress{CService{peer_in_in_addr, 8333}, NODE_NETWORK},
/*nKeyedNetGroupIn=*/0,
/*nLocalHostNonceIn=*/0,
/*addrBindIn=*/CAddress{},
/*addrNameIn=*/std::string{},
/*conn_type_in=*/ConnectionType::INBOUND,
/*inbound_onion=*/false};
peer_in.fSuccessfullyConnected = true;
peer_in.SetAddrLocal(peer_us);
// Without the fix peer_us:8333 is chosen instead of the proper peer_us:peer_us.GetPort().
chosen_local_addr = GetLocalAddrForPeer(peer_in);
BOOST_REQUIRE(chosen_local_addr);
BOOST_CHECK(*chosen_local_addr == peer_us);
m_node.args->ForceSetArg("-bind", "");
}
BOOST_AUTO_TEST_CASE(LimitedAndReachable_Network)
{
BOOST_CHECK(g_reachable_nets.Contains(NET_IPV4));
BOOST_CHECK(g_reachable_nets.Contains(NET_IPV6));
BOOST_CHECK(g_reachable_nets.Contains(NET_ONION));
BOOST_CHECK(g_reachable_nets.Contains(NET_I2P));
BOOST_CHECK(g_reachable_nets.Contains(NET_CJDNS));
g_reachable_nets.Remove(NET_IPV4);
g_reachable_nets.Remove(NET_IPV6);
g_reachable_nets.Remove(NET_ONION);
g_reachable_nets.Remove(NET_I2P);
g_reachable_nets.Remove(NET_CJDNS);
BOOST_CHECK(!g_reachable_nets.Contains(NET_IPV4));
BOOST_CHECK(!g_reachable_nets.Contains(NET_IPV6));
BOOST_CHECK(!g_reachable_nets.Contains(NET_ONION));
BOOST_CHECK(!g_reachable_nets.Contains(NET_I2P));
BOOST_CHECK(!g_reachable_nets.Contains(NET_CJDNS));
g_reachable_nets.Add(NET_IPV4);
g_reachable_nets.Add(NET_IPV6);