55 std::vector<unsigned char> vchSourceGroupKey = netgroupman.
GetGroup(src);
73 if (
nTime > now + 10min) {
102 fChance *= pow(0.66, std::min(
nAttempts, 8));
108 : insecure_rand{deterministic}
109 , nKey{deterministic ?
uint256{1} : insecure_rand.rand256()}
110 , m_consistency_check_ratio{consistency_check_ratio}
111 , m_netgroupman{netgroupman}
113 for (
auto& bucket : vvNew) {
114 for (
auto& entry : bucket) {
118 for (
auto& bucket : vvTried) {
119 for (
auto& entry : bucket) {
130 template <
typename Stream>
181 static constexpr uint8_t lowest_compatible = Format::V4_MULTIPORT;
190 std::unordered_map<int, int> mapUnkIds;
192 for (
const auto& entry : mapInfo) {
193 mapUnkIds[entry.first] = nIds;
194 const AddrInfo& info = entry.second;
202 for (
const auto& entry : mapInfo) {
203 const AddrInfo& info = entry.second;
213 if (vvNew[bucket][i] != -1)
218 if (vvNew[bucket][i] != -1) {
219 int nIndex = mapUnkIds[vvNew[bucket][i]];
229 template <
typename Stream>
237 s_ >> Using<CustomUintFormatter<1>>(
format);
239 int stream_version = s_.GetVersion();
240 if (
format >= Format::V3_BIP155) {
252 "Corrupted addrman database: The compat value (%u) " 253 "is lower than the expected minimum value %u.",
259 "Unsupported format of addrman database: %u. It is compatible with formats >=%u, " 260 "but the maximum supported by this version of %s is %u.",
269 if (
format >= Format::V1_DETERMINISTIC) {
270 nUBuckets ^= (1 << 30);
274 throw std::ios_base::failure(
275 strprintf(
"Corrupt AddrMan serialization: nNew=%d, should be in [0, %d]",
281 throw std::ios_base::failure(
282 strprintf(
"Corrupt AddrMan serialization: nTried=%d, should be in [0, %d]",
288 for (
int n = 0; n < nNew; n++) {
293 vRandom.push_back(n);
299 for (
int n = 0; n < nTried; n++) {
303 int nKBucketPos = info.GetBucketPosition(
nKey,
false, nKBucket);
305 && vvTried[nKBucket][nKBucketPos] == -1) {
306 info.nRandomPos = vRandom.size();
307 info.fInTried =
true;
308 vRandom.push_back(nIdCount);
309 mapInfo[nIdCount] = info;
310 mapAddr[info] = nIdCount;
311 vvTried[nKBucket][nKBucketPos] = nIdCount;
322 std::vector<std::pair<int, int>> bucket_entries;
324 for (
int bucket = 0; bucket < nUBuckets; ++bucket) {
327 for (
int n = 0; n < num_entries; ++n) {
330 if (entry_index >= 0 && entry_index < nNew) {
331 bucket_entries.emplace_back(bucket, entry_index);
340 uint256 serialized_asmap_checksum;
341 if (
format >= Format::V2_ASMAP) {
342 s >> serialized_asmap_checksum;
345 serialized_asmap_checksum == supplied_asmap_checksum};
347 if (!restore_bucketing) {
351 for (
auto bucket_entry : bucket_entries) {
352 int bucket{bucket_entry.first};
353 const int entry_index{bucket_entry.second};
354 AddrInfo& info = mapInfo[entry_index];
365 if (restore_bucketing && vvNew[bucket][bucket_position] == -1) {
367 vvNew[bucket][bucket_position] = entry_index;
374 if (vvNew[bucket][bucket_position] == -1) {
375 vvNew[bucket][bucket_position] = entry_index;
383 for (
auto it = mapInfo.cbegin(); it != mapInfo.cend(); ) {
384 if (it->second.fInTried ==
false && it->second.nRefCount == 0) {
385 const auto itCopy = it++;
392 if (nLost + nLostUnk > 0) {
393 LogPrint(
BCLog::ADDRMAN,
"addrman lost %i new and %i tried addresses due to collisions or invalid addresses\n", nLostUnk, nLost);
397 if (check_code != 0) {
399 "Corrupt data. Consistency check failed with code %s",
408 const auto it = mapAddr.find(addr);
409 if (it == mapAddr.end())
412 *pnId = (*it).second;
413 const auto it2 = mapInfo.find((*it).second);
414 if (it2 != mapInfo.end())
415 return &(*it2).second;
423 int nId = nIdCount++;
424 mapInfo[nId] =
AddrInfo(addr, addrSource);
426 mapInfo[nId].nRandomPos = vRandom.size();
427 vRandom.push_back(nId);
430 return &mapInfo[nId];
437 if (nRndPos1 == nRndPos2)
440 assert(nRndPos1 < vRandom.size() && nRndPos2 < vRandom.size());
442 int nId1 = vRandom[nRndPos1];
443 int nId2 = vRandom[nRndPos2];
445 const auto it_1{mapInfo.find(nId1)};
446 const auto it_2{mapInfo.find(nId2)};
447 assert(it_1 != mapInfo.end());
448 assert(it_2 != mapInfo.end());
450 it_1->second.nRandomPos = nRndPos2;
451 it_2->second.nRandomPos = nRndPos1;
453 vRandom[nRndPos1] = nId2;
454 vRandom[nRndPos2] = nId1;
461 assert(mapInfo.count(nId) != 0);
464 assert(info.nRefCount == 0);
466 SwapRandom(info.nRandomPos, vRandom.size() - 1);
478 if (vvNew[nUBucket][nUBucketPos] != -1) {
479 int nIdDelete = vvNew[nUBucket][nUBucketPos];
480 AddrInfo& infoDelete = mapInfo[nIdDelete];
483 vvNew[nUBucket][nUBucketPos] = -1;
500 if (vvNew[bucket][pos] == nId) {
501 vvNew[bucket][pos] = -1;
515 if (vvTried[nKBucket][nKBucketPos] != -1) {
517 int nIdEvict = vvTried[nKBucket][nKBucketPos];
518 assert(mapInfo.count(nIdEvict) == 1);
519 AddrInfo& infoOld = mapInfo[nIdEvict];
523 vvTried[nKBucket][nKBucketPos] = -1;
528 int nUBucketPos = infoOld.GetBucketPosition(
nKey,
true, nUBucket);
530 assert(vvNew[nUBucket][nUBucketPos] == -1);
533 infoOld.nRefCount = 1;
534 vvNew[nUBucket][nUBucketPos] = nIdEvict;
537 infoOld.ToString(), nKBucket, nKBucketPos, nUBucket, nUBucketPos);
539 assert(vvTried[nKBucket][nKBucketPos] == -1);
541 vvTried[nKBucket][nKBucketPos] = nId;
564 const auto update_interval{currently_online ? 1h : 24h};
565 if (pinfo->
nTime < addr.
nTime - update_interval - time_penalty) {
587 for (
int n = 0; n < pinfo->
nRefCount; n++)
589 if (nFactor > 1 && (insecure_rand.randrange(nFactor) != 0))
599 bool fInsert = vvNew[nUBucket][nUBucketPos] == -1;
600 if (vvNew[nUBucket][nUBucketPos] != nId) {
602 AddrInfo& infoExisting = mapInfo[vvNew[nUBucket][nUBucketPos]];
611 vvNew[nUBucket][nUBucketPos] = nId;
634 if (!pinfo)
return false;
657 if (test_before_evict && (vvTried[tried_bucket][tried_bucket_pos] != -1)) {
662 auto colliding_entry = mapInfo.find(vvTried[tried_bucket][tried_bucket_pos]);
664 colliding_entry != mapInfo.end() ? colliding_entry->second.ToString() :
"",
680 for (std::vector<CAddress>::const_iterator it = vAddr.begin(); it != vAddr.end(); it++) {
684 LogPrint(
BCLog::ADDRMAN,
"Added %i addresses (of %i) from %s: %i tried, %i new\n", added, vAddr.size(),
source.ToString(), nTried, nNew);
713 if (vRandom.empty())
return {};
715 if (newOnly && nNew == 0)
return {};
719 (nTried > 0 && (nNew == 0 || insecure_rand.randbool() == 0))) {
721 double fChanceFactor = 1.0;
736 const auto it_found{mapInfo.find(nId)};
737 assert(it_found != mapInfo.end());
738 const AddrInfo& info{it_found->second};
740 if (insecure_rand.randbits(30) < fChanceFactor * info.GetChance() * (1 << 30)) {
742 return {info, info.m_last_try};
745 fChanceFactor *= 1.2;
749 double fChanceFactor = 1.0;
764 const auto it_found{mapInfo.find(nId)};
765 assert(it_found != mapInfo.end());
766 const AddrInfo& info{it_found->second};
768 if (insecure_rand.randbits(30) < fChanceFactor * info.GetChance() * (1 << 30)) {
770 return {info, info.m_last_try};
773 fChanceFactor *= 1.2;
778 std::vector<CAddress>
AddrManImpl::GetAddr_(
size_t max_addresses,
size_t max_pct, std::optional<Network> network)
const 782 size_t nNodes = vRandom.size();
784 nNodes = max_pct * nNodes / 100;
786 if (max_addresses != 0) {
787 nNodes = std::min(nNodes, max_addresses);
791 const auto now{Now<NodeSeconds>()};
792 std::vector<CAddress> addresses;
793 for (
unsigned int n = 0; n < vRandom.size(); n++) {
794 if (addresses.size() >= nNodes)
797 int nRndPos = insecure_rand.randrange(vRandom.size() - n) + n;
799 const auto it{mapInfo.find(vRandom[n])};
800 assert(it != mapInfo.end());
805 if (network != std::nullopt && ai.GetNetClass() != network)
continue;
808 if (ai.IsTerrible(now))
continue;
810 addresses.push_back(ai);
829 const auto update_interval{20min};
830 if (time - info.
nTime > update_interval) {
858 bool erase_collision =
false;
861 if (mapInfo.count(id_new) != 1) {
862 erase_collision =
true;
864 AddrInfo& info_new = mapInfo[id_new];
870 erase_collision =
true;
871 }
else if (vvTried[tried_bucket][tried_bucket_pos] != -1) {
874 int id_old = vvTried[tried_bucket][tried_bucket_pos];
875 AddrInfo& info_old = mapInfo[id_old];
877 const auto current_time{Now<NodeSeconds>()};
881 erase_collision =
true;
885 if (current_time - info_old.
m_last_try > 60s) {
889 Good_(info_new,
false, current_time);
890 erase_collision =
true;
897 Good_(info_new,
false, current_time);
898 erase_collision =
true;
901 Good_(info_new,
false, Now<NodeSeconds>());
902 erase_collision =
true;
906 if (erase_collision) {
927 if (mapInfo.count(id_new) != 1) {
932 const AddrInfo& newInfo = mapInfo[id_new];
938 const AddrInfo& info_old = mapInfo[vvTried[tried_bucket][tried_bucket_pos]];
948 if (!addr_info)
return std::nullopt;
975 LogPrintf(
"ADDRMAN CONSISTENCY CHECK FAILED!!! err=%i\n", err);
987 std::unordered_set<int> setTried;
988 std::unordered_map<int, int> mapNew;
990 if (vRandom.size() != (size_t)(nTried + nNew))
993 for (
const auto& entry : mapInfo) {
995 const AddrInfo& info = entry.second;
997 if (!TicksSinceEpoch<std::chrono::seconds>(info.
m_last_success)) {
1010 const auto it{mapAddr.find(info)};
1011 if (it == mapAddr.end() || it->second != n) {
1024 if (setTried.size() != (size_t)nTried)
1026 if (mapNew.size() != (size_t)nNew)
1031 if (vvTried[n][i] != -1) {
1032 if (!setTried.count(vvTried[n][i]))
1034 const auto it{mapInfo.find(vvTried[n][i])};
1035 if (it == mapInfo.end() || it->second.GetTriedBucket(nKey, m_netgroupman) != n) {
1038 if (it->second.GetBucketPosition(nKey,
false, n) != i) {
1041 setTried.erase(vvTried[n][i]);
1048 if (vvNew[n][i] != -1) {
1049 if (!mapNew.count(vvNew[n][i]))
1051 const auto it{mapInfo.find(vvNew[n][i])};
1052 if (it == mapInfo.end() || it->second.GetBucketPosition(nKey,
true, n) != i) {
1055 if (--mapNew[vvNew[n][i]] == 0)
1056 mapNew.erase(vvNew[n][i]);
1061 if (setTried.size())
1074 return vRandom.size();
1090 auto ret =
Good_(addr,
true, time);
1099 Attempt_(addr, fCountFailure, time);
1124 const auto addrRet =
Select_(newOnly);
1129 std::vector<CAddress>
AddrManImpl::GetAddr(
size_t max_addresses,
size_t max_pct, std::optional<Network> network)
const 1133 const auto addresses =
GetAddr_(max_addresses, max_pct, network);
1164 : m_impl(
std::make_unique<
AddrManImpl>(netgroupman, deterministic, consistency_check_ratio)) {}
1168 template <
typename Stream>
1171 m_impl->Serialize<Stream>(s_);
1174 template <
typename Stream>
1177 m_impl->Unserialize<Stream>(s_);
1200 return m_impl->Good(addr, time);
1205 m_impl->Attempt(addr, fCountFailure, time);
1210 m_impl->ResolveCollisions();
1215 return m_impl->SelectTriedCollision();
1220 return m_impl->Select(newOnly);
1223 std::vector<CAddress>
AddrMan::GetAddr(
size_t max_addresses,
size_t max_pct, std::optional<Network> network)
const 1225 return m_impl->GetAddr(max_addresses, max_pct, network);
1230 m_impl->Connected(addr, time);
1235 m_impl->SetServices(addr, nServices);
1240 return m_impl->FindAddressEntry(addr);
const std::unique_ptr< AddrManImpl > m_impl
void Connected(const CService &addr, NodeSeconds time) EXCLUSIVE_LOCKS_REQUIRED(!cs)
std::vector< unsigned char > GetGroup(const CNetAddr &address) const
Get the canonical identifier of the network group for address.
static constexpr uint8_t INCOMPATIBILITY_BASE
The initial value of a field that is incremented every time an incompatible format change is made (su...
void Connected_(const CService &addr, NodeSeconds time) EXCLUSIVE_LOCKS_REQUIRED(cs)
ServiceFlags
nServices flags
const NetGroupManager & m_netgroupman
Reference to the netgroup manager.
#define LogPrint(category,...)
uint256 GetAsmapChecksum() const
Get a checksum identifying the asmap being used.
bool Good_(const CService &addr, bool test_before_evict, NodeSeconds time) EXCLUSIVE_LOCKS_REQUIRED(cs)
void Unserialize(Stream &s_)
static constexpr int ADDRMAN_BUCKET_SIZE
void SwapRandom(unsigned int nRandomPos1, unsigned int nRandomPos2) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Swap two elements in vRandom.
std::optional< AddressPosition > FindAddressEntry(const CAddress &addr)
Test-only function Find the address record in AddrMan and return information about its position...
static constexpr int ADDRMAN_TRIED_BUCKET_COUNT
std::vector< CAddress > GetAddr(size_t max_addresses, size_t max_pct, std::optional< Network > network) const EXCLUSIVE_LOCKS_REQUIRED(!cs)
void Attempt_(const CService &addr, bool fCountFailure, NodeSeconds time) EXCLUSIVE_LOCKS_REQUIRED(cs)
static constexpr int32_t ADDRMAN_MAX_FAILURES
How many successive failures are allowed ...
bool Add_(const std::vector< CAddress > &vAddr, const CNetAddr &source, std::chrono::seconds time_penalty) EXCLUSIVE_LOCKS_REQUIRED(cs)
int nRandomPos
position in vRandom
Double ended buffer combining vector and stream-like interfaces.
std::pair< CAddress, NodeSeconds > Select(bool newOnly) const EXCLUSIVE_LOCKS_REQUIRED(!cs)
int CheckAddrman() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Perform consistency check, regardless of m_consistency_check_ratio.
static constexpr size_t ADDRMAN_SET_TRIED_COLLISION_SIZE
The maximum number of tried addr collisions to store.
Reads data from an underlying stream, while hashing the read data.
void ResolveCollisions()
See if any to-be-evicted tried table entries have been tested and if so resolve the collisions...
uint256 nKey
secret key to randomize bucket select with
std::pair< CAddress, NodeSeconds > SelectTriedCollision_() EXCLUSIVE_LOCKS_REQUIRED(cs)
void ResolveCollisions() EXCLUSIVE_LOCKS_REQUIRED(!cs)
static constexpr int32_t ADDRMAN_RETRIES
After how many failed attempts we give up on a new node.
std::pair< CAddress, NodeSeconds > Select(bool newOnly=false) const
Choose an address to connect to.
static constexpr int ADDRV2_FORMAT
A flag that is ORed into the protocol version to designate that addresses should be serialized in (un...
std::chrono::time_point< NodeClock, std::chrono::seconds > NodeSeconds
int GetBucketPosition(const uint256 &nKey, bool fNew, int nBucket) const
Calculate in which position of a bucket to store this entry.
int nAttempts
connection attempts since last successful attempt
void ResolveCollisions_() EXCLUSIVE_LOCKS_REQUIRED(cs)
std::pair< CAddress, NodeSeconds > SelectTriedCollision() EXCLUSIVE_LOCKS_REQUIRED(!cs)
NodeSeconds m_last_try
last try whatsoever by us (memory only)
bool Add(const std::vector< CAddress > &vAddr, const CNetAddr &source, std::chrono::seconds time_penalty=0s)
Attempt to add one or more addresses to addrman's new table.
std::vector< CAddress > GetAddr_(size_t max_addresses, size_t max_pct, std::optional< Network > network) const EXCLUSIVE_LOCKS_REQUIRED(cs)
int nRefCount
reference count in new sets (memory only)
size_t size() const EXCLUSIVE_LOCKS_REQUIRED(!cs)
static constexpr auto ADDRMAN_MIN_FAIL
...
void Attempt(const CService &addr, bool fCountFailure, NodeSeconds time) EXCLUSIVE_LOCKS_REQUIRED(!cs)
A combination of a network address (CNetAddr) and a (TCP) port.
Extended statistics about a CAddress.
void Attempt(const CService &addr, bool fCountFailure, NodeSeconds time=Now< NodeSeconds >())
Mark an entry as connection attempted to.
NodeSeconds m_last_count_attempt
last counted attempt (memory only)
A CService with information about it as peer.
void Connected(const CService &addr, NodeSeconds time=Now< NodeSeconds >())
We have successfully connected to this peer.
std::vector< unsigned char > GetKey() const
void Serialize(Stream &s_) const EXCLUSIVE_LOCKS_REQUIRED(!cs)
uint32_t GetMappedAS(const CNetAddr &address) const
Get the autonomous system on the BGP path to address.
bool Add(const std::vector< CAddress > &vAddr, const CNetAddr &source, std::chrono::seconds time_penalty) EXCLUSIVE_LOCKS_REQUIRED(!cs)
NodeSeconds nTime
Always included in serialization. The behavior is unspecified if the value is not representable as ui...
int GetNewBucket(const uint256 &nKey, const CNetAddr &src, const NetGroupManager &netgroupman) const
Calculate in which "new" bucket this entry belongs, given a certain source.
void Serialize(Stream &s_) const
void ClearNew(int nUBucket, int nUBucketPos) EXCLUSIVE_LOCKS_REQUIRED(cs)
Clear a position in a "new" table. This is the only place where entries are actually deleted...
std::vector< CAddress > GetAddr(size_t max_addresses, size_t max_pct, std::optional< Network > network) const
Return all or many randomly selected addresses, optionally by network.
void Check() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Consistency check, taking into account m_consistency_check_ratio.
#define Assume(val)
Assume is the identity function.
static constexpr Format FILE_FORMAT
The maximum format this software knows it can unserialize.
Format
Serialization versions.
std::pair< CAddress, NodeSeconds > Select_(bool newOnly) const EXCLUSIVE_LOCKS_REQUIRED(cs)
bool IsTerrible(NodeSeconds now=Now< NodeSeconds >()) const
Determine whether the statistics about this entry are bad enough so that it can just be deleted...
void Unserialize(Stream &s_) EXCLUSIVE_LOCKS_REQUIRED(!cs)
static time_point now() noexcept
Return current system time or mocked time, if set.
std::pair< CAddress, NodeSeconds > SelectTriedCollision()
Randomly select an address in the tried table that another address is attempting to evict...
ServiceFlags nServices
Serialized as uint64_t in V1, and as CompactSize in V2.
AddrInfo * Find(const CService &addr, int *pnId=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs)
Find an entry.
bool Good(const CService &addr, NodeSeconds time) EXCLUSIVE_LOCKS_REQUIRED(!cs)
AddrManImpl(const NetGroupManager &netgroupman, bool deterministic, int32_t consistency_check_ratio)
double GetChance(NodeSeconds now=Now< NodeSeconds >()) const
Calculate the relative chance this entry should be given when selecting nodes to connect to...
void MakeTried(AddrInfo &info, int nId) EXCLUSIVE_LOCKS_REQUIRED(cs)
Move an entry from the "new" table(s) to the "tried" table.
static constexpr int ADDRMAN_NEW_BUCKET_COUNT
static constexpr uint32_t ADDRMAN_TRIED_BUCKETS_PER_GROUP
Over how many buckets entries with tried addresses from a single group (/16 for IPv4) are spread...
void Delete(int nId) EXCLUSIVE_LOCKS_REQUIRED(cs)
Delete an entry. It must not be in tried, and have refcount 0.
void SetServices(const CService &addr, ServiceFlags nServices)
Update an entry's service bits.
Writes data to an underlying source stream, while hashing the written data.
size_t size() const
Return the number of (unique) addresses in all tables.
bool fInTried
in tried set? (memory only)
std::optional< AddressPosition > FindAddressEntry_(const CAddress &addr) EXCLUSIVE_LOCKS_REQUIRED(cs)
std::string ToString() const
bool AddSingle(const CAddress &addr, const CNetAddr &source, std::chrono::seconds time_penalty) EXCLUSIVE_LOCKS_REQUIRED(cs)
Attempt to add a single address to addrman's new table.
static constexpr auto ADDRMAN_REPLACEMENT
How recent a successful connection should be before we allow an address to be evicted from tried...
std::set< int > m_tried_collisions
Holds addrs inserted into tried table that collide with existing entries. Test-before-evict disciplin...
Test-only struct, capturing info about an address in AddrMan.
Mutex cs
A mutex to protect the inner data structures.
static constexpr auto ADDRMAN_TEST_WINDOW
The maximum time we'll spend trying to resolve a tried table collision.
const int32_t m_consistency_check_ratio
Perform consistency checks every m_consistency_check_ratio operations (if non-zero).
bool Good(const CService &addr, NodeSeconds time=Now< NodeSeconds >())
Mark an address record as accessible and attempt to move it to addrman's tried table.
int GetTriedBucket(const uint256 &nKey, const NetGroupManager &netgroupman) const
Calculate in which "tried" bucket this entry belongs.
std::optional< AddressPosition > FindAddressEntry(const CAddress &addr) EXCLUSIVE_LOCKS_REQUIRED(!cs)
AddrInfo * Create(const CAddress &addr, const CNetAddr &addrSource, int *pnId=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs)
Create a new entry and add it to the internal data structures mapInfo, mapAddr and vRandom...
void SetServices(const CService &addr, ServiceFlags nServices) EXCLUSIVE_LOCKS_REQUIRED(!cs)
NodeSeconds m_last_success
last successful connection by us
static constexpr auto ADDRMAN_HORIZON
How old addresses can maximally be.
static constexpr int32_t ADDRMAN_NEW_BUCKETS_PER_ADDRESS
Maximum number of times an address can occur in the new table.
#define LOG_TIME_MILLIS_WITH_CATEGORY_MSG_ONCE(end_msg, log_category)
AddrMan(const NetGroupManager &netgroupman, bool deterministic, int32_t consistency_check_ratio)
void SetServices_(const CService &addr, ServiceFlags nServices) EXCLUSIVE_LOCKS_REQUIRED(cs)
static constexpr uint32_t ADDRMAN_NEW_BUCKETS_PER_SOURCE_GROUP
Over how many buckets entries with new addresses originating from a single group are spread...