| 17 | } |
| 18 | |
| 19 | std::vector<unsigned char> NetGroupManager::GetGroup(const CNetAddr& address) const |
| 20 | { |
| 21 | std::vector<unsigned char> vchRet; |
| 22 | // If non-empty asmap is supplied and the address is IPv4/IPv6, |
| 23 | // return ASN to be used for bucketing. |
| 24 | uint32_t asn = GetMappedAS(address); |
| 25 | if (asn != 0) { // Either asmap was empty, or address has non-asmappable net class (e.g. TOR). |
| 26 | vchRet.push_back(NET_IPV6); // IPv4 and IPv6 with same ASN should be in the same bucket |
| 27 | for (int i = 0; i < 4; i++) { |
| 28 | vchRet.push_back((asn >> (8 * i)) & 0xFF); |
| 29 | } |
| 30 | return vchRet; |
| 31 | } |
| 32 | |
| 33 | vchRet.push_back(address.GetNetClass()); |
| 34 | int nStartByte{0}; |
| 35 | int nBits{0}; |
| 36 | |
| 37 | if (address.IsLocal()) { |
| 38 | // all local addresses belong to the same group |
| 39 | } else if (address.IsInternal()) { |
| 40 | // All internal-usage addresses get their own group. |
| 41 | // Skip over the INTERNAL_IN_IPV6_PREFIX returned by CAddress::GetAddrBytes(). |
| 42 | nStartByte = INTERNAL_IN_IPV6_PREFIX.size(); |
| 43 | nBits = ADDR_INTERNAL_SIZE * 8; |
| 44 | } else if (!address.IsRoutable()) { |
| 45 | // all other unroutable addresses belong to the same group |
| 46 | } else if (address.HasLinkedIPv4()) { |
| 47 | // IPv4 addresses (and mapped IPv4 addresses) use /16 groups |
| 48 | uint32_t ipv4 = address.GetLinkedIPv4(); |
| 49 | vchRet.push_back((ipv4 >> 24) & 0xFF); |
| 50 | vchRet.push_back((ipv4 >> 16) & 0xFF); |
| 51 | return vchRet; |
| 52 | } else if (address.IsTor() || address.IsI2P()) { |
| 53 | nBits = 4; |
| 54 | } else if (address.IsCJDNS()) { |
| 55 | // Treat in the same way as Tor and I2P because the address in all of |
| 56 | // them is "random" bytes (derived from a public key). However in CJDNS |
| 57 | // the first byte is a constant (see CJDNS_PREFIX), so the random bytes |
| 58 | // come after it. Thus skip the constant 8 bits at the start. |
| 59 | nBits = 12; |
| 60 | } else if (address.IsHeNet()) { |
| 61 | // for he.net, use /36 groups |
| 62 | nBits = 36; |
| 63 | } else { |
| 64 | // for the rest of the IPv6 network, use /32 groups |
| 65 | nBits = 32; |
| 66 | } |
| 67 | |
| 68 | // Push our address onto vchRet. |
| 69 | auto addr_bytes = address.GetAddrBytes(); |
| 70 | const size_t num_bytes = nBits / 8; |
| 71 | vchRet.insert(vchRet.end(), addr_bytes.begin() + nStartByte, addr_bytes.begin() + nStartByte + num_bytes); |
| 72 | nBits %= 8; |
| 73 | // ...for the last byte, push nBits and for the rest of the byte push 1's |
| 74 | if (nBits > 0) { |
| 75 | assert(num_bytes < addr_bytes.size()); |
| 76 | vchRet.push_back(addr_bytes[num_bytes + nStartByte] | ((1 << (8 - nBits)) - 1)); |