Bitcoin ABC 0.32.6
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.ToString(), 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.ToString(), 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",
661 addr.ToString(), addr.GetMappedAS(m_asmap), nUBucket,
662 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.ToString()
721 : "",
722 addr.ToString(), 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",
727 addr.ToString(), addr.GetMappedAS(m_asmap), tried_bucket,
728 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.ToString(), 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.ToString());
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 int nId = vvNew[nUBucket][(nUBucketPos + i) % ADDRMAN_BUCKET_SIZE];
843 const auto it_found{mapInfo.find(nId)};
844 assert(it_found != mapInfo.end());
845 const AddrInfo &info{it_found->second};
846 // With probability GetChance() * fChanceFactor, return the entry.
847 if (insecure_rand.randbits(30) <
848 fChanceFactor * info.GetChance() * (1 << 30)) {
849 LogPrint(BCLog::ADDRMAN, "Selected %s from new\n",
850 info.ToString());
851 return {info, info.m_last_try};
852 }
853 // Otherwise start over with a (likely) different bucket, and
854 // increased chance factor.
855 fChanceFactor *= 1.2;
856 }
857 }
858}
859
860std::vector<CAddress>
861AddrManImpl::GetAddr_(size_t max_addresses, size_t max_pct,
862 std::optional<Network> network) const {
864
865 size_t nNodes = vRandom.size();
866 if (max_pct != 0) {
867 nNodes = max_pct * nNodes / 100;
868 }
869 if (max_addresses != 0) {
870 nNodes = std::min(nNodes, max_addresses);
871 }
872
873 // gather a list of random nodes, skipping those of low quality
874 const auto now{Now<NodeSeconds>()};
875 std::vector<CAddress> addresses;
876 for (unsigned int n = 0; n < vRandom.size(); n++) {
877 if (addresses.size() >= nNodes) {
878 break;
879 }
880
881 int nRndPos = insecure_rand.randrange(vRandom.size() - n) + n;
882 SwapRandom(n, nRndPos);
883 const auto it{mapInfo.find(vRandom[n])};
884 assert(it != mapInfo.end());
885
886 const AddrInfo &ai{it->second};
887
888 // Filter by network (optional)
889 if (network != std::nullopt && ai.GetNetClass() != network) {
890 continue;
891 }
892
893 // Filter for quality
894 if (ai.IsTerrible(now)) {
895 continue;
896 }
897
898 addresses.push_back(ai);
899 }
900 LogPrint(BCLog::ADDRMAN, "GetAddr returned %d random addresses\n",
901 addresses.size());
902 return addresses;
903}
904
907
908 AddrInfo *pinfo = Find(addr);
909
910 // if not found, bail out
911 if (!pinfo) {
912 return;
913 }
914
915 AddrInfo &info = *pinfo;
916
917 // update info
918 const auto update_interval{20min};
919 if (time - info.nTime > update_interval) {
920 info.nTime = time;
921 }
922}
923
924void AddrManImpl::SetServices_(const CService &addr, ServiceFlags nServices) {
926
927 AddrInfo *pinfo = Find(addr);
928
929 // if not found, bail out
930 if (!pinfo) {
931 return;
932 }
933
934 AddrInfo &info = *pinfo;
935
936 // update info
937 info.nServices = nServices;
938}
939
942
943 const auto current_time{Now<NodeSeconds>()};
944
945 for (std::set<nid_type>::iterator it = m_tried_collisions.begin();
946 it != m_tried_collisions.end();) {
947 nid_type id_new = *it;
948
949 bool erase_collision = false;
950
951 // If id_new not found in mapInfo remove it from
952 // m_tried_collisions.
953 auto id_new_it = mapInfo.find(id_new);
954 if (id_new_it == mapInfo.end()) {
955 erase_collision = true;
956 } else {
957 AddrInfo &info_new = mapInfo[id_new];
958
959 // Which tried bucket to move the entry to.
960 int tried_bucket = info_new.GetTriedBucket(nKey, m_asmap);
961 int tried_bucket_pos =
962 info_new.GetBucketPosition(nKey, false, tried_bucket);
963 if (!info_new.IsValid()) {
964 // id_new may no longer map to a valid address
965 erase_collision = true;
966 } else if (vvTried[tried_bucket][tried_bucket_pos] != -1) {
967 // The position in the tried bucket is not empty
968
969 // Get the to-be-evicted address that is being tested
970 nid_type id_old = vvTried[tried_bucket][tried_bucket_pos];
971 AddrInfo &info_old = mapInfo[id_old];
972
973 // Has successfully connected in last X hours
974 if (current_time - info_old.m_last_success <
976 erase_collision = true;
977 } else if (current_time - info_old.m_last_try <
979 // attempted to connect and failed in last X hours
980
981 // Give address at least 60 seconds to successfully
982 // connect
983 if (current_time - info_old.m_last_try > 60s) {
985 "Replacing %s with %s in tried table\n",
986 info_old.ToString(), info_new.ToString());
987
988 // Replaces an existing address already in the
989 // tried table with the new address
990 Good_(info_new, false, current_time);
991 erase_collision = true;
992 }
993 } else if (current_time - info_new.m_last_success >
995 // If the collision hasn't resolved in some
996 // reasonable amount of time, just evict the old
997 // entry -- we must not be able to connect to it for
998 // some reason.
1000 "Unable to test; replacing %s with %s in tried "
1001 "table anyway\n",
1002 info_old.ToString(), info_new.ToString());
1003 Good_(info_new, false, current_time);
1004 erase_collision = true;
1005 }
1006 } else {
1007 // Collision is not actually a collision anymore
1008 Good_(info_new, false, current_time);
1009 erase_collision = true;
1010 }
1011 }
1012
1013 if (erase_collision) {
1014 m_tried_collisions.erase(it++);
1015 } else {
1016 it++;
1017 }
1018 }
1019}
1020
1021std::pair<CAddress, NodeSeconds> AddrManImpl::SelectTriedCollision_() {
1023
1024 if (m_tried_collisions.size() == 0) {
1025 return {};
1026 }
1027
1028 std::set<nid_type>::iterator it = m_tried_collisions.begin();
1029
1030 // Selects a random element from m_tried_collisions
1031 std::advance(it, insecure_rand.randrange(m_tried_collisions.size()));
1032 nid_type id_new = *it;
1033
1034 // If id_new not found in mapInfo remove it from m_tried_collisions.
1035 auto id_new_it = mapInfo.find(id_new);
1036 if (id_new_it == mapInfo.end()) {
1037 m_tried_collisions.erase(it);
1038 return {};
1039 }
1040
1041 const AddrInfo &newInfo = id_new_it->second;
1042
1043 // which tried bucket to move the entry to
1044 int tried_bucket = newInfo.GetTriedBucket(nKey, m_asmap);
1045 int tried_bucket_pos = newInfo.GetBucketPosition(nKey, false, tried_bucket);
1046
1047 const AddrInfo &info_old = mapInfo[vvTried[tried_bucket][tried_bucket_pos]];
1048 return {info_old, info_old.m_last_try};
1049}
1050
1053
1054 // Run consistency checks 1 in m_consistency_check_ratio times if enabled
1055 if (m_consistency_check_ratio == 0) {
1056 return;
1057 }
1058 if (insecure_rand.randrange(m_consistency_check_ratio) >= 1) {
1059 return;
1060 }
1061
1062 const int err{CheckAddrman()};
1063 if (err) {
1064 LogPrintf("ADDRMAN CONSISTENCY CHECK FAILED!!! err=%i\n", err);
1065 assert(false);
1066 }
1067}
1068
1071
1073 strprintf("new %i, tried %i, total %u", nNew, nTried, vRandom.size()),
1075
1076 std::unordered_set<nid_type> setTried;
1077 std::unordered_map<nid_type, int> mapNew;
1078
1079 if (vRandom.size() != size_t(nTried + nNew)) {
1080 return -7;
1081 }
1082
1083 for (const auto &entry : mapInfo) {
1084 nid_type n = entry.first;
1085 const AddrInfo &info = entry.second;
1086 if (info.fInTried) {
1087 if (!TicksSinceEpoch<std::chrono::seconds>(info.m_last_success)) {
1088 return -1;
1089 }
1090 if (info.nRefCount) {
1091 return -2;
1092 }
1093 setTried.insert(n);
1094 } else {
1095 if (info.nRefCount < 0 ||
1097 return -3;
1098 }
1099 if (!info.nRefCount) {
1100 return -4;
1101 }
1102 mapNew[n] = info.nRefCount;
1103 }
1104 const auto it{mapAddr.find(info)};
1105 if (it == mapAddr.end() || it->second != n) {
1106 return -5;
1107 }
1108 if (info.nRandomPos < 0 || size_t(info.nRandomPos) >= vRandom.size() ||
1109 vRandom[info.nRandomPos] != n) {
1110 return -14;
1111 }
1112 if (info.m_last_try < NodeSeconds{0s}) {
1113 return -6;
1114 }
1115 if (info.m_last_success < NodeSeconds{0s}) {
1116 return -8;
1117 }
1118 }
1119
1120 if (setTried.size() != size_t(nTried)) {
1121 return -9;
1122 }
1123 if (mapNew.size() != size_t(nNew)) {
1124 return -10;
1125 }
1126
1127 for (int n = 0; n < ADDRMAN_TRIED_BUCKET_COUNT; n++) {
1128 for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) {
1129 if (vvTried[n][i] != -1) {
1130 if (!setTried.count(vvTried[n][i])) {
1131 return -11;
1132 }
1133 const auto it{mapInfo.find(vvTried[n][i])};
1134 if (it == mapInfo.end() ||
1135 it->second.GetTriedBucket(nKey, m_asmap) != n) {
1136 return -17;
1137 }
1138 if (it->second.GetBucketPosition(nKey, false, n) != i) {
1139 return -18;
1140 }
1141 setTried.erase(vvTried[n][i]);
1142 }
1143 }
1144 }
1145
1146 for (int n = 0; n < ADDRMAN_NEW_BUCKET_COUNT; n++) {
1147 for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) {
1148 if (vvNew[n][i] != -1) {
1149 if (!mapNew.count(vvNew[n][i])) {
1150 return -12;
1151 }
1152 const auto it{mapInfo.find(vvNew[n][i])};
1153 if (it == mapInfo.end() ||
1154 it->second.GetBucketPosition(nKey, true, n) != i) {
1155 return -19;
1156 }
1157 if (--mapNew[vvNew[n][i]] == 0) {
1158 mapNew.erase(vvNew[n][i]);
1159 }
1160 }
1161 }
1162 }
1163
1164 if (setTried.size()) {
1165 return -13;
1166 }
1167 if (mapNew.size()) {
1168 return -15;
1169 }
1170 if (nKey.IsNull()) {
1171 return -16;
1172 }
1173
1174 return 0;
1175}
1176
1177size_t AddrManImpl::size() const {
1178 // TODO: Cache this in an atomic to avoid this overhead
1179 LOCK(cs);
1180 return vRandom.size();
1181}
1182
1183bool AddrManImpl::Add(const std::vector<CAddress> &vAddr,
1184 const CNetAddr &source,
1185 std::chrono::seconds time_penalty) {
1186 LOCK(cs);
1187 Check();
1188 auto ret = Add_(vAddr, source, time_penalty);
1189 Check();
1190 return ret;
1191}
1192
1193void AddrManImpl::Good(const CService &addr, bool test_before_evict,
1194 NodeSeconds time) {
1195 LOCK(cs);
1196 Check();
1197 Good_(addr, test_before_evict, time);
1198 Check();
1199}
1200
1201void AddrManImpl::Attempt(const CService &addr, bool fCountFailure,
1202 NodeSeconds time) {
1203 LOCK(cs);
1204 Check();
1205 Attempt_(addr, fCountFailure, time);
1206 Check();
1207}
1208
1210 LOCK(cs);
1211 Check();
1213 Check();
1214}
1215
1216std::pair<CAddress, NodeSeconds> AddrManImpl::SelectTriedCollision() {
1217 LOCK(cs);
1218 Check();
1219 auto ret = SelectTriedCollision_();
1220 Check();
1221 return ret;
1222}
1223
1224std::pair<CAddress, NodeSeconds> AddrManImpl::Select(bool newOnly) const {
1225 LOCK(cs);
1226 Check();
1227 auto addrRet = Select_(newOnly);
1228 Check();
1229 return addrRet;
1230}
1231
1232std::vector<CAddress>
1233AddrManImpl::GetAddr(size_t max_addresses, size_t max_pct,
1234 std::optional<Network> network) const {
1235 LOCK(cs);
1236 Check();
1237 auto addresses = GetAddr_(max_addresses, max_pct, network);
1238 Check();
1239 return addresses;
1240}
1241
1243 LOCK(cs);
1244 Check();
1245 Connected_(addr, time);
1246 Check();
1247}
1248
1249void AddrManImpl::SetServices(const CService &addr, ServiceFlags nServices) {
1250 LOCK(cs);
1251 Check();
1252 SetServices_(addr, nServices);
1253 Check();
1254}
1255
1256const std::vector<bool> &AddrManImpl::GetAsmap() const {
1257 return m_asmap;
1258}
1259
1260AddrMan::AddrMan(std::vector<bool> asmap, bool deterministic,
1261 int32_t consistency_check_ratio)
1262 : m_impl(std::make_unique<AddrManImpl>(std::move(asmap), deterministic,
1263 consistency_check_ratio)) {}
1264
1265AddrMan::~AddrMan() = default;
1266
1267template <typename Stream> void AddrMan::Serialize(Stream &s_) const {
1268 m_impl->Serialize<Stream>(s_);
1269}
1270
1271template <typename Stream> void AddrMan::Unserialize(Stream &s_) {
1272 m_impl->Unserialize<Stream>(s_);
1273}
1274
1275// explicit instantiation
1276template void AddrMan::Serialize(HashedSourceWriter<AutoFile> &s) const;
1277template void AddrMan::Serialize(DataStream &s) const;
1278template void AddrMan::Unserialize(AutoFile &s);
1280template void AddrMan::Unserialize(DataStream &s);
1282
1283size_t AddrMan::size() const {
1284 return m_impl->size();
1285}
1286
1287bool AddrMan::Add(const std::vector<CAddress> &vAddr, const CNetAddr &source,
1288 std::chrono::seconds time_penalty) {
1289 return m_impl->Add(vAddr, source, time_penalty);
1290}
1291
1292void AddrMan::Good(const CService &addr, bool test_before_evict,
1293 NodeSeconds time) {
1294 m_impl->Good(addr, test_before_evict, time);
1295}
1296
1297void AddrMan::Attempt(const CService &addr, bool fCountFailure,
1298 NodeSeconds time) {
1299 m_impl->Attempt(addr, fCountFailure, time);
1300}
1301
1303 m_impl->ResolveCollisions();
1304}
1305
1306std::pair<CAddress, NodeSeconds> AddrMan::SelectTriedCollision() {
1307 return m_impl->SelectTriedCollision();
1308}
1309
1310std::pair<CAddress, NodeSeconds> AddrMan::Select(bool newOnly) const {
1311 return m_impl->Select(newOnly);
1312}
1313
1314std::vector<CAddress> AddrMan::GetAddr(size_t max_addresses, size_t max_pct,
1315 std::optional<Network> network) const {
1316 return m_impl->GetAddr(max_addresses, max_pct, network);
1317}
1318
1319void AddrMan::Connected(const CService &addr, NodeSeconds time) {
1320 m_impl->Connected(addr, time);
1321}
1322
1323void AddrMan::SetServices(const CService &addr, ServiceFlags nServices) {
1324 m_impl->SetServices(addr, nServices);
1325}
1326
1327const std::vector<bool> &AddrMan::GetAsmap() const {
1328 return m_impl->GetAsmap();
1329}
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:97
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:1319
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:1314
const std::vector< bool > & GetAsmap() const
Definition: addrman.cpp:1327
void Attempt(const CService &addr, bool fCountFailure, NodeSeconds time=Now< NodeSeconds >())
Mark an entry as connection attempted to.
Definition: addrman.cpp:1297
std::pair< CAddress, NodeSeconds > Select(bool newOnly=false) const
Choose an address to connect to.
Definition: addrman.cpp:1310
void ResolveCollisions()
See if any to-be-evicted tried table entries have been tested and if so resolve the collisions.
Definition: addrman.cpp:1302
void Serialize(Stream &s_) const
Definition: addrman.cpp:1267
size_t size() const
Return the number of (unique) addresses in all tables.
Definition: addrman.cpp:1283
void Unserialize(Stream &s_)
Definition: addrman.cpp:1271
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:1292
std::pair< CAddress, NodeSeconds > SelectTriedCollision()
Randomly select an address in the tried table that another address is attempting to evict.
Definition: addrman.cpp:1306
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:1287
AddrMan(std::vector< bool > asmap, bool deterministic, int32_t consistency_check_ratio)
Definition: addrman.cpp:1260
void SetServices(const CService &addr, ServiceFlags nServices)
Update an entry's service bits.
Definition: addrman.cpp:1323
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:1224
void Connected_(const CService &addr, NodeSeconds time) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: addrman.cpp:905
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:940
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:1242
std::vector< CAddress > GetAddr(size_t max_addresses, size_t max_pct, std::optional< Network > network) const EXCLUSIVE_LOCKS_REQUIRED(!cs)
Definition: addrman.cpp:1233
size_t size() const EXCLUSIVE_LOCKS_REQUIRED(!cs)
Definition: addrman.cpp:1177
void SetServices(const CService &addr, ServiceFlags nServices) EXCLUSIVE_LOCKS_REQUIRED(!cs)
Definition: addrman.cpp:1249
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:924
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:1256
void Check() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Consistency check, taking into account m_consistency_check_ratio.
Definition: addrman.cpp:1051
int CheckAddrman() const EXCLUSIVE_LOCKS_REQUIRED(cs)
Perform consistency check, regardless of m_consistency_check_ratio.
Definition: addrman.cpp:1069
bool Add(const std::vector< CAddress > &vAddr, const CNetAddr &source, std::chrono::seconds time_penalty) EXCLUSIVE_LOCKS_REQUIRED(!cs)
Definition: addrman.cpp:1183
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:1021
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:1216
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:1201
void Good(const CService &addr, bool test_before_evict, NodeSeconds time) EXCLUSIVE_LOCKS_REQUIRED(!cs)
Definition: addrman.cpp:1193
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:1209
std::vector< CAddress > GetAddr_(size_t max_addresses, size_t max_pct, std::optional< Network > network) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: addrman.cpp:861
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:443
ServiceFlags nServices
Serialized as uint64_t in V1, and as CompactSize in V2.
Definition: protocol.h:555
NodeSeconds nTime
Always included in serialization, except in the network format on INIT_PROTO_VERSION.
Definition: protocol.h:553
static constexpr SerParams V1_DISK
Definition: protocol.h:500
static constexpr SerParams V2_DISK
Definition: protocol.h:501
Network address.
Definition: netaddress.h:114
bool IsRoutable() const
Definition: netaddress.cpp:509
bool IsValid() const
Definition: netaddress.cpp:474
std::vector< uint8_t > GetGroup(const std::vector< bool > &asmap) const
Get the canonical identifier of our network group.
Definition: netaddress.cpp:803
uint32_t GetMappedAS(const std::vector< bool > &asmap) const
Definition: netaddress.cpp:759
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:573
std::string ToString() const
std::vector< uint8_t > GetKey() 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:336
const char * source
Definition: rpcconsole.cpp:56
static time_point now() noexcept
Return current system time or mocked time, if set.
Definition: time.cpp:71
#define LOCK(cs)
Definition: sync.h:306
std::chrono::time_point< NodeClock, std::chrono::seconds > NodeSeconds
Definition: time.h:25
#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())