PIVX Core  5.6.99
P2P Digital Currency
netaddress.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2021 The Bitcoin Core developers
3 // Copyright (c) 2017-2021 The PIVX Core developers
4 // Distributed under the MIT software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 
7 #include "crypto/common.h"
8 #include "crypto/sha3.h"
9 #include "netaddress.h"
10 #include "hash.h"
11 #include "prevector.h"
12 #include "tinyformat.h"
13 #include "util/asmap.h"
14 #include "util/string.h"
15 #include "utilstrencodings.h"
16 
17 #include <algorithm>
18 #include <array>
19 #include <cstdint>
20 #include <ios>
21 #include <iterator>
22 #include <tuple>
23 
24 constexpr size_t CNetAddr::V1_SERIALIZATION_SIZE;
25 constexpr size_t CNetAddr::MAX_ADDRV2_SIZE;
26 
28 {
29  switch (m_net) {
30  case NET_IPV4:
31  return BIP155Network::IPV4;
32  case NET_IPV6:
33  return BIP155Network::IPV6;
34  case NET_ONION:
35  switch (m_addr.size()) {
36  case ADDR_TORV2_SIZE:
37  return BIP155Network::TORV2;
38  case ADDR_TORV3_SIZE:
39  return BIP155Network::TORV3;
40  default:
41  assert(false);
42  }
43  case NET_I2P:
44  return BIP155Network::I2P;
45  case NET_CJDNS:
46  return BIP155Network::CJDNS;
47  case NET_INTERNAL: // should have been handled before calling this function
48  case NET_UNROUTABLE: // m_net is never and should not be set to NET_UNROUTABLE
49  case NET_MAX: // m_net is never and should not be set to NET_MAX
50  assert(false);
51  } // no default case, so the compiler can warn about missing cases
52 
53  assert(false);
54 }
55 
56 bool CNetAddr::SetNetFromBIP155Network(uint8_t possible_bip155_net, size_t address_size)
57 {
58  switch (possible_bip155_net) {
60  if (address_size == ADDR_IPV4_SIZE) {
61  m_net = NET_IPV4;
62  return true;
63  }
64  throw std::ios_base::failure(
65  strprintf("BIP155 IPv4 address with length %u (should be %u)", address_size,
66  ADDR_IPV4_SIZE));
68  if (address_size == ADDR_IPV6_SIZE) {
69  m_net = NET_IPV6;
70  return true;
71  }
72  throw std::ios_base::failure(
73  strprintf("BIP155 IPv6 address with length %u (should be %u)", address_size,
74  ADDR_IPV6_SIZE));
75  case BIP155Network::TORV2:
76  if (address_size == ADDR_TORV2_SIZE) {
77  m_net = NET_ONION;
78  return true;
79  }
80  throw std::ios_base::failure(
81  strprintf("BIP155 TORv2 address with length %u (should be %u)", address_size,
82  ADDR_TORV2_SIZE));
83  case BIP155Network::TORV3:
84  if (address_size == ADDR_TORV3_SIZE) {
85  m_net = NET_ONION;
86  return true;
87  }
88  throw std::ios_base::failure(
89  strprintf("BIP155 TORv3 address with length %u (should be %u)", address_size,
90  ADDR_TORV3_SIZE));
91  case BIP155Network::I2P:
92  if (address_size == ADDR_I2P_SIZE) {
93  m_net = NET_I2P;
94  return true;
95  }
96  throw std::ios_base::failure(
97  strprintf("BIP155 I2P address with length %u (should be %u)", address_size,
98  ADDR_I2P_SIZE));
99  case BIP155Network::CJDNS:
100  if (address_size == ADDR_CJDNS_SIZE) {
101  m_net = NET_CJDNS;
102  return true;
103  }
104  throw std::ios_base::failure(
105  strprintf("BIP155 CJDNS address with length %u (should be %u)", address_size,
106  ADDR_CJDNS_SIZE));
107  }
108 
109  // Don't throw on addresses with unknown network ids (maybe from the future).
110  // Instead silently drop them and have the unserialization code consume
111  // subsequent ones which may be known to us.
112  return false;
113 }
114 
121 
122 void CNetAddr::SetIP(const CNetAddr& ipIn)
123 {
124  // Size check.
125  switch (ipIn.m_net) {
126  case NET_IPV4:
127  assert(ipIn.m_addr.size() == ADDR_IPV4_SIZE);
128  break;
129  case NET_IPV6:
130  assert(ipIn.m_addr.size() == ADDR_IPV6_SIZE);
131  break;
132  case NET_ONION:
133  assert(ipIn.m_addr.size() == ADDR_TORV2_SIZE || ipIn.m_addr.size() == ADDR_TORV3_SIZE);
134  break;
135  case NET_I2P:
136  assert(ipIn.m_addr.size() == ADDR_I2P_SIZE);
137  break;
138  case NET_CJDNS:
139  assert(ipIn.m_addr.size() == ADDR_CJDNS_SIZE);
140  break;
141  case NET_INTERNAL:
142  assert(ipIn.m_addr.size() == ADDR_INTERNAL_SIZE);
143  break;
144  case NET_UNROUTABLE:
145  case NET_MAX:
146  assert(false);
147  } // no default case, so the compiler can warn about missing cases
148 
149  m_net = ipIn.m_net;
150  m_addr = ipIn.m_addr;
151 }
152 
154 {
155  assert(ipv6.size() == ADDR_IPV6_SIZE);
156 
157  size_t skip{0};
158 
159  if (HasPrefix(ipv6, IPV4_IN_IPV6_PREFIX)) {
160  // IPv4-in-IPv6
161  m_net = NET_IPV4;
162  skip = sizeof(IPV4_IN_IPV6_PREFIX);
163  } else if (HasPrefix(ipv6, TORV2_IN_IPV6_PREFIX)) {
164  // TORv2-in-IPv6
165  m_net = NET_ONION;
166  skip = sizeof(TORV2_IN_IPV6_PREFIX);
167  } else if (HasPrefix(ipv6, INTERNAL_IN_IPV6_PREFIX)) {
168  // Internal-in-IPv6
170  skip = sizeof(INTERNAL_IN_IPV6_PREFIX);
171  } else {
172  // IPv6
173  m_net = NET_IPV6;
174  }
175 
176  m_addr.assign(ipv6.begin() + skip, ipv6.end());
177 }
178 
185 bool CNetAddr::SetInternal(const std::string &name)
186 {
187  if (name.empty()) {
188  return false;
189  }
191  unsigned char hash[32] = {};
192  CSHA256().Write((const unsigned char*)name.data(), name.size()).Finalize(hash);
193  m_addr.assign(hash, hash + ADDR_INTERNAL_SIZE);
194  return true;
195 }
196 
197 namespace torv3 {
198 // https://gitweb.torproject.org/torspec.git/tree/rend-spec-v3.txt#n2135
199 static constexpr size_t CHECKSUM_LEN = 2;
200 static const unsigned char VERSION[] = {3};
201 static constexpr size_t TOTAL_LEN = ADDR_TORV3_SIZE + CHECKSUM_LEN + sizeof(VERSION);
202 
203 static void Checksum(Span<const uint8_t> addr_pubkey, uint8_t (&checksum)[CHECKSUM_LEN])
204 {
205  // TORv3 CHECKSUM = H(".onion checksum" | PUBKEY | VERSION)[:2]
206  static const unsigned char prefix[] = ".onion checksum";
207  static constexpr size_t prefix_len = 15;
208 
209  SHA3_256 hasher;
210 
211  hasher.Write(MakeSpan(prefix).first(prefix_len));
212  hasher.Write(addr_pubkey);
213  hasher.Write(VERSION);
214 
215  uint8_t checksum_full[SHA3_256::OUTPUT_SIZE];
216 
217  hasher.Finalize(checksum_full);
218 
219  memcpy(checksum, checksum_full, sizeof(checksum));
220 }
221 
222 }; // namespace torv3
223 
231 bool CNetAddr::SetSpecial(const std::string& str)
232 {
233  static const char* suffix{".onion"};
234  static constexpr size_t suffix_len{6};
235 
236  if (!ValidAsCString(str) || str.size() <= suffix_len ||
237  str.substr(str.size() - suffix_len) != suffix) {
238  return false;
239  }
240 
241  bool invalid;
242  const auto& input = DecodeBase32(str.substr(0, str.size() - suffix_len).c_str(), &invalid);
243 
244  if (invalid) {
245  return false;
246  }
247 
248  switch (input.size()) {
249  case ADDR_TORV2_SIZE:
250  m_net = NET_ONION;
251  m_addr.assign(input.begin(), input.end());
252  return true;
253  case torv3::TOTAL_LEN: {
254  Span<const uint8_t> input_pubkey{input.data(), ADDR_TORV3_SIZE};
255  Span<const uint8_t> input_checksum{input.data() + ADDR_TORV3_SIZE, torv3::CHECKSUM_LEN};
256  Span<const uint8_t> input_version{input.data() + ADDR_TORV3_SIZE + torv3::CHECKSUM_LEN, sizeof(torv3::VERSION)};
257 
258  uint8_t calculated_checksum[torv3::CHECKSUM_LEN];
259  torv3::Checksum(input_pubkey, calculated_checksum);
260 
261  if (input_checksum != calculated_checksum || input_version != torv3::VERSION) {
262  return false;
263  }
264 
265  m_net = NET_ONION;
266  m_addr.assign(input_pubkey.begin(), input_pubkey.end());
267  return true;
268  }
269  }
270 
271  return false;
272 }
273 
274 CNetAddr::CNetAddr(const struct in_addr& ipv4Addr)
275 {
276  m_net = NET_IPV4;
277  const uint8_t* ptr = reinterpret_cast<const uint8_t*>(&ipv4Addr);
278  m_addr.assign(ptr, ptr + ADDR_IPV4_SIZE);
279 }
280 
281 CNetAddr::CNetAddr(const struct in6_addr& ipv6Addr, const uint32_t scope)
282 {
283  SetLegacyIPv6(Span<const uint8_t>(reinterpret_cast<const uint8_t*>(&ipv6Addr), sizeof(ipv6Addr)));
284  scopeId = scope;
285 }
286 
288 {
289  if (!IsIPv4() && !IsIPv6()) {
290  return false;
291  }
292  return std::all_of(m_addr.begin(), m_addr.end(), [](uint8_t b) { return b == 0; });
293 }
294 
295 bool CNetAddr::IsIPv4() const { return m_net == NET_IPV4; }
296 
297 bool CNetAddr::IsIPv6() const { return m_net == NET_IPV6; }
298 
300 {
301  return IsIPv4() && (
302  m_addr[0] == 10 ||
303  (m_addr[0] == 192 && m_addr[1] == 168) ||
304  (m_addr[0] == 172 && m_addr[1] >= 16 && m_addr[1] <= 31));
305 }
306 
308 {
309  return IsIPv4() && m_addr[0] == 198 && (m_addr[1] == 18 || m_addr[1] == 19);
310 }
311 
313 {
314  return IsIPv4() && HasPrefix(m_addr, std::array<uint8_t, 2>{169, 254});
315 }
316 
318 {
319  return IsIPv4() && m_addr[0] == 100 && m_addr[1] >= 64 && m_addr[1] <= 127;
320 }
321 
323 {
324  return IsIPv4() && (HasPrefix(m_addr, std::array<uint8_t, 3>{192, 0, 2}) ||
325  HasPrefix(m_addr, std::array<uint8_t, 3>{198, 51, 100}) ||
326  HasPrefix(m_addr, std::array<uint8_t, 3>{203, 0, 113}));
327 }
328 
330 {
331  return IsIPv6() && HasPrefix(m_addr, std::array<uint8_t, 4>{0x20, 0x01, 0x0D, 0xB8});
332 }
333 
335 {
336  return IsIPv6() && HasPrefix(m_addr, std::array<uint8_t, 2>{0x20, 0x02});
337 }
338 
340 {
341  return IsIPv6() &&
342  HasPrefix(m_addr, std::array<uint8_t, 12>{0x00, 0x64, 0xFF, 0x9B, 0x00, 0x00,
343  0x00, 0x00, 0x00, 0x00, 0x00, 0x00});
344 }
345 
347 {
348  return IsIPv6() && HasPrefix(m_addr, std::array<uint8_t, 4>{0x20, 0x01, 0x00, 0x00});
349 }
350 
352 {
353  return IsIPv6() && HasPrefix(m_addr, std::array<uint8_t, 8>{0xFE, 0x80, 0x00, 0x00,
354  0x00, 0x00, 0x00, 0x00});
355 }
356 
358 {
359  return IsIPv6() && (m_addr[0] & 0xFE) == 0xFC;
360 }
361 
363 {
364  return IsIPv6() &&
365  HasPrefix(m_addr, std::array<uint8_t, 12>{0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
366  0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00});
367 }
368 
370 {
371  return IsIPv6() && HasPrefix(m_addr, std::array<uint8_t, 3>{0x20, 0x01, 0x00}) &&
372  (m_addr[3] & 0xF0) == 0x10;
373 }
374 
376 {
377  return IsIPv6() && HasPrefix(m_addr, std::array<uint8_t, 3>{0x20, 0x01, 0x00}) &&
378  (m_addr[3] & 0xF0) == 0x20;
379 }
380 
381 bool CNetAddr::IsHeNet() const
382 {
383  return IsIPv6() && HasPrefix(m_addr, std::array<uint8_t, 4>{0x20, 0x01, 0x04, 0x70});
384 }
385 
390 bool CNetAddr::IsTor() const { return m_net == NET_ONION; }
391 
395 bool CNetAddr::IsI2P() const { return m_net == NET_I2P; }
396 
400 bool CNetAddr::IsCJDNS() const { return m_net == NET_CJDNS; }
401 
402 bool CNetAddr::IsLocal() const
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 
418 bool CNetAddr::IsValid() const
419 {
420  // Cleanup 3-byte shifted addresses caused by garbage in size field
421  // of addr messages from versions before 0.2.9 checksum.
422  // Two consecutive addr messages look like this:
423  // header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...
424  // so if the first length field is garbled, it reads the second batch
425  // of addr misaligned by 3 bytes.
426  if (IsIPv6() && memcmp(m_addr.data(), IPV4_IN_IPV6_PREFIX.data() + 3,
427  sizeof(IPV4_IN_IPV6_PREFIX) - 3) == 0) {
428  return false;
429  }
430 
431  // unspecified IPv6 address (::/128)
432  unsigned char ipNone6[16] = {};
433  if (IsIPv6() && memcmp(m_addr.data(), ipNone6, sizeof(ipNone6)) == 0) {
434  return false;
435  }
436 
437  // documentation IPv6 address
438  if (IsRFC3849())
439  return false;
440 
441  if (IsInternal())
442  return false;
443 
444  if (IsIPv4()) {
445  const uint32_t addr = ReadBE32(m_addr.data());
446  if (addr == INADDR_ANY || addr == INADDR_NONE) {
447  return false;
448  }
449  }
450 
451  return true;
452 }
453 
455 {
456  return IsValid() && !(IsRFC1918() || IsRFC2544() || IsRFC3927() || IsRFC4862() || IsRFC6598() || IsRFC5737() || (IsRFC4193() && !IsTor()) || IsRFC4843() || IsRFC7343() || IsLocal() || IsInternal());
457 }
458 
465 {
466  return m_net == NET_INTERNAL;
467 }
468 
470 {
471  switch (m_net) {
472  case NET_IPV4:
473  case NET_IPV6:
474  case NET_INTERNAL:
475  return true;
476  case NET_ONION:
477  return m_addr.size() == ADDR_TORV2_SIZE;
478  case NET_I2P:
479  case NET_CJDNS:
480  return false;
481  case NET_UNROUTABLE: // m_net is never and should not be set to NET_UNROUTABLE
482  case NET_MAX: // m_net is never and should not be set to NET_MAX
483  assert(false);
484  } // no default case, so the compiler can warn about missing cases
485 
486  assert(false);
487 }
488 
489 enum Network CNetAddr::GetNetwork() const
490 {
491  if (IsInternal())
492  return NET_INTERNAL;
493 
494  if (!IsRoutable())
495  return NET_UNROUTABLE;
496 
497  return m_net;
498 }
499 
500 static std::string IPv6ToString(Span<const uint8_t> a)
501 {
502  assert(a.size() == ADDR_IPV6_SIZE);
503  // clang-format off
504  return strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
505  ReadBE16(&a[0]),
506  ReadBE16(&a[2]),
507  ReadBE16(&a[4]),
508  ReadBE16(&a[6]),
509  ReadBE16(&a[8]),
510  ReadBE16(&a[10]),
511  ReadBE16(&a[12]),
512  ReadBE16(&a[14]));
513  // clang-format on
514 }
515 
516 std::string CNetAddr::ToStringIP() const
517 {
518  switch (m_net) {
519  case NET_IPV4:
520  case NET_IPV6: {
521  CService serv(*this, 0);
522  struct sockaddr_storage sockaddr;
523  socklen_t socklen = sizeof(sockaddr);
524  if (serv.GetSockAddr((struct sockaddr*)&sockaddr, &socklen)) {
525  char name[1025] = "";
526  if (!getnameinfo((const struct sockaddr*)&sockaddr, socklen, name,
527  sizeof(name), nullptr, 0, NI_NUMERICHOST))
528  return std::string(name);
529  }
530  if (m_net == NET_IPV4) {
531  return strprintf("%u.%u.%u.%u", m_addr[0], m_addr[1], m_addr[2], m_addr[3]);
532  }
533  return IPv6ToString(m_addr);
534  }
535  case NET_ONION:
536  switch (m_addr.size()) {
537  case ADDR_TORV2_SIZE:
538  return EncodeBase32(m_addr) + ".onion";
539  case ADDR_TORV3_SIZE: {
540 
541  uint8_t checksum[torv3::CHECKSUM_LEN];
542  torv3::Checksum(m_addr, checksum);
543 
544  // TORv3 onion_address = base32(PUBKEY | CHECKSUM | VERSION) + ".onion"
546  address.insert(address.end(), checksum, checksum + torv3::CHECKSUM_LEN);
547  address.insert(address.end(), torv3::VERSION, torv3::VERSION + sizeof(torv3::VERSION));
548 
549  return EncodeBase32(address) + ".onion";
550  }
551  default:
552  assert(false);
553  }
554  case NET_I2P:
555  return EncodeBase32(m_addr, false /* don't pad with = */) + ".b32.i2p";
556  case NET_CJDNS:
557  return IPv6ToString(m_addr);
558  case NET_INTERNAL:
559  return EncodeBase32(m_addr) + ".internal";
560  case NET_UNROUTABLE: // m_net is never and should not be set to NET_UNROUTABLE
561  case NET_MAX: // m_net is never and should not be set to NET_MAX
562  assert(false);
563  } // no default case, so the compiler can warn about missing cases
564 
565  assert(false);
566 }
567 
568 std::string CNetAddr::ToString() const
569 {
570  return ToStringIP();
571 }
572 
573 bool operator==(const CNetAddr& a, const CNetAddr& b)
574 {
575  return a.m_net == b.m_net && a.m_addr == b.m_addr;
576 }
577 
578 bool operator!=(const CNetAddr& a, const CNetAddr& b)
579 {
580  return a.m_net != b.m_net || a.m_addr != b.m_addr;
581 }
582 
583 bool operator<(const CNetAddr& a, const CNetAddr& b)
584 {
585  return std::tie(a.m_net, a.m_addr) < std::tie(b.m_net, b.m_addr);
586 }
587 
588 bool CNetAddr::GetInAddr(struct in_addr* pipv4Addr) const
589 {
590  if (!IsIPv4())
591  return false;
592  assert(sizeof(*pipv4Addr) == m_addr.size());
593  memcpy(pipv4Addr, m_addr.data(), m_addr.size());
594  return true;
595 }
596 
607 bool CNetAddr::GetIn6Addr(struct in6_addr* pipv6Addr) const
608 {
609  if (!IsIPv6()) {
610  return false;
611  }
612  assert(sizeof(*pipv6Addr) == m_addr.size());
613  memcpy(pipv6Addr, m_addr.data(), m_addr.size());
614  return true;
615 }
616 
618 {
619  return IsRoutable() && (IsIPv4() || IsRFC6145() || IsRFC6052() || IsRFC3964() || IsRFC4380());
620 }
621 
622 uint32_t CNetAddr::GetLinkedIPv4() const
623 {
624  if (IsIPv4()) {
625  return ReadBE32(m_addr.data());
626  } else if (IsRFC6052() || IsRFC6145()) {
627  // mapped IPv4, SIIT translated IPv4: the IPv4 address is the last 4 bytes of the address
628  return ReadBE32(MakeSpan(m_addr).last(ADDR_IPV4_SIZE).data());
629  } else if (IsRFC3964()) {
630  // 6to4 tunneled IPv4: the IPv4 address is in bytes 2-6
631  return ReadBE32(MakeSpan(m_addr).subspan(2, ADDR_IPV4_SIZE).data());
632  } else if (IsRFC4380()) {
633  // Teredo tunneled IPv4: the IPv4 address is in the last 4 bytes of the address, but bitflipped
634  return ~ReadBE32(MakeSpan(m_addr).last(ADDR_IPV4_SIZE).data());
635  }
636  assert(false);
637 }
638 
640 {
641  // Make sure that if we return NET_IPV6, then IsIPv6() is true. The callers expect that.
642 
643  // Check for "internal" first because such addresses are also !IsRoutable()
644  // and we don't want to return NET_UNROUTABLE in that case.
645  if (IsInternal()) {
646  return NET_INTERNAL;
647  }
648  if (!IsRoutable()) {
649  return NET_UNROUTABLE;
650  }
651  if (HasLinkedIPv4()) {
652  return NET_IPV4;
653  }
654  return m_net;
655 }
656 
657 uint32_t CNetAddr::GetMappedAS(const std::vector<bool> &asmap) const {
658  uint32_t net_class = GetNetClass();
659  if (asmap.size() == 0 || (net_class != NET_IPV4 && net_class != NET_IPV6)) {
660  return 0; // Indicates not found, safe because AS0 is reserved per RFC7607.
661  }
662  std::vector<bool> ip_bits(128);
663  if (HasLinkedIPv4()) {
664  // For lookup, treat as if it was just an IPv4 address (IPV4_IN_IPV6_PREFIX + IPv4 bits)
665  for (int8_t byte_i = 0; byte_i < 12; ++byte_i) {
666  for (uint8_t bit_i = 0; bit_i < 8; ++bit_i) {
667  ip_bits[byte_i * 8 + bit_i] = (IPV4_IN_IPV6_PREFIX[byte_i] >> (7 - bit_i)) & 1;
668  }
669  }
670  uint32_t ipv4 = GetLinkedIPv4();
671  for (int i = 0; i < 32; ++i) {
672  ip_bits[96 + i] = (ipv4 >> (31 - i)) & 1;
673  }
674  } else {
675  // Use all 128 bits of the IPv6 address otherwise
676  assert(IsIPv6());
677  for (int8_t byte_i = 0; byte_i < 16; ++byte_i) {
678  uint8_t cur_byte = m_addr[byte_i];
679  for (uint8_t bit_i = 0; bit_i < 8; ++bit_i) {
680  ip_bits[byte_i * 8 + bit_i] = (cur_byte >> (7 - bit_i)) & 1;
681  }
682  }
683  }
684  uint32_t mapped_as = Interpret(asmap, ip_bits);
685  return mapped_as;
686 }
687 
698 std::vector<unsigned char> CNetAddr::GetGroup(const std::vector<bool> &asmap) const
699 {
700  std::vector<unsigned char> vchRet;
701  uint32_t net_class = GetNetClass();
702  // If non-empty asmap is supplied and the address is IPv4/IPv6,
703  // return ASN to be used for bucketing.
704  uint32_t asn = GetMappedAS(asmap);
705  if (asn != 0) { // Either asmap was empty, or address has non-asmappable net class (e.g. TOR).
706  vchRet.push_back(NET_IPV6); // IPv4 and IPv6 with same ASN should be in the same bucket
707  for (int i = 0; i < 4; i++) {
708  vchRet.push_back((asn >> (8 * i)) & 0xFF);
709  }
710  return vchRet;
711  }
712 
713  vchRet.push_back(net_class);
714  int nBits{0};
715 
716  if (IsLocal()) {
717  // all local addresses belong to the same group
718  } else if (IsInternal()) {
719  // all internal-usage addresses get their own group
720  nBits = ADDR_INTERNAL_SIZE * 8;
721  } else if (!IsRoutable()) {
722  // all other unroutable addresses belong to the same group
723  } else if (HasLinkedIPv4()) {
724  // IPv4 addresses (and mapped IPv4 addresses) use /16 groups
725  uint32_t ipv4 = GetLinkedIPv4();
726  vchRet.push_back((ipv4 >> 24) & 0xFF);
727  vchRet.push_back((ipv4 >> 16) & 0xFF);
728  return vchRet;
729  } else if (IsTor() || IsI2P() || IsCJDNS()) {
730  nBits = 4;
731  } else if (IsHeNet()) {
732  // for he.net, use /36 groups
733  nBits = 36;
734  } else {
735  // for the rest of the IPv6 network, use /32 groups
736  nBits = 32;
737  }
738 
739  // Push our address onto vchRet.
740  const size_t num_bytes = nBits / 8;
741  vchRet.insert(vchRet.end(), m_addr.begin(), m_addr.begin() + num_bytes);
742  nBits %= 8;
743  // ...for the last byte, push nBits and for the rest of the byte push 1's
744  if (nBits > 0) {
745  assert(num_bytes < m_addr.size());
746  vchRet.push_back(m_addr[num_bytes] | ((1 << (8 - nBits)) - 1));
747  }
748 
749  return vchRet;
750 }
751 
752 std::vector<unsigned char> CNetAddr::GetAddrBytes() const
753 {
754  if (IsAddrV1Compatible()) {
755  uint8_t serialized[V1_SERIALIZATION_SIZE];
756  SerializeV1Array(serialized);
757  return {std::begin(serialized), std::end(serialized)};
758  }
759  return std::vector<unsigned char>(m_addr.begin(), m_addr.end());
760 }
761 
762 uint64_t CNetAddr::GetHash() const
763 {
764  uint256 hash = Hash(m_addr.begin(), m_addr.end());
765  uint64_t nRet;
766  memcpy(&nRet, &hash, sizeof(nRet));
767  return nRet;
768 }
769 
770 // private extensions to enum Network, only returned by GetExtNetwork,
771 // and only used in GetReachabilityFrom
772 static const int NET_UNKNOWN = NET_MAX + 0;
773 static const int NET_TEREDO = NET_MAX + 1;
774 int static GetExtNetwork(const CNetAddr *addr)
775 {
776  if (addr == nullptr)
777  return NET_UNKNOWN;
778  if (addr->IsRFC4380())
779  return NET_TEREDO;
780  return addr->GetNetwork();
781 }
782 
784 int CNetAddr::GetReachabilityFrom(const CNetAddr *paddrPartner) const
785 {
786  enum Reachability {
787  REACH_UNREACHABLE,
788  REACH_DEFAULT,
789  REACH_TEREDO,
790  REACH_IPV6_WEAK,
791  REACH_IPV4,
792  REACH_IPV6_STRONG,
793  REACH_PRIVATE
794  };
795 
796  if (!IsRoutable() || IsInternal())
797  return REACH_UNREACHABLE;
798 
799  int ourNet = GetExtNetwork(this);
800  int theirNet = GetExtNetwork(paddrPartner);
801  bool fTunnel = IsRFC3964() || IsRFC6052() || IsRFC6145();
802 
803  switch(theirNet) {
804  case NET_IPV4:
805  switch(ourNet) {
806  default: return REACH_DEFAULT;
807  case NET_IPV4: return REACH_IPV4;
808  }
809  case NET_IPV6:
810  switch(ourNet) {
811  default: return REACH_DEFAULT;
812  case NET_TEREDO: return REACH_TEREDO;
813  case NET_IPV4: return REACH_IPV4;
814  case NET_IPV6: return fTunnel ? REACH_IPV6_WEAK : REACH_IPV6_STRONG; // only prefer giving our IPv6 address if it's not tunnelled
815  }
816  case NET_ONION:
817  switch(ourNet) {
818  default: return REACH_DEFAULT;
819  case NET_IPV4: return REACH_IPV4; // Tor users can connect to IPv4 as well
820  case NET_ONION: return REACH_PRIVATE;
821  }
822  case NET_TEREDO:
823  switch(ourNet) {
824  default: return REACH_DEFAULT;
825  case NET_TEREDO: return REACH_TEREDO;
826  case NET_IPV6: return REACH_IPV6_WEAK;
827  case NET_IPV4: return REACH_IPV4;
828  }
829  case NET_UNKNOWN:
830  case NET_UNROUTABLE:
831  default:
832  switch(ourNet) {
833  default: return REACH_DEFAULT;
834  case NET_TEREDO: return REACH_TEREDO;
835  case NET_IPV6: return REACH_IPV6_WEAK;
836  case NET_IPV4: return REACH_IPV4;
837  case NET_ONION: return REACH_PRIVATE; // either from Tor, or don't care about our address
838  }
839  }
840 }
841 
843 {
844 }
845 
846 CService::CService(const CNetAddr& cip, uint16_t portIn) : CNetAddr(cip), port(portIn)
847 {
848 }
849 
850 CService::CService(const struct in_addr& ipv4Addr, uint16_t portIn) : CNetAddr(ipv4Addr), port(portIn)
851 {
852 }
853 
854 CService::CService(const struct in6_addr& ipv6Addr, uint16_t portIn) : CNetAddr(ipv6Addr), port(portIn)
855 {
856 }
857 
858 CService::CService(const struct sockaddr_in& addr) : CNetAddr(addr.sin_addr), port(ntohs(addr.sin_port))
859 {
860  assert(addr.sin_family == AF_INET);
861 }
862 
863 CService::CService(const struct sockaddr_in6 &addr) : CNetAddr(addr.sin6_addr, addr.sin6_scope_id), port(ntohs(addr.sin6_port))
864 {
865  assert(addr.sin6_family == AF_INET6);
866 }
867 
868 bool CService::SetSockAddr(const struct sockaddr *paddr)
869 {
870  switch (paddr->sa_family) {
871  case AF_INET:
872  *this = CService(*(const struct sockaddr_in*)paddr);
873  return true;
874  case AF_INET6:
875  *this = CService(*(const struct sockaddr_in6*)paddr);
876  return true;
877  default:
878  return false;
879  }
880 }
881 
882 uint16_t CService::GetPort() const
883 {
884  return port;
885 }
886 
887 bool operator==(const CService& a, const CService& b)
888 {
889  return static_cast<CNetAddr>(a) == static_cast<CNetAddr>(b) && a.port == b.port;
890 }
891 
892 bool operator!=(const CService& a, const CService& b)
893 {
894  return static_cast<CNetAddr>(a) != static_cast<CNetAddr>(b) || a.port != b.port;
895 }
896 
897 bool operator<(const CService& a, const CService& b)
898 {
899  return static_cast<CNetAddr>(a) < static_cast<CNetAddr>(b) || (static_cast<CNetAddr>(a) == static_cast<CNetAddr>(b) && a.port < b.port);
900 }
901 
902 bool CService::GetSockAddr(struct sockaddr* paddr, socklen_t *addrlen) const
903 {
904  if (IsIPv4()) {
905  if (*addrlen < (socklen_t)sizeof(struct sockaddr_in))
906  return false;
907  *addrlen = sizeof(struct sockaddr_in);
908  struct sockaddr_in *paddrin = (struct sockaddr_in*)paddr;
909  memset(paddrin, 0, *addrlen);
910  if (!GetInAddr(&paddrin->sin_addr))
911  return false;
912  paddrin->sin_family = AF_INET;
913  paddrin->sin_port = htons(port);
914  return true;
915  }
916  if (IsIPv6()) {
917  if (*addrlen < (socklen_t)sizeof(struct sockaddr_in6))
918  return false;
919  *addrlen = sizeof(struct sockaddr_in6);
920  struct sockaddr_in6 *paddrin6 = (struct sockaddr_in6*)paddr;
921  memset(paddrin6, 0, *addrlen);
922  if (!GetIn6Addr(&paddrin6->sin6_addr))
923  return false;
924  paddrin6->sin6_scope_id = scopeId;
925  paddrin6->sin6_family = AF_INET6;
926  paddrin6->sin6_port = htons(port);
927  return true;
928  }
929  return false;
930 }
931 
932 std::vector<unsigned char> CService::GetKey() const
933 {
934  auto key = GetAddrBytes();
935  key.push_back(port / 0x100); // most significant byte of our port
936  key.push_back(port & 0x0FF); // least significant byte of our port
937  return key;
938 }
939 
940 std::string CService::ToStringPort() const
941 {
942  return strprintf("%u", port);
943 }
944 
945 std::string CService::ToStringIPPort() const
946 {
947  if (IsIPv4() || IsTor() || IsI2P() || IsInternal()) {
948  return ToStringIP() + ":" + ToStringPort();
949  } else {
950  return "[" + ToStringIP() + "]:" + ToStringPort();
951  }
952 }
953 
954 std::string CService::ToString() const
955 {
956  return ToStringIPPort();
957 }
958 
960  valid(false)
961 {
962  memset(netmask, 0, sizeof(netmask));
963 }
964 
965 CSubNet::CSubNet(const CNetAddr& addr, uint8_t mask) : CSubNet()
966 {
967  valid = (addr.IsIPv4() && mask <= ADDR_IPV4_SIZE * 8) ||
968  (addr.IsIPv6() && mask <= ADDR_IPV6_SIZE * 8);
969  if (!valid) {
970  return;
971  }
972 
973  assert(mask <= sizeof(netmask) * 8);
974 
975  network = addr;
976 
977  uint8_t n = mask;
978  for (size_t i = 0; i < network.m_addr.size(); ++i) {
979  const uint8_t bits = n < 8 ? n : 8;
980  netmask[i] = (uint8_t)((uint8_t)0xFF << (8 - bits)); // Set first bits.
981  network.m_addr[i] &= netmask[i]; // Normalize network according to netmask.
982  n -= bits;
983  }
984 }
985 
990 static inline int NetmaskBits(uint8_t x)
991 {
992  switch(x) {
993  case 0x00: return 0;
994  case 0x80: return 1;
995  case 0xc0: return 2;
996  case 0xe0: return 3;
997  case 0xf0: return 4;
998  case 0xf8: return 5;
999  case 0xfc: return 6;
1000  case 0xfe: return 7;
1001  case 0xff: return 8;
1002  default: return -1;
1003  }
1004 }
1005 
1006 CSubNet::CSubNet(const CNetAddr& addr, const CNetAddr& mask) : CSubNet()
1007 {
1008  valid = (addr.IsIPv4() || addr.IsIPv6()) && addr.m_net == mask.m_net;
1009  if (!valid) {
1010  return;
1011  }
1012  // Check if `mask` contains 1-bits after 0-bits (which is an invalid netmask).
1013  bool zeros_found = false;
1014  for (auto b : mask.m_addr) {
1015  const int num_bits = NetmaskBits(b);
1016  if (num_bits == -1 || (zeros_found && num_bits != 0)) {
1017  valid = false;
1018  return;
1019  }
1020  if (num_bits < 8) {
1021  zeros_found = true;
1022  }
1023  }
1024 
1025  assert(mask.m_addr.size() <= sizeof(netmask));
1026 
1027  memcpy(netmask, mask.m_addr.data(), mask.m_addr.size());
1028 
1029  network = addr;
1030 
1031  // Normalize network according to netmask
1032  for (size_t x = 0; x < network.m_addr.size(); ++x) {
1033  network.m_addr[x] &= netmask[x];
1034  }
1035 }
1036 
1038 {
1039  valid = addr.IsIPv4() || addr.IsIPv6();
1040  if (!valid) {
1041  return;
1042  }
1043 
1044  assert(addr.m_addr.size() <= sizeof(netmask));
1045 
1046  memset(netmask, 0xFF, addr.m_addr.size());
1047 
1048  network = addr;
1049 }
1050 
1051 bool CSubNet::Match(const CNetAddr &addr) const
1052 {
1053  if (!valid || !addr.IsValid() || network.m_net != addr.m_net)
1054  return false;
1055  assert(network.m_addr.size() == addr.m_addr.size());
1056  for (size_t x = 0; x < addr.m_addr.size(); ++x) {
1057  if ((addr.m_addr[x] & netmask[x]) != network.m_addr[x]) {
1058  return false;
1059  }
1060  }
1061  return true;
1062 }
1063 
1064 std::string CSubNet::ToString() const
1065 {
1066  assert(network.m_addr.size() <= sizeof(netmask));
1067 
1068  uint8_t cidr = 0;
1069 
1070  for (size_t i = 0; i < network.m_addr.size(); ++i) {
1071  if (netmask[i] == 0x00) {
1072  break;
1073  }
1074  cidr += NetmaskBits(netmask[i]);
1075  }
1076 
1077  return network.ToString() + strprintf("/%u", cidr);
1078 }
1079 
1080 bool CSubNet::IsValid() const
1081 {
1082  return valid;
1083 }
1084 
1085 bool operator==(const CSubNet& a, const CSubNet& b)
1086 {
1087  return a.valid == b.valid && a.network == b.network && !memcmp(a.netmask, b.netmask, 16);
1088 }
1089 
1090 bool operator!=(const CSubNet& a, const CSubNet& b)
1091 {
1092  return !(a==b);
1093 }
1094 
1095 bool operator<(const CSubNet& a, const CSubNet& b)
1096 {
1097  return (a.network < b.network || (a.network == b.network && memcmp(a.netmask, b.netmask, 16) < 0));
1098 }
uint32_t Interpret(const std::vector< bool > &asmap, const std::vector< bool > &ip)
Definition: asmap.cpp:67
false
Definition: bls_dkg.cpp:151
Network address.
Definition: netaddress.h:120
Network GetNetClass() const
Definition: netaddress.cpp:639
uint32_t scopeId
Definition: netaddress.h:133
void SerializeV1Array(uint8_t(&arr)[V1_SERIALIZATION_SIZE]) const
Serialize in pre-ADDRv2/BIP155 format to an array.
Definition: netaddress.h:294
std::string ToStringIP() const
Definition: netaddress.cpp:516
prevector< ADDR_IPV6_SIZE, uint8_t > m_addr
Raw representation of the network address.
Definition: netaddress.h:126
bool IsBindAny() const
Definition: netaddress.cpp:287
bool IsRFC6052() const
Definition: netaddress.cpp:339
void SetIP(const CNetAddr &ip)
Definition: netaddress.cpp:122
bool IsRFC7343() const
Definition: netaddress.cpp:375
bool GetIn6Addr(struct in6_addr *pipv6Addr) const
Try to get our IPv6 address.
Definition: netaddress.cpp:607
std::vector< unsigned char > GetAddrBytes() const
Definition: netaddress.cpp:752
std::string ToString() const
Definition: netaddress.cpp:568
bool IsCJDNS() const
Check whether this object represents a CJDNS address.
Definition: netaddress.cpp:400
bool IsTor() const
Check whether this object represents a TOR address.
Definition: netaddress.cpp:390
bool IsRoutable() const
Definition: netaddress.cpp:454
bool GetInAddr(struct in_addr *pipv4Addr) const
Definition: netaddress.cpp:588
bool HasLinkedIPv4() const
Whether this address has a linked IPv4 address (see GetLinkedIPv4()).
Definition: netaddress.cpp:617
Network m_net
Network to which this address belongs.
Definition: netaddress.h:131
bool IsRFC5737() const
Definition: netaddress.cpp:322
void SetLegacyIPv6(Span< const uint8_t > ipv6)
Set from a legacy IPv6 address.
Definition: netaddress.cpp:153
bool IsRFC6598() const
Definition: netaddress.cpp:317
bool IsRFC1918() const
Definition: netaddress.cpp:299
bool IsValid() const
Definition: netaddress.cpp:418
bool IsIPv4() const
Definition: netaddress.cpp:295
BIP155Network GetBIP155Network() const
Get the BIP155 network id of this address.
Definition: netaddress.cpp:27
uint32_t GetLinkedIPv4() const
For IPv4, mapped IPv4, SIIT translated IPv4, Teredo, 6to4 tunneled addresses, return the relevant IPv...
Definition: netaddress.cpp:622
bool IsRFC3849() const
Definition: netaddress.cpp:329
bool IsHeNet() const
Definition: netaddress.cpp:381
bool IsLocal() const
Definition: netaddress.cpp:402
uint64_t GetHash() const
Definition: netaddress.cpp:762
static constexpr size_t V1_SERIALIZATION_SIZE
Size of CNetAddr when serialized as ADDRv1 (pre-BIP155) (in bytes).
Definition: netaddress.h:266
bool SetSpecial(const std::string &strName)
Parse a TOR address and set this object to it.
Definition: netaddress.cpp:231
bool IsIPv6() const
Definition: netaddress.cpp:297
bool IsInternal() const
Definition: netaddress.cpp:464
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:56
bool SetInternal(const std::string &name)
Transform an arbitrary string into a non-routable ipv6 address.
Definition: netaddress.cpp:185
bool IsRFC4193() const
Definition: netaddress.cpp:357
std::vector< unsigned char > GetGroup(const std::vector< bool > &asmap) const
Get the canonical identifier of our network group.
Definition: netaddress.cpp:698
uint32_t GetMappedAS(const std::vector< bool > &asmap) const
Definition: netaddress.cpp:657
int GetReachabilityFrom(const CNetAddr *paddrPartner=nullptr) const
Calculates a metric for how reachable (*this) is from a given partner.
Definition: netaddress.cpp:784
static constexpr size_t MAX_ADDRV2_SIZE
Maximum size of an address as defined in BIP155 (in bytes).
Definition: netaddress.h:273
bool IsRFC2544() const
Definition: netaddress.cpp:307
enum Network GetNetwork() const
Definition: netaddress.cpp:489
bool IsRFC6145() const
Definition: netaddress.cpp:362
CNetAddr()
Construct an unspecified IPv6 network address (::/128).
Definition: netaddress.cpp:120
bool IsRFC3964() const
Definition: netaddress.cpp:334
bool IsRFC4380() const
Definition: netaddress.cpp:346
bool IsAddrV1Compatible() const
Check if the current object can be serialized in pre-ADDRv2/BIP155 format.
Definition: netaddress.cpp:469
BIP155Network
BIP155 network ids recognized by this software.
Definition: netaddress.h:254
bool IsRFC3927() const
Definition: netaddress.cpp:312
bool IsRFC4862() const
Definition: netaddress.cpp:351
bool IsRFC4843() const
Definition: netaddress.cpp:369
bool IsI2P() const
Check whether this object represents an I2P address.
Definition: netaddress.cpp:395
A hasher class for SHA-256.
Definition: sha256.h:13
void Finalize(unsigned char hash[OUTPUT_SIZE])
Definition: sha256.cpp:168
CSHA256 & Write(const unsigned char *data, size_t len)
Definition: sha256.cpp:142
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:484
std::string ToStringIPPort() const
Definition: netaddress.cpp:945
std::string ToString() const
Definition: netaddress.cpp:954
uint16_t GetPort() const
Definition: netaddress.cpp:882
bool SetSockAddr(const struct sockaddr *paddr)
Definition: netaddress.cpp:868
std::string ToStringPort() const
Definition: netaddress.cpp:940
uint16_t port
Definition: netaddress.h:486
bool GetSockAddr(struct sockaddr *paddr, socklen_t *addrlen) const
Definition: netaddress.cpp:902
std::vector< unsigned char > GetKey() const
Definition: netaddress.cpp:932
bool valid
Is this value valid? (only used to signal parse errors)
Definition: netaddress.h:460
CNetAddr network
Network (base) address.
Definition: netaddress.h:456
uint8_t netmask[16]
Netmask, in network byte order.
Definition: netaddress.h:458
std::string ToString() const
bool IsValid() const
bool Match(const CNetAddr &addr) const
Definition: sha3.h:17
SHA3_256 & Write(Span< const unsigned char > data)
Definition: sha3.cpp:111
SHA3_256 & Finalize(Span< unsigned char > output)
Definition: sha3.cpp:141
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:93
constexpr std::size_t size() const noexcept
Definition: span.h:182
constexpr C * data() const noexcept
Definition: span.h:169
constexpr C * end() const noexcept
Definition: span.h:171
constexpr C * begin() const noexcept
Definition: span.h:170
Implements a drop-in replacement for std::vector<T> which stores up to N elements directly (without h...
Definition: prevector.h:38
size_type size() const
Definition: prevector.h:277
value_type * data()
Definition: prevector.h:526
iterator begin()
Definition: prevector.h:285
iterator end()
Definition: prevector.h:287
void assign(size_type n, const T &val)
Definition: prevector.h:213
256-bit opaque blob.
Definition: uint256.h:138
if(!read_stdin(buffer))
Definition: fuzz.cpp:72
void * memcpy(void *a, const void *b, size_t c)
uint256 Hash(const T1 pbegin, const T1 pend)
Compute the 256-bit hash of an object.
Definition: hash.h:173
#define VERSION
bool operator==(const CNetAddr &a, const CNetAddr &b)
Definition: netaddress.cpp:573
bool operator!=(const CNetAddr &a, const CNetAddr &b)
Definition: netaddress.cpp:578
bool operator<(const CNetAddr &a, const CNetAddr &b)
Definition: netaddress.cpp:583
Network
A network type.
Definition: netaddress.h:44
@ NET_I2P
I2P.
Definition: netaddress.h:58
@ NET_CJDNS
CJDNS.
Definition: netaddress.h:61
@ NET_MAX
Dummy value to indicate the number of NET_* constants.
Definition: netaddress.h:68
@ NET_ONION
TOR (v2 or v3)
Definition: netaddress.h:55
@ NET_IPV6
IPv6.
Definition: netaddress.h:52
@ NET_IPV4
IPv4.
Definition: netaddress.h:49
@ NET_UNROUTABLE
Addresses from these networks are not publicly routable on the global Internet.
Definition: netaddress.h:46
@ NET_INTERNAL
A set of addresses that represent the hash of a string or FQDN.
Definition: netaddress.h:65
@ IPV4
Definition: netbase.cpp:266
@ IPV6
Definition: netbase.cpp:268
const char * prefix
Definition: rest.cpp:564
const char * name
Definition: rest.cpp:37
constexpr Span< A > MakeSpan(A(&a)[N])
MakeSpan for arrays:
Definition: span.h:221
NODISCARD 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:53
bool ValidAsCString(const std::string &str) noexcept
Check if a string does not contain any embedded NUL (\0) characters.
Definition: string.h:44
#define strprintf
Definition: tinyformat.h:1056
std::string EncodeBase32(Span< const unsigned char > input, bool pad)
Base32 encode.
std::vector< unsigned char > DecodeBase32(const char *p, bool *pfInvalid)