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