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