Line data Source code
1 : // Copyright (c) 2009-2021 The Bitcoin Core developers
2 : // Copyright (c) 2017-2021 The PIVX 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 : #ifndef PIVX_NETADDRESS_H
7 : #define PIVX_NETADDRESS_H
8 :
9 : #if defined(HAVE_CONFIG_H)
10 : #include "config/pivx-config.h"
11 : #endif
12 :
13 : #include "compat.h"
14 : #include "serialize.h"
15 : #include "span.h"
16 : #include "prevector.h"
17 : #include "tinyformat.h"
18 : #include "utilstrencodings.h"
19 : #include "util/string.h"
20 :
21 : #include <array>
22 : #include <cstdint>
23 : #include <ios>
24 : #include <string>
25 : #include <vector>
26 :
27 : /**
28 : * A flag that is ORed into the protocol version to designate that addresses
29 : * should be serialized in (unserialized from) v2 format (BIP155).
30 : * Make sure that this does not collide with any of the values in `version.h`
31 : */
32 : static constexpr int ADDRV2_FORMAT = 0x20000000;
33 :
34 : /**
35 : * A network type.
36 : * @note An address may belong to more than one network, for example `10.0.0.1`
37 : * belongs to both `NET_UNROUTABLE` and `NET_IPV4`.
38 : * Keep these sequential starting from 0 and `NET_MAX` as the last entry.
39 : * We have loops like `for (int i = 0; i < NET_MAX; i++)` that expect to iterate
40 : * over all enum values and also `GetExtNetwork()` "extends" this enum by
41 : * introducing standalone constants starting from `NET_MAX`.
42 : */
43 : enum Network
44 : {
45 : /// Addresses from these networks are not publicly routable on the global Internet.
46 : NET_UNROUTABLE = 0,
47 :
48 : /// IPv4
49 : NET_IPV4,
50 :
51 : /// IPv6
52 : NET_IPV6,
53 :
54 : /// TOR (v2 or v3)
55 : NET_ONION,
56 :
57 : /// I2P
58 : NET_I2P,
59 :
60 : /// CJDNS
61 : NET_CJDNS,
62 :
63 : /// A set of addresses that represent the hash of a string or FQDN. We use
64 : /// them in CAddrMan to keep track of which DNS seeds were used.
65 : NET_INTERNAL,
66 :
67 : /// Dummy value to indicate the number of NET_* constants.
68 : NET_MAX,
69 : };
70 :
71 : /// Prefix of an IPv6 address when it contains an embedded IPv4 address.
72 : /// Used when (un)serializing addresses in ADDRv1 format (pre-BIP155).
73 : static const std::array<uint8_t, 12> IPV4_IN_IPV6_PREFIX{
74 : 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF
75 : };
76 :
77 : /// Prefix of an IPv6 address when it contains an embedded TORv2 address.
78 : /// Used when (un)serializing addresses in ADDRv1 format (pre-BIP155).
79 : /// Such dummy IPv6 addresses are guaranteed to not be publicly routable as they
80 : /// fall under RFC4193's fc00::/7 subnet allocated to unique-local addresses.
81 : static const std::array<uint8_t, 6> TORV2_IN_IPV6_PREFIX{
82 : 0xFD, 0x87, 0xD8, 0x7E, 0xEB, 0x43
83 : };
84 :
85 : /// Prefix of an IPv6 address when it contains an embedded "internal" address.
86 : /// Used when (un)serializing addresses in ADDRv1 format (pre-BIP155).
87 : /// The prefix comes from 0xFD + SHA256("bitcoin")[0:5].
88 : /// Such dummy IPv6 addresses are guaranteed to not be publicly routable as they
89 : /// fall under RFC4193's fc00::/7 subnet allocated to unique-local addresses.
90 : static const std::array<uint8_t, 6> INTERNAL_IN_IPV6_PREFIX{
91 : 0xFD, 0x6B, 0x88, 0xC0, 0x87, 0x24 // 0xFD + sha256("bitcoin")[0:5].
92 : };
93 :
94 : /// Size of IPv4 address (in bytes).
95 : static constexpr size_t ADDR_IPV4_SIZE = 4;
96 :
97 : /// Size of IPv6 address (in bytes).
98 : static constexpr size_t ADDR_IPV6_SIZE = 16;
99 :
100 : /// Size of TORv2 address (in bytes).
101 : static constexpr size_t ADDR_TORV2_SIZE = 10;
102 :
103 : /// Size of TORv3 address (in bytes). This is the length of just the address
104 : /// as used in BIP155, without the checksum and the version byte.
105 : static constexpr size_t ADDR_TORV3_SIZE = 32;
106 :
107 : /// Size of I2P address (in bytes).
108 : static constexpr size_t ADDR_I2P_SIZE = 32;
109 :
110 : /// Size of CJDNS address (in bytes).
111 : static constexpr size_t ADDR_CJDNS_SIZE = 16;
112 :
113 : /// Size of "internal" (NET_INTERNAL) address (in bytes).
114 : static constexpr size_t ADDR_INTERNAL_SIZE = 10;
115 :
116 : /**
117 : * Network address.
118 : */
119 7062329 : class CNetAddr
120 : {
121 : protected:
122 : /**
123 : * Raw representation of the network address.
124 : * In network byte order (big endian) for IPv4 and IPv6.
125 : */
126 : prevector<ADDR_IPV6_SIZE, uint8_t> m_addr{ADDR_IPV6_SIZE, 0x0};
127 :
128 : /**
129 : * Network to which this address belongs.
130 : */
131 : Network m_net{NET_IPV6};
132 :
133 : uint32_t scopeId{0}; // for scoped/link-local ipv6 addresses
134 :
135 : public:
136 : CNetAddr();
137 : explicit CNetAddr(const struct in_addr& ipv4Addr);
138 : void SetIP(const CNetAddr& ip);
139 :
140 : /**
141 : * Set from a legacy IPv6 address.
142 : * Legacy IPv6 address may be a normal IPv6 address, or another address
143 : * (e.g. IPv4) disguised as IPv6. This encoding is used in the legacy
144 : * `addr` encoding.
145 : */
146 : void SetLegacyIPv6(Span<const uint8_t> ipv6);
147 :
148 : /**
149 : * Transform an arbitrary string into a non-routable ipv6 address.
150 : * Useful for mapping resolved addresses back to their source.
151 : */
152 : bool SetInternal(const std::string& name);
153 :
154 : bool SetSpecial(const std::string& strName); // for Tor addresses
155 : bool IsBindAny() const; // INADDR_ANY equivalent
156 : bool IsIPv4() const; // IPv4 mapped address (::FFFF:0:0/96, 0.0.0.0/0)
157 : bool IsIPv6() const; // IPv6 address (not mapped IPv4, not Tor)
158 : bool IsRFC1918() const; // IPv4 private networks (10.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12)
159 : bool IsRFC2544() const; // IPv4 inter-network communications (198.18.0.0/15)
160 : bool IsRFC6598() const; // IPv4 ISP-level NAT (100.64.0.0/10)
161 : bool IsRFC5737() const; // IPv4 documentation addresses (192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24)
162 : bool IsRFC3849() const; // IPv6 documentation address (2001:0DB8::/32)
163 : bool IsRFC3927() const; // IPv4 autoconfig (169.254.0.0/16)
164 : bool IsRFC3964() const; // IPv6 6to4 tunnelling (2002::/16)
165 : bool IsRFC4193() const; // IPv6 unique local (FC00::/7)
166 : bool IsRFC4380() const; // IPv6 Teredo tunnelling (2001::/32)
167 : bool IsRFC4843() const; // IPv6 ORCHID (deprecated) (2001:10::/28)
168 : bool IsRFC7343() const; // IPv6 ORCHIDv2 (2001:20::/28)
169 : bool IsRFC4862() const; // IPv6 autoconfig (FE80::/64)
170 : bool IsRFC6052() const; // IPv6 well-known prefix (64:FF9B::/96)
171 : bool IsRFC6145() const; // IPv6 IPv4-translated address (::FFFF:0:0:0/96)
172 : bool IsHeNet() const; // IPv6 Hurricane Electric - https://he.net (2001:0470::/36)
173 : bool IsTor() const;
174 : bool IsI2P() const;
175 : bool IsCJDNS() const;
176 : bool IsLocal() const;
177 : bool IsRoutable() const;
178 : bool IsInternal() const;
179 : bool IsValid() const;
180 :
181 : /**
182 : * Check if the current object can be serialized in pre-ADDRv2/BIP155 format.
183 : */
184 : bool IsAddrV1Compatible() const;
185 :
186 : enum Network GetNetwork() const;
187 : std::string ToString() const;
188 : std::string ToStringIP() const;
189 : uint64_t GetHash() const;
190 : bool GetInAddr(struct in_addr* pipv4Addr) const;
191 : Network GetNetClass() const;
192 :
193 : //! For IPv4, mapped IPv4, SIIT translated IPv4, Teredo, 6to4 tunneled addresses, return the relevant IPv4 address as a uint32.
194 : uint32_t GetLinkedIPv4() const;
195 : //! Whether this address has a linked IPv4 address (see GetLinkedIPv4()).
196 : bool HasLinkedIPv4() const;
197 :
198 : // The AS on the BGP path to the node we use to diversify
199 : // peers in AddrMan bucketing based on the AS infrastructure.
200 : // The ip->AS mapping depends on how asmap is constructed.
201 : uint32_t GetMappedAS(const std::vector<bool> &asmap) const;
202 :
203 : std::vector<unsigned char> GetGroup(const std::vector<bool> &asmap) const;
204 : std::vector<unsigned char> GetAddrBytes() const;
205 : int GetReachabilityFrom(const CNetAddr* paddrPartner = nullptr) const;
206 :
207 : explicit CNetAddr(const struct in6_addr& pipv6Addr, const uint32_t scope = 0);
208 : bool GetIn6Addr(struct in6_addr* pipv6Addr) const;
209 :
210 : friend bool operator==(const CNetAddr& a, const CNetAddr& b);
211 : friend bool operator!=(const CNetAddr& a, const CNetAddr& b);
212 : friend bool operator<(const CNetAddr& a, const CNetAddr& b);
213 :
214 : /**
215 : * Whether this address should be relayed to other peers even if we can't reach it ourselves.
216 : */
217 0 : bool IsRelayable() const
218 : {
219 0 : return IsIPv4() || IsIPv6() || IsTor();
220 : }
221 :
222 : /**
223 : * Serialize to a stream.
224 : */
225 : template <typename Stream>
226 89687 : void Serialize(Stream& s) const
227 : {
228 41290 : if (s.GetVersion() & ADDRV2_FORMAT) {
229 85320 : SerializeV2Stream(s);
230 : } else {
231 53011 : SerializeV1Stream(s);
232 : }
233 89687 : }
234 :
235 : /**
236 : * Unserialize from a stream.
237 : */
238 : template <typename Stream>
239 10785 : void Unserialize(Stream& s)
240 : {
241 10785 : if (s.GetVersion() & ADDRV2_FORMAT) {
242 5499 : UnserializeV2Stream(s);
243 : } else {
244 5286 : UnserializeV1Stream(s);
245 : }
246 10774 : }
247 :
248 : friend class CSubNet;
249 :
250 : private:
251 : /**
252 : * BIP155 network ids recognized by this software.
253 : */
254 : enum BIP155Network : uint8_t {
255 : IPV4 = 1,
256 : IPV6 = 2,
257 : TORV2 = 3,
258 : TORV3 = 4,
259 : I2P = 5,
260 : CJDNS = 6,
261 : };
262 :
263 : /**
264 : * Size of CNetAddr when serialized as ADDRv1 (pre-BIP155) (in bytes).
265 : */
266 : static constexpr size_t V1_SERIALIZATION_SIZE = ADDR_IPV6_SIZE;
267 :
268 : /**
269 : * Maximum size of an address as defined in BIP155 (in bytes).
270 : * This is only the size of the address, not the entire CNetAddr object
271 : * when serialized.
272 : */
273 : static constexpr size_t MAX_ADDRV2_SIZE = 512;
274 :
275 : /**
276 : * Get the BIP155 network id of this address.
277 : * Must not be called for IsInternal() objects.
278 : * @returns BIP155 network id
279 : */
280 : BIP155Network GetBIP155Network() const;
281 :
282 : /**
283 : * Set `m_net` from the provided BIP155 network id and size after validation.
284 : * @retval true the network was recognized, is valid and `m_net` was set
285 : * @retval false not recognised (from future?) and should be silently ignored
286 : * @throws std::ios_base::failure if the network is one of the BIP155 founding
287 : * networks (id 1..6) with wrong address size.
288 : */
289 : bool SetNetFromBIP155Network(uint8_t possible_bip155_net, size_t address_size);
290 :
291 : /**
292 : * Serialize in pre-ADDRv2/BIP155 format to an array.
293 : */
294 20134 : void SerializeV1Array(uint8_t (&arr)[V1_SERIALIZATION_SIZE]) const
295 : {
296 20134 : size_t prefix_size;
297 :
298 20134 : switch (m_net) {
299 2825 : case NET_IPV6:
300 2825 : assert(m_addr.size() == sizeof(arr));
301 5650 : memcpy(arr, m_addr.data(), m_addr.size());
302 : return;
303 17302 : case NET_IPV4:
304 17302 : prefix_size = sizeof(IPV4_IN_IPV6_PREFIX);
305 17302 : assert(prefix_size + m_addr.size() == sizeof(arr));
306 17302 : memcpy(arr, IPV4_IN_IPV6_PREFIX.data(), prefix_size);
307 34604 : memcpy(arr + prefix_size, m_addr.data(), m_addr.size());
308 : return;
309 5 : case NET_ONION:
310 6 : if (m_addr.size() == ADDR_TORV3_SIZE) {
311 : break;
312 : }
313 4 : prefix_size = sizeof(TORV2_IN_IPV6_PREFIX);
314 4 : assert(prefix_size + m_addr.size() == sizeof(arr));
315 4 : memcpy(arr, TORV2_IN_IPV6_PREFIX.data(), prefix_size);
316 8 : memcpy(arr + prefix_size, m_addr.data(), m_addr.size());
317 : return;
318 2 : case NET_INTERNAL:
319 2 : prefix_size = sizeof(INTERNAL_IN_IPV6_PREFIX);
320 4 : assert(prefix_size + m_addr.size() == sizeof(arr));
321 2 : memcpy(arr, INTERNAL_IN_IPV6_PREFIX.data(), prefix_size);
322 6 : memcpy(arr + prefix_size, m_addr.data(), m_addr.size());
323 : return;
324 : case NET_I2P:
325 : break;
326 : case NET_CJDNS:
327 : break;
328 0 : case NET_UNROUTABLE:
329 0 : case NET_MAX:
330 0 : assert(false);
331 : } // no default case, so the compiler can warn about missing cases
332 :
333 : // Serialize TORv3, I2P and CJDNS as all-zeros.
334 1 : memset(arr, 0x0, V1_SERIALIZATION_SIZE);
335 : }
336 :
337 : /**
338 : * Serialize in pre-ADDRv2/BIP155 format to a stream.
339 : */
340 : template <typename Stream>
341 4368 : void SerializeV1Stream(Stream& s) const
342 : {
343 : uint8_t serialized[V1_SERIALIZATION_SIZE];
344 :
345 4368 : SerializeV1Array(serialized);
346 :
347 4346 : s << serialized;
348 4368 : }
349 :
350 : /**
351 : * Serialize as ADDRv2 / BIP155.
352 : */
353 : template <typename Stream>
354 85320 : void SerializeV2Stream(Stream& s) const
355 : {
356 85320 : if (IsInternal()) {
357 : // Serialize NET_INTERNAL as embedded in IPv6. We need to
358 : // serialize such addresses from addrman.
359 1 : s << static_cast<uint8_t>(BIP155Network::IPV6);
360 1 : s << COMPACTSIZE(ADDR_IPV6_SIZE);
361 1 : SerializeV1Stream(s);
362 1 : return;
363 : }
364 :
365 85319 : s << static_cast<uint8_t>(GetBIP155Network());
366 85319 : s << m_addr;
367 : }
368 :
369 : /**
370 : * Unserialize from a pre-ADDRv2/BIP155 format from an array.
371 : */
372 5286 : void UnserializeV1Array(uint8_t (&arr)[V1_SERIALIZATION_SIZE])
373 : {
374 : // Use SetLegacyIPv6() so that m_net is set correctly. For example
375 : // ::FFFF:0102:0304 should be set as m_net=NET_IPV4 (1.2.3.4).
376 10572 : SetLegacyIPv6(arr);
377 : }
378 :
379 : /**
380 : * Unserialize from a pre-ADDRv2/BIP155 format from a stream.
381 : */
382 : template <typename Stream>
383 5286 : void UnserializeV1Stream(Stream& s)
384 : {
385 : uint8_t serialized[V1_SERIALIZATION_SIZE];
386 :
387 5286 : s >> serialized;
388 :
389 5286 : UnserializeV1Array(serialized);
390 5286 : }
391 :
392 : /**
393 : * Unserialize from a ADDRv2 / BIP155 format.
394 : */
395 : template <typename Stream>
396 5499 : void UnserializeV2Stream(Stream& s)
397 : {
398 : uint8_t bip155_net;
399 5499 : s >> bip155_net;
400 :
401 : size_t address_size;
402 5499 : s >> COMPACTSIZE(address_size);
403 :
404 5499 : if (address_size > MAX_ADDRV2_SIZE) {
405 : throw std::ios_base::failure(strprintf(
406 6 : "Address too long: %u > %u", address_size, MAX_ADDRV2_SIZE));
407 : }
408 :
409 5496 : scopeId = 0;
410 :
411 5496 : if (SetNetFromBIP155Network(bip155_net, address_size)) {
412 5485 : m_addr.resize(address_size);
413 10970 : s >> MakeSpan(m_addr);
414 :
415 5484 : if (m_net != NET_IPV6) {
416 5482 : return;
417 : }
418 :
419 : // Do some special checks on IPv6 addresses.
420 :
421 : // Recognize NET_INTERNAL embedded in IPv6, such addresses are not
422 : // gossiped but could be coming from addrman, when unserializing from
423 : // disk.
424 12 : if (HasPrefix(m_addr, INTERNAL_IN_IPV6_PREFIX)) {
425 1 : m_net = NET_INTERNAL;
426 2 : memmove(m_addr.data(), m_addr.data() + INTERNAL_IN_IPV6_PREFIX.size(),
427 : ADDR_INTERNAL_SIZE);
428 1 : m_addr.resize(ADDR_INTERNAL_SIZE);
429 1 : return;
430 : }
431 :
432 21 : if (!HasPrefix(m_addr, IPV4_IN_IPV6_PREFIX) &&
433 10 : !HasPrefix(m_addr, TORV2_IN_IPV6_PREFIX)) {
434 : return;
435 : }
436 :
437 : // IPv4 and TORv2 are not supposed to be embedded in IPv6 (like in V1
438 : // encoding). Unserialize as !IsValid(), thus ignoring them.
439 : } else {
440 : // If we receive an unknown BIP155 network id (from the future?) then
441 : // ignore the address - unserialize as !IsValid().
442 4 : s.ignore(address_size);
443 : }
444 :
445 : // Mimic a default-constructed CNetAddr object which is !IsValid() and thus
446 : // will not be gossiped, but continue reading next addresses from the stream.
447 6 : m_net = NET_IPV6;
448 6 : m_addr.assign(ADDR_IPV6_SIZE, 0x0);
449 : }
450 : };
451 :
452 5298 : class CSubNet
453 : {
454 : protected:
455 : /// Network (base) address
456 : CNetAddr network;
457 : /// Netmask, in network byte order
458 : uint8_t netmask[16];
459 : /// Is this value valid? (only used to signal parse errors)
460 : bool valid;
461 :
462 : public:
463 : CSubNet();
464 : CSubNet(const CNetAddr& addr, uint8_t mask);
465 : CSubNet(const CNetAddr& addr, const CNetAddr& mask);
466 :
467 : //constructor for single ip subnet (<ipv4>/32 or <ipv6>/128)
468 : explicit CSubNet(const CNetAddr& addr);
469 :
470 : bool Match(const CNetAddr& addr) const;
471 :
472 : std::string ToString() const;
473 : bool IsValid() const;
474 :
475 : friend bool operator==(const CSubNet& a, const CSubNet& b);
476 : friend bool operator!=(const CSubNet& a, const CSubNet& b);
477 : friend bool operator<(const CSubNet& a, const CSubNet& b);
478 :
479 50 : SERIALIZE_METHODS(CSubNet, obj) { READWRITE(obj.network, obj.netmask, obj.valid); }
480 : };
481 :
482 : /** A combination of a network address (CNetAddr) and a (TCP) port */
483 5241602 : class CService : public CNetAddr
484 : {
485 : protected:
486 : uint16_t port; // host order
487 :
488 : public:
489 : CService();
490 : CService(const CNetAddr& ip, uint16_t port);
491 : CService(const struct in_addr& ipv4Addr, uint16_t port);
492 : explicit CService(const struct sockaddr_in& addr);
493 : uint16_t GetPort() const;
494 : bool GetSockAddr(struct sockaddr* paddr, socklen_t* addrlen) const;
495 : bool SetSockAddr(const struct sockaddr* paddr);
496 : friend bool operator==(const CService& a, const CService& b);
497 : friend bool operator!=(const CService& a, const CService& b);
498 : friend bool operator<(const CService& a, const CService& b);
499 : std::vector<unsigned char> GetKey() const;
500 : std::string ToString() const;
501 : std::string ToStringPort() const;
502 : std::string ToStringIPPort() const;
503 :
504 : CService(const struct in6_addr& ipv6Addr, uint16_t port);
505 : explicit CService(const struct sockaddr_in6& addr);
506 :
507 161027 : SERIALIZE_METHODS(CService, obj)
508 : {
509 82409 : READWRITEAS(CNetAddr, obj);
510 82407 : READWRITE(Using<BigEndianFormatter<2>>(obj.port));
511 82407 : }
512 : };
513 :
514 : #endif // PIVX_NETADDRESS_H
|