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