Bitcoin Core  26.1.0
P2P Digital Currency
addrman.cpp
Go to the documentation of this file.
1 // Copyright (c) 2012 Pieter Wuille
2 // Copyright (c) 2012-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 <addrman.h>
7 #include <addrman_impl.h>
8 
9 #include <hash.h>
10 #include <logging.h>
11 #include <logging/timer.h>
12 #include <netaddress.h>
13 #include <protocol.h>
14 #include <random.h>
15 #include <serialize.h>
16 #include <streams.h>
17 #include <tinyformat.h>
18 #include <uint256.h>
19 #include <util/check.h>
20 #include <util/time.h>
21 
22 #include <cmath>
23 #include <optional>
24 
26 static constexpr uint32_t ADDRMAN_TRIED_BUCKETS_PER_GROUP{8};
28 static constexpr uint32_t ADDRMAN_NEW_BUCKETS_PER_SOURCE_GROUP{64};
30 static constexpr int32_t ADDRMAN_NEW_BUCKETS_PER_ADDRESS{8};
32 static constexpr auto ADDRMAN_HORIZON{30 * 24h};
34 static constexpr int32_t ADDRMAN_RETRIES{3};
36 static constexpr int32_t ADDRMAN_MAX_FAILURES{10};
38 static constexpr auto ADDRMAN_MIN_FAIL{7 * 24h};
40 static constexpr auto ADDRMAN_REPLACEMENT{4h};
42 static constexpr size_t ADDRMAN_SET_TRIED_COLLISION_SIZE{10};
44 static constexpr auto ADDRMAN_TEST_WINDOW{40min};
45 
46 int AddrInfo::GetTriedBucket(const uint256& nKey, const NetGroupManager& netgroupman) const
47 {
48  uint64_t hash1 = (HashWriter{} << nKey << GetKey()).GetCheapHash();
49  uint64_t hash2 = (HashWriter{} << nKey << netgroupman.GetGroup(*this) << (hash1 % ADDRMAN_TRIED_BUCKETS_PER_GROUP)).GetCheapHash();
50  return hash2 % ADDRMAN_TRIED_BUCKET_COUNT;
51 }
52 
53 int AddrInfo::GetNewBucket(const uint256& nKey, const CNetAddr& src, const NetGroupManager& netgroupman) const
54 {
55  std::vector<unsigned char> vchSourceGroupKey = netgroupman.GetGroup(src);
56  uint64_t hash1 = (HashWriter{} << nKey << netgroupman.GetGroup(*this) << vchSourceGroupKey).GetCheapHash();
57  uint64_t hash2 = (HashWriter{} << nKey << vchSourceGroupKey << (hash1 % ADDRMAN_NEW_BUCKETS_PER_SOURCE_GROUP)).GetCheapHash();
58  return hash2 % ADDRMAN_NEW_BUCKET_COUNT;
59 }
60 
61 int AddrInfo::GetBucketPosition(const uint256& nKey, bool fNew, int bucket) const
62 {
63  uint64_t hash1 = (HashWriter{} << nKey << (fNew ? uint8_t{'N'} : uint8_t{'K'}) << bucket << GetKey()).GetCheapHash();
64  return hash1 % ADDRMAN_BUCKET_SIZE;
65 }
66 
68 {
69  if (now - m_last_try <= 1min) { // never remove things tried in the last minute
70  return false;
71  }
72 
73  if (nTime > now + 10min) { // came in a flying DeLorean
74  return true;
75  }
76 
77  if (now - nTime > ADDRMAN_HORIZON) { // not seen in recent history
78  return true;
79  }
80 
81  if (TicksSinceEpoch<std::chrono::seconds>(m_last_success) == 0 && nAttempts >= ADDRMAN_RETRIES) { // tried N times and never a success
82  return true;
83  }
84 
85  if (now - m_last_success > ADDRMAN_MIN_FAIL && nAttempts >= ADDRMAN_MAX_FAILURES) { // N successive failures in the last week
86  return true;
87  }
88 
89  return false;
90 }
91 
93 {
94  double fChance = 1.0;
95 
96  // deprioritize very recent attempts away
97  if (now - m_last_try < 10min) {
98  fChance *= 0.01;
99  }
100 
101  // deprioritize 66% after each failed attempt, but at most 1/28th to avoid the search taking forever or overly penalizing outages.
102  fChance *= pow(0.66, std::min(nAttempts, 8));
103 
104  return fChance;
105 }
106 
107 AddrManImpl::AddrManImpl(const NetGroupManager& netgroupman, bool deterministic, int32_t consistency_check_ratio)
108  : insecure_rand{deterministic}
109  , nKey{deterministic ? uint256{1} : insecure_rand.rand256()}
110  , m_consistency_check_ratio{consistency_check_ratio}
111  , m_netgroupman{netgroupman}
112 {
113  for (auto& bucket : vvNew) {
114  for (auto& entry : bucket) {
115  entry = -1;
116  }
117  }
118  for (auto& bucket : vvTried) {
119  for (auto& entry : bucket) {
120  entry = -1;
121  }
122  }
123 }
124 
126 {
127  nKey.SetNull();
128 }
129 
130 template <typename Stream>
131 void AddrManImpl::Serialize(Stream& s_) const
132 {
133  LOCK(cs);
134 
173  // Always serialize in the latest version (FILE_FORMAT).
175 
176  s << static_cast<uint8_t>(FILE_FORMAT);
177 
178  // Increment `lowest_compatible` iff a newly introduced format is incompatible with
179  // the previous one.
180  static constexpr uint8_t lowest_compatible = Format::V4_MULTIPORT;
181  s << static_cast<uint8_t>(INCOMPATIBILITY_BASE + lowest_compatible);
182 
183  s << nKey;
184  s << nNew;
185  s << nTried;
186 
187  int nUBuckets = ADDRMAN_NEW_BUCKET_COUNT ^ (1 << 30);
188  s << nUBuckets;
189  std::unordered_map<int, int> mapUnkIds;
190  int nIds = 0;
191  for (const auto& entry : mapInfo) {
192  mapUnkIds[entry.first] = nIds;
193  const AddrInfo& info = entry.second;
194  if (info.nRefCount) {
195  assert(nIds != nNew); // this means nNew was wrong, oh ow
196  s << info;
197  nIds++;
198  }
199  }
200  nIds = 0;
201  for (const auto& entry : mapInfo) {
202  const AddrInfo& info = entry.second;
203  if (info.fInTried) {
204  assert(nIds != nTried); // this means nTried was wrong, oh ow
205  s << info;
206  nIds++;
207  }
208  }
209  for (int bucket = 0; bucket < ADDRMAN_NEW_BUCKET_COUNT; bucket++) {
210  int nSize = 0;
211  for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) {
212  if (vvNew[bucket][i] != -1)
213  nSize++;
214  }
215  s << nSize;
216  for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) {
217  if (vvNew[bucket][i] != -1) {
218  int nIndex = mapUnkIds[vvNew[bucket][i]];
219  s << nIndex;
220  }
221  }
222  }
223  // Store asmap checksum after bucket entries so that it
224  // can be ignored by older clients for backward compatibility.
226 }
227 
228 template <typename Stream>
229 void AddrManImpl::Unserialize(Stream& s_)
230 {
231  LOCK(cs);
232 
233  assert(vRandom.empty());
234 
235  Format format;
236  s_ >> Using<CustomUintFormatter<1>>(format);
237 
238  const auto ser_params = (format >= Format::V3_BIP155 ? CAddress::V2_DISK : CAddress::V1_DISK);
239  ParamsStream s{ser_params, s_};
240 
241  uint8_t compat;
242  s >> compat;
243  if (compat < INCOMPATIBILITY_BASE) {
244  throw std::ios_base::failure(strprintf(
245  "Corrupted addrman database: The compat value (%u) "
246  "is lower than the expected minimum value %u.",
247  compat, INCOMPATIBILITY_BASE));
248  }
249  const uint8_t lowest_compatible = compat - INCOMPATIBILITY_BASE;
250  if (lowest_compatible > FILE_FORMAT) {
252  "Unsupported format of addrman database: %u. It is compatible with formats >=%u, "
253  "but the maximum supported by this version of %s is %u.",
254  uint8_t{format}, lowest_compatible, PACKAGE_NAME, uint8_t{FILE_FORMAT}));
255  }
256 
257  s >> nKey;
258  s >> nNew;
259  s >> nTried;
260  int nUBuckets = 0;
261  s >> nUBuckets;
262  if (format >= Format::V1_DETERMINISTIC) {
263  nUBuckets ^= (1 << 30);
264  }
265 
266  if (nNew > ADDRMAN_NEW_BUCKET_COUNT * ADDRMAN_BUCKET_SIZE || nNew < 0) {
267  throw std::ios_base::failure(
268  strprintf("Corrupt AddrMan serialization: nNew=%d, should be in [0, %d]",
269  nNew,
271  }
272 
273  if (nTried > ADDRMAN_TRIED_BUCKET_COUNT * ADDRMAN_BUCKET_SIZE || nTried < 0) {
274  throw std::ios_base::failure(
275  strprintf("Corrupt AddrMan serialization: nTried=%d, should be in [0, %d]",
276  nTried,
278  }
279 
280  // Deserialize entries from the new table.
281  for (int n = 0; n < nNew; n++) {
282  AddrInfo& info = mapInfo[n];
283  s >> info;
284  mapAddr[info] = n;
285  info.nRandomPos = vRandom.size();
286  vRandom.push_back(n);
287  m_network_counts[info.GetNetwork()].n_new++;
288  }
289  nIdCount = nNew;
290 
291  // Deserialize entries from the tried table.
292  int nLost = 0;
293  for (int n = 0; n < nTried; n++) {
294  AddrInfo info;
295  s >> info;
296  int nKBucket = info.GetTriedBucket(nKey, m_netgroupman);
297  int nKBucketPos = info.GetBucketPosition(nKey, false, nKBucket);
298  if (info.IsValid()
299  && vvTried[nKBucket][nKBucketPos] == -1) {
300  info.nRandomPos = vRandom.size();
301  info.fInTried = true;
302  vRandom.push_back(nIdCount);
303  mapInfo[nIdCount] = info;
304  mapAddr[info] = nIdCount;
305  vvTried[nKBucket][nKBucketPos] = nIdCount;
306  nIdCount++;
307  m_network_counts[info.GetNetwork()].n_tried++;
308  } else {
309  nLost++;
310  }
311  }
312  nTried -= nLost;
313 
314  // Store positions in the new table buckets to apply later (if possible).
315  // An entry may appear in up to ADDRMAN_NEW_BUCKETS_PER_ADDRESS buckets,
316  // so we store all bucket-entry_index pairs to iterate through later.
317  std::vector<std::pair<int, int>> bucket_entries;
318 
319  for (int bucket = 0; bucket < nUBuckets; ++bucket) {
320  int num_entries{0};
321  s >> num_entries;
322  for (int n = 0; n < num_entries; ++n) {
323  int entry_index{0};
324  s >> entry_index;
325  if (entry_index >= 0 && entry_index < nNew) {
326  bucket_entries.emplace_back(bucket, entry_index);
327  }
328  }
329  }
330 
331  // If the bucket count and asmap checksum haven't changed, then attempt
332  // to restore the entries to the buckets/positions they were in before
333  // serialization.
334  uint256 supplied_asmap_checksum{m_netgroupman.GetAsmapChecksum()};
335  uint256 serialized_asmap_checksum;
336  if (format >= Format::V2_ASMAP) {
337  s >> serialized_asmap_checksum;
338  }
339  const bool restore_bucketing{nUBuckets == ADDRMAN_NEW_BUCKET_COUNT &&
340  serialized_asmap_checksum == supplied_asmap_checksum};
341 
342  if (!restore_bucketing) {
343  LogPrint(BCLog::ADDRMAN, "Bucketing method was updated, re-bucketing addrman entries from disk\n");
344  }
345 
346  for (auto bucket_entry : bucket_entries) {
347  int bucket{bucket_entry.first};
348  const int entry_index{bucket_entry.second};
349  AddrInfo& info = mapInfo[entry_index];
350 
351  // Don't store the entry in the new bucket if it's not a valid address for our addrman
352  if (!info.IsValid()) continue;
353 
354  // The entry shouldn't appear in more than
355  // ADDRMAN_NEW_BUCKETS_PER_ADDRESS. If it has already, just skip
356  // this bucket_entry.
357  if (info.nRefCount >= ADDRMAN_NEW_BUCKETS_PER_ADDRESS) continue;
358 
359  int bucket_position = info.GetBucketPosition(nKey, true, bucket);
360  if (restore_bucketing && vvNew[bucket][bucket_position] == -1) {
361  // Bucketing has not changed, using existing bucket positions for the new table
362  vvNew[bucket][bucket_position] = entry_index;
363  ++info.nRefCount;
364  } else {
365  // In case the new table data cannot be used (bucket count wrong or new asmap),
366  // try to give them a reference based on their primary source address.
367  bucket = info.GetNewBucket(nKey, m_netgroupman);
368  bucket_position = info.GetBucketPosition(nKey, true, bucket);
369  if (vvNew[bucket][bucket_position] == -1) {
370  vvNew[bucket][bucket_position] = entry_index;
371  ++info.nRefCount;
372  }
373  }
374  }
375 
376  // Prune new entries with refcount 0 (as a result of collisions or invalid address).
377  int nLostUnk = 0;
378  for (auto it = mapInfo.cbegin(); it != mapInfo.cend(); ) {
379  if (it->second.fInTried == false && it->second.nRefCount == 0) {
380  const auto itCopy = it++;
381  Delete(itCopy->first);
382  ++nLostUnk;
383  } else {
384  ++it;
385  }
386  }
387  if (nLost + nLostUnk > 0) {
388  LogPrint(BCLog::ADDRMAN, "addrman lost %i new and %i tried addresses due to collisions or invalid addresses\n", nLostUnk, nLost);
389  }
390 
391  const int check_code{CheckAddrman()};
392  if (check_code != 0) {
393  throw std::ios_base::failure(strprintf(
394  "Corrupt data. Consistency check failed with code %s",
395  check_code));
396  }
397 }
398 
399 AddrInfo* AddrManImpl::Find(const CService& addr, int* pnId)
400 {
402 
403  const auto it = mapAddr.find(addr);
404  if (it == mapAddr.end())
405  return nullptr;
406  if (pnId)
407  *pnId = (*it).second;
408  const auto it2 = mapInfo.find((*it).second);
409  if (it2 != mapInfo.end())
410  return &(*it2).second;
411  return nullptr;
412 }
413 
414 AddrInfo* AddrManImpl::Create(const CAddress& addr, const CNetAddr& addrSource, int* pnId)
415 {
417 
418  int nId = nIdCount++;
419  mapInfo[nId] = AddrInfo(addr, addrSource);
420  mapAddr[addr] = nId;
421  mapInfo[nId].nRandomPos = vRandom.size();
422  vRandom.push_back(nId);
423  nNew++;
424  m_network_counts[addr.GetNetwork()].n_new++;
425  if (pnId)
426  *pnId = nId;
427  return &mapInfo[nId];
428 }
429 
430 void AddrManImpl::SwapRandom(unsigned int nRndPos1, unsigned int nRndPos2) const
431 {
433 
434  if (nRndPos1 == nRndPos2)
435  return;
436 
437  assert(nRndPos1 < vRandom.size() && nRndPos2 < vRandom.size());
438 
439  int nId1 = vRandom[nRndPos1];
440  int nId2 = vRandom[nRndPos2];
441 
442  const auto it_1{mapInfo.find(nId1)};
443  const auto it_2{mapInfo.find(nId2)};
444  assert(it_1 != mapInfo.end());
445  assert(it_2 != mapInfo.end());
446 
447  it_1->second.nRandomPos = nRndPos2;
448  it_2->second.nRandomPos = nRndPos1;
449 
450  vRandom[nRndPos1] = nId2;
451  vRandom[nRndPos2] = nId1;
452 }
453 
454 void AddrManImpl::Delete(int nId)
455 {
457 
458  assert(mapInfo.count(nId) != 0);
459  AddrInfo& info = mapInfo[nId];
460  assert(!info.fInTried);
461  assert(info.nRefCount == 0);
462 
463  SwapRandom(info.nRandomPos, vRandom.size() - 1);
464  m_network_counts[info.GetNetwork()].n_new--;
465  vRandom.pop_back();
466  mapAddr.erase(info);
467  mapInfo.erase(nId);
468  nNew--;
469 }
470 
471 void AddrManImpl::ClearNew(int nUBucket, int nUBucketPos)
472 {
474 
475  // if there is an entry in the specified bucket, delete it.
476  if (vvNew[nUBucket][nUBucketPos] != -1) {
477  int nIdDelete = vvNew[nUBucket][nUBucketPos];
478  AddrInfo& infoDelete = mapInfo[nIdDelete];
479  assert(infoDelete.nRefCount > 0);
480  infoDelete.nRefCount--;
481  vvNew[nUBucket][nUBucketPos] = -1;
482  LogPrint(BCLog::ADDRMAN, "Removed %s from new[%i][%i]\n", infoDelete.ToStringAddrPort(), nUBucket, nUBucketPos);
483  if (infoDelete.nRefCount == 0) {
484  Delete(nIdDelete);
485  }
486  }
487 }
488 
489 void AddrManImpl::MakeTried(AddrInfo& info, int nId)
490 {
492 
493  // remove the entry from all new buckets
494  const int start_bucket{info.GetNewBucket(nKey, m_netgroupman)};
495  for (int n = 0; n < ADDRMAN_NEW_BUCKET_COUNT; ++n) {
496  const int bucket{(start_bucket + n) % ADDRMAN_NEW_BUCKET_COUNT};
497  const int pos{info.GetBucketPosition(nKey, true, bucket)};
498  if (vvNew[bucket][pos] == nId) {
499  vvNew[bucket][pos] = -1;
500  info.nRefCount--;
501  if (info.nRefCount == 0) break;
502  }
503  }
504  nNew--;
505  m_network_counts[info.GetNetwork()].n_new--;
506 
507  assert(info.nRefCount == 0);
508 
509  // which tried bucket to move the entry to
510  int nKBucket = info.GetTriedBucket(nKey, m_netgroupman);
511  int nKBucketPos = info.GetBucketPosition(nKey, false, nKBucket);
512 
513  // first make space to add it (the existing tried entry there is moved to new, deleting whatever is there).
514  if (vvTried[nKBucket][nKBucketPos] != -1) {
515  // find an item to evict
516  int nIdEvict = vvTried[nKBucket][nKBucketPos];
517  assert(mapInfo.count(nIdEvict) == 1);
518  AddrInfo& infoOld = mapInfo[nIdEvict];
519 
520  // Remove the to-be-evicted item from the tried set.
521  infoOld.fInTried = false;
522  vvTried[nKBucket][nKBucketPos] = -1;
523  nTried--;
524  m_network_counts[infoOld.GetNetwork()].n_tried--;
525 
526  // find which new bucket it belongs to
527  int nUBucket = infoOld.GetNewBucket(nKey, m_netgroupman);
528  int nUBucketPos = infoOld.GetBucketPosition(nKey, true, nUBucket);
529  ClearNew(nUBucket, nUBucketPos);
530  assert(vvNew[nUBucket][nUBucketPos] == -1);
531 
532  // Enter it into the new set again.
533  infoOld.nRefCount = 1;
534  vvNew[nUBucket][nUBucketPos] = nIdEvict;
535  nNew++;
536  m_network_counts[infoOld.GetNetwork()].n_new++;
537  LogPrint(BCLog::ADDRMAN, "Moved %s from tried[%i][%i] to new[%i][%i] to make space\n",
538  infoOld.ToStringAddrPort(), nKBucket, nKBucketPos, nUBucket, nUBucketPos);
539  }
540  assert(vvTried[nKBucket][nKBucketPos] == -1);
541 
542  vvTried[nKBucket][nKBucketPos] = nId;
543  nTried++;
544  info.fInTried = true;
545  m_network_counts[info.GetNetwork()].n_tried++;
546 }
547 
548 bool AddrManImpl::AddSingle(const CAddress& addr, const CNetAddr& source, std::chrono::seconds time_penalty)
549 {
551 
552  if (!addr.IsRoutable())
553  return false;
554 
555  int nId;
556  AddrInfo* pinfo = Find(addr, &nId);
557 
558  // Do not set a penalty for a source's self-announcement
559  if (addr == source) {
560  time_penalty = 0s;
561  }
562 
563  if (pinfo) {
564  // periodically update nTime
565  const bool currently_online{NodeClock::now() - addr.nTime < 24h};
566  const auto update_interval{currently_online ? 1h : 24h};
567  if (pinfo->nTime < addr.nTime - update_interval - time_penalty) {
568  pinfo->nTime = std::max(NodeSeconds{0s}, addr.nTime - time_penalty);
569  }
570 
571  // add services
572  pinfo->nServices = ServiceFlags(pinfo->nServices | addr.nServices);
573 
574  // do not update if no new information is present
575  if (addr.nTime <= pinfo->nTime) {
576  return false;
577  }
578 
579  // do not update if the entry was already in the "tried" table
580  if (pinfo->fInTried)
581  return false;
582 
583  // do not update if the max reference count is reached
585  return false;
586 
587  // stochastic test: previous nRefCount == N: 2^N times harder to increase it
588  int nFactor = 1;
589  for (int n = 0; n < pinfo->nRefCount; n++)
590  nFactor *= 2;
591  if (nFactor > 1 && (insecure_rand.randrange(nFactor) != 0))
592  return false;
593  } else {
594  pinfo = Create(addr, source, &nId);
595  pinfo->nTime = std::max(NodeSeconds{0s}, pinfo->nTime - time_penalty);
596  }
597 
598  int nUBucket = pinfo->GetNewBucket(nKey, source, m_netgroupman);
599  int nUBucketPos = pinfo->GetBucketPosition(nKey, true, nUBucket);
600  bool fInsert = vvNew[nUBucket][nUBucketPos] == -1;
601  if (vvNew[nUBucket][nUBucketPos] != nId) {
602  if (!fInsert) {
603  AddrInfo& infoExisting = mapInfo[vvNew[nUBucket][nUBucketPos]];
604  if (infoExisting.IsTerrible() || (infoExisting.nRefCount > 1 && pinfo->nRefCount == 0)) {
605  // Overwrite the existing new table entry.
606  fInsert = true;
607  }
608  }
609  if (fInsert) {
610  ClearNew(nUBucket, nUBucketPos);
611  pinfo->nRefCount++;
612  vvNew[nUBucket][nUBucketPos] = nId;
613  LogPrint(BCLog::ADDRMAN, "Added %s mapped to AS%i to new[%i][%i]\n",
614  addr.ToStringAddrPort(), m_netgroupman.GetMappedAS(addr), nUBucket, nUBucketPos);
615  } else {
616  if (pinfo->nRefCount == 0) {
617  Delete(nId);
618  }
619  }
620  }
621  return fInsert;
622 }
623 
624 bool AddrManImpl::Good_(const CService& addr, bool test_before_evict, NodeSeconds time)
625 {
627 
628  int nId;
629 
630  m_last_good = time;
631 
632  AddrInfo* pinfo = Find(addr, &nId);
633 
634  // if not found, bail out
635  if (!pinfo) return false;
636 
637  AddrInfo& info = *pinfo;
638 
639  // update info
640  info.m_last_success = time;
641  info.m_last_try = time;
642  info.nAttempts = 0;
643  // nTime is not updated here, to avoid leaking information about
644  // currently-connected peers.
645 
646  // if it is already in the tried set, don't do anything else
647  if (info.fInTried) return false;
648 
649  // if it is not in new, something bad happened
650  if (!Assume(info.nRefCount > 0)) return false;
651 
652 
653  // which tried bucket to move the entry to
654  int tried_bucket = info.GetTriedBucket(nKey, m_netgroupman);
655  int tried_bucket_pos = info.GetBucketPosition(nKey, false, tried_bucket);
656 
657  // Will moving this address into tried evict another entry?
658  if (test_before_evict && (vvTried[tried_bucket][tried_bucket_pos] != -1)) {
660  m_tried_collisions.insert(nId);
661  }
662  // Output the entry we'd be colliding with, for debugging purposes
663  auto colliding_entry = mapInfo.find(vvTried[tried_bucket][tried_bucket_pos]);
664  LogPrint(BCLog::ADDRMAN, "Collision with %s while attempting to move %s to tried table. Collisions=%d\n",
665  colliding_entry != mapInfo.end() ? colliding_entry->second.ToStringAddrPort() : "",
666  addr.ToStringAddrPort(),
667  m_tried_collisions.size());
668  return false;
669  } else {
670  // move nId to the tried tables
671  MakeTried(info, nId);
672  LogPrint(BCLog::ADDRMAN, "Moved %s mapped to AS%i to tried[%i][%i]\n",
673  addr.ToStringAddrPort(), m_netgroupman.GetMappedAS(addr), tried_bucket, tried_bucket_pos);
674  return true;
675  }
676 }
677 
678 bool AddrManImpl::Add_(const std::vector<CAddress>& vAddr, const CNetAddr& source, std::chrono::seconds time_penalty)
679 {
680  int added{0};
681  for (std::vector<CAddress>::const_iterator it = vAddr.begin(); it != vAddr.end(); it++) {
682  added += AddSingle(*it, source, time_penalty) ? 1 : 0;
683  }
684  if (added > 0) {
685  LogPrint(BCLog::ADDRMAN, "Added %i addresses (of %i) from %s: %i tried, %i new\n", added, vAddr.size(), source.ToStringAddr(), nTried, nNew);
686  }
687  return added > 0;
688 }
689 
690 void AddrManImpl::Attempt_(const CService& addr, bool fCountFailure, NodeSeconds time)
691 {
693 
694  AddrInfo* pinfo = Find(addr);
695 
696  // if not found, bail out
697  if (!pinfo)
698  return;
699 
700  AddrInfo& info = *pinfo;
701 
702  // update info
703  info.m_last_try = time;
704  if (fCountFailure && info.m_last_count_attempt < m_last_good) {
705  info.m_last_count_attempt = time;
706  info.nAttempts++;
707  }
708 }
709 
710 std::pair<CAddress, NodeSeconds> AddrManImpl::Select_(bool new_only, std::optional<Network> network) const
711 {
713 
714  if (vRandom.empty()) return {};
715 
716  size_t new_count = nNew;
717  size_t tried_count = nTried;
718 
719  if (network.has_value()) {
720  auto it = m_network_counts.find(*network);
721  if (it == m_network_counts.end()) return {};
722 
723  auto counts = it->second;
724  new_count = counts.n_new;
725  tried_count = counts.n_tried;
726  }
727 
728  if (new_only && new_count == 0) return {};
729  if (new_count + tried_count == 0) return {};
730 
731  // Decide if we are going to search the new or tried table
732  // If either option is viable, use a 50% chance to choose
733  bool search_tried;
734  if (new_only || tried_count == 0) {
735  search_tried = false;
736  } else if (new_count == 0) {
737  search_tried = true;
738  } else {
739  search_tried = insecure_rand.randbool();
740  }
741 
742  const int bucket_count{search_tried ? ADDRMAN_TRIED_BUCKET_COUNT : ADDRMAN_NEW_BUCKET_COUNT};
743 
744  // Loop through the addrman table until we find an appropriate entry
745  double chance_factor = 1.0;
746  while (1) {
747  // Pick a bucket, and an initial position in that bucket.
748  int bucket = insecure_rand.randrange(bucket_count);
749  int initial_position = insecure_rand.randrange(ADDRMAN_BUCKET_SIZE);
750 
751  // Iterate over the positions of that bucket, starting at the initial one,
752  // and looping around.
753  int i, position, node_id;
754  for (i = 0; i < ADDRMAN_BUCKET_SIZE; ++i) {
755  position = (initial_position + i) % ADDRMAN_BUCKET_SIZE;
756  node_id = GetEntry(search_tried, bucket, position);
757  if (node_id != -1) {
758  if (network.has_value()) {
759  const auto it{mapInfo.find(node_id)};
760  if (Assume(it != mapInfo.end()) && it->second.GetNetwork() == *network) break;
761  } else {
762  break;
763  }
764  }
765  }
766 
767  // If the bucket is entirely empty, start over with a (likely) different one.
768  if (i == ADDRMAN_BUCKET_SIZE) continue;
769 
770  // Find the entry to return.
771  const auto it_found{mapInfo.find(node_id)};
772  assert(it_found != mapInfo.end());
773  const AddrInfo& info{it_found->second};
774 
775  // With probability GetChance() * chance_factor, return the entry.
776  if (insecure_rand.randbits(30) < chance_factor * info.GetChance() * (1 << 30)) {
777  LogPrint(BCLog::ADDRMAN, "Selected %s from %s\n", info.ToStringAddrPort(), search_tried ? "tried" : "new");
778  return {info, info.m_last_try};
779  }
780 
781  // Otherwise start over with a (likely) different bucket, and increased chance factor.
782  chance_factor *= 1.2;
783  }
784 }
785 
786 int AddrManImpl::GetEntry(bool use_tried, size_t bucket, size_t position) const
787 {
789 
790  if (use_tried) {
791  if (Assume(position < ADDRMAN_BUCKET_SIZE) && Assume(bucket < ADDRMAN_TRIED_BUCKET_COUNT)) {
792  return vvTried[bucket][position];
793  }
794  } else {
795  if (Assume(position < ADDRMAN_BUCKET_SIZE) && Assume(bucket < ADDRMAN_NEW_BUCKET_COUNT)) {
796  return vvNew[bucket][position];
797  }
798  }
799 
800  return -1;
801 }
802 
803 std::vector<CAddress> AddrManImpl::GetAddr_(size_t max_addresses, size_t max_pct, std::optional<Network> network) const
804 {
806 
807  size_t nNodes = vRandom.size();
808  if (max_pct != 0) {
809  nNodes = max_pct * nNodes / 100;
810  }
811  if (max_addresses != 0) {
812  nNodes = std::min(nNodes, max_addresses);
813  }
814 
815  // gather a list of random nodes, skipping those of low quality
816  const auto now{Now<NodeSeconds>()};
817  std::vector<CAddress> addresses;
818  for (unsigned int n = 0; n < vRandom.size(); n++) {
819  if (addresses.size() >= nNodes)
820  break;
821 
822  int nRndPos = insecure_rand.randrange(vRandom.size() - n) + n;
823  SwapRandom(n, nRndPos);
824  const auto it{mapInfo.find(vRandom[n])};
825  assert(it != mapInfo.end());
826 
827  const AddrInfo& ai{it->second};
828 
829  // Filter by network (optional)
830  if (network != std::nullopt && ai.GetNetClass() != network) continue;
831 
832  // Filter for quality
833  if (ai.IsTerrible(now)) continue;
834 
835  addresses.push_back(ai);
836  }
837  LogPrint(BCLog::ADDRMAN, "GetAddr returned %d random addresses\n", addresses.size());
838  return addresses;
839 }
840 
841 std::vector<std::pair<AddrInfo, AddressPosition>> AddrManImpl::GetEntries_(bool from_tried) const
842 {
844 
845  const int bucket_count = from_tried ? ADDRMAN_TRIED_BUCKET_COUNT : ADDRMAN_NEW_BUCKET_COUNT;
846  std::vector<std::pair<AddrInfo, AddressPosition>> infos;
847  for (int bucket = 0; bucket < bucket_count; ++bucket) {
848  for (int position = 0; position < ADDRMAN_BUCKET_SIZE; ++position) {
849  int id = GetEntry(from_tried, bucket, position);
850  if (id >= 0) {
851  AddrInfo info = mapInfo.at(id);
852  AddressPosition location = AddressPosition(
853  from_tried,
854  /*multiplicity_in=*/from_tried ? 1 : info.nRefCount,
855  bucket,
856  position);
857  infos.emplace_back(info, location);
858  }
859  }
860  }
861 
862  return infos;
863 }
864 
866 {
868 
869  AddrInfo* pinfo = Find(addr);
870 
871  // if not found, bail out
872  if (!pinfo)
873  return;
874 
875  AddrInfo& info = *pinfo;
876 
877  // update info
878  const auto update_interval{20min};
879  if (time - info.nTime > update_interval) {
880  info.nTime = time;
881  }
882 }
883 
884 void AddrManImpl::SetServices_(const CService& addr, ServiceFlags nServices)
885 {
887 
888  AddrInfo* pinfo = Find(addr);
889 
890  // if not found, bail out
891  if (!pinfo)
892  return;
893 
894  AddrInfo& info = *pinfo;
895 
896  // update info
897  info.nServices = nServices;
898 }
899 
901 {
903 
904  for (std::set<int>::iterator it = m_tried_collisions.begin(); it != m_tried_collisions.end();) {
905  int id_new = *it;
906 
907  bool erase_collision = false;
908 
909  // If id_new not found in mapInfo remove it from m_tried_collisions
910  if (mapInfo.count(id_new) != 1) {
911  erase_collision = true;
912  } else {
913  AddrInfo& info_new = mapInfo[id_new];
914 
915  // Which tried bucket to move the entry to.
916  int tried_bucket = info_new.GetTriedBucket(nKey, m_netgroupman);
917  int tried_bucket_pos = info_new.GetBucketPosition(nKey, false, tried_bucket);
918  if (!info_new.IsValid()) { // id_new may no longer map to a valid address
919  erase_collision = true;
920  } else if (vvTried[tried_bucket][tried_bucket_pos] != -1) { // The position in the tried bucket is not empty
921 
922  // Get the to-be-evicted address that is being tested
923  int id_old = vvTried[tried_bucket][tried_bucket_pos];
924  AddrInfo& info_old = mapInfo[id_old];
925 
926  const auto current_time{Now<NodeSeconds>()};
927 
928  // Has successfully connected in last X hours
929  if (current_time - info_old.m_last_success < ADDRMAN_REPLACEMENT) {
930  erase_collision = true;
931  } else if (current_time - info_old.m_last_try < ADDRMAN_REPLACEMENT) { // attempted to connect and failed in last X hours
932 
933  // Give address at least 60 seconds to successfully connect
934  if (current_time - info_old.m_last_try > 60s) {
935  LogPrint(BCLog::ADDRMAN, "Replacing %s with %s in tried table\n", info_old.ToStringAddrPort(), info_new.ToStringAddrPort());
936 
937  // Replaces an existing address already in the tried table with the new address
938  Good_(info_new, false, current_time);
939  erase_collision = true;
940  }
941  } else if (current_time - info_new.m_last_success > ADDRMAN_TEST_WINDOW) {
942  // If the collision hasn't resolved in some reasonable amount of time,
943  // just evict the old entry -- we must not be able to
944  // connect to it for some reason.
945  LogPrint(BCLog::ADDRMAN, "Unable to test; replacing %s with %s in tried table anyway\n", info_old.ToStringAddrPort(), info_new.ToStringAddrPort());
946  Good_(info_new, false, current_time);
947  erase_collision = true;
948  }
949  } else { // Collision is not actually a collision anymore
950  Good_(info_new, false, Now<NodeSeconds>());
951  erase_collision = true;
952  }
953  }
954 
955  if (erase_collision) {
956  m_tried_collisions.erase(it++);
957  } else {
958  it++;
959  }
960  }
961 }
962 
963 std::pair<CAddress, NodeSeconds> AddrManImpl::SelectTriedCollision_()
964 {
966 
967  if (m_tried_collisions.size() == 0) return {};
968 
969  std::set<int>::iterator it = m_tried_collisions.begin();
970 
971  // Selects a random element from m_tried_collisions
972  std::advance(it, insecure_rand.randrange(m_tried_collisions.size()));
973  int id_new = *it;
974 
975  // If id_new not found in mapInfo remove it from m_tried_collisions
976  if (mapInfo.count(id_new) != 1) {
977  m_tried_collisions.erase(it);
978  return {};
979  }
980 
981  const AddrInfo& newInfo = mapInfo[id_new];
982 
983  // which tried bucket to move the entry to
984  int tried_bucket = newInfo.GetTriedBucket(nKey, m_netgroupman);
985  int tried_bucket_pos = newInfo.GetBucketPosition(nKey, false, tried_bucket);
986 
987  const AddrInfo& info_old = mapInfo[vvTried[tried_bucket][tried_bucket_pos]];
988  return {info_old, info_old.m_last_try};
989 }
990 
991 std::optional<AddressPosition> AddrManImpl::FindAddressEntry_(const CAddress& addr)
992 {
994 
995  AddrInfo* addr_info = Find(addr);
996 
997  if (!addr_info) return std::nullopt;
998 
999  if(addr_info->fInTried) {
1000  int bucket{addr_info->GetTriedBucket(nKey, m_netgroupman)};
1001  return AddressPosition(/*tried_in=*/true,
1002  /*multiplicity_in=*/1,
1003  /*bucket_in=*/bucket,
1004  /*position_in=*/addr_info->GetBucketPosition(nKey, false, bucket));
1005  } else {
1006  int bucket{addr_info->GetNewBucket(nKey, m_netgroupman)};
1007  return AddressPosition(/*tried_in=*/false,
1008  /*multiplicity_in=*/addr_info->nRefCount,
1009  /*bucket_in=*/bucket,
1010  /*position_in=*/addr_info->GetBucketPosition(nKey, true, bucket));
1011  }
1012 }
1013 
1014 size_t AddrManImpl::Size_(std::optional<Network> net, std::optional<bool> in_new) const
1015 {
1016  AssertLockHeld(cs);
1017 
1018  if (!net.has_value()) {
1019  if (in_new.has_value()) {
1020  return *in_new ? nNew : nTried;
1021  } else {
1022  return vRandom.size();
1023  }
1024  }
1025  if (auto it = m_network_counts.find(*net); it != m_network_counts.end()) {
1026  auto net_count = it->second;
1027  if (in_new.has_value()) {
1028  return *in_new ? net_count.n_new : net_count.n_tried;
1029  } else {
1030  return net_count.n_new + net_count.n_tried;
1031  }
1032  }
1033  return 0;
1034 }
1035 
1037 {
1038  AssertLockHeld(cs);
1039 
1040  // Run consistency checks 1 in m_consistency_check_ratio times if enabled
1041  if (m_consistency_check_ratio == 0) return;
1042  if (insecure_rand.randrange(m_consistency_check_ratio) >= 1) return;
1043 
1044  const int err{CheckAddrman()};
1045  if (err) {
1046  LogPrintf("ADDRMAN CONSISTENCY CHECK FAILED!!! err=%i\n", err);
1047  assert(false);
1048  }
1049 }
1050 
1052 {
1053  AssertLockHeld(cs);
1054 
1056  strprintf("new %i, tried %i, total %u", nNew, nTried, vRandom.size()), BCLog::ADDRMAN);
1057 
1058  std::unordered_set<int> setTried;
1059  std::unordered_map<int, int> mapNew;
1060  std::unordered_map<Network, NewTriedCount> local_counts;
1061 
1062  if (vRandom.size() != (size_t)(nTried + nNew))
1063  return -7;
1064 
1065  for (const auto& entry : mapInfo) {
1066  int n = entry.first;
1067  const AddrInfo& info = entry.second;
1068  if (info.fInTried) {
1069  if (!TicksSinceEpoch<std::chrono::seconds>(info.m_last_success)) {
1070  return -1;
1071  }
1072  if (info.nRefCount)
1073  return -2;
1074  setTried.insert(n);
1075  local_counts[info.GetNetwork()].n_tried++;
1076  } else {
1077  if (info.nRefCount < 0 || info.nRefCount > ADDRMAN_NEW_BUCKETS_PER_ADDRESS)
1078  return -3;
1079  if (!info.nRefCount)
1080  return -4;
1081  mapNew[n] = info.nRefCount;
1082  local_counts[info.GetNetwork()].n_new++;
1083  }
1084  const auto it{mapAddr.find(info)};
1085  if (it == mapAddr.end() || it->second != n) {
1086  return -5;
1087  }
1088  if (info.nRandomPos < 0 || (size_t)info.nRandomPos >= vRandom.size() || vRandom[info.nRandomPos] != n)
1089  return -14;
1090  if (info.m_last_try < NodeSeconds{0s}) {
1091  return -6;
1092  }
1093  if (info.m_last_success < NodeSeconds{0s}) {
1094  return -8;
1095  }
1096  }
1097 
1098  if (setTried.size() != (size_t)nTried)
1099  return -9;
1100  if (mapNew.size() != (size_t)nNew)
1101  return -10;
1102 
1103  for (int n = 0; n < ADDRMAN_TRIED_BUCKET_COUNT; n++) {
1104  for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) {
1105  if (vvTried[n][i] != -1) {
1106  if (!setTried.count(vvTried[n][i]))
1107  return -11;
1108  const auto it{mapInfo.find(vvTried[n][i])};
1109  if (it == mapInfo.end() || it->second.GetTriedBucket(nKey, m_netgroupman) != n) {
1110  return -17;
1111  }
1112  if (it->second.GetBucketPosition(nKey, false, n) != i) {
1113  return -18;
1114  }
1115  setTried.erase(vvTried[n][i]);
1116  }
1117  }
1118  }
1119 
1120  for (int n = 0; n < ADDRMAN_NEW_BUCKET_COUNT; n++) {
1121  for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) {
1122  if (vvNew[n][i] != -1) {
1123  if (!mapNew.count(vvNew[n][i]))
1124  return -12;
1125  const auto it{mapInfo.find(vvNew[n][i])};
1126  if (it == mapInfo.end() || it->second.GetBucketPosition(nKey, true, n) != i) {
1127  return -19;
1128  }
1129  if (--mapNew[vvNew[n][i]] == 0)
1130  mapNew.erase(vvNew[n][i]);
1131  }
1132  }
1133  }
1134 
1135  if (setTried.size())
1136  return -13;
1137  if (mapNew.size())
1138  return -15;
1139  if (nKey.IsNull())
1140  return -16;
1141 
1142  // It's possible that m_network_counts may have all-zero entries that local_counts
1143  // doesn't have if addrs from a network were being added and then removed again in the past.
1144  if (m_network_counts.size() < local_counts.size()) {
1145  return -20;
1146  }
1147  for (const auto& [net, count] : m_network_counts) {
1148  if (local_counts[net].n_new != count.n_new || local_counts[net].n_tried != count.n_tried) {
1149  return -21;
1150  }
1151  }
1152 
1153  return 0;
1154 }
1155 
1156 size_t AddrManImpl::Size(std::optional<Network> net, std::optional<bool> in_new) const
1157 {
1158  LOCK(cs);
1159  Check();
1160  auto ret = Size_(net, in_new);
1161  Check();
1162  return ret;
1163 }
1164 
1165 bool AddrManImpl::Add(const std::vector<CAddress>& vAddr, const CNetAddr& source, std::chrono::seconds time_penalty)
1166 {
1167  LOCK(cs);
1168  Check();
1169  auto ret = Add_(vAddr, source, time_penalty);
1170  Check();
1171  return ret;
1172 }
1173 
1174 bool AddrManImpl::Good(const CService& addr, NodeSeconds time)
1175 {
1176  LOCK(cs);
1177  Check();
1178  auto ret = Good_(addr, /*test_before_evict=*/true, time);
1179  Check();
1180  return ret;
1181 }
1182 
1183 void AddrManImpl::Attempt(const CService& addr, bool fCountFailure, NodeSeconds time)
1184 {
1185  LOCK(cs);
1186  Check();
1187  Attempt_(addr, fCountFailure, time);
1188  Check();
1189 }
1190 
1192 {
1193  LOCK(cs);
1194  Check();
1196  Check();
1197 }
1198 
1199 std::pair<CAddress, NodeSeconds> AddrManImpl::SelectTriedCollision()
1200 {
1201  LOCK(cs);
1202  Check();
1203  auto ret = SelectTriedCollision_();
1204  Check();
1205  return ret;
1206 }
1207 
1208 std::pair<CAddress, NodeSeconds> AddrManImpl::Select(bool new_only, std::optional<Network> network) const
1209 {
1210  LOCK(cs);
1211  Check();
1212  auto addrRet = Select_(new_only, network);
1213  Check();
1214  return addrRet;
1215 }
1216 
1217 std::vector<CAddress> AddrManImpl::GetAddr(size_t max_addresses, size_t max_pct, std::optional<Network> network) const
1218 {
1219  LOCK(cs);
1220  Check();
1221  auto addresses = GetAddr_(max_addresses, max_pct, network);
1222  Check();
1223  return addresses;
1224 }
1225 
1226 std::vector<std::pair<AddrInfo, AddressPosition>> AddrManImpl::GetEntries(bool from_tried) const
1227 {
1228  LOCK(cs);
1229  Check();
1230  auto addrInfos = GetEntries_(from_tried);
1231  Check();
1232  return addrInfos;
1233 }
1234 
1236 {
1237  LOCK(cs);
1238  Check();
1239  Connected_(addr, time);
1240  Check();
1241 }
1242 
1243 void AddrManImpl::SetServices(const CService& addr, ServiceFlags nServices)
1244 {
1245  LOCK(cs);
1246  Check();
1247  SetServices_(addr, nServices);
1248  Check();
1249 }
1250 
1251 std::optional<AddressPosition> AddrManImpl::FindAddressEntry(const CAddress& addr)
1252 {
1253  LOCK(cs);
1254  Check();
1255  auto entry = FindAddressEntry_(addr);
1256  Check();
1257  return entry;
1258 }
1259 
1260 AddrMan::AddrMan(const NetGroupManager& netgroupman, bool deterministic, int32_t consistency_check_ratio)
1261  : m_impl(std::make_unique<AddrManImpl>(netgroupman, deterministic, consistency_check_ratio)) {}
1262 
1263 AddrMan::~AddrMan() = default;
1264 
1265 template <typename Stream>
1266 void AddrMan::Serialize(Stream& s_) const
1267 {
1268  m_impl->Serialize<Stream>(s_);
1269 }
1270 
1271 template <typename Stream>
1272 void AddrMan::Unserialize(Stream& s_)
1273 {
1274  m_impl->Unserialize<Stream>(s_);
1275 }
1276 
1277 // explicit instantiation
1278 template void AddrMan::Serialize(HashedSourceWriter<AutoFile>&) const;
1279 template void AddrMan::Serialize(DataStream&) const;
1280 template void AddrMan::Unserialize(AutoFile&);
1282 template void AddrMan::Unserialize(DataStream&);
1284 
1285 size_t AddrMan::Size(std::optional<Network> net, std::optional<bool> in_new) const
1286 {
1287  return m_impl->Size(net, in_new);
1288 }
1289 
1290 bool AddrMan::Add(const std::vector<CAddress>& vAddr, const CNetAddr& source, std::chrono::seconds time_penalty)
1291 {
1292  return m_impl->Add(vAddr, source, time_penalty);
1293 }
1294 
1295 bool AddrMan::Good(const CService& addr, NodeSeconds time)
1296 {
1297  return m_impl->Good(addr, time);
1298 }
1299 
1300 void AddrMan::Attempt(const CService& addr, bool fCountFailure, NodeSeconds time)
1301 {
1302  m_impl->Attempt(addr, fCountFailure, time);
1303 }
1304 
1306 {
1307  m_impl->ResolveCollisions();
1308 }
1309 
1310 std::pair<CAddress, NodeSeconds> AddrMan::SelectTriedCollision()
1311 {
1312  return m_impl->SelectTriedCollision();
1313 }
1314 
1315 std::pair<CAddress, NodeSeconds> AddrMan::Select(bool new_only, std::optional<Network> network) const
1316 {
1317  return m_impl->Select(new_only, network);
1318 }
1319 
1320 std::vector<CAddress> AddrMan::GetAddr(size_t max_addresses, size_t max_pct, std::optional<Network> network) const
1321 {
1322  return m_impl->GetAddr(max_addresses, max_pct, network);
1323 }
1324 
1325 std::vector<std::pair<AddrInfo, AddressPosition>> AddrMan::GetEntries(bool use_tried) const
1326 {
1327  return m_impl->GetEntries(use_tried);
1328 }
1329 
1330 void AddrMan::Connected(const CService& addr, NodeSeconds time)
1331 {
1332  m_impl->Connected(addr, time);
1333 }
1334 
1335 void AddrMan::SetServices(const CService& addr, ServiceFlags nServices)
1336 {
1337  m_impl->SetServices(addr, nServices);
1338 }
1339 
1340 std::optional<AddressPosition> AddrMan::FindAddressEntry(const CAddress& addr)
1341 {
1342  return m_impl->FindAddressEntry(addr);
1343 }
Wrapper that overrides the GetParams() function of a stream (and hides GetVersion/GetType).
Definition: serialize.h:1142
const std::unique_ptr< AddrManImpl > m_impl
Definition: addrman.h:90
void Connected(const CService &addr, NodeSeconds time) EXCLUSIVE_LOCKS_REQUIRED(!cs)
Definition: addrman.cpp:1235
std::vector< unsigned char > GetGroup(const CNetAddr &address) const
Get the canonical identifier of the network group for address.
Definition: netgroup.cpp:17
size_t Size(std::optional< Network > net=std::nullopt, std::optional< bool > in_new=std::nullopt) const
Return size information about addrman.
Definition: addrman.cpp:1285
static constexpr uint8_t INCOMPATIBILITY_BASE
The initial value of a field that is incremented every time an incompatible format change is made (su...
Definition: addrman_impl.h:180
int ret
AssertLockHeld(pool.cs)
void Connected_(const CService &addr, NodeSeconds time) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: addrman.cpp:865
ServiceFlags
nServices flags
Definition: protocol.h:274
const NetGroupManager & m_netgroupman
Reference to the netgroup manager.
Definition: addrman_impl.h:218
#define LogPrint(category,...)
Definition: logging.h:246
assert(!tx.IsCoinBase())
uint256 GetAsmapChecksum() const
Get a checksum identifying the asmap being used.
Definition: netgroup.cpp:10
bool Good_(const CService &addr, bool test_before_evict, NodeSeconds time) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: addrman.cpp:624
void Unserialize(Stream &s_)
Definition: addrman.cpp:1272
static constexpr int ADDRMAN_BUCKET_SIZE
Definition: addrman_impl.h:34
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1162
void SwapRandom(unsigned int nRandomPos1, unsigned int nRandomPos2) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Swap two elements in vRandom.
Definition: addrman.cpp:430
std::pair< CAddress, NodeSeconds > Select(bool new_only, std::optional< Network > network) const EXCLUSIVE_LOCKS_REQUIRED(!cs)
Definition: addrman.cpp:1208
int GetEntry(bool use_tried, size_t bucket, size_t position) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Helper to generalize looking up an addrman entry from either table.
Definition: addrman.cpp:786
std::optional< AddressPosition > FindAddressEntry(const CAddress &addr)
Test-only function Find the address record in AddrMan and return information about its position...
Definition: addrman.cpp:1340
std::vector< std::pair< AddrInfo, AddressPosition > > GetEntries_(bool from_tried) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: addrman.cpp:841
static constexpr int ADDRMAN_TRIED_BUCKET_COUNT
Definition: addrman_impl.h:28
std::vector< CAddress > GetAddr(size_t max_addresses, size_t max_pct, std::optional< Network > network) const EXCLUSIVE_LOCKS_REQUIRED(!cs)
Definition: addrman.cpp:1217
void Attempt_(const CService &addr, bool fCountFailure, NodeSeconds time) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: addrman.cpp:690
static constexpr int32_t ADDRMAN_MAX_FAILURES
How many successive failures are allowed ...
Definition: addrman.cpp:36
bool Add_(const std::vector< CAddress > &vAddr, const CNetAddr &source, std::chrono::seconds time_penalty) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: addrman.cpp:678
size_t Size_(std::optional< Network > net, std::optional< bool > in_new) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: addrman.cpp:1014
static constexpr SerParams V1_DISK
Definition: protocol.h:406
std::pair< CAddress, NodeSeconds > Select_(bool new_only, std::optional< Network > network) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: addrman.cpp:710
#define PACKAGE_NAME
int nRandomPos
position in vRandom
Definition: addrman_impl.h:64
int CheckAddrman() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Perform consistency check, regardless of m_consistency_check_ratio.
Definition: addrman.cpp:1051
size_t Size(std::optional< Network > net, std::optional< bool > in_new) const EXCLUSIVE_LOCKS_REQUIRED(!cs)
Definition: addrman.cpp:1156
static constexpr size_t ADDRMAN_SET_TRIED_COLLISION_SIZE
The maximum number of tried addr collisions to store.
Definition: addrman.cpp:42
int GetBucketPosition(const uint256 &nKey, bool fNew, int bucket) const
Calculate in which position of a bucket to store this entry.
Definition: addrman.cpp:61
Netgroup manager.
Definition: netgroup.h:16
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:470
enum Network GetNetwork() const
Definition: netaddress.cpp:497
void ResolveCollisions()
See if any to-be-evicted tried table entries have been tested and if so resolve the collisions...
Definition: addrman.cpp:1305
std::string ToStringAddrPort() const
Definition: netaddress.cpp:889
uint256 nKey
secret key to randomize bucket select with
Definition: addrman_impl.h:157
std::pair< CAddress, NodeSeconds > SelectTriedCollision_() EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: addrman.cpp:963
void ResolveCollisions() EXCLUSIVE_LOCKS_REQUIRED(!cs)
Definition: addrman.cpp:1191
bool IsValid() const
Definition: netaddress.cpp:425
static constexpr int32_t ADDRMAN_RETRIES
After how many failed attempts we give up on a new node.
Definition: addrman.cpp:34
std::chrono::time_point< NodeClock, std::chrono::seconds > NodeSeconds
Definition: time.h:23
static constexpr SerParams V2_DISK
Definition: protocol.h:407
int nAttempts
connection attempts since last successful attempt
Definition: addrman_impl.h:55
void ResolveCollisions_() EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: addrman.cpp:900
const char * source
Definition: rpcconsole.cpp:59
std::pair< CAddress, NodeSeconds > SelectTriedCollision() EXCLUSIVE_LOCKS_REQUIRED(!cs)
Definition: addrman.cpp:1199
NodeSeconds m_last_try
last try whatsoever by us (memory only)
Definition: addrman_impl.h:43
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&#39;s new table.
Definition: addrman.cpp:1290
std::vector< CAddress > GetAddr_(size_t max_addresses, size_t max_pct, std::optional< Network > network) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: addrman.cpp:803
int nRefCount
reference count in new sets (memory only)
Definition: addrman_impl.h:58
static constexpr auto ADDRMAN_MIN_FAIL
...
Definition: addrman.cpp:38
#define LOCK(cs)
Definition: sync.h:258
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:192
void Attempt(const CService &addr, bool fCountFailure, NodeSeconds time) EXCLUSIVE_LOCKS_REQUIRED(!cs)
Definition: addrman.cpp:1183
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:534
A writer stream (for serialization) that computes a 256-bit hash.
Definition: hash.h:101
void format(std::ostream &out, const char *fmt, const Args &... args)
Format list of arguments to the stream according to given format string.
Definition: tinyformat.h:1060
Extended statistics about a CAddress.
Definition: addrman_impl.h:39
void Attempt(const CService &addr, bool fCountFailure, NodeSeconds time=Now< NodeSeconds >())
Mark an entry as connection attempted to.
Definition: addrman.cpp:1300
NodeSeconds m_last_count_attempt
last counted attempt (memory only)
Definition: addrman_impl.h:46
A CService with information about it as peer.
Definition: protocol.h:362
void Connected(const CService &addr, NodeSeconds time=Now< NodeSeconds >())
We have successfully connected to this peer.
Definition: addrman.cpp:1330
std::vector< unsigned char > GetKey() const
Definition: netaddress.cpp:881
void Serialize(Stream &s_) const EXCLUSIVE_LOCKS_REQUIRED(!cs)
Definition: addrman.cpp:131
uint32_t GetMappedAS(const CNetAddr &address) const
Get the autonomous system on the BGP path to address.
Definition: netgroup.cpp:80
bool Add(const std::vector< CAddress > &vAddr, const CNetAddr &source, std::chrono::seconds time_penalty) EXCLUSIVE_LOCKS_REQUIRED(!cs)
Definition: addrman.cpp:1165
NodeSeconds nTime
Always included in serialization. The behavior is unspecified if the value is not representable as ui...
Definition: protocol.h:452
int GetNewBucket(const uint256 &nKey, const CNetAddr &src, const NetGroupManager &netgroupman) const
Calculate in which "new" bucket this entry belongs, given a certain source.
Definition: addrman.cpp:53
void Serialize(Stream &s_) const
Definition: addrman.cpp:1266
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...
Definition: addrman.cpp:471
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.
Definition: addrman.cpp:1320
void Check() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Consistency check, taking into account m_consistency_check_ratio.
Definition: addrman.cpp:1036
bool IsRoutable() const
Definition: netaddress.cpp:463
#define Assume(val)
Assume is the identity function.
Definition: check.h:85
static constexpr Format FILE_FORMAT
The maximum format this software knows it can unserialize.
Definition: addrman_impl.h:173
Format
Serialization versions.
Definition: addrman_impl.h:160
std::pair< CAddress, NodeSeconds > Select(bool new_only=false, std::optional< Network > network=std::nullopt) const
Choose an address to connect to.
Definition: addrman.cpp:1315
bool IsTerrible(NodeSeconds now=Now< NodeSeconds >()) const
Determine whether the statistics about this entry are bad enough so that it can just be deleted...
Definition: addrman.cpp:67
Network address.
Definition: netaddress.h:115
256-bit opaque blob.
Definition: uint256.h:106
void Unserialize(Stream &s_) EXCLUSIVE_LOCKS_REQUIRED(!cs)
Definition: addrman.cpp:229
static time_point now() noexcept
Return current system time or mocked time, if set.
Definition: time.cpp:70
std::pair< CAddress, NodeSeconds > SelectTriedCollision()
Randomly select an address in the tried table that another address is attempting to evict...
Definition: addrman.cpp:1310
ServiceFlags nServices
Serialized as uint64_t in V1, and as CompactSize in V2.
Definition: protocol.h:454
AddrInfo * Find(const CService &addr, int *pnId=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs)
Find an entry.
Definition: addrman.cpp:399
bool Good(const CService &addr, NodeSeconds time) EXCLUSIVE_LOCKS_REQUIRED(!cs)
Definition: addrman.cpp:1174
AddrManImpl(const NetGroupManager &netgroupman, bool deterministic, int32_t consistency_check_ratio)
Definition: addrman.cpp:107
double GetChance(NodeSeconds now=Now< NodeSeconds >()) const
Calculate the relative chance this entry should be given when selecting nodes to connect to...
Definition: addrman.cpp:92
void MakeTried(AddrInfo &info, int nId) EXCLUSIVE_LOCKS_REQUIRED(cs)
Move an entry from the "new" table(s) to the "tried" table.
Definition: addrman.cpp:489
std::vector< std::pair< AddrInfo, AddressPosition > > GetEntries(bool from_tried) const EXCLUSIVE_LOCKS_REQUIRED(!cs)
Definition: addrman.cpp:1226
constexpr void SetNull()
Definition: uint256.h:49
static constexpr int ADDRMAN_NEW_BUCKET_COUNT
Definition: addrman_impl.h:31
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...
Definition: addrman.cpp:26
void Delete(int nId) EXCLUSIVE_LOCKS_REQUIRED(cs)
Delete an entry. It must not be in tried, and have refcount 0.
Definition: addrman.cpp:454
void SetServices(const CService &addr, ServiceFlags nServices)
Update an entry&#39;s service bits.
Definition: addrman.cpp:1335
Writes data to an underlying source stream, while hashing the written data.
Definition: hash.h:202
static int count
bool fInTried
in tried set? (memory only)
Definition: addrman_impl.h:61
std::optional< AddressPosition > FindAddressEntry_(const CAddress &addr) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: addrman.cpp:991
Reads data from an underlying stream, while hashing the read data.
Definition: hash.h:168
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&#39;s new table.
Definition: addrman.cpp:548
static constexpr auto ADDRMAN_REPLACEMENT
How recent a successful connection should be before we allow an address to be evicted from tried...
Definition: addrman.cpp:40
std::set< int > m_tried_collisions
Holds addrs inserted into tried table that collide with existing entries. Test-before-evict disciplin...
Definition: addrman_impl.h:209
Location information for an address in AddrMan.
Definition: addrman.h:34
Mutex cs
A mutex to protect the inner data structures.
Definition: addrman_impl.h:151
static constexpr auto ADDRMAN_TEST_WINDOW
The maximum time we&#39;ll spend trying to resolve a tried table collision.
Definition: addrman.cpp:44
const int32_t m_consistency_check_ratio
Perform consistency checks every m_consistency_check_ratio operations (if non-zero).
Definition: addrman_impl.h:215
bool Good(const CService &addr, NodeSeconds time=Now< NodeSeconds >())
Mark an address record as accessible and attempt to move it to addrman&#39;s tried table.
Definition: addrman.cpp:1295
#define LogPrintf(...)
Definition: logging.h:237
int GetTriedBucket(const uint256 &nKey, const NetGroupManager &netgroupman) const
Calculate in which "tried" bucket this entry belongs.
Definition: addrman.cpp:46
std::optional< AddressPosition > FindAddressEntry(const CAddress &addr) EXCLUSIVE_LOCKS_REQUIRED(!cs)
Definition: addrman.cpp:1251
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...
Definition: addrman.cpp:414
void SetServices(const CService &addr, ServiceFlags nServices) EXCLUSIVE_LOCKS_REQUIRED(!cs)
Definition: addrman.cpp:1243
NodeSeconds m_last_success
last successful connection by us
Definition: addrman_impl.h:52
static constexpr auto ADDRMAN_HORIZON
How old addresses can maximally be.
Definition: addrman.cpp:32
static constexpr int32_t ADDRMAN_NEW_BUCKETS_PER_ADDRESS
Maximum number of times an address can occur in the new table.
Definition: addrman.cpp:30
std::vector< std::pair< AddrInfo, AddressPosition > > GetEntries(bool from_tried) const
Returns an information-location pair for all addresses in the selected addrman table.
Definition: addrman.cpp:1325
#define LOG_TIME_MILLIS_WITH_CATEGORY_MSG_ONCE(end_msg, log_category)
Definition: timer.h:105
AddrMan(const NetGroupManager &netgroupman, bool deterministic, int32_t consistency_check_ratio)
Definition: addrman.cpp:1260
void SetServices_(const CService &addr, ServiceFlags nServices) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: addrman.cpp:884
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...
Definition: addrman.cpp:28