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