Branch data Line data Source code
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 : :
29 : 14077626 : int AddrInfo::GetTriedBucket(const uint256& nKey, const NetGroupManager& netgroupman) const
30 : : {
31 [ + - + - ]: 14077626 : uint64_t hash1 = (HashWriter{} << nKey << GetKey()).GetCheapHash();
32 [ + - + - : 14077626 : uint64_t hash2 = (HashWriter{} << nKey << netgroupman.GetGroup(*this) << (hash1 % ADDRMAN_TRIED_BUCKETS_PER_GROUP)).GetCheapHash();
+ - ]
33 : 14077626 : return hash2 % ADDRMAN_TRIED_BUCKET_COUNT;
34 : : }
35 : :
36 : 14466420 : int AddrInfo::GetNewBucket(const uint256& nKey, const CNetAddr& src, const NetGroupManager& netgroupman) const
37 : : {
38 : 14466420 : std::vector<unsigned char> vchSourceGroupKey = netgroupman.GetGroup(src);
39 [ + - + - : 28932840 : uint64_t hash1 = (HashWriter{} << nKey << netgroupman.GetGroup(*this) << vchSourceGroupKey).GetCheapHash();
+ - + - +
- ]
40 [ + - + - : 14466420 : uint64_t hash2 = (HashWriter{} << nKey << vchSourceGroupKey << (hash1 % ADDRMAN_NEW_BUCKETS_PER_SOURCE_GROUP)).GetCheapHash();
+ - + - +
- ]
41 : 14466420 : return hash2 % ADDRMAN_NEW_BUCKET_COUNT;
42 : 14466420 : }
43 : :
44 : 40348901 : int AddrInfo::GetBucketPosition(const uint256& nKey, bool fNew, int bucket) const
45 : : {
46 [ + + + - : 54426527 : uint64_t hash1 = (HashWriter{} << nKey << (fNew ? uint8_t{'N'} : uint8_t{'K'}) << bucket << GetKey()).GetCheapHash();
+ - ]
47 : 40348901 : return hash1 % ADDRMAN_BUCKET_SIZE;
48 : : }
49 : :
50 : 3615405 : bool AddrInfo::IsTerrible(NodeSeconds now) const
51 : : {
52 [ + + ]: 3615405 : if (now - m_last_try <= 1min) { // never remove things tried in the last minute
53 : : return false;
54 : : }
55 : :
56 [ + + ]: 2880319 : if (nTime > now + 10min) { // came in a flying DeLorean
57 : : return true;
58 : : }
59 : :
60 [ + + ]: 1635273 : if (now - nTime > ADDRMAN_HORIZON) { // not seen in recent history
61 : : return true;
62 : : }
63 : :
64 [ + + + + ]: 65652 : 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 [ + + + + ]: 65065 : if (now - m_last_success > ADDRMAN_MIN_FAIL && nAttempts >= ADDRMAN_MAX_FAILURES) { // N successive failures in the last week
69 : 994 : return true;
70 : : }
71 : :
72 : : return false;
73 : : }
74 : :
75 : 4269 : double AddrInfo::GetChance(NodeSeconds now) const
76 : : {
77 : 4269 : double fChance = 1.0;
78 : :
79 : : // deprioritize very recent attempts away
80 [ + + ]: 4269 : if (now - m_last_try < 10min) {
81 : 2166 : 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 [ + + ]: 4269 : fChance *= pow(0.66, std::min(nAttempts, 8));
86 : :
87 : 4269 : return fChance;
88 : : }
89 : :
90 : 27435 : AddrManImpl::AddrManImpl(const NetGroupManager& netgroupman, bool deterministic, int32_t consistency_check_ratio)
91 : 27435 : : insecure_rand{deterministic}
92 [ + + ]: 27435 : , nKey{deterministic ? uint256{1} : insecure_rand.rand256()}
93 : 27435 : , m_consistency_check_ratio{consistency_check_ratio}
94 : 54870 : , m_netgroupman{netgroupman}
95 : : {
96 [ + + ]: 28120875 : for (auto& bucket : vvNew) {
97 [ + + ]: 1826073600 : for (auto& entry : bucket) {
98 : 1797980160 : entry = -1;
99 : : }
100 : : }
101 [ + + ]: 7050795 : for (auto& bucket : vvTried) {
102 [ + + ]: 456518400 : for (auto& entry : bucket) {
103 : 449495040 : entry = -1;
104 : : }
105 : : }
106 : 27435 : }
107 : :
108 : 27435 : AddrManImpl::~AddrManImpl()
109 : : {
110 : 27435 : nKey.SetNull();
111 : 27435 : }
112 : :
113 : : template <typename Stream>
114 : 3056 : void AddrManImpl::Serialize(Stream& s_) const
115 : : {
116 [ + - ]: 3056 : LOCK(cs);
117 : :
118 : : /**
119 : : * Serialized format.
120 : : * * format version byte (@see `Format`)
121 : : * * lowest compatible format version byte. This is used to help old software decide
122 : : * whether to parse the file. For example:
123 : : * * Bitcoin Core version N knows how to parse up to format=3. If a new format=4 is
124 : : * introduced in version N+1 that is compatible with format=3 and it is known that
125 : : * version N will be able to parse it, then version N+1 will write
126 : : * (format=4, lowest_compatible=3) in the first two bytes of the file, and so
127 : : * version N will still try to parse it.
128 : : * * Bitcoin Core version N+2 introduces a new incompatible format=5. It will write
129 : : * (format=5, lowest_compatible=5) and so any versions that do not know how to parse
130 : : * format=5 will not try to read the file.
131 : : * * nKey
132 : : * * nNew
133 : : * * nTried
134 : : * * number of "new" buckets XOR 2**30
135 : : * * all new addresses (total count: nNew)
136 : : * * all tried addresses (total count: nTried)
137 : : * * for each new bucket:
138 : : * * number of elements
139 : : * * for each element: index in the serialized "all new addresses"
140 : : * * asmap version
141 : : *
142 : : * 2**30 is xorred with the number of buckets to make addrman deserializer v0 detect it
143 : : * as incompatible. This is necessary because it did not check the version number on
144 : : * deserialization.
145 : : *
146 : : * vvNew, vvTried, mapInfo, mapAddr and vRandom are never encoded explicitly;
147 : : * they are instead reconstructed from the other information.
148 : : *
149 : : * This format is more complex, but significantly smaller (at most 1.5 MiB), and supports
150 : : * changes to the ADDRMAN_ parameters without breaking the on-disk structure.
151 : : *
152 : : * We don't use SERIALIZE_METHODS since the serialization and deserialization code has
153 : : * very little in common.
154 : : */
155 : :
156 : : // Always serialize in the latest version (FILE_FORMAT).
157 : 3056 : ParamsStream s{s_, CAddress::V2_DISK};
158 : :
159 [ + - ]: 3056 : s << static_cast<uint8_t>(FILE_FORMAT);
160 : :
161 : : // Increment `lowest_compatible` iff a newly introduced format is incompatible with
162 : : // the previous one.
163 : : static constexpr uint8_t lowest_compatible = Format::V4_MULTIPORT;
164 [ + - ]: 3056 : s << static_cast<uint8_t>(INCOMPATIBILITY_BASE + lowest_compatible);
165 : :
166 [ + - ]: 3056 : s << nKey;
167 [ + - ]: 3056 : s << nNew;
168 [ + - ]: 3056 : s << nTried;
169 : :
170 [ + - ]: 3056 : int nUBuckets = ADDRMAN_NEW_BUCKET_COUNT ^ (1 << 30);
171 : 3056 : s << nUBuckets;
172 : 3056 : std::unordered_map<nid_type, int> mapUnkIds;
173 : 3056 : int nIds = 0;
174 [ + + + - ]: 7458692 : for (const auto& entry : mapInfo) {
175 [ + - ]: 7455636 : mapUnkIds[entry.first] = nIds;
176 : 7455636 : const AddrInfo& info = entry.second;
177 [ + + ]: 7455636 : if (info.nRefCount) {
178 [ - + ]: 4258484 : assert(nIds != nNew); // this means nNew was wrong, oh ow
179 : 4258484 : s << info;
180 : 4258484 : nIds++;
181 : : }
182 : : }
183 : 3056 : nIds = 0;
184 [ + + + + ]: 7458692 : for (const auto& entry : mapInfo) {
185 : 7455636 : const AddrInfo& info = entry.second;
186 [ + + ]: 7455636 : if (info.fInTried) {
187 [ - + ]: 3197152 : assert(nIds != nTried); // this means nTried was wrong, oh ow
188 : 3197152 : s << info;
189 : 3197152 : nIds++;
190 : : }
191 : : }
192 [ + + ]: 3132400 : for (int bucket = 0; bucket < ADDRMAN_NEW_BUCKET_COUNT; bucket++) {
193 : : int nSize = 0;
194 [ + + ]: 203407360 : for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) {
195 [ + + ]: 200278016 : if (vvNew[bucket][i] != -1)
196 : 4425528 : nSize++;
197 : : }
198 : 203407360 : s << nSize;
199 [ + + ]: 203407360 : for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) {
200 [ + + ]: 200278016 : if (vvNew[bucket][i] != -1) {
201 [ + - + - ]: 4425528 : int nIndex = mapUnkIds[vvNew[bucket][i]];
202 : 200278016 : 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.
208 [ + - ]: 6112 : s << m_netgroupman.GetAsmapVersion();
209 [ + - ]: 6112 : }
210 : :
211 : : template <typename Stream>
212 : 5581 : void AddrManImpl::Unserialize(Stream& s_)
213 : : {
214 : 5581 : LOCK(cs);
215 : :
216 [ - + ]: 5581 : assert(vRandom.empty());
217 : :
218 : : Format format;
219 [ + + ]: 5581 : s_ >> Using<CustomUintFormatter<1>>(format);
220 : :
221 [ + + + + ]: 5518 : const auto ser_params = (format >= Format::V3_BIP155 ? CAddress::V2_DISK : CAddress::V1_DISK);
222 [ + + ]: 5518 : ParamsStream s{s_, ser_params};
223 : :
224 : : uint8_t compat;
225 : 5431 : s >> compat;
226 [ + + ]: 5431 : if (compat < INCOMPATIBILITY_BASE) {
227 [ + - + - ]: 686 : throw std::ios_base::failure(strprintf(
228 : : "Corrupted addrman database: The compat value (%u) "
229 : : "is lower than the expected minimum value %u.",
230 : : compat, INCOMPATIBILITY_BASE));
231 : : }
232 : 5088 : const uint8_t lowest_compatible = compat - INCOMPATIBILITY_BASE;
233 [ + + ]: 5088 : if (lowest_compatible > FILE_FORMAT) {
234 : 824 : throw InvalidAddrManVersionError(strprintf(
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.",
237 [ + - ]: 412 : uint8_t{format}, lowest_compatible, CLIENT_NAME, uint8_t{FILE_FORMAT}));
238 : : }
239 : :
240 [ + + ]: 4676 : s >> nKey;
241 [ + + ]: 4650 : s >> nNew;
242 [ + + ]: 4648 : s >> nTried;
243 [ + + ]: 4646 : int nUBuckets = 0;
244 : 4638 : s >> nUBuckets;
245 [ + + ]: 4638 : if (format >= Format::V1_DETERMINISTIC) {
246 : 2915 : nUBuckets ^= (1 << 30);
247 : : }
248 : :
249 [ + + ]: 4638 : if (nNew > ADDRMAN_NEW_BUCKET_COUNT * ADDRMAN_BUCKET_SIZE || nNew < 0) {
250 [ + - ]: 136 : throw std::ios_base::failure(
251 : 68 : strprintf("Corrupt AddrMan serialization: nNew=%d, should be in [0, %d]",
252 : : nNew,
253 [ + - ]: 68 : ADDRMAN_NEW_BUCKET_COUNT * ADDRMAN_BUCKET_SIZE));
254 : : }
255 : :
256 [ + + ]: 4570 : if (nTried > ADDRMAN_TRIED_BUCKET_COUNT * ADDRMAN_BUCKET_SIZE || nTried < 0) {
257 [ + - ]: 110 : throw std::ios_base::failure(
258 : 55 : strprintf("Corrupt AddrMan serialization: nTried=%d, should be in [0, %d]",
259 : : nTried,
260 [ + - ]: 55 : ADDRMAN_TRIED_BUCKET_COUNT * ADDRMAN_BUCKET_SIZE));
261 : : }
262 : :
263 : : // Deserialize entries from the new table.
264 [ + + ]: 3852988 : for (int n = 0; n < nNew; n++) {
265 [ + - + + ]: 3849295 : AddrInfo& info = mapInfo[n];
266 : 3848473 : s >> info;
267 [ + - ]: 3848473 : mapAddr[info] = n;
268 [ - + ]: 3848473 : info.nRandomPos = vRandom.size();
269 [ + - ]: 3848473 : vRandom.push_back(n);
270 [ + - + - ]: 3848473 : m_network_counts[info.GetNetwork()].n_new++;
271 : : }
272 : 3693 : nIdCount = nNew;
273 : :
274 : : // Deserialize entries from the tried table.
275 : 3693 : int nLost = 0;
276 [ + + ]: 3231628 : for (int n = 0; n < nTried; n++) {
277 [ + - ]: 3227935 : AddrInfo info;
278 : 3227443 : s >> info;
279 [ + - ]: 3227443 : int nKBucket = info.GetTriedBucket(nKey, m_netgroupman);
280 [ + - ]: 3227443 : int nKBucketPos = info.GetBucketPosition(nKey, false, nKBucket);
281 [ + - ]: 3227443 : if (info.IsValid()
282 [ + + + + ]: 3227443 : && vvTried[nKBucket][nKBucketPos] == -1) {
283 [ - + ]: 3174022 : info.nRandomPos = vRandom.size();
284 : 3174022 : info.fInTried = true;
285 [ + - ]: 3174022 : vRandom.push_back(nIdCount);
286 [ + - ]: 3174022 : mapInfo[nIdCount] = info;
287 [ + - ]: 3174022 : mapAddr[info] = nIdCount;
288 : 3174022 : vvTried[nKBucket][nKBucketPos] = nIdCount;
289 : 3174022 : nIdCount++;
290 [ + - + - ]: 3174022 : m_network_counts[info.GetNetwork()].n_tried++;
291 : : } else {
292 : 53421 : nLost++;
293 : : }
294 : : }
295 : 3201 : 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 : 3201 : std::vector<std::pair<int, int>> bucket_entries;
301 : :
302 [ + + ]: 1401069 : for (int bucket = 0; bucket < nUBuckets; ++bucket) {
303 [ + + ]: 1397979 : int num_entries{0};
304 : 6465916 : s >> num_entries;
305 [ + + ]: 6465916 : for (int n = 0; n < num_entries; ++n) {
306 [ + + ]: 5068048 : int entry_index{0};
307 : 5067968 : s >> entry_index;
308 [ + + + + ]: 5067968 : if (entry_index >= 0 && entry_index < nNew) {
309 [ + - ]: 5002004 : 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.
317 [ + - ]: 3090 : uint256 supplied_asmap_version{m_netgroupman.GetAsmapVersion()};
318 : 3090 : uint256 serialized_asmap_version;
319 [ + + ]: 3090 : if (format >= Format::V2_ASMAP) {
320 : 3067 : s >> serialized_asmap_version;
321 : : }
322 [ + + ]: 3067 : const bool restore_bucketing{nUBuckets == ADDRMAN_NEW_BUCKET_COUNT &&
323 : 4800 : serialized_asmap_version == supplied_asmap_version};
324 : :
325 : : if (!restore_bucketing) {
326 [ + - - + : 1733 : LogDebug(BCLog::ADDRMAN, "Bucketing method was updated, re-bucketing addrman entries from disk\n");
- - ]
327 : : }
328 : :
329 [ + + ]: 4193021 : for (auto bucket_entry : bucket_entries) {
330 : 4189954 : int bucket{bucket_entry.first};
331 : 4189954 : const int entry_index{bucket_entry.second};
332 [ + - ]: 4189954 : AddrInfo& info = mapInfo[entry_index];
333 : :
334 : : // Don't store the entry in the new bucket if it's not a valid address for our addrman
335 [ + - + + ]: 4189954 : 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 [ + + ]: 4170688 : if (info.nRefCount >= ADDRMAN_NEW_BUCKETS_PER_ADDRESS) continue;
341 : :
342 [ + - ]: 4131783 : int bucket_position = info.GetBucketPosition(nKey, true, bucket);
343 [ + + + + ]: 4131783 : if (restore_bucketing && vvNew[bucket][bucket_position] == -1) {
344 : : // Bucketing has not changed, using existing bucket positions for the new table
345 : 3746959 : vvNew[bucket][bucket_position] = entry_index;
346 : 3746959 : ++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 [ + - ]: 384824 : bucket = info.GetNewBucket(nKey, m_netgroupman);
351 [ + - ]: 384824 : bucket_position = info.GetBucketPosition(nKey, true, bucket);
352 [ + + ]: 384824 : if (vvNew[bucket][bucket_position] == -1) {
353 : 2948 : vvNew[bucket][bucket_position] = entry_index;
354 : 2948 : ++info.nRefCount;
355 : : }
356 : : }
357 : : }
358 : :
359 : : // Prune new entries with refcount 0 (as a result of collisions or invalid address).
360 : 3067 : int nLostUnk = 0;
361 [ + + + + ]: 6913837 : for (auto it = mapInfo.cbegin(); it != mapInfo.cend(); ) {
362 [ + + + + ]: 6910770 : if (it->second.fInTried == false && it->second.nRefCount == 0) {
363 [ + - ]: 134309 : const auto itCopy = it++;
364 [ + - ]: 134309 : Delete(itCopy->first);
365 : 134309 : ++nLostUnk;
366 : : } else {
367 : 6776461 : ++it;
368 : : }
369 : : }
370 [ + + ]: 3067 : if (nLost + nLostUnk > 0) {
371 [ + - - + : 836 : LogDebug(BCLog::ADDRMAN, "addrman lost %i new and %i tried addresses due to collisions or invalid addresses\n", nLostUnk, nLost);
- - ]
372 : : }
373 : :
374 [ + - ]: 3067 : const int check_code{CheckAddrman()};
375 [ + + ]: 3067 : if (check_code != 0) {
376 [ + - + - ]: 534 : throw std::ios_base::failure(strprintf(
377 : : "Corrupt data. Consistency check failed with code %s",
378 : : check_code));
379 : : }
380 [ + - ]: 6001 : }
381 : :
382 : 18032815 : AddrInfo* AddrManImpl::Find(const CService& addr, nid_type* pnId)
383 : : {
384 : 18032815 : AssertLockHeld(cs);
385 : :
386 : 18032815 : const auto it = mapAddr.find(addr);
387 [ + + ]: 18032815 : if (it == mapAddr.end())
388 : : return nullptr;
389 [ + + ]: 6796862 : if (pnId)
390 : 6776202 : *pnId = (*it).second;
391 : 6796862 : const auto it2 = mapInfo.find((*it).second);
392 [ + - ]: 6796862 : if (it2 != mapInfo.end())
393 : 6796862 : return &(*it2).second;
394 : : return nullptr;
395 : : }
396 : :
397 : 10388463 : AddrInfo* AddrManImpl::Create(const CAddress& addr, const CNetAddr& addrSource, nid_type* pnId)
398 : : {
399 : 10388463 : AssertLockHeld(cs);
400 : :
401 : 10388463 : nid_type nId = nIdCount++;
402 [ + - ]: 10388463 : mapInfo[nId] = AddrInfo(addr, addrSource);
403 : 10388463 : mapAddr[addr] = nId;
404 [ - + ]: 10388463 : mapInfo[nId].nRandomPos = vRandom.size();
405 : 10388463 : vRandom.push_back(nId);
406 : 10388463 : nNew++;
407 : 10388463 : m_network_counts[addr.GetNetwork()].n_new++;
408 [ + - ]: 10388463 : if (pnId)
409 : 10388463 : *pnId = nId;
410 : 10388463 : return &mapInfo[nId];
411 : : }
412 : :
413 : 3807154 : void AddrManImpl::SwapRandom(unsigned int nRndPos1, unsigned int nRndPos2) const
414 : : {
415 : 3807154 : AssertLockHeld(cs);
416 : :
417 [ + + ]: 3807154 : if (nRndPos1 == nRndPos2)
418 : : return;
419 : :
420 [ - + + - : 2964670 : assert(nRndPos1 < vRandom.size() && nRndPos2 < vRandom.size());
- + ]
421 : :
422 : 2964670 : nid_type nId1 = vRandom[nRndPos1];
423 : 2964670 : nid_type nId2 = vRandom[nRndPos2];
424 : :
425 : 2964670 : const auto it_1{mapInfo.find(nId1)};
426 : 2964670 : const auto it_2{mapInfo.find(nId2)};
427 [ - + ]: 2964670 : assert(it_1 != mapInfo.end());
428 [ + - ]: 2964670 : assert(it_2 != mapInfo.end());
429 : :
430 : 2964670 : it_1->second.nRandomPos = nRndPos2;
431 : 2964670 : it_2->second.nRandomPos = nRndPos1;
432 : :
433 : 2964670 : vRandom[nRndPos1] = nId2;
434 : 2964670 : vRandom[nRndPos2] = nId1;
435 : : }
436 : :
437 : 2959722 : void AddrManImpl::Delete(nid_type nId)
438 : : {
439 : 2959722 : AssertLockHeld(cs);
440 : :
441 [ - + ]: 2959722 : assert(mapInfo.contains(nId));
442 : 2959722 : AddrInfo& info = mapInfo[nId];
443 [ - + ]: 2959722 : assert(!info.fInTried);
444 [ - + ]: 2959722 : assert(info.nRefCount == 0);
445 : :
446 [ - + ]: 2959722 : SwapRandom(info.nRandomPos, vRandom.size() - 1);
447 : 2959722 : m_network_counts[info.GetNetwork()].n_new--;
448 : 2959722 : vRandom.pop_back();
449 : 2959722 : mapAddr.erase(info);
450 : 2959722 : mapInfo.erase(nId);
451 : 2959722 : nNew--;
452 : 2959722 : }
453 : :
454 : 9923076 : void AddrManImpl::ClearNew(int nUBucket, int nUBucketPos)
455 : : {
456 : 9923076 : AssertLockHeld(cs);
457 : :
458 : : // if there is an entry in the specified bucket, delete it.
459 [ + + ]: 9923076 : if (vvNew[nUBucket][nUBucketPos] != -1) {
460 : 2181854 : nid_type nIdDelete = vvNew[nUBucket][nUBucketPos];
461 : 2181854 : AddrInfo& infoDelete = mapInfo[nIdDelete];
462 [ - + ]: 2181854 : assert(infoDelete.nRefCount > 0);
463 : 2181854 : infoDelete.nRefCount--;
464 : 2181854 : vvNew[nUBucket][nUBucketPos] = -1;
465 [ - + - - ]: 2181854 : LogDebug(BCLog::ADDRMAN, "Removed %s from new[%i][%i]\n", infoDelete.ToStringAddrPort(), nUBucket, nUBucketPos);
466 [ + + ]: 2181854 : if (infoDelete.nRefCount == 0) {
467 : 2087190 : Delete(nIdDelete);
468 : : }
469 : : }
470 : 9923076 : }
471 : :
472 : 3199146 : void AddrManImpl::MakeTried(AddrInfo& info, nid_type nId)
473 : : {
474 : 3199146 : AssertLockHeld(cs);
475 : :
476 : : // remove the entry from all new buckets
477 : 3199146 : const int start_bucket{info.GetNewBucket(nKey, m_netgroupman)};
478 [ + - ]: 7122842 : for (int n = 0; n < ADDRMAN_NEW_BUCKET_COUNT; ++n) {
479 : 7122842 : const int bucket{(start_bucket + n) % ADDRMAN_NEW_BUCKET_COUNT};
480 : 7122842 : const int pos{info.GetBucketPosition(nKey, true, bucket)};
481 [ + + ]: 7122842 : if (vvNew[bucket][pos] == nId) {
482 : 3207497 : vvNew[bucket][pos] = -1;
483 : 3207497 : info.nRefCount--;
484 [ + + ]: 3207497 : if (info.nRefCount == 0) break;
485 : : }
486 : : }
487 : 3199146 : nNew--;
488 : 3199146 : m_network_counts[info.GetNetwork()].n_new--;
489 : :
490 [ - + ]: 3199146 : assert(info.nRefCount == 0);
491 : :
492 : : // which tried bucket to move the entry to
493 : 3199146 : int nKBucket = info.GetTriedBucket(nKey, m_netgroupman);
494 : 3199146 : 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 [ + + ]: 3199146 : if (vvTried[nKBucket][nKBucketPos] != -1) {
498 : : // find an item to evict
499 : 2268 : nid_type nIdEvict = vvTried[nKBucket][nKBucketPos];
500 [ - + ]: 2268 : assert(mapInfo.contains(nIdEvict));
501 : 2268 : AddrInfo& infoOld = mapInfo[nIdEvict];
502 : :
503 : : // Remove the to-be-evicted item from the tried set.
504 : 2268 : infoOld.fInTried = false;
505 : 2268 : vvTried[nKBucket][nKBucketPos] = -1;
506 : 2268 : nTried--;
507 : 2268 : m_network_counts[infoOld.GetNetwork()].n_tried--;
508 : :
509 : : // find which new bucket it belongs to
510 : 2268 : int nUBucket = infoOld.GetNewBucket(nKey, m_netgroupman);
511 : 2268 : int nUBucketPos = infoOld.GetBucketPosition(nKey, true, nUBucket);
512 : 2268 : ClearNew(nUBucket, nUBucketPos);
513 [ - + ]: 2268 : assert(vvNew[nUBucket][nUBucketPos] == -1);
514 : :
515 : : // Enter it into the new set again.
516 : 2268 : infoOld.nRefCount = 1;
517 : 2268 : vvNew[nUBucket][nUBucketPos] = nIdEvict;
518 : 2268 : nNew++;
519 : 2268 : m_network_counts[infoOld.GetNetwork()].n_new++;
520 [ - + - - ]: 2268 : 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 : : }
523 [ - + ]: 3199146 : assert(vvTried[nKBucket][nKBucketPos] == -1);
524 : :
525 : 3199146 : vvTried[nKBucket][nKBucketPos] = nId;
526 : 3199146 : nTried++;
527 : 3199146 : info.fInTried = true;
528 : 3199146 : m_network_counts[info.GetNetwork()].n_tried++;
529 : 3199146 : }
530 : :
531 : 12646031 : bool AddrManImpl::AddSingle(const CAddress& addr, const CNetAddr& source, std::chrono::seconds time_penalty)
532 : : {
533 : 12646031 : AssertLockHeld(cs);
534 : :
535 [ + + ]: 12646031 : if (!addr.IsRoutable())
536 : : return false;
537 : :
538 : 12441241 : nid_type nId;
539 : 12441241 : AddrInfo* pinfo = Find(addr, &nId);
540 : :
541 : : // Do not set a penalty for a source's self-announcement
542 [ + + ]: 12441241 : if (addr == source) {
543 : 151155 : time_penalty = 0s;
544 : : }
545 : :
546 [ + + ]: 12441241 : if (pinfo) {
547 : : // periodically update nTime
548 : 2052778 : const bool currently_online{NodeClock::now() - addr.nTime < 24h};
549 [ + + ]: 2052778 : const auto update_interval{currently_online ? 1h : 24h};
550 [ + + ]: 2052778 : if (pinfo->nTime < addr.nTime - update_interval - time_penalty) {
551 : 112651 : pinfo->nTime = std::max(NodeSeconds{0s}, addr.nTime - time_penalty);
552 : : }
553 : :
554 : : // add services
555 : 2052778 : pinfo->nServices = ServiceFlags(pinfo->nServices | addr.nServices);
556 : :
557 : : // do not update if no new information is present
558 [ + + ]: 2052778 : if (addr.nTime <= pinfo->nTime) {
559 : : return false;
560 : : }
561 : :
562 : : // do not update if the entry was already in the "tried" table
563 [ + + ]: 1742561 : if (pinfo->fInTried)
564 : : return false;
565 : :
566 : : // do not update if the max reference count is reached
567 [ + + ]: 1085361 : 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 [ + - ]: 1084395 : if (pinfo->nRefCount > 0) {
572 : 1084395 : const int nFactor{1 << pinfo->nRefCount};
573 [ + + ]: 1084395 : if (insecure_rand.randrange(nFactor) != 0) return false;
574 : : }
575 : : } else {
576 : 10388463 : pinfo = Create(addr, source, &nId);
577 : 10388463 : pinfo->nTime = std::max(NodeSeconds{0s}, pinfo->nTime - time_penalty);
578 : : }
579 : :
580 : 10880182 : int nUBucket = pinfo->GetNewBucket(nKey, source, m_netgroupman);
581 : 10880182 : int nUBucketPos = pinfo->GetBucketPosition(nKey, true, nUBucket);
582 : 10880182 : bool fInsert = vvNew[nUBucket][nUBucketPos] == -1;
583 [ + + ]: 10880182 : if (vvNew[nUBucket][nUBucketPos] != nId) {
584 [ + + ]: 10674924 : if (!fInsert) {
585 : 2935669 : AddrInfo& infoExisting = mapInfo[vvNew[nUBucket][nUBucketPos]];
586 [ + + + + : 2935669 : if (infoExisting.IsTerrible() || (infoExisting.nRefCount > 1 && pinfo->nRefCount == 0)) {
+ + ]
587 : : // Overwrite the existing new table entry.
588 : : fInsert = true;
589 : : }
590 : : }
591 [ + + ]: 8493371 : if (fInsert) {
592 : 9920808 : ClearNew(nUBucket, nUBucketPos);
593 : 9920808 : pinfo->nRefCount++;
594 : 9920808 : vvNew[nUBucket][nUBucketPos] = nId;
595 : 9920808 : const auto mapped_as{m_netgroupman.GetMappedAS(addr)};
596 [ - + - - : 9920808 : 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 [ + + ]: 754116 : if (pinfo->nRefCount == 0) {
600 : 738223 : Delete(nId);
601 : : }
602 : : }
603 : : }
604 : : return fInsert;
605 : : }
606 : :
607 : 5492031 : bool AddrManImpl::Good_(const CService& addr, bool test_before_evict, NodeSeconds time)
608 : : {
609 : 5492031 : AssertLockHeld(cs);
610 : :
611 : 5492031 : nid_type nId;
612 : :
613 : 5492031 : m_last_good = time;
614 : :
615 : 5492031 : AddrInfo* pinfo = Find(addr, &nId);
616 : :
617 : : // if not found, bail out
618 [ + + ]: 5492031 : if (!pinfo) return false;
619 : :
620 : 4723424 : AddrInfo& info = *pinfo;
621 : :
622 : : // update info
623 : 4723424 : info.m_last_success = time;
624 : 4723424 : info.m_last_try = time;
625 : 4723424 : 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 [ + + ]: 4723424 : if (info.fInTried) return false;
631 : :
632 : : // if it is not in new, something bad happened
633 [ + - ]: 4424684 : if (!Assume(info.nRefCount > 0)) return false;
634 : :
635 : :
636 : : // which tried bucket to move the entry to
637 : 4424684 : int tried_bucket = info.GetTriedBucket(nKey, m_netgroupman);
638 : 4424684 : int tried_bucket_pos = info.GetBucketPosition(nKey, false, tried_bucket);
639 : :
640 : : // Will moving this address into tried evict another entry?
641 [ + + + + ]: 4424684 : if (test_before_evict && (vvTried[tried_bucket][tried_bucket_pos] != -1)) {
642 [ + + ]: 1225538 : if (m_tried_collisions.size() < ADDRMAN_SET_TRIED_COLLISION_SIZE) {
643 : 27119 : m_tried_collisions.insert(nId);
644 : : }
645 : : // Output the entry we'd be colliding with, for debugging purposes
646 : 1225538 : auto colliding_entry = mapInfo.find(vvTried[tried_bucket][tried_bucket_pos]);
647 [ - + - - : 1225538 : 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 : 1225538 : return false;
652 : : } else {
653 : : // move nId to the tried tables
654 : 3199146 : MakeTried(info, nId);
655 : 3199146 : const auto mapped_as{m_netgroupman.GetMappedAS(addr)};
656 [ - + - - : 3199146 : 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 : 3199146 : return true;
659 : : }
660 : : }
661 : :
662 : 9653272 : bool AddrManImpl::Add_(const std::vector<CAddress>& vAddr, const CNetAddr& source, std::chrono::seconds time_penalty)
663 : : {
664 : 9653272 : int added{0};
665 [ + + ]: 22299303 : for (std::vector<CAddress>::const_iterator it = vAddr.begin(); it != vAddr.end(); it++) {
666 [ + + ]: 15371254 : added += AddSingle(*it, source, time_penalty) ? 1 : 0;
667 : : }
668 [ + + ]: 9653272 : if (added > 0) {
669 [ - + - - : 7949790 : LogDebug(BCLog::ADDRMAN, "Added %i addresses (of %i) from %s: %i tried, %i new\n", added, vAddr.size(), source.ToStringAddr(), nTried, nNew);
- - ]
670 : : }
671 : 9653272 : return added > 0;
672 : : }
673 : :
674 : 17708 : void AddrManImpl::Attempt_(const CService& addr, bool fCountFailure, NodeSeconds time)
675 : : {
676 : 17708 : AssertLockHeld(cs);
677 : :
678 : 17708 : AddrInfo* pinfo = Find(addr);
679 : :
680 : : // if not found, bail out
681 [ + + ]: 17708 : if (!pinfo)
682 : : return;
683 : :
684 : 4323 : AddrInfo& info = *pinfo;
685 : :
686 : : // update info
687 : 4323 : info.m_last_try = time;
688 [ + + + + ]: 4323 : if (fCountFailure && info.m_last_count_attempt < m_last_good) {
689 : 1519 : info.m_last_count_attempt = time;
690 : 1519 : info.nAttempts++;
691 : : }
692 : : }
693 : :
694 : 1784 : std::pair<CAddress, NodeSeconds> AddrManImpl::Select_(bool new_only, const std::unordered_set<Network>& networks) const
695 : : {
696 : 1784 : AssertLockHeld(cs);
697 : :
698 [ + + ]: 1784 : if (vRandom.empty()) return {};
699 : :
700 : 1213 : size_t new_count = nNew;
701 : 1213 : size_t tried_count = nTried;
702 : :
703 [ + + ]: 1213 : if (!networks.empty()) {
704 : 241 : new_count = 0;
705 : 241 : tried_count = 0;
706 [ + + ]: 1295 : for (auto& network : networks) {
707 : 1054 : auto it = m_network_counts.find(network);
708 [ + + ]: 1054 : if (it == m_network_counts.end()) {
709 : 569 : continue;
710 : : }
711 : 485 : auto counts = it->second;
712 : 485 : new_count += counts.n_new;
713 : 485 : tried_count += counts.n_tried;
714 : : }
715 : : }
716 : :
717 [ + + ]: 1213 : if (new_only && new_count == 0) return {};
718 [ + + ]: 1203 : 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 : 1183 : bool search_tried;
723 [ + + ]: 1183 : if (new_only || tried_count == 0) {
724 : : search_tried = false;
725 [ + + ]: 259 : } else if (new_count == 0) {
726 : : search_tried = true;
727 : : } else {
728 : 224 : search_tried = insecure_rand.randbool();
729 : : }
730 : :
731 [ + + ]: 224 : const int bucket_count{search_tried ? ADDRMAN_TRIED_BUCKET_COUNT : ADDRMAN_NEW_BUCKET_COUNT};
732 : :
733 : : // Loop through the addrman table until we find an appropriate entry
734 : 1183 : double chance_factor = 1.0;
735 : 2495180 : while (1) {
736 : : // Pick a bucket.
737 : 2495180 : 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.
742 : 2495180 : nid_type copied_bucket[ADDRMAN_BUCKET_SIZE];
743 : 2495180 : int copied_count = 0;
744 [ + + ]: 162186700 : for (int i = 0; i < ADDRMAN_BUCKET_SIZE; ++i) {
745 : 159691520 : auto node_id = GetEntry(search_tried, bucket, i);
746 [ + + ]: 159691520 : if (node_id != -1) copied_bucket[copied_count++] = node_id;
747 : : }
748 : : // Then try to find a random non-filtered one among them.
749 : 2495180 : nid_type node_id = -1;
750 [ + + ]: 2504393 : while (copied_count > 0) {
751 : : // Pick a random entry.
752 : 13482 : auto pos = insecure_rand.randrange(copied_count);
753 : 13482 : node_id = copied_bucket[pos];
754 : : // No filtering is to be applied; we are good.
755 [ + + ]: 13482 : if (networks.empty()) break;
756 : : // Check the filter otherwise.
757 : 9900 : const auto it{mapInfo.find(node_id)};
758 [ + - + - : 19800 : 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.
760 : 9213 : copied_bucket[pos] = copied_bucket[--copied_count];
761 : : }
762 : : // If the bucket is empty or only contains filtered entries, start over with a (likely)
763 : : // different one.
764 [ + + ]: 2495180 : if (copied_count == 0) continue;
765 : 4269 : Assume(node_id != -1);
766 : :
767 : : // Find the entry to return.
768 : 4269 : const auto it_found{mapInfo.find(node_id)};
769 [ + - ]: 4269 : assert(it_found != mapInfo.end());
770 : 4269 : const AddrInfo& info{it_found->second};
771 : :
772 : : // With probability GetChance() * chance_factor, return the entry.
773 [ + + ]: 4269 : if (insecure_rand.randbits<30>() < chance_factor * info.GetChance() * (1 << 30)) {
774 [ - + - - : 1183 : LogDebug(BCLog::ADDRMAN, "Selected %s from %s\n", info.ToStringAddrPort(), search_tried ? "tried" : "new");
- - ]
775 : 1183 : return {info, info.m_last_try};
776 : : }
777 : :
778 : : // Otherwise start over with a (likely) different bucket, and increased chance factor.
779 : 3086 : chance_factor *= 1.2;
780 : : }
781 : : }
782 : :
783 : 159773440 : nid_type AddrManImpl::GetEntry(bool use_tried, size_t bucket, size_t position) const
784 : : {
785 : 159773440 : AssertLockHeld(cs);
786 : :
787 [ + + ]: 159773440 : if (use_tried) {
788 [ + - + - ]: 10971136 : if (Assume(position < ADDRMAN_BUCKET_SIZE) && Assume(bucket < ADDRMAN_TRIED_BUCKET_COUNT)) {
789 : 10971136 : return vvTried[bucket][position];
790 : : }
791 : : } else {
792 [ + - + - ]: 148802304 : if (Assume(position < ADDRMAN_BUCKET_SIZE) && Assume(bucket < ADDRMAN_NEW_BUCKET_COUNT)) {
793 : 148802304 : return vvNew[bucket][position];
794 : : }
795 : : }
796 : :
797 : : return -1;
798 : : }
799 : :
800 : 44227 : std::vector<CAddress> AddrManImpl::GetAddr_(size_t max_addresses, size_t max_pct, std::optional<Network> network, const bool filtered) const
801 : : {
802 : 44227 : AssertLockHeld(cs);
803 : 44227 : Assume(max_pct <= 100);
804 : :
805 [ - + ]: 44227 : size_t nNodes = vRandom.size();
806 [ + + ]: 44227 : if (max_pct != 0) {
807 [ + - ]: 33452 : max_pct = std::min(max_pct, size_t{100});
808 : 33452 : nNodes = max_pct * nNodes / 100;
809 : : }
810 [ + + ]: 44227 : if (max_addresses != 0) {
811 [ + + ]: 67436 : nNodes = std::min(nNodes, max_addresses);
812 : : }
813 : :
814 : : // gather a list of random nodes, skipping those of low quality
815 : 44227 : const auto now{Now<NodeSeconds>()};
816 : 44227 : std::vector<CAddress> addresses;
817 [ + - ]: 44227 : addresses.reserve(nNodes);
818 [ - + + + ]: 891659 : for (unsigned int n = 0; n < vRandom.size(); n++) {
819 [ - + + + ]: 848800 : if (addresses.size() >= nNodes)
820 : : break;
821 : :
822 : 847432 : int nRndPos = insecure_rand.randrange(vRandom.size() - n) + n;
823 [ + - ]: 847432 : SwapRandom(n, nRndPos);
824 : 847432 : const auto it{mapInfo.find(vRandom[n])};
825 [ - + ]: 847432 : assert(it != mapInfo.end());
826 : :
827 [ + + ]: 847432 : const AddrInfo& ai{it->second};
828 : :
829 : : // Filter by network (optional)
830 [ + + + - : 847432 : if (network != std::nullopt && ai.GetNetClass() != network) continue;
+ + ]
831 : :
832 : : // Filter for quality
833 [ + - + + : 679736 : if (ai.IsTerrible(now) && filtered) continue;
+ + ]
834 : :
835 [ + - ]: 440467 : addresses.push_back(ai);
836 : : }
837 [ + - + + : 44227 : LogDebug(BCLog::ADDRMAN, "GetAddr returned %d random addresses\n", addresses.size());
- + + - ]
838 : 44227 : return addresses;
839 : 0 : }
840 : :
841 : 2 : std::vector<std::pair<AddrInfo, AddressPosition>> AddrManImpl::GetEntries_(bool from_tried) const
842 : : {
843 : 2 : AssertLockHeld(cs);
844 : :
845 [ + + ]: 2 : const int bucket_count = from_tried ? ADDRMAN_TRIED_BUCKET_COUNT : ADDRMAN_NEW_BUCKET_COUNT;
846 : 2 : std::vector<std::pair<AddrInfo, AddressPosition>> infos;
847 [ + + ]: 1282 : for (int bucket = 0; bucket < bucket_count; ++bucket) {
848 [ + + ]: 83200 : for (int position = 0; position < ADDRMAN_BUCKET_SIZE; ++position) {
849 [ + - ]: 81920 : nid_type id = GetEntry(from_tried, bucket, position);
850 [ - + ]: 81920 : if (id >= 0) {
851 [ # # ]: 0 : AddrInfo info = mapInfo.at(id);
852 : 0 : AddressPosition location = AddressPosition(
853 : : from_tried,
854 : : /*multiplicity_in=*/from_tried ? 1 : info.nRefCount,
855 : : bucket,
856 [ # # # # ]: 0 : position);
857 [ # # ]: 0 : infos.emplace_back(info, location);
858 : 0 : }
859 : : }
860 : : }
861 : :
862 : 2 : return infos;
863 : 0 : }
864 : :
865 : 17711 : void AddrManImpl::Connected_(const CService& addr, NodeSeconds time)
866 : : {
867 : 17711 : AssertLockHeld(cs);
868 : :
869 : 17711 : AddrInfo* pinfo = Find(addr);
870 : :
871 : : // if not found, bail out
872 [ + + ]: 17711 : if (!pinfo)
873 : : return;
874 : :
875 : 4556 : AddrInfo& info = *pinfo;
876 : :
877 : : // update info
878 : 4556 : const auto update_interval{20min};
879 [ + + ]: 4556 : if (time - info.nTime > update_interval) {
880 : 735 : info.nTime = time;
881 : : }
882 : : }
883 : :
884 : 64124 : void AddrManImpl::SetServices_(const CService& addr, ServiceFlags nServices)
885 : : {
886 : 64124 : AssertLockHeld(cs);
887 : :
888 : 64124 : AddrInfo* pinfo = Find(addr);
889 : :
890 : : // if not found, bail out
891 [ + + ]: 64124 : if (!pinfo)
892 : : return;
893 : :
894 : 11781 : AddrInfo& info = *pinfo;
895 : :
896 : : // update info
897 : 11781 : info.nServices = nServices;
898 : : }
899 : :
900 : 8652 : void AddrManImpl::ResolveCollisions_()
901 : : {
902 : 8652 : AssertLockHeld(cs);
903 : :
904 [ + + ]: 21265 : for (std::set<nid_type>::iterator it = m_tried_collisions.begin(); it != m_tried_collisions.end();) {
905 : 12613 : nid_type id_new = *it;
906 : :
907 : 12613 : bool erase_collision = false;
908 : :
909 : : // If id_new not found in mapInfo remove it from m_tried_collisions
910 [ + + ]: 12613 : if (!mapInfo.contains(id_new)) {
911 : : erase_collision = true;
912 : : } else {
913 : 12442 : AddrInfo& info_new = mapInfo[id_new];
914 : :
915 : : // Which tried bucket to move the entry to.
916 : 12442 : int tried_bucket = info_new.GetTriedBucket(nKey, m_netgroupman);
917 : 12442 : int tried_bucket_pos = info_new.GetBucketPosition(nKey, false, tried_bucket);
918 [ + - ]: 12442 : 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.
923 : 12442 : Assume(vvTried[tried_bucket][tried_bucket_pos] != -1);
924 : :
925 : : // Get the to-be-evicted address that is being tested
926 : 12442 : nid_type id_old = vvTried[tried_bucket][tried_bucket_pos];
927 : 12442 : AddrInfo& info_old = mapInfo[id_old];
928 : :
929 : 12442 : const auto current_time{Now<NodeSeconds>()};
930 : :
931 : : // Has successfully connected in last X hours
932 [ + + ]: 12442 : if (current_time - info_old.m_last_success < ADDRMAN_REPLACEMENT) {
933 : : erase_collision = true;
934 [ + + ]: 6693 : } 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 [ + + ]: 643 : if (current_time - info_old.m_last_try > 60s) {
938 [ - + - - : 3 : 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 : 3 : Good_(info_new, false, current_time);
942 : 3 : erase_collision = true;
943 : : }
944 [ + + ]: 6050 : } 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 [ - + - - : 2265 : LogDebug(BCLog::ADDRMAN, "Unable to test; replacing %s with %s in tried table anyway\n", info_old.ToStringAddrPort(), info_new.ToStringAddrPort());
- - ]
949 : 2265 : Good_(info_new, false, current_time);
950 : 2265 : erase_collision = true;
951 : : }
952 : : }
953 : : }
954 : :
955 : 2268 : if (erase_collision) {
956 : 8188 : m_tried_collisions.erase(it++);
957 : : } else {
958 : 4425 : it++;
959 : : }
960 : : }
961 : 8652 : }
962 : :
963 : 70661 : std::pair<CAddress, NodeSeconds> AddrManImpl::SelectTriedCollision_()
964 : : {
965 : 70661 : AssertLockHeld(cs);
966 : :
967 [ + + ]: 70661 : if (m_tried_collisions.size() == 0) return {};
968 : :
969 : 45525 : std::set<nid_type>::iterator it = m_tried_collisions.begin();
970 : :
971 : : // Selects a random element from m_tried_collisions
972 : 45525 : std::advance(it, insecure_rand.randrange(m_tried_collisions.size()));
973 : 45525 : nid_type id_new = *it;
974 : :
975 : : // If id_new not found in mapInfo remove it from m_tried_collisions
976 [ + + ]: 45525 : if (!mapInfo.contains(id_new)) {
977 : 450 : m_tried_collisions.erase(it);
978 : 450 : return {};
979 : : }
980 : :
981 : 45075 : const AddrInfo& newInfo = mapInfo[id_new];
982 : :
983 : : // which tried bucket to move the entry to
984 : 45075 : int tried_bucket = newInfo.GetTriedBucket(nKey, m_netgroupman);
985 : 45075 : int tried_bucket_pos = newInfo.GetBucketPosition(nKey, false, tried_bucket);
986 : :
987 : 45075 : Assume(vvTried[tried_bucket][tried_bucket_pos] != -1);
988 : 45075 : const AddrInfo& info_old = mapInfo[vvTried[tried_bucket][tried_bucket_pos]];
989 : 45075 : return {info_old, info_old.m_last_try};
990 : : }
991 : :
992 : 0 : std::optional<AddressPosition> AddrManImpl::FindAddressEntry_(const CAddress& addr)
993 : : {
994 : 0 : AssertLockHeld(cs);
995 : :
996 : 0 : AddrInfo* addr_info = Find(addr);
997 : :
998 [ # # ]: 0 : if (!addr_info) return std::nullopt;
999 : :
1000 [ # # ]: 0 : if(addr_info->fInTried) {
1001 : 0 : int bucket{addr_info->GetTriedBucket(nKey, m_netgroupman)};
1002 : 0 : return AddressPosition(/*tried_in=*/true,
1003 : : /*multiplicity_in=*/1,
1004 : : /*bucket_in=*/bucket,
1005 : 0 : /*position_in=*/addr_info->GetBucketPosition(nKey, false, bucket));
1006 : : } else {
1007 : 0 : int bucket{addr_info->GetNewBucket(nKey, m_netgroupman)};
1008 : 0 : return AddressPosition(/*tried_in=*/false,
1009 : : /*multiplicity_in=*/addr_info->nRefCount,
1010 : : /*bucket_in=*/bucket,
1011 : 0 : /*position_in=*/addr_info->GetBucketPosition(nKey, true, bucket));
1012 : : }
1013 : : }
1014 : :
1015 : 6838682 : size_t AddrManImpl::Size_(std::optional<Network> net, std::optional<bool> in_new) const
1016 : : {
1017 : 6838682 : AssertLockHeld(cs);
1018 : :
1019 [ + + ]: 6838682 : if (!net.has_value()) {
1020 [ + + ]: 6837375 : if (in_new.has_value()) {
1021 [ + + ]: 71 : return *in_new ? nNew : nTried;
1022 : : } else {
1023 [ - + ]: 6837304 : return vRandom.size();
1024 : : }
1025 : : }
1026 [ + + ]: 1307 : if (auto it = m_network_counts.find(*net); it != m_network_counts.end()) {
1027 [ + + ]: 571 : auto net_count = it->second;
1028 [ + + ]: 571 : if (in_new.has_value()) {
1029 [ + + ]: 406 : return *in_new ? net_count.n_new : net_count.n_tried;
1030 : : } else {
1031 : 165 : return net_count.n_new + net_count.n_tried;
1032 : : }
1033 : : }
1034 : : return 0;
1035 : : }
1036 : :
1037 : 44413172 : void AddrManImpl::Check() const
1038 : : {
1039 : 44413172 : AssertLockHeld(cs);
1040 : :
1041 : : // Run consistency checks 1 in m_consistency_check_ratio times if enabled
1042 [ - + ]: 44413172 : if (m_consistency_check_ratio == 0) return;
1043 [ # # ]: 0 : if (insecure_rand.randrange(m_consistency_check_ratio) >= 1) return;
1044 : :
1045 : 0 : const int err{CheckAddrman()};
1046 [ # # ]: 0 : if (err) {
1047 : 0 : LogError("ADDRMAN CONSISTENCY CHECK FAILED!!! err=%i", err);
1048 : 0 : assert(false);
1049 : : }
1050 : : }
1051 : :
1052 : 3067 : int AddrManImpl::CheckAddrman() const
1053 : : {
1054 : 3067 : AssertLockHeld(cs);
1055 : :
1056 [ - + + - : 6134 : LOG_TIME_MILLIS_WITH_CATEGORY_MSG_ONCE(
+ - ]
1057 : : strprintf("new %i, tried %i, total %u", nNew, nTried, vRandom.size()), BCLog::ADDRMAN);
1058 : :
1059 [ - + ]: 3067 : std::unordered_set<nid_type> setTried;
1060 [ - + ]: 3067 : std::unordered_map<nid_type, int> mapNew;
1061 : 3067 : std::unordered_map<Network, NewTriedCount> local_counts;
1062 : :
1063 [ - + + - ]: 3067 : if (vRandom.size() != (size_t)(nTried + nNew))
1064 : : return -7;
1065 : :
1066 [ + + + + ]: 6778169 : for (const auto& entry : mapInfo) {
1067 : 6775362 : nid_type n = entry.first;
1068 : 6775362 : const AddrInfo& info = entry.second;
1069 [ + + ]: 6775362 : if (info.fInTried) {
1070 [ + + ]: 3169246 : if (!TicksSinceEpoch<std::chrono::seconds>(info.m_last_success)) {
1071 : : return -1;
1072 : : }
1073 [ + - ]: 3169211 : if (info.nRefCount)
1074 : : return -2;
1075 [ + - ]: 3169211 : setTried.insert(n);
1076 [ + - + - ]: 3169211 : local_counts[info.GetNetwork()].n_tried++;
1077 : : } else {
1078 [ + - ]: 3606116 : if (info.nRefCount < 0 || info.nRefCount > ADDRMAN_NEW_BUCKETS_PER_ADDRESS)
1079 : : return -3;
1080 [ + - ]: 3606116 : if (!info.nRefCount)
1081 : : return -4;
1082 [ + - ]: 3606116 : mapNew[n] = info.nRefCount;
1083 [ + - + - ]: 3606116 : local_counts[info.GetNetwork()].n_new++;
1084 : : }
1085 [ + - ]: 6775327 : const auto it{mapAddr.find(info)};
1086 [ + + + + ]: 6775327 : if (it == mapAddr.end() || it->second != n) {
1087 : : return -5;
1088 : : }
1089 [ + - - + : 6775295 : if (info.nRandomPos < 0 || (size_t)info.nRandomPos >= vRandom.size() || vRandom[info.nRandomPos] != n)
+ - + - ]
1090 : : return -14;
1091 [ + - ]: 6775295 : if (info.m_last_try < NodeSeconds{0s}) {
1092 : : return -6;
1093 : : }
1094 [ + + ]: 6775295 : if (info.m_last_success < NodeSeconds{0s}) {
1095 : : return -8;
1096 : : }
1097 : : }
1098 : :
1099 [ + - ]: 2807 : if (setTried.size() != (size_t)nTried)
1100 : : return -9;
1101 [ + - ]: 2807 : if (mapNew.size() != (size_t)nNew)
1102 : : return -10;
1103 : :
1104 [ + + ]: 721399 : for (int n = 0; n < ADDRMAN_TRIED_BUCKET_COUNT; n++) {
1105 [ + + ]: 46708480 : for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) {
1106 [ + + ]: 45989888 : if (vvTried[n][i] != -1) {
1107 [ + - ]: 3168836 : if (!setTried.contains(vvTried[n][i]))
1108 : : return -11;
1109 : 3168836 : const auto it{mapInfo.find(vvTried[n][i])};
1110 [ + - + - : 3168836 : if (it == mapInfo.end() || it->second.GetTriedBucket(nKey, m_netgroupman) != n) {
+ - ]
1111 : 0 : return -17;
1112 : : }
1113 [ + - + - ]: 3168836 : if (it->second.GetBucketPosition(nKey, false, n) != i) {
1114 : : return -18;
1115 : : }
1116 : 3168836 : setTried.erase(vvTried[n][i]);
1117 : : }
1118 : : }
1119 : : }
1120 : :
1121 [ + + ]: 2877175 : for (int n = 0; n < ADDRMAN_NEW_BUCKET_COUNT; n++) {
1122 [ + + ]: 186833920 : for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) {
1123 [ + + ]: 183959552 : if (vvNew[n][i] != -1) {
1124 [ + - ]: 3749376 : if (!mapNew.contains(vvNew[n][i]))
1125 : : return -12;
1126 : 3749376 : const auto it{mapInfo.find(vvNew[n][i])};
1127 [ + - + - : 3749376 : if (it == mapInfo.end() || it->second.GetBucketPosition(nKey, true, n) != i) {
+ - ]
1128 : 0 : return -19;
1129 : : }
1130 [ + - + + ]: 3749376 : if (--mapNew[vvNew[n][i]] == 0)
1131 : 3605764 : mapNew.erase(vvNew[n][i]);
1132 : : }
1133 : : }
1134 : : }
1135 : :
1136 [ + - ]: 2807 : if (setTried.size())
1137 : : return -13;
1138 [ + - ]: 2807 : if (mapNew.size())
1139 : : return -15;
1140 [ + + ]: 5614 : 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 [ + - ]: 2800 : if (m_network_counts.size() < local_counts.size()) {
1146 : : return -20;
1147 : : }
1148 [ + + + - ]: 11357 : for (const auto& [net, count] : m_network_counts) {
1149 [ + - + - : 16580 : if (local_counts[net].n_new != count.n_new || local_counts[net].n_tried != count.n_tried) {
+ - ]
1150 : 0 : return -21;
1151 : : }
1152 : : }
1153 : :
1154 : : return 0;
1155 : 3067 : }
1156 : :
1157 : 6838682 : size_t AddrManImpl::Size(std::optional<Network> net, std::optional<bool> in_new) const
1158 : : {
1159 : 6838682 : LOCK(cs);
1160 [ + - ]: 6838682 : Check();
1161 [ + - ]: 6838682 : auto ret = Size_(net, in_new);
1162 [ + - ]: 6838682 : Check();
1163 [ + - ]: 6838682 : return ret;
1164 : 6838682 : }
1165 : :
1166 : 9653272 : bool AddrManImpl::Add(const std::vector<CAddress>& vAddr, const CNetAddr& source, std::chrono::seconds time_penalty)
1167 : : {
1168 : 9653272 : LOCK(cs);
1169 [ + - ]: 9653272 : Check();
1170 [ + - ]: 9653272 : auto ret = Add_(vAddr, source, time_penalty);
1171 [ + - ]: 9653272 : Check();
1172 [ + - ]: 9653272 : return ret;
1173 : 9653272 : }
1174 : :
1175 : 5489763 : bool AddrManImpl::Good(const CService& addr, NodeSeconds time)
1176 : : {
1177 : 5489763 : LOCK(cs);
1178 [ + - ]: 5489763 : Check();
1179 [ + - ]: 5489763 : auto ret = Good_(addr, /*test_before_evict=*/true, time);
1180 [ + - ]: 5489763 : Check();
1181 [ + - ]: 5489763 : return ret;
1182 : 5489763 : }
1183 : :
1184 : 17708 : void AddrManImpl::Attempt(const CService& addr, bool fCountFailure, NodeSeconds time)
1185 : : {
1186 : 17708 : LOCK(cs);
1187 [ + - ]: 17708 : Check();
1188 [ + - ]: 17708 : Attempt_(addr, fCountFailure, time);
1189 [ + - ]: 17708 : Check();
1190 : 17708 : }
1191 : :
1192 : 8652 : void AddrManImpl::ResolveCollisions()
1193 : : {
1194 : 8652 : LOCK(cs);
1195 [ + - ]: 8652 : Check();
1196 [ + - ]: 8652 : ResolveCollisions_();
1197 [ + - ]: 8652 : Check();
1198 : 8652 : }
1199 : :
1200 : 70661 : std::pair<CAddress, NodeSeconds> AddrManImpl::SelectTriedCollision()
1201 : : {
1202 : 70661 : LOCK(cs);
1203 [ + - ]: 70661 : Check();
1204 [ + - ]: 70661 : auto ret = SelectTriedCollision_();
1205 [ + - ]: 70661 : Check();
1206 [ + - ]: 70661 : return ret;
1207 : 70661 : }
1208 : :
1209 : 1784 : std::pair<CAddress, NodeSeconds> AddrManImpl::Select(bool new_only, const std::unordered_set<Network>& networks) const
1210 : : {
1211 : 1784 : LOCK(cs);
1212 [ + - ]: 1784 : Check();
1213 [ + - ]: 1784 : auto addrRet = Select_(new_only, networks);
1214 [ + - ]: 1784 : Check();
1215 [ + - ]: 1784 : return addrRet;
1216 : 1784 : }
1217 : :
1218 : 44227 : std::vector<CAddress> AddrManImpl::GetAddr(size_t max_addresses, size_t max_pct, std::optional<Network> network, const bool filtered) const
1219 : : {
1220 : 44227 : LOCK(cs);
1221 [ + - ]: 44227 : Check();
1222 [ + - ]: 44227 : auto addresses = GetAddr_(max_addresses, max_pct, network, filtered);
1223 [ + - ]: 44227 : Check();
1224 [ + - ]: 44227 : return addresses;
1225 : 44227 : }
1226 : :
1227 : 2 : std::vector<std::pair<AddrInfo, AddressPosition>> AddrManImpl::GetEntries(bool from_tried) const
1228 : : {
1229 : 2 : LOCK(cs);
1230 [ + - ]: 2 : Check();
1231 [ + - ]: 2 : auto addrInfos = GetEntries_(from_tried);
1232 [ + - ]: 2 : Check();
1233 [ + - ]: 2 : return addrInfos;
1234 : 2 : }
1235 : :
1236 : 17711 : void AddrManImpl::Connected(const CService& addr, NodeSeconds time)
1237 : : {
1238 : 17711 : LOCK(cs);
1239 [ + - ]: 17711 : Check();
1240 [ + - ]: 17711 : Connected_(addr, time);
1241 [ + - ]: 17711 : Check();
1242 : 17711 : }
1243 : :
1244 : 64124 : void AddrManImpl::SetServices(const CService& addr, ServiceFlags nServices)
1245 : : {
1246 : 64124 : LOCK(cs);
1247 [ + - ]: 64124 : Check();
1248 [ + - ]: 64124 : SetServices_(addr, nServices);
1249 [ + - ]: 64124 : Check();
1250 : 64124 : }
1251 : :
1252 : 0 : std::optional<AddressPosition> AddrManImpl::FindAddressEntry(const CAddress& addr)
1253 : : {
1254 : 0 : LOCK(cs);
1255 [ # # ]: 0 : Check();
1256 [ # # ]: 0 : auto entry = FindAddressEntry_(addr);
1257 [ # # ]: 0 : Check();
1258 [ # # ]: 0 : return entry;
1259 : 0 : }
1260 : :
1261 : 27435 : AddrMan::AddrMan(const NetGroupManager& netgroupman, bool deterministic, int32_t consistency_check_ratio)
1262 : 27435 : : m_impl(std::make_unique<AddrManImpl>(netgroupman, deterministic, consistency_check_ratio)) {}
1263 : :
1264 : 27435 : AddrMan::~AddrMan() = default;
1265 : :
1266 : : template <typename Stream>
1267 : 3056 : void AddrMan::Serialize(Stream& s_) const
1268 : : {
1269 : 3056 : m_impl->Serialize<Stream>(s_);
1270 : 3056 : }
1271 : :
1272 : : template <typename Stream>
1273 : 5581 : void AddrMan::Unserialize(Stream& s_)
1274 : : {
1275 : 5581 : m_impl->Unserialize<Stream>(s_);
1276 : 2800 : }
1277 : :
1278 : : // explicit instantiation
1279 : : template void AddrMan::Serialize(HashedSourceWriter<AutoFile>&) const;
1280 : : template void AddrMan::Serialize(DataStream&) const;
1281 : : template void AddrMan::Unserialize(HashVerifier<AutoFile>&);
1282 : : template void AddrMan::Unserialize(DataStream&);
1283 : : template void AddrMan::Unserialize(HashVerifier<DataStream>&);
1284 : :
1285 : 6838682 : size_t AddrMan::Size(std::optional<Network> net, std::optional<bool> in_new) const
1286 : : {
1287 : 6838682 : return m_impl->Size(net, in_new);
1288 : : }
1289 : :
1290 : 9653272 : bool AddrMan::Add(const std::vector<CAddress>& vAddr, const CNetAddr& source, std::chrono::seconds time_penalty)
1291 : : {
1292 : 9653272 : return m_impl->Add(vAddr, source, time_penalty);
1293 : : }
1294 : :
1295 : 5489763 : bool AddrMan::Good(const CService& addr, NodeSeconds time)
1296 : : {
1297 : 5489763 : return m_impl->Good(addr, time);
1298 : : }
1299 : :
1300 : 17708 : void AddrMan::Attempt(const CService& addr, bool fCountFailure, NodeSeconds time)
1301 : : {
1302 : 17708 : m_impl->Attempt(addr, fCountFailure, time);
1303 : 17708 : }
1304 : :
1305 : 8652 : void AddrMan::ResolveCollisions()
1306 : : {
1307 : 8652 : m_impl->ResolveCollisions();
1308 : 8652 : }
1309 : :
1310 : 70661 : std::pair<CAddress, NodeSeconds> AddrMan::SelectTriedCollision()
1311 : : {
1312 : 70661 : return m_impl->SelectTriedCollision();
1313 : : }
1314 : :
1315 : 1784 : std::pair<CAddress, NodeSeconds> AddrMan::Select(bool new_only, const std::unordered_set<Network>& networks) const
1316 : : {
1317 : 1784 : return m_impl->Select(new_only, networks);
1318 : : }
1319 : :
1320 : 44227 : std::vector<CAddress> AddrMan::GetAddr(size_t max_addresses, size_t max_pct, std::optional<Network> network, const bool filtered) const
1321 : : {
1322 : 44227 : return m_impl->GetAddr(max_addresses, max_pct, network, filtered);
1323 : : }
1324 : :
1325 : 2 : std::vector<std::pair<AddrInfo, AddressPosition>> AddrMan::GetEntries(bool use_tried) const
1326 : : {
1327 : 2 : return m_impl->GetEntries(use_tried);
1328 : : }
1329 : :
1330 : 17711 : void AddrMan::Connected(const CService& addr, NodeSeconds time)
1331 : : {
1332 : 17711 : m_impl->Connected(addr, time);
1333 : 17711 : }
1334 : :
1335 : 64124 : void AddrMan::SetServices(const CService& addr, ServiceFlags nServices)
1336 : : {
1337 : 64124 : m_impl->SetServices(addr, nServices);
1338 : 64124 : }
1339 : :
1340 : 0 : std::optional<AddressPosition> AddrMan::FindAddressEntry(const CAddress& addr)
1341 : : {
1342 : 0 : return m_impl->FindAddressEntry(addr);
1343 : : }
|