Bitcoin Core 28.99.0
P2P Digital Currency
netaddress.cpp
Go to the documentation of this file.
1// Copyright (c) 2009-2010 Satoshi Nakamoto
2// Copyright (c) 2009-2022 The Bitcoin Core developers
3// Distributed under the MIT software license, see the accompanying
4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6#include <netaddress.h>
7
8#include <crypto/common.h>
9#include <crypto/sha3.h>
10#include <hash.h>
11#include <prevector.h>
12#include <tinyformat.h>
13#include <util/strencodings.h>
14#include <util/string.h>
15
16#include <algorithm>
17#include <array>
18#include <cstdint>
19#include <ios>
20#include <iterator>
21#include <tuple>
22
24using util::HasPrefix;
25
27{
28 switch (m_net) {
29 case NET_IPV4:
31 case NET_IPV6:
33 case NET_ONION:
34 return BIP155Network::TORV3;
35 case NET_I2P:
36 return BIP155Network::I2P;
37 case NET_CJDNS:
38 return BIP155Network::CJDNS;
39 case NET_INTERNAL: // should have been handled before calling this function
40 case NET_UNROUTABLE: // m_net is never and should not be set to NET_UNROUTABLE
41 case NET_MAX: // m_net is never and should not be set to NET_MAX
42 assert(false);
43 } // no default case, so the compiler can warn about missing cases
44
45 assert(false);
46}
47
48bool CNetAddr::SetNetFromBIP155Network(uint8_t possible_bip155_net, size_t address_size)
49{
50 switch (possible_bip155_net) {
52 if (address_size == ADDR_IPV4_SIZE) {
54 return true;
55 }
56 throw std::ios_base::failure(
57 strprintf("BIP155 IPv4 address with length %u (should be %u)", address_size,
60 if (address_size == ADDR_IPV6_SIZE) {
62 return true;
63 }
64 throw std::ios_base::failure(
65 strprintf("BIP155 IPv6 address with length %u (should be %u)", address_size,
67 case BIP155Network::TORV3:
68 if (address_size == ADDR_TORV3_SIZE) {
70 return true;
71 }
72 throw std::ios_base::failure(
73 strprintf("BIP155 TORv3 address with length %u (should be %u)", address_size,
76 if (address_size == ADDR_I2P_SIZE) {
77 m_net = NET_I2P;
78 return true;
79 }
80 throw std::ios_base::failure(
81 strprintf("BIP155 I2P address with length %u (should be %u)", address_size,
83 case BIP155Network::CJDNS:
84 if (address_size == ADDR_CJDNS_SIZE) {
86 return true;
87 }
88 throw std::ios_base::failure(
89 strprintf("BIP155 CJDNS address with length %u (should be %u)", address_size,
91 }
92
93 // Don't throw on addresses with unknown network ids (maybe from the future).
94 // Instead silently drop them and have the unserialization code consume
95 // subsequent ones which may be known to us.
96 return false;
97}
98
104CNetAddr::CNetAddr() = default;
105
106void CNetAddr::SetIP(const CNetAddr& ipIn)
107{
108 // Size check.
109 switch (ipIn.m_net) {
110 case NET_IPV4:
111 assert(ipIn.m_addr.size() == ADDR_IPV4_SIZE);
112 break;
113 case NET_IPV6:
114 assert(ipIn.m_addr.size() == ADDR_IPV6_SIZE);
115 break;
116 case NET_ONION:
118 break;
119 case NET_I2P:
120 assert(ipIn.m_addr.size() == ADDR_I2P_SIZE);
121 break;
122 case NET_CJDNS:
124 break;
125 case NET_INTERNAL:
127 break;
128 case NET_UNROUTABLE:
129 case NET_MAX:
130 assert(false);
131 } // no default case, so the compiler can warn about missing cases
132
133 m_net = ipIn.m_net;
134 m_addr = ipIn.m_addr;
135}
136
138{
139 assert(ipv6.size() == ADDR_IPV6_SIZE);
140
141 size_t skip{0};
142
143 if (HasPrefix(ipv6, IPV4_IN_IPV6_PREFIX)) {
144 // IPv4-in-IPv6
145 m_net = NET_IPV4;
146 skip = sizeof(IPV4_IN_IPV6_PREFIX);
147 } else if (HasPrefix(ipv6, TORV2_IN_IPV6_PREFIX)) {
148 // TORv2-in-IPv6 (unsupported). Unserialize as !IsValid(), thus ignoring them.
149 // Mimic a default-constructed CNetAddr object which is !IsValid() and thus
150 // will not be gossiped, but continue reading next addresses from the stream.
151 m_net = NET_IPV6;
153 return;
154 } else if (HasPrefix(ipv6, INTERNAL_IN_IPV6_PREFIX)) {
155 // Internal-in-IPv6
157 skip = sizeof(INTERNAL_IN_IPV6_PREFIX);
158 } else {
159 // IPv6
160 m_net = NET_IPV6;
161 }
162
163 m_addr.assign(ipv6.begin() + skip, ipv6.end());
164}
165
172bool CNetAddr::SetInternal(const std::string &name)
173{
174 if (name.empty()) {
175 return false;
176 }
178 unsigned char hash[32] = {};
179 CSHA256().Write((const unsigned char*)name.data(), name.size()).Finalize(hash);
180 m_addr.assign(hash, hash + ADDR_INTERNAL_SIZE);
181 return true;
182}
183
184namespace torv3 {
185// https://gitweb.torproject.org/torspec.git/tree/rend-spec-v3.txt?id=7116c9cdaba248aae07a3f1d0e15d9dd102f62c5#n2175
186static constexpr size_t CHECKSUM_LEN = 2;
187static const unsigned char VERSION[] = {3};
188static constexpr size_t TOTAL_LEN = ADDR_TORV3_SIZE + CHECKSUM_LEN + sizeof(VERSION);
189
190static void Checksum(Span<const uint8_t> addr_pubkey, uint8_t (&checksum)[CHECKSUM_LEN])
191{
192 // TORv3 CHECKSUM = H(".onion checksum" | PUBKEY | VERSION)[:2]
193 static const unsigned char prefix[] = ".onion checksum";
194 static constexpr size_t prefix_len = 15;
195
196 SHA3_256 hasher;
197
198 hasher.Write(Span{prefix}.first(prefix_len));
199 hasher.Write(addr_pubkey);
200 hasher.Write(VERSION);
201
202 uint8_t checksum_full[SHA3_256::OUTPUT_SIZE];
203
204 hasher.Finalize(checksum_full);
205
206 memcpy(checksum, checksum_full, sizeof(checksum));
207}
208
209}; // namespace torv3
210
211bool CNetAddr::SetSpecial(const std::string& addr)
212{
213 if (!ContainsNoNUL(addr)) {
214 return false;
215 }
216
217 if (SetTor(addr)) {
218 return true;
219 }
220
221 if (SetI2P(addr)) {
222 return true;
223 }
224
225 return false;
226}
227
228bool CNetAddr::SetTor(const std::string& addr)
229{
230 static const char* suffix{".onion"};
231 static constexpr size_t suffix_len{6};
232
233 if (addr.size() <= suffix_len || addr.substr(addr.size() - suffix_len) != suffix) {
234 return false;
235 }
236
237 auto input = DecodeBase32(std::string_view{addr}.substr(0, addr.size() - suffix_len));
238
239 if (!input) {
240 return false;
241 }
242
243 if (input->size() == torv3::TOTAL_LEN) {
244 Span<const uint8_t> input_pubkey{input->data(), ADDR_TORV3_SIZE};
247
248 if (!std::ranges::equal(input_version, torv3::VERSION)) {
249 return false;
250 }
251
252 uint8_t calculated_checksum[torv3::CHECKSUM_LEN];
253 torv3::Checksum(input_pubkey, calculated_checksum);
254
255 if (!std::ranges::equal(input_checksum, calculated_checksum)) {
256 return false;
257 }
258
260 m_addr.assign(input_pubkey.begin(), input_pubkey.end());
261 return true;
262 }
263
264 return false;
265}
266
267bool CNetAddr::SetI2P(const std::string& addr)
268{
269 // I2P addresses that we support consist of 52 base32 characters + ".b32.i2p".
270 static constexpr size_t b32_len{52};
271 static const char* suffix{".b32.i2p"};
272 static constexpr size_t suffix_len{8};
273
274 if (addr.size() != b32_len + suffix_len || ToLower(addr.substr(b32_len)) != suffix) {
275 return false;
276 }
277
278 // Remove the ".b32.i2p" suffix and pad to a multiple of 8 chars, so DecodeBase32()
279 // can decode it.
280 const std::string b32_padded = addr.substr(0, b32_len) + "====";
281
282 auto address_bytes = DecodeBase32(b32_padded);
283
284 if (!address_bytes || address_bytes->size() != ADDR_I2P_SIZE) {
285 return false;
286 }
287
288 m_net = NET_I2P;
289 m_addr.assign(address_bytes->begin(), address_bytes->end());
290
291 return true;
292}
293
294CNetAddr::CNetAddr(const struct in_addr& ipv4Addr)
295{
296 m_net = NET_IPV4;
297 const uint8_t* ptr = reinterpret_cast<const uint8_t*>(&ipv4Addr);
298 m_addr.assign(ptr, ptr + ADDR_IPV4_SIZE);
299}
300
301CNetAddr::CNetAddr(const struct in6_addr& ipv6Addr, const uint32_t scope)
302{
303 SetLegacyIPv6({reinterpret_cast<const uint8_t*>(&ipv6Addr), sizeof(ipv6Addr)});
304 m_scope_id = scope;
305}
306
308{
309 if (!IsIPv4() && !IsIPv6()) {
310 return false;
311 }
312 return std::all_of(m_addr.begin(), m_addr.end(), [](uint8_t b) { return b == 0; });
313}
314
316{
317 return IsIPv4() && (
318 m_addr[0] == 10 ||
319 (m_addr[0] == 192 && m_addr[1] == 168) ||
320 (m_addr[0] == 172 && m_addr[1] >= 16 && m_addr[1] <= 31));
321}
322
324{
325 return IsIPv4() && m_addr[0] == 198 && (m_addr[1] == 18 || m_addr[1] == 19);
326}
327
329{
330 return IsIPv4() && HasPrefix(m_addr, std::array<uint8_t, 2>{169, 254});
331}
332
334{
335 return IsIPv4() && m_addr[0] == 100 && m_addr[1] >= 64 && m_addr[1] <= 127;
336}
337
339{
340 return IsIPv4() && (HasPrefix(m_addr, std::array<uint8_t, 3>{192, 0, 2}) ||
341 HasPrefix(m_addr, std::array<uint8_t, 3>{198, 51, 100}) ||
342 HasPrefix(m_addr, std::array<uint8_t, 3>{203, 0, 113}));
343}
344
346{
347 return IsIPv6() && HasPrefix(m_addr, std::array<uint8_t, 4>{0x20, 0x01, 0x0D, 0xB8});
348}
349
351{
352 return IsIPv6() && HasPrefix(m_addr, std::array<uint8_t, 2>{0x20, 0x02});
353}
354
356{
357 return IsIPv6() &&
358 HasPrefix(m_addr, std::array<uint8_t, 12>{0x00, 0x64, 0xFF, 0x9B, 0x00, 0x00,
359 0x00, 0x00, 0x00, 0x00, 0x00, 0x00});
360}
361
363{
364 return IsIPv6() && HasPrefix(m_addr, std::array<uint8_t, 4>{0x20, 0x01, 0x00, 0x00});
365}
366
368{
369 return IsIPv6() && HasPrefix(m_addr, std::array<uint8_t, 8>{0xFE, 0x80, 0x00, 0x00,
370 0x00, 0x00, 0x00, 0x00});
371}
372
374{
375 return IsIPv6() && (m_addr[0] & 0xFE) == 0xFC;
376}
377
379{
380 return IsIPv6() &&
381 HasPrefix(m_addr, std::array<uint8_t, 12>{0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
382 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00});
383}
384
386{
387 return IsIPv6() && HasPrefix(m_addr, std::array<uint8_t, 3>{0x20, 0x01, 0x00}) &&
388 (m_addr[3] & 0xF0) == 0x10;
389}
390
392{
393 return IsIPv6() && HasPrefix(m_addr, std::array<uint8_t, 3>{0x20, 0x01, 0x00}) &&
394 (m_addr[3] & 0xF0) == 0x20;
395}
396
398{
399 return IsIPv6() && HasPrefix(m_addr, std::array<uint8_t, 4>{0x20, 0x01, 0x04, 0x70});
400}
401
403{
404 // IPv4 loopback (127.0.0.0/8 or 0.0.0.0/8)
405 if (IsIPv4() && (m_addr[0] == 127 || m_addr[0] == 0)) {
406 return true;
407 }
408
409 // IPv6 loopback (::1/128)
410 static const unsigned char pchLocal[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
411 if (IsIPv6() && memcmp(m_addr.data(), pchLocal, sizeof(pchLocal)) == 0) {
412 return true;
413 }
414
415 return false;
416}
417
429{
430 // unspecified IPv6 address (::/128)
431 unsigned char ipNone6[16] = {};
432 if (IsIPv6() && memcmp(m_addr.data(), ipNone6, sizeof(ipNone6)) == 0) {
433 return false;
434 }
435
436 if (IsCJDNS() && !HasCJDNSPrefix()) {
437 return false;
438 }
439
440 // documentation IPv6 address
441 if (IsRFC3849())
442 return false;
443
444 if (IsInternal())
445 return false;
446
447 if (IsIPv4()) {
448 const uint32_t addr = ReadBE32(m_addr.data());
449 if (addr == INADDR_ANY || addr == INADDR_NONE) {
450 return false;
451 }
452 }
453
454 return true;
455}
456
467{
468 return IsValid() && !(IsRFC1918() || IsRFC2544() || IsRFC3927() || IsRFC4862() || IsRFC6598() || IsRFC5737() || IsRFC4193() || IsRFC4843() || IsRFC7343() || IsLocal() || IsInternal());
469}
470
477{
478 return m_net == NET_INTERNAL;
479}
480
482{
483 switch (m_net) {
484 case NET_IPV4:
485 case NET_IPV6:
486 case NET_INTERNAL:
487 return true;
488 case NET_ONION:
489 case NET_I2P:
490 case NET_CJDNS:
491 return false;
492 case NET_UNROUTABLE: // m_net is never and should not be set to NET_UNROUTABLE
493 case NET_MAX: // m_net is never and should not be set to NET_MAX
494 assert(false);
495 } // no default case, so the compiler can warn about missing cases
496
497 assert(false);
498}
499
501{
502 if (IsInternal())
503 return NET_INTERNAL;
504
505 if (!IsRoutable())
506 return NET_UNROUTABLE;
507
508 return m_net;
509}
510
512{
513 return strprintf("%u.%u.%u.%u", a[0], a[1], a[2], a[3]);
514}
515
516// Return an IPv6 address text representation with zero compression as described in RFC 5952
517// ("A Recommendation for IPv6 Address Text Representation").
518static std::string IPv6ToString(Span<const uint8_t> a, uint32_t scope_id)
519{
520 assert(a.size() == ADDR_IPV6_SIZE);
521 const std::array groups{
522 ReadBE16(&a[0]),
523 ReadBE16(&a[2]),
524 ReadBE16(&a[4]),
525 ReadBE16(&a[6]),
526 ReadBE16(&a[8]),
527 ReadBE16(&a[10]),
528 ReadBE16(&a[12]),
529 ReadBE16(&a[14]),
530 };
531
532 // The zero compression implementation is inspired by Rust's std::net::Ipv6Addr, see
533 // https://github.com/rust-lang/rust/blob/cc4103089f40a163f6d143f06359cba7043da29b/library/std/src/net/ip.rs#L1635-L1683
534 struct ZeroSpan {
535 size_t start_index{0};
536 size_t len{0};
537 };
538
539 // Find longest sequence of consecutive all-zero fields. Use first zero sequence if two or more
540 // zero sequences of equal length are found.
541 ZeroSpan longest, current;
542 for (size_t i{0}; i < groups.size(); ++i) {
543 if (groups[i] != 0) {
544 current = {i + 1, 0};
545 continue;
546 }
547 current.len += 1;
548 if (current.len > longest.len) {
549 longest = current;
550 }
551 }
552
553 std::string r;
554 r.reserve(39);
555 for (size_t i{0}; i < groups.size(); ++i) {
556 // Replace the longest sequence of consecutive all-zero fields with two colons ("::").
557 if (longest.len >= 2 && i >= longest.start_index && i < longest.start_index + longest.len) {
558 if (i == longest.start_index) {
559 r += "::";
560 }
561 continue;
562 }
563 r += strprintf("%s%x", ((!r.empty() && r.back() != ':') ? ":" : ""), groups[i]);
564 }
565
566 if (scope_id != 0) {
567 r += strprintf("%%%u", scope_id);
568 }
569
570 return r;
571}
572
574{
575 uint8_t checksum[torv3::CHECKSUM_LEN];
576 torv3::Checksum(addr, checksum);
577 // TORv3 onion_address = base32(PUBKEY | CHECKSUM | VERSION) + ".onion"
578 prevector<torv3::TOTAL_LEN, uint8_t> address{addr.begin(), addr.end()};
579 address.insert(address.end(), checksum, checksum + torv3::CHECKSUM_LEN);
580 address.insert(address.end(), torv3::VERSION, torv3::VERSION + sizeof(torv3::VERSION));
581 return EncodeBase32(address) + ".onion";
582}
583
584std::string CNetAddr::ToStringAddr() const
585{
586 switch (m_net) {
587 case NET_IPV4:
588 return IPv4ToString(m_addr);
589 case NET_IPV6:
591 case NET_ONION:
592 return OnionToString(m_addr);
593 case NET_I2P:
594 return EncodeBase32(m_addr, false /* don't pad with = */) + ".b32.i2p";
595 case NET_CJDNS:
596 return IPv6ToString(m_addr, 0);
597 case NET_INTERNAL:
598 return EncodeBase32(m_addr) + ".internal";
599 case NET_UNROUTABLE: // m_net is never and should not be set to NET_UNROUTABLE
600 case NET_MAX: // m_net is never and should not be set to NET_MAX
601 assert(false);
602 } // no default case, so the compiler can warn about missing cases
603
604 assert(false);
605}
606
607bool operator==(const CNetAddr& a, const CNetAddr& b)
608{
609 return a.m_net == b.m_net && a.m_addr == b.m_addr;
610}
611
612bool operator<(const CNetAddr& a, const CNetAddr& b)
613{
614 return std::tie(a.m_net, a.m_addr) < std::tie(b.m_net, b.m_addr);
615}
616
627bool CNetAddr::GetInAddr(struct in_addr* pipv4Addr) const
628{
629 if (!IsIPv4())
630 return false;
631 assert(sizeof(*pipv4Addr) == m_addr.size());
632 memcpy(pipv4Addr, m_addr.data(), m_addr.size());
633 return true;
634}
635
646bool CNetAddr::GetIn6Addr(struct in6_addr* pipv6Addr) const
647{
648 if (!IsIPv6() && !IsCJDNS()) {
649 return false;
650 }
651 assert(sizeof(*pipv6Addr) == m_addr.size());
652 memcpy(pipv6Addr, m_addr.data(), m_addr.size());
653 return true;
654}
655
657{
658 return IsRoutable() && (IsIPv4() || IsRFC6145() || IsRFC6052() || IsRFC3964() || IsRFC4380());
659}
660
662{
663 if (IsIPv4()) {
664 return ReadBE32(m_addr.data());
665 } else if (IsRFC6052() || IsRFC6145()) {
666 // mapped IPv4, SIIT translated IPv4: the IPv4 address is the last 4 bytes of the address
667 return ReadBE32(Span{m_addr}.last(ADDR_IPV4_SIZE).data());
668 } else if (IsRFC3964()) {
669 // 6to4 tunneled IPv4: the IPv4 address is in bytes 2-6
670 return ReadBE32(Span{m_addr}.subspan(2, ADDR_IPV4_SIZE).data());
671 } else if (IsRFC4380()) {
672 // Teredo tunneled IPv4: the IPv4 address is in the last 4 bytes of the address, but bitflipped
673 return ~ReadBE32(Span{m_addr}.last(ADDR_IPV4_SIZE).data());
674 }
675 assert(false);
676}
677
679{
680 // Make sure that if we return NET_IPV6, then IsIPv6() is true. The callers expect that.
681
682 // Check for "internal" first because such addresses are also !IsRoutable()
683 // and we don't want to return NET_UNROUTABLE in that case.
684 if (IsInternal()) {
685 return NET_INTERNAL;
686 }
687 if (!IsRoutable()) {
688 return NET_UNROUTABLE;
689 }
690 if (HasLinkedIPv4()) {
691 return NET_IPV4;
692 }
693 return m_net;
694}
695
696std::vector<unsigned char> CNetAddr::GetAddrBytes() const
697{
698 if (IsAddrV1Compatible()) {
699 uint8_t serialized[V1_SERIALIZATION_SIZE];
700 SerializeV1Array(serialized);
701 return {std::begin(serialized), std::end(serialized)};
702 }
703 return std::vector<unsigned char>(m_addr.begin(), m_addr.end());
704}
705
706// private extensions to enum Network, only returned by GetExtNetwork,
707// and only used in GetReachabilityFrom
708static const int NET_TEREDO = NET_MAX;
709int static GetExtNetwork(const CNetAddr& addr)
710{
711 if (addr.IsRFC4380())
712 return NET_TEREDO;
713 return addr.GetNetwork();
714}
715
717int CNetAddr::GetReachabilityFrom(const CNetAddr& paddrPartner) const
718{
719 enum Reachability {
720 REACH_UNREACHABLE,
721 REACH_DEFAULT,
722 REACH_TEREDO,
723 REACH_IPV6_WEAK,
724 REACH_IPV4,
725 REACH_IPV6_STRONG,
726 REACH_PRIVATE
727 };
728
729 if (!IsRoutable() || IsInternal())
730 return REACH_UNREACHABLE;
731
732 int ourNet = GetExtNetwork(*this);
733 int theirNet = GetExtNetwork(paddrPartner);
734 bool fTunnel = IsRFC3964() || IsRFC6052() || IsRFC6145();
735
736 switch(theirNet) {
737 case NET_IPV4:
738 switch(ourNet) {
739 default: return REACH_DEFAULT;
740 case NET_IPV4: return REACH_IPV4;
741 }
742 case NET_IPV6:
743 switch(ourNet) {
744 default: return REACH_DEFAULT;
745 case NET_TEREDO: return REACH_TEREDO;
746 case NET_IPV4: return REACH_IPV4;
747 case NET_IPV6: return fTunnel ? REACH_IPV6_WEAK : REACH_IPV6_STRONG; // only prefer giving our IPv6 address if it's not tunnelled
748 }
749 case NET_ONION:
750 switch(ourNet) {
751 default: return REACH_DEFAULT;
752 case NET_IPV4: return REACH_IPV4; // Tor users can connect to IPv4 as well
753 case NET_ONION: return REACH_PRIVATE;
754 }
755 case NET_I2P:
756 switch (ourNet) {
757 case NET_I2P: return REACH_PRIVATE;
758 default: return REACH_DEFAULT;
759 }
760 case NET_CJDNS:
761 switch (ourNet) {
762 case NET_CJDNS: return REACH_PRIVATE;
763 default: return REACH_DEFAULT;
764 }
765 case NET_TEREDO:
766 switch(ourNet) {
767 default: return REACH_DEFAULT;
768 case NET_TEREDO: return REACH_TEREDO;
769 case NET_IPV6: return REACH_IPV6_WEAK;
770 case NET_IPV4: return REACH_IPV4;
771 }
772 case NET_UNROUTABLE:
773 default:
774 switch(ourNet) {
775 default: return REACH_DEFAULT;
776 case NET_TEREDO: return REACH_TEREDO;
777 case NET_IPV6: return REACH_IPV6_WEAK;
778 case NET_IPV4: return REACH_IPV4;
779 case NET_ONION: return REACH_PRIVATE; // either from Tor, or don't care about our address
780 }
781 }
782}
783
785{
786}
787
788CService::CService(const CNetAddr& cip, uint16_t portIn) : CNetAddr(cip), port(portIn)
789{
790}
791
792CService::CService(const struct in_addr& ipv4Addr, uint16_t portIn) : CNetAddr(ipv4Addr), port(portIn)
793{
794}
795
796CService::CService(const struct in6_addr& ipv6Addr, uint16_t portIn) : CNetAddr(ipv6Addr), port(portIn)
797{
798}
799
800CService::CService(const struct sockaddr_in& addr) : CNetAddr(addr.sin_addr), port(ntohs(addr.sin_port))
801{
802 assert(addr.sin_family == AF_INET);
803}
804
805CService::CService(const struct sockaddr_in6 &addr) : CNetAddr(addr.sin6_addr, addr.sin6_scope_id), port(ntohs(addr.sin6_port))
806{
807 assert(addr.sin6_family == AF_INET6);
808}
809
810bool CService::SetSockAddr(const struct sockaddr *paddr)
811{
812 switch (paddr->sa_family) {
813 case AF_INET:
814 *this = CService(*(const struct sockaddr_in*)paddr);
815 return true;
816 case AF_INET6:
817 *this = CService(*(const struct sockaddr_in6*)paddr);
818 return true;
819 default:
820 return false;
821 }
822}
823
824sa_family_t CService::GetSAFamily() const
825{
826 switch (m_net) {
827 case NET_IPV4:
828 return AF_INET;
829 case NET_IPV6:
830 case NET_CJDNS:
831 return AF_INET6;
832 default:
833 return AF_UNSPEC;
834 }
835}
836
837uint16_t CService::GetPort() const
838{
839 return port;
840}
841
842bool operator==(const CService& a, const CService& b)
843{
844 return static_cast<CNetAddr>(a) == static_cast<CNetAddr>(b) && a.port == b.port;
845}
846
847bool operator<(const CService& a, const CService& b)
848{
849 return static_cast<CNetAddr>(a) < static_cast<CNetAddr>(b) || (static_cast<CNetAddr>(a) == static_cast<CNetAddr>(b) && a.port < b.port);
850}
851
864bool CService::GetSockAddr(struct sockaddr* paddr, socklen_t *addrlen) const
865{
866 if (IsIPv4()) {
867 if (*addrlen < (socklen_t)sizeof(struct sockaddr_in))
868 return false;
869 *addrlen = sizeof(struct sockaddr_in);
870 struct sockaddr_in *paddrin = (struct sockaddr_in*)paddr;
871 memset(paddrin, 0, *addrlen);
872 if (!GetInAddr(&paddrin->sin_addr))
873 return false;
874 paddrin->sin_family = AF_INET;
875 paddrin->sin_port = htons(port);
876 return true;
877 }
878 if (IsIPv6() || IsCJDNS()) {
879 if (*addrlen < (socklen_t)sizeof(struct sockaddr_in6))
880 return false;
881 *addrlen = sizeof(struct sockaddr_in6);
882 struct sockaddr_in6 *paddrin6 = (struct sockaddr_in6*)paddr;
883 memset(paddrin6, 0, *addrlen);
884 if (!GetIn6Addr(&paddrin6->sin6_addr))
885 return false;
886 paddrin6->sin6_scope_id = m_scope_id;
887 paddrin6->sin6_family = AF_INET6;
888 paddrin6->sin6_port = htons(port);
889 return true;
890 }
891 return false;
892}
893
897std::vector<unsigned char> CService::GetKey() const
898{
899 auto key = GetAddrBytes();
900 key.push_back(port / 0x100); // most significant byte of our port
901 key.push_back(port & 0x0FF); // least significant byte of our port
902 return key;
903}
904
905std::string CService::ToStringAddrPort() const
906{
907 const auto port_str = strprintf("%u", port);
908
909 if (IsIPv4() || IsTor() || IsI2P() || IsInternal()) {
910 return ToStringAddr() + ":" + port_str;
911 } else {
912 return "[" + ToStringAddr() + "]:" + port_str;
913 }
914}
915
917 valid(false)
918{
919 memset(netmask, 0, sizeof(netmask));
920}
921
922CSubNet::CSubNet(const CNetAddr& addr, uint8_t mask) : CSubNet()
923{
924 valid = (addr.IsIPv4() && mask <= ADDR_IPV4_SIZE * 8) ||
925 (addr.IsIPv6() && mask <= ADDR_IPV6_SIZE * 8);
926 if (!valid) {
927 return;
928 }
929
930 assert(mask <= sizeof(netmask) * 8);
931
932 network = addr;
933
934 uint8_t n = mask;
935 for (size_t i = 0; i < network.m_addr.size(); ++i) {
936 const uint8_t bits = n < 8 ? n : 8;
937 netmask[i] = (uint8_t)((uint8_t)0xFF << (8 - bits)); // Set first bits.
938 network.m_addr[i] &= netmask[i]; // Normalize network according to netmask.
939 n -= bits;
940 }
941}
942
947static inline int NetmaskBits(uint8_t x)
948{
949 switch(x) {
950 case 0x00: return 0;
951 case 0x80: return 1;
952 case 0xc0: return 2;
953 case 0xe0: return 3;
954 case 0xf0: return 4;
955 case 0xf8: return 5;
956 case 0xfc: return 6;
957 case 0xfe: return 7;
958 case 0xff: return 8;
959 default: return -1;
960 }
961}
962
963CSubNet::CSubNet(const CNetAddr& addr, const CNetAddr& mask) : CSubNet()
964{
965 valid = (addr.IsIPv4() || addr.IsIPv6()) && addr.m_net == mask.m_net;
966 if (!valid) {
967 return;
968 }
969 // Check if `mask` contains 1-bits after 0-bits (which is an invalid netmask).
970 bool zeros_found = false;
971 for (auto b : mask.m_addr) {
972 const int num_bits = NetmaskBits(b);
973 if (num_bits == -1 || (zeros_found && num_bits != 0)) {
974 valid = false;
975 return;
976 }
977 if (num_bits < 8) {
978 zeros_found = true;
979 }
980 }
981
982 assert(mask.m_addr.size() <= sizeof(netmask));
983
984 memcpy(netmask, mask.m_addr.data(), mask.m_addr.size());
985
986 network = addr;
987
988 // Normalize network according to netmask
989 for (size_t x = 0; x < network.m_addr.size(); ++x) {
990 network.m_addr[x] &= netmask[x];
991 }
992}
993
995{
996 switch (addr.m_net) {
997 case NET_IPV4:
998 case NET_IPV6:
999 valid = true;
1000 assert(addr.m_addr.size() <= sizeof(netmask));
1001 memset(netmask, 0xFF, addr.m_addr.size());
1002 break;
1003 case NET_ONION:
1004 case NET_I2P:
1005 case NET_CJDNS:
1006 valid = true;
1007 break;
1008 case NET_INTERNAL:
1009 case NET_UNROUTABLE:
1010 case NET_MAX:
1011 return;
1012 }
1013
1014 network = addr;
1015}
1016
1021bool CSubNet::Match(const CNetAddr &addr) const
1022{
1023 if (!valid || !addr.IsValid() || network.m_net != addr.m_net)
1024 return false;
1025
1026 switch (network.m_net) {
1027 case NET_IPV4:
1028 case NET_IPV6:
1029 break;
1030 case NET_ONION:
1031 case NET_I2P:
1032 case NET_CJDNS:
1033 case NET_INTERNAL:
1034 return addr == network;
1035 case NET_UNROUTABLE:
1036 case NET_MAX:
1037 return false;
1038 }
1039
1040 assert(network.m_addr.size() == addr.m_addr.size());
1041 for (size_t x = 0; x < addr.m_addr.size(); ++x) {
1042 if ((addr.m_addr[x] & netmask[x]) != network.m_addr[x]) {
1043 return false;
1044 }
1045 }
1046 return true;
1047}
1048
1049std::string CSubNet::ToString() const
1050{
1051 std::string suffix;
1052
1053 switch (network.m_net) {
1054 case NET_IPV4:
1055 case NET_IPV6: {
1056 assert(network.m_addr.size() <= sizeof(netmask));
1057
1058 uint8_t cidr = 0;
1059
1060 for (size_t i = 0; i < network.m_addr.size(); ++i) {
1061 if (netmask[i] == 0x00) {
1062 break;
1063 }
1064 cidr += NetmaskBits(netmask[i]);
1065 }
1066
1067 suffix = strprintf("/%u", cidr);
1068 break;
1069 }
1070 case NET_ONION:
1071 case NET_I2P:
1072 case NET_CJDNS:
1073 case NET_INTERNAL:
1074 case NET_UNROUTABLE:
1075 case NET_MAX:
1076 break;
1077 }
1078
1079 return network.ToStringAddr() + suffix;
1080}
1081
1083{
1084 return valid;
1085}
1086
1087bool operator==(const CSubNet& a, const CSubNet& b)
1088{
1089 return a.valid == b.valid && a.network == b.network && !memcmp(a.netmask, b.netmask, 16);
1090}
1091
1092bool operator<(const CSubNet& a, const CSubNet& b)
1093{
1094 return (a.network < b.network || (a.network == b.network && memcmp(a.netmask, b.netmask, 16) < 0));
1095}
if(!SetupNetworking())
Network address.
Definition: netaddress.h:112
Network GetNetClass() const
Definition: netaddress.cpp:678
void SerializeV1Array(uint8_t(&arr)[V1_SERIALIZATION_SIZE]) const
Serialize in pre-ADDRv2/BIP155 format to an array.
Definition: netaddress.h:324
std::string ToStringAddr() const
Definition: netaddress.cpp:584
prevector< ADDR_IPV6_SIZE, uint8_t > m_addr
Raw representation of the network address.
Definition: netaddress.h:118
bool IsBindAny() const
Definition: netaddress.cpp:307
bool IsRFC6052() const
Definition: netaddress.cpp:355
void SetIP(const CNetAddr &ip)
Definition: netaddress.cpp:106
bool SetSpecial(const std::string &addr)
Parse a Tor or I2P address and set this object to it.
Definition: netaddress.cpp:211
bool IsRFC7343() const
Definition: netaddress.cpp:391
bool GetIn6Addr(struct in6_addr *pipv6Addr) const
Try to get our IPv6 (or CJDNS) address.
Definition: netaddress.cpp:646
std::vector< unsigned char > GetAddrBytes() const
Definition: netaddress.cpp:696
bool IsCJDNS() const
Definition: netaddress.h:176
bool IsTor() const
Definition: netaddress.h:174
bool IsRoutable() const
Definition: netaddress.cpp:466
bool GetInAddr(struct in_addr *pipv4Addr) const
Try to get our IPv4 address.
Definition: netaddress.cpp:627
bool HasLinkedIPv4() const
Whether this address has a linked IPv4 address (see GetLinkedIPv4()).
Definition: netaddress.cpp:656
bool HasCJDNSPrefix() const
Definition: netaddress.h:177
Network m_net
Network to which this address belongs.
Definition: netaddress.h:123
bool IsRFC5737() const
Definition: netaddress.cpp:338
void SetLegacyIPv6(Span< const uint8_t > ipv6)
Set from a legacy IPv6 address.
Definition: netaddress.cpp:137
bool SetI2P(const std::string &addr)
Parse an I2P address and set this object to it.
Definition: netaddress.cpp:267
bool IsRFC6598() const
Definition: netaddress.cpp:333
bool IsRFC1918() const
Definition: netaddress.cpp:315
bool IsValid() const
Definition: netaddress.cpp:428
bool IsIPv4() const
Definition: netaddress.h:157
BIP155Network GetBIP155Network() const
Get the BIP155 network id of this address.
Definition: netaddress.cpp:26
uint32_t GetLinkedIPv4() const
For IPv4, mapped IPv4, SIIT translated IPv4, Teredo, 6to4 tunneled addresses, return the relevant IPv...
Definition: netaddress.cpp:661
bool SetTor(const std::string &addr)
Parse a Tor address and set this object to it.
Definition: netaddress.cpp:228
uint32_t m_scope_id
Scope id if scoped/link-local IPV6 address.
Definition: netaddress.h:129
bool IsRFC3849() const
Definition: netaddress.cpp:345
bool IsHeNet() const
Definition: netaddress.cpp:397
bool IsLocal() const
Definition: netaddress.cpp:402
static constexpr size_t V1_SERIALIZATION_SIZE
Size of CNetAddr when serialized as ADDRv1 (pre-BIP155) (in bytes).
Definition: netaddress.h:296
bool IsIPv6() const
Definition: netaddress.h:158
bool IsInternal() const
Definition: netaddress.cpp:476
bool SetNetFromBIP155Network(uint8_t possible_bip155_net, size_t address_size)
Set m_net from the provided BIP155 network id and size after validation.
Definition: netaddress.cpp:48
bool SetInternal(const std::string &name)
Create an "internal" address that represents a name or FQDN.
Definition: netaddress.cpp:172
bool IsRFC4193() const
Definition: netaddress.cpp:373
bool IsRFC2544() const
Definition: netaddress.cpp:323
enum Network GetNetwork() const
Definition: netaddress.cpp:500
bool IsRFC6145() const
Definition: netaddress.cpp:378
int GetReachabilityFrom(const CNetAddr &paddrPartner) const
Calculates a metric for how reachable (*this) is from a given partner.
Definition: netaddress.cpp:717
CNetAddr()
Construct an unspecified IPv6 network address (::/128).
bool IsRFC3964() const
Definition: netaddress.cpp:350
bool IsRFC4380() const
Definition: netaddress.cpp:362
bool IsAddrV1Compatible() const
Check if the current object can be serialized in pre-ADDRv2/BIP155 format.
Definition: netaddress.cpp:481
BIP155Network
BIP155 network ids recognized by this software.
Definition: netaddress.h:263
bool IsRFC3927() const
Definition: netaddress.cpp:328
bool IsRFC4862() const
Definition: netaddress.cpp:367
bool IsRFC4843() const
Definition: netaddress.cpp:385
bool IsI2P() const
Definition: netaddress.h:175
A hasher class for SHA-256.
Definition: sha256.h:14
void Finalize(unsigned char hash[OUTPUT_SIZE])
Definition: sha256.cpp:727
CSHA256 & Write(const unsigned char *data, size_t len)
Definition: sha256.cpp:701
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:531
uint16_t GetPort() const
Definition: netaddress.cpp:837
bool SetSockAddr(const struct sockaddr *paddr)
Definition: netaddress.cpp:810
sa_family_t GetSAFamily() const
Get the address family.
Definition: netaddress.cpp:824
uint16_t port
Definition: netaddress.h:533
bool GetSockAddr(struct sockaddr *paddr, socklen_t *addrlen) const
Obtain the IPv4/6 socket address this represents.
Definition: netaddress.cpp:864
std::string ToStringAddrPort() const
Definition: netaddress.cpp:905
std::vector< unsigned char > GetKey() const
Definition: netaddress.cpp:897
bool valid
Is this value valid? (only used to signal parse errors)
Definition: netaddress.h:487
CNetAddr network
Network (base) address.
Definition: netaddress.h:483
uint8_t netmask[16]
Netmask, in network byte order.
Definition: netaddress.h:485
std::string ToString() const
bool IsValid() const
CSubNet()
Construct an invalid subnet (empty, Match() always returns false).
Definition: netaddress.cpp:916
bool Match(const CNetAddr &addr) const
Definition: sha3.h:17
SHA3_256 & Write(Span< const unsigned char > data)
Definition: sha3.cpp:106
SHA3_256 & Finalize(Span< unsigned char > output)
Definition: sha3.cpp:136
static constexpr size_t OUTPUT_SIZE
Definition: sha3.h:33
A Span is an object that can refer to a contiguous sequence of objects.
Definition: span.h:98
constexpr std::size_t size() const noexcept
Definition: span.h:187
constexpr C * data() const noexcept
Definition: span.h:174
constexpr C * begin() const noexcept
Definition: span.h:175
constexpr C * end() const noexcept
Definition: span.h:176
Implements a drop-in replacement for std::vector<T> which stores up to N elements directly (without h...
Definition: prevector.h:37
size_type size() const
Definition: prevector.h:294
value_type * data()
Definition: prevector.h:533
iterator begin()
Definition: prevector.h:302
iterator end()
Definition: prevector.h:304
void assign(size_type n, const T &val)
Definition: prevector.h:223
static uint16_t ReadBE16(const unsigned char *ptr)
Definition: common.h:52
static uint32_t ReadBE32(const unsigned char *ptr)
Definition: common.h:59
@ I2P
Definition: logging.h:65
static const unsigned char VERSION[]
Definition: netaddress.cpp:187
static constexpr size_t CHECKSUM_LEN
Definition: netaddress.cpp:186
static void Checksum(Span< const uint8_t > addr_pubkey, uint8_t(&checksum)[CHECKSUM_LEN])
Definition: netaddress.cpp:190
static constexpr size_t TOTAL_LEN
Definition: netaddress.cpp:188
bool HasPrefix(const T1 &obj, const std::array< uint8_t, PREFIX_LEN > &prefix)
Check whether a container begins with the given prefix.
Definition: string.h:245
bool ContainsNoNUL(std::string_view str) noexcept
Check if a string does not contain any embedded NUL (\0) characters.
Definition: string.h:221
static const int NET_TEREDO
Definition: netaddress.cpp:708
static int NetmaskBits(uint8_t x)
Definition: netaddress.cpp:947
bool operator==(const CNetAddr &a, const CNetAddr &b)
Definition: netaddress.cpp:607
std::string OnionToString(Span< const uint8_t > addr)
Definition: netaddress.cpp:573
static std::string IPv6ToString(Span< const uint8_t > a, uint32_t scope_id)
Definition: netaddress.cpp:518
static std::string IPv4ToString(Span< const uint8_t > a)
Definition: netaddress.cpp:511
bool operator<(const CNetAddr &a, const CNetAddr &b)
Definition: netaddress.cpp:612
static int GetExtNetwork(const CNetAddr &addr)
Definition: netaddress.cpp:709
static constexpr size_t ADDR_CJDNS_SIZE
Size of CJDNS address (in bytes).
Definition: netaddress.h:98
static constexpr size_t ADDR_TORV3_SIZE
Size of TORv3 address (in bytes).
Definition: netaddress.h:92
static constexpr size_t ADDR_I2P_SIZE
Size of I2P address (in bytes).
Definition: netaddress.h:95
static constexpr size_t ADDR_INTERNAL_SIZE
Size of "internal" (NET_INTERNAL) address (in bytes).
Definition: netaddress.h:101
static const std::array< uint8_t, 6 > INTERNAL_IN_IPV6_PREFIX
Prefix of an IPv6 address when it contains an embedded "internal" address.
Definition: netaddress.h:76
static constexpr size_t ADDR_IPV4_SIZE
Size of IPv4 address (in bytes).
Definition: netaddress.h:85
static const std::array< uint8_t, 6 > TORV2_IN_IPV6_PREFIX
Prefix of an IPv6 address when it contains an embedded TORv2 address.
Definition: netaddress.h:68
Network
A network type.
Definition: netaddress.h:32
@ NET_I2P
I2P.
Definition: netaddress.h:46
@ NET_CJDNS
CJDNS.
Definition: netaddress.h:49
@ NET_MAX
Dummy value to indicate the number of NET_* constants.
Definition: netaddress.h:56
@ NET_ONION
TOR (v2 or v3)
Definition: netaddress.h:43
@ NET_IPV6
IPv6.
Definition: netaddress.h:40
@ NET_IPV4
IPv4.
Definition: netaddress.h:37
@ NET_UNROUTABLE
Addresses from these networks are not publicly routable on the global Internet.
Definition: netaddress.h:34
@ NET_INTERNAL
A set of addresses that represent the hash of a string or FQDN.
Definition: netaddress.h:53
static const std::array< uint8_t, 12 > IPV4_IN_IPV6_PREFIX
Prefix of an IPv6 address when it contains an embedded IPv4 address.
Definition: netaddress.h:61
static constexpr size_t ADDR_IPV6_SIZE
Size of IPv6 address (in bytes).
Definition: netaddress.h:88
@ IPV4
Definition: netbase.cpp:284
@ IPV6
Definition: netbase.cpp:286
const char * prefix
Definition: rest.cpp:1009
const char * name
Definition: rest.cpp:49
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1165
std::optional< std::vector< unsigned char > > DecodeBase32(std::string_view str)
std::string EncodeBase32(Span< const unsigned char > input, bool pad)
Base32 encode.
std::string ToLower(std::string_view str)
Returns the lowercase equivalent of the given string.
assert(!tx.IsCoinBase())