bitcoin core ipc fuzz coverage

Coverage Report

Created: 2026-08-26 16:12

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/home/enochazariah/dev/bitcoin-invariants/src/addrman.cpp
Line
Count
Source
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
int AddrInfo::GetTriedBucket(const uint256& nKey, const NetGroupManager& netgroupman) const
30
0
{
31
0
    uint64_t hash1 = (HashWriter{} << nKey << GetKey()).GetCheapHash();
32
0
    uint64_t hash2 = (HashWriter{} << nKey << netgroupman.GetGroup(*this) << (hash1 % ADDRMAN_TRIED_BUCKETS_PER_GROUP)).GetCheapHash();
33
0
    return hash2 % ADDRMAN_TRIED_BUCKET_COUNT;
34
0
}
35
36
int AddrInfo::GetNewBucket(const uint256& nKey, const CNetAddr& src, const NetGroupManager& netgroupman) const
37
0
{
38
0
    std::vector<unsigned char> vchSourceGroupKey = netgroupman.GetGroup(src);
39
0
    uint64_t hash1 = (HashWriter{} << nKey << netgroupman.GetGroup(*this) << vchSourceGroupKey).GetCheapHash();
40
0
    uint64_t hash2 = (HashWriter{} << nKey << vchSourceGroupKey << (hash1 % ADDRMAN_NEW_BUCKETS_PER_SOURCE_GROUP)).GetCheapHash();
41
0
    return hash2 % ADDRMAN_NEW_BUCKET_COUNT;
42
0
}
43
44
int AddrInfo::GetBucketPosition(const uint256& nKey, bool fNew, int bucket) const
45
0
{
46
0
    uint64_t hash1 = (HashWriter{} << nKey << (fNew ? uint8_t{'N'} : uint8_t{'K'}) << bucket << GetKey()).GetCheapHash();
47
0
    return hash1 % ADDRMAN_BUCKET_SIZE;
48
0
}
49
50
bool AddrInfo::IsTerrible(NodeSeconds now) const
51
0
{
52
0
    if (now - m_last_try <= 1min) { // never remove things tried in the last minute
53
0
        return false;
54
0
    }
55
56
0
    if (nTime > now + 10min) { // came in a flying DeLorean
57
0
        return true;
58
0
    }
59
60
0
    if (now - nTime > ADDRMAN_HORIZON) { // not seen in recent history
61
0
        return true;
62
0
    }
63
64
0
    if (TicksSinceEpoch<std::chrono::seconds>(m_last_success) == 0 && nAttempts >= ADDRMAN_RETRIES) { // tried N times and never a success
65
0
        return true;
66
0
    }
67
68
0
    if (now - m_last_success > ADDRMAN_MIN_FAIL && nAttempts >= ADDRMAN_MAX_FAILURES) { // N successive failures in the last week
69
0
        return true;
70
0
    }
71
72
0
    return false;
73
0
}
74
75
double AddrInfo::GetChance(NodeSeconds now) const
76
0
{
77
0
    double fChance = 1.0;
78
79
    // deprioritize very recent attempts away
80
0
    if (now - m_last_try < 10min) {
81
0
        fChance *= 0.01;
82
0
    }
83
84
    // deprioritize 66% after each failed attempt, but at most 1/28th to avoid the search taking forever or overly penalizing outages.
85
0
    fChance *= pow(0.66, std::min(nAttempts, 8));
86
87
0
    return fChance;
88
0
}
89
90
AddrManImpl::AddrManImpl(const NetGroupManager& netgroupman, bool deterministic, int32_t consistency_check_ratio)
91
0
    : insecure_rand{deterministic}
92
0
    , nKey{deterministic ? uint256{1} : insecure_rand.rand256()}
93
0
    , m_consistency_check_ratio{consistency_check_ratio}
94
0
    , m_netgroupman{netgroupman}
95
0
{
96
0
    for (auto& bucket : vvNew) {
97
0
        for (auto& entry : bucket) {
98
0
            entry = -1;
99
0
        }
100
0
    }
101
0
    for (auto& bucket : vvTried) {
102
0
        for (auto& entry : bucket) {
103
0
            entry = -1;
104
0
        }
105
0
    }
106
0
}
107
108
AddrManImpl::~AddrManImpl()
109
0
{
110
0
    nKey.SetNull();
111
0
}
112
113
template <typename Stream>
114
void AddrManImpl::Serialize(Stream& s_) const
115
0
{
116
0
    LOCK(cs);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock BITCOIN_UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define BITCOIN_UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
    LOCK(cs);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock BITCOIN_UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define BITCOIN_UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
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
0
    ParamsStream s{s_, CAddress::V2_DISK};
158
159
0
    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
0
    static constexpr uint8_t lowest_compatible = Format::V4_MULTIPORT;
164
0
    s << static_cast<uint8_t>(INCOMPATIBILITY_BASE + lowest_compatible);
165
166
0
    s << nKey;
167
0
    s << nNew;
168
0
    s << nTried;
169
170
0
    int nUBuckets = ADDRMAN_NEW_BUCKET_COUNT ^ (1 << 30);
171
0
    s << nUBuckets;
172
0
    std::unordered_map<nid_type, int> mapUnkIds;
173
0
    int nIds = 0;
174
0
    for (const auto& entry : mapInfo) {
175
0
        mapUnkIds[entry.first] = nIds;
176
0
        const AddrInfo& info = entry.second;
177
0
        if (info.nRefCount) {
178
0
            assert(nIds != nNew); // this means nNew was wrong, oh ow
179
0
            s << info;
180
0
            nIds++;
181
0
        }
182
0
    }
183
0
    nIds = 0;
184
0
    for (const auto& entry : mapInfo) {
185
0
        const AddrInfo& info = entry.second;
186
0
        if (info.fInTried) {
187
0
            assert(nIds != nTried); // this means nTried was wrong, oh ow
188
0
            s << info;
189
0
            nIds++;
190
0
        }
191
0
    }
192
0
    for (int bucket = 0; bucket < ADDRMAN_NEW_BUCKET_COUNT; bucket++) {
193
0
        int nSize = 0;
194
0
        for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) {
195
0
            if (vvNew[bucket][i] != -1)
196
0
                nSize++;
197
0
        }
198
0
        s << nSize;
199
0
        for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) {
200
0
            if (vvNew[bucket][i] != -1) {
201
0
                int nIndex = mapUnkIds[vvNew[bucket][i]];
202
0
                s << nIndex;
203
0
            }
204
0
        }
205
0
    }
206
    // Store asmap version after bucket entries so that it
207
    // can be ignored by older clients for backward compatibility.
208
0
    s << m_netgroupman.GetAsmapVersion();
209
0
}
Unexecuted instantiation: void AddrManImpl::Serialize<HashedSourceWriter<AutoFile>>(HashedSourceWriter<AutoFile>&) const
Unexecuted instantiation: void AddrManImpl::Serialize<DataStream>(DataStream&) const
210
211
template <typename Stream>
212
void AddrManImpl::Unserialize(Stream& s_)
213
0
{
214
0
    LOCK(cs);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock BITCOIN_UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define BITCOIN_UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
    LOCK(cs);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock BITCOIN_UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define BITCOIN_UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
    LOCK(cs);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock BITCOIN_UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define BITCOIN_UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
    LOCK(cs);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock BITCOIN_UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define BITCOIN_UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
215
216
0
    assert(vRandom.empty());
217
218
0
    Format format;
219
0
    s_ >> Using<CustomUintFormatter<1>>(format);
220
221
0
    const auto ser_params = (format >= Format::V3_BIP155 ? CAddress::V2_DISK : CAddress::V1_DISK);
222
0
    ParamsStream s{s_, ser_params};
223
224
0
    uint8_t compat;
225
0
    s >> compat;
226
0
    if (compat < INCOMPATIBILITY_BASE) {
227
0
        throw std::ios_base::failure(strprintf(
Line
Count
Source
1172
0
#define strprintf tfm::format
        throw std::ios_base::failure(strprintf(
Line
Count
Source
1172
0
#define strprintf tfm::format
        throw std::ios_base::failure(strprintf(
Line
Count
Source
1172
0
#define strprintf tfm::format
        throw std::ios_base::failure(strprintf(
Line
Count
Source
1172
0
#define strprintf tfm::format
228
0
            "Corrupted addrman database: The compat value (%u) "
229
0
            "is lower than the expected minimum value %u.",
230
0
            compat, INCOMPATIBILITY_BASE));
231
0
    }
232
0
    const uint8_t lowest_compatible = compat - INCOMPATIBILITY_BASE;
233
0
    if (lowest_compatible > FILE_FORMAT) {
234
0
        throw InvalidAddrManVersionError(strprintf(
Line
Count
Source
1172
0
#define strprintf tfm::format
        throw InvalidAddrManVersionError(strprintf(
Line
Count
Source
1172
0
#define strprintf tfm::format
        throw InvalidAddrManVersionError(strprintf(
Line
Count
Source
1172
0
#define strprintf tfm::format
        throw InvalidAddrManVersionError(strprintf(
Line
Count
Source
1172
0
#define strprintf tfm::format
235
0
            "Unsupported format of addrman database: %u. It is compatible with formats >=%u, "
236
0
            "but the maximum supported by this version of %s is %u.",
237
0
            uint8_t{format}, lowest_compatible, CLIENT_NAME, uint8_t{FILE_FORMAT}));
Line
Count
Source
98
0
#define CLIENT_NAME "Bitcoin Core"
            uint8_t{format}, lowest_compatible, CLIENT_NAME, uint8_t{FILE_FORMAT}));
Line
Count
Source
98
0
#define CLIENT_NAME "Bitcoin Core"
            uint8_t{format}, lowest_compatible, CLIENT_NAME, uint8_t{FILE_FORMAT}));
Line
Count
Source
98
0
#define CLIENT_NAME "Bitcoin Core"
            uint8_t{format}, lowest_compatible, CLIENT_NAME, uint8_t{FILE_FORMAT}));
Line
Count
Source
98
0
#define CLIENT_NAME "Bitcoin Core"
238
0
    }
239
240
0
    s >> nKey;
241
0
    s >> nNew;
242
0
    s >> nTried;
243
0
    int nUBuckets = 0;
244
0
    s >> nUBuckets;
245
0
    if (format >= Format::V1_DETERMINISTIC) {
246
0
        nUBuckets ^= (1 << 30);
247
0
    }
248
249
0
    if (nNew > ADDRMAN_NEW_BUCKET_COUNT * ADDRMAN_BUCKET_SIZE || nNew < 0) {
250
0
        throw std::ios_base::failure(
251
0
                strprintf("Corrupt AddrMan serialization: nNew=%d, should be in [0, %d]",
Line
Count
Source
1172
0
#define strprintf tfm::format
                strprintf("Corrupt AddrMan serialization: nNew=%d, should be in [0, %d]",
Line
Count
Source
1172
0
#define strprintf tfm::format
                strprintf("Corrupt AddrMan serialization: nNew=%d, should be in [0, %d]",
Line
Count
Source
1172
0
#define strprintf tfm::format
                strprintf("Corrupt AddrMan serialization: nNew=%d, should be in [0, %d]",
Line
Count
Source
1172
0
#define strprintf tfm::format
252
0
                    nNew,
253
0
                    ADDRMAN_NEW_BUCKET_COUNT * ADDRMAN_BUCKET_SIZE));
254
0
    }
255
256
0
    if (nTried > ADDRMAN_TRIED_BUCKET_COUNT * ADDRMAN_BUCKET_SIZE || nTried < 0) {
257
0
        throw std::ios_base::failure(
258
0
                strprintf("Corrupt AddrMan serialization: nTried=%d, should be in [0, %d]",
Line
Count
Source
1172
0
#define strprintf tfm::format
                strprintf("Corrupt AddrMan serialization: nTried=%d, should be in [0, %d]",
Line
Count
Source
1172
0
#define strprintf tfm::format
                strprintf("Corrupt AddrMan serialization: nTried=%d, should be in [0, %d]",
Line
Count
Source
1172
0
#define strprintf tfm::format
                strprintf("Corrupt AddrMan serialization: nTried=%d, should be in [0, %d]",
Line
Count
Source
1172
0
#define strprintf tfm::format
259
0
                    nTried,
260
0
                    ADDRMAN_TRIED_BUCKET_COUNT * ADDRMAN_BUCKET_SIZE));
261
0
    }
262
263
    // Deserialize entries from the new table.
264
0
    for (int n = 0; n < nNew; n++) {
265
0
        AddrInfo& info = mapInfo[n];
266
0
        s >> info;
267
0
        mapAddr[info] = n;
268
0
        info.nRandomPos = vRandom.size();
269
0
        vRandom.push_back(n);
270
0
        m_network_counts[info.GetNetwork()].n_new++;
271
0
    }
272
0
    nIdCount = nNew;
273
274
    // Deserialize entries from the tried table.
275
0
    int nLost = 0;
276
0
    for (int n = 0; n < nTried; n++) {
277
0
        AddrInfo info;
278
0
        s >> info;
279
0
        int nKBucket = info.GetTriedBucket(nKey, m_netgroupman);
280
0
        int nKBucketPos = info.GetBucketPosition(nKey, false, nKBucket);
281
0
        if (info.IsValid()
282
0
                && vvTried[nKBucket][nKBucketPos] == -1) {
283
0
            info.nRandomPos = vRandom.size();
284
0
            info.fInTried = true;
285
0
            vRandom.push_back(nIdCount);
286
0
            mapInfo[nIdCount] = info;
287
0
            mapAddr[info] = nIdCount;
288
0
            vvTried[nKBucket][nKBucketPos] = nIdCount;
289
0
            nIdCount++;
290
0
            m_network_counts[info.GetNetwork()].n_tried++;
291
0
        } else {
292
0
            nLost++;
293
0
        }
294
0
    }
295
0
    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
0
    std::vector<std::pair<int, int>> bucket_entries;
301
302
0
    for (int bucket = 0; bucket < nUBuckets; ++bucket) {
303
0
        int num_entries{0};
304
0
        s >> num_entries;
305
0
        for (int n = 0; n < num_entries; ++n) {
306
0
            int entry_index{0};
307
0
            s >> entry_index;
308
0
            if (entry_index >= 0 && entry_index < nNew) {
309
0
                bucket_entries.emplace_back(bucket, entry_index);
310
0
            }
311
0
        }
312
0
    }
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
0
    uint256 supplied_asmap_version{m_netgroupman.GetAsmapVersion()};
318
0
    uint256 serialized_asmap_version;
319
0
    if (format >= Format::V2_ASMAP) {
320
0
        s >> serialized_asmap_version;
321
0
    }
322
0
    const bool restore_bucketing{nUBuckets == ADDRMAN_NEW_BUCKET_COUNT &&
323
0
        serialized_asmap_version == supplied_asmap_version};
324
325
0
    if (!restore_bucketing) {
326
0
        LogDebug(BCLog::ADDRMAN, "Bucketing method was updated, re-bucketing addrman entries from disk\n");
Line
Count
Source
143
0
#define LogDebug(category, ...) detail_LogIfCategoryAndLevelEnabled(category, util::log::ShouldDebugLog, util::log::Level::Debug, __VA_ARGS__)
Line
Count
Source
136
0
    do {                                                                                      \
137
0
        if (shouldlog(category)) {                                                            \
138
0
            detail_LogWithSrcLoc((category), (level), util::log::NO_RATE_LIMIT, __VA_ARGS__); \
Line
Count
Source
119
0
#define detail_LogWithSrcLoc(category, level, ...) util::log::LogPrintFormatInternal(SourceLocation{__func__}, category, level, __VA_ARGS__)
139
0
        }                                                                                     \
140
0
    } while (0)
        LogDebug(BCLog::ADDRMAN, "Bucketing method was updated, re-bucketing addrman entries from disk\n");
Line
Count
Source
143
0
#define LogDebug(category, ...) detail_LogIfCategoryAndLevelEnabled(category, util::log::ShouldDebugLog, util::log::Level::Debug, __VA_ARGS__)
Line
Count
Source
136
0
    do {                                                                                      \
137
0
        if (shouldlog(category)) {                                                            \
138
0
            detail_LogWithSrcLoc((category), (level), util::log::NO_RATE_LIMIT, __VA_ARGS__); \
Line
Count
Source
119
0
#define detail_LogWithSrcLoc(category, level, ...) util::log::LogPrintFormatInternal(SourceLocation{__func__}, category, level, __VA_ARGS__)
139
0
        }                                                                                     \
140
0
    } while (0)
        LogDebug(BCLog::ADDRMAN, "Bucketing method was updated, re-bucketing addrman entries from disk\n");
Line
Count
Source
143
0
#define LogDebug(category, ...) detail_LogIfCategoryAndLevelEnabled(category, util::log::ShouldDebugLog, util::log::Level::Debug, __VA_ARGS__)
Line
Count
Source
136
0
    do {                                                                                      \
137
0
        if (shouldlog(category)) {                                                            \
138
0
            detail_LogWithSrcLoc((category), (level), util::log::NO_RATE_LIMIT, __VA_ARGS__); \
Line
Count
Source
119
0
#define detail_LogWithSrcLoc(category, level, ...) util::log::LogPrintFormatInternal(SourceLocation{__func__}, category, level, __VA_ARGS__)
139
0
        }                                                                                     \
140
0
    } while (0)
        LogDebug(BCLog::ADDRMAN, "Bucketing method was updated, re-bucketing addrman entries from disk\n");
Line
Count
Source
143
0
#define LogDebug(category, ...) detail_LogIfCategoryAndLevelEnabled(category, util::log::ShouldDebugLog, util::log::Level::Debug, __VA_ARGS__)
Line
Count
Source
136
0
    do {                                                                                      \
137
0
        if (shouldlog(category)) {                                                            \
138
0
            detail_LogWithSrcLoc((category), (level), util::log::NO_RATE_LIMIT, __VA_ARGS__); \
Line
Count
Source
119
0
#define detail_LogWithSrcLoc(category, level, ...) util::log::LogPrintFormatInternal(SourceLocation{__func__}, category, level, __VA_ARGS__)
139
0
        }                                                                                     \
140
0
    } while (0)
327
0
    }
328
329
0
    for (auto bucket_entry : bucket_entries) {
330
0
        int bucket{bucket_entry.first};
331
0
        const int entry_index{bucket_entry.second};
332
0
        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
0
        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
0
        if (info.nRefCount >= ADDRMAN_NEW_BUCKETS_PER_ADDRESS) continue;
341
342
0
        int bucket_position = info.GetBucketPosition(nKey, true, bucket);
343
0
        if (restore_bucketing && vvNew[bucket][bucket_position] == -1) {
344
            // Bucketing has not changed, using existing bucket positions for the new table
345
0
            vvNew[bucket][bucket_position] = entry_index;
346
0
            ++info.nRefCount;
347
0
        } 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
0
            bucket = info.GetNewBucket(nKey, m_netgroupman);
351
0
            bucket_position = info.GetBucketPosition(nKey, true, bucket);
352
0
            if (vvNew[bucket][bucket_position] == -1) {
353
0
                vvNew[bucket][bucket_position] = entry_index;
354
0
                ++info.nRefCount;
355
0
            }
356
0
        }
357
0
    }
358
359
    // Prune new entries with refcount 0 (as a result of collisions or invalid address).
360
0
    int nLostUnk = 0;
361
0
    for (auto it = mapInfo.cbegin(); it != mapInfo.cend(); ) {
362
0
        if (it->second.fInTried == false && it->second.nRefCount == 0) {
363
0
            const auto itCopy = it++;
364
0
            Delete(itCopy->first);
365
0
            ++nLostUnk;
366
0
        } else {
367
0
            ++it;
368
0
        }
369
0
    }
370
0
    if (nLost + nLostUnk > 0) {
371
0
        LogDebug(BCLog::ADDRMAN, "addrman lost %i new and %i tried addresses due to collisions or invalid addresses\n", nLostUnk, nLost);
Line
Count
Source
143
0
#define LogDebug(category, ...) detail_LogIfCategoryAndLevelEnabled(category, util::log::ShouldDebugLog, util::log::Level::Debug, __VA_ARGS__)
Line
Count
Source
136
0
    do {                                                                                      \
137
0
        if (shouldlog(category)) {                                                            \
138
0
            detail_LogWithSrcLoc((category), (level), util::log::NO_RATE_LIMIT, __VA_ARGS__); \
Line
Count
Source
119
0
#define detail_LogWithSrcLoc(category, level, ...) util::log::LogPrintFormatInternal(SourceLocation{__func__}, category, level, __VA_ARGS__)
139
0
        }                                                                                     \
140
0
    } while (0)
        LogDebug(BCLog::ADDRMAN, "addrman lost %i new and %i tried addresses due to collisions or invalid addresses\n", nLostUnk, nLost);
Line
Count
Source
143
0
#define LogDebug(category, ...) detail_LogIfCategoryAndLevelEnabled(category, util::log::ShouldDebugLog, util::log::Level::Debug, __VA_ARGS__)
Line
Count
Source
136
0
    do {                                                                                      \
137
0
        if (shouldlog(category)) {                                                            \
138
0
            detail_LogWithSrcLoc((category), (level), util::log::NO_RATE_LIMIT, __VA_ARGS__); \
Line
Count
Source
119
0
#define detail_LogWithSrcLoc(category, level, ...) util::log::LogPrintFormatInternal(SourceLocation{__func__}, category, level, __VA_ARGS__)
139
0
        }                                                                                     \
140
0
    } while (0)
        LogDebug(BCLog::ADDRMAN, "addrman lost %i new and %i tried addresses due to collisions or invalid addresses\n", nLostUnk, nLost);
Line
Count
Source
143
0
#define LogDebug(category, ...) detail_LogIfCategoryAndLevelEnabled(category, util::log::ShouldDebugLog, util::log::Level::Debug, __VA_ARGS__)
Line
Count
Source
136
0
    do {                                                                                      \
137
0
        if (shouldlog(category)) {                                                            \
138
0
            detail_LogWithSrcLoc((category), (level), util::log::NO_RATE_LIMIT, __VA_ARGS__); \
Line
Count
Source
119
0
#define detail_LogWithSrcLoc(category, level, ...) util::log::LogPrintFormatInternal(SourceLocation{__func__}, category, level, __VA_ARGS__)
139
0
        }                                                                                     \
140
0
    } while (0)
        LogDebug(BCLog::ADDRMAN, "addrman lost %i new and %i tried addresses due to collisions or invalid addresses\n", nLostUnk, nLost);
Line
Count
Source
143
0
#define LogDebug(category, ...) detail_LogIfCategoryAndLevelEnabled(category, util::log::ShouldDebugLog, util::log::Level::Debug, __VA_ARGS__)
Line
Count
Source
136
0
    do {                                                                                      \
137
0
        if (shouldlog(category)) {                                                            \
138
0
            detail_LogWithSrcLoc((category), (level), util::log::NO_RATE_LIMIT, __VA_ARGS__); \
Line
Count
Source
119
0
#define detail_LogWithSrcLoc(category, level, ...) util::log::LogPrintFormatInternal(SourceLocation{__func__}, category, level, __VA_ARGS__)
139
0
        }                                                                                     \
140
0
    } while (0)
372
0
    }
373
374
0
    const int check_code{CheckAddrman()};
375
0
    if (check_code != 0) {
376
0
        throw std::ios_base::failure(strprintf(
Line
Count
Source
1172
0
#define strprintf tfm::format
        throw std::ios_base::failure(strprintf(
Line
Count
Source
1172
0
#define strprintf tfm::format
        throw std::ios_base::failure(strprintf(
Line
Count
Source
1172
0
#define strprintf tfm::format
        throw std::ios_base::failure(strprintf(
Line
Count
Source
1172
0
#define strprintf tfm::format
377
0
            "Corrupt data. Consistency check failed with code %s",
378
0
            check_code));
379
0
    }
380
0
}
Unexecuted instantiation: void AddrManImpl::Unserialize<AutoFile>(AutoFile&)
Unexecuted instantiation: void AddrManImpl::Unserialize<HashVerifier<AutoFile>>(HashVerifier<AutoFile>&)
Unexecuted instantiation: void AddrManImpl::Unserialize<DataStream>(DataStream&)
Unexecuted instantiation: void AddrManImpl::Unserialize<HashVerifier<DataStream>>(HashVerifier<DataStream>&)
381
382
AddrInfo* AddrManImpl::Find(const CService& addr, nid_type* pnId)
383
0
{
384
0
    AssertLockHeld(cs);
Line
Count
Source
144
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
385
386
0
    const auto it = mapAddr.find(addr);
387
0
    if (it == mapAddr.end())
388
0
        return nullptr;
389
0
    if (pnId)
390
0
        *pnId = (*it).second;
391
0
    const auto it2 = mapInfo.find((*it).second);
392
0
    if (it2 != mapInfo.end())
393
0
        return &(*it2).second;
394
0
    return nullptr;
395
0
}
396
397
AddrInfo* AddrManImpl::Create(const CAddress& addr, const CNetAddr& addrSource, nid_type* pnId)
398
0
{
399
0
    AssertLockHeld(cs);
Line
Count
Source
144
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
400
401
0
    nid_type nId = nIdCount++;
402
0
    mapInfo[nId] = AddrInfo(addr, addrSource);
403
0
    mapAddr[addr] = nId;
404
0
    mapInfo[nId].nRandomPos = vRandom.size();
405
0
    vRandom.push_back(nId);
406
0
    nNew++;
407
0
    m_network_counts[addr.GetNetwork()].n_new++;
408
0
    if (pnId)
409
0
        *pnId = nId;
410
0
    return &mapInfo[nId];
411
0
}
412
413
void AddrManImpl::SwapRandom(unsigned int nRndPos1, unsigned int nRndPos2) const
414
0
{
415
0
    AssertLockHeld(cs);
Line
Count
Source
144
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
416
417
0
    if (nRndPos1 == nRndPos2)
418
0
        return;
419
420
0
    assert(nRndPos1 < vRandom.size() && nRndPos2 < vRandom.size());
421
422
0
    nid_type nId1 = vRandom[nRndPos1];
423
0
    nid_type nId2 = vRandom[nRndPos2];
424
425
0
    const auto it_1{mapInfo.find(nId1)};
426
0
    const auto it_2{mapInfo.find(nId2)};
427
0
    assert(it_1 != mapInfo.end());
428
0
    assert(it_2 != mapInfo.end());
429
430
0
    it_1->second.nRandomPos = nRndPos2;
431
0
    it_2->second.nRandomPos = nRndPos1;
432
433
0
    vRandom[nRndPos1] = nId2;
434
0
    vRandom[nRndPos2] = nId1;
435
0
}
436
437
void AddrManImpl::Delete(nid_type nId)
438
0
{
439
0
    AssertLockHeld(cs);
Line
Count
Source
144
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
440
441
0
    assert(mapInfo.contains(nId));
442
0
    AddrInfo& info = mapInfo[nId];
443
0
    assert(!info.fInTried);
444
0
    assert(info.nRefCount == 0);
445
446
0
    SwapRandom(info.nRandomPos, vRandom.size() - 1);
447
0
    m_network_counts[info.GetNetwork()].n_new--;
448
0
    vRandom.pop_back();
449
0
    mapAddr.erase(info);
450
0
    mapInfo.erase(nId);
451
0
    nNew--;
452
0
}
453
454
void AddrManImpl::ClearNew(int nUBucket, int nUBucketPos)
455
0
{
456
0
    AssertLockHeld(cs);
Line
Count
Source
144
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
457
458
    // if there is an entry in the specified bucket, delete it.
459
0
    if (vvNew[nUBucket][nUBucketPos] != -1) {
460
0
        nid_type nIdDelete = vvNew[nUBucket][nUBucketPos];
461
0
        AddrInfo& infoDelete = mapInfo[nIdDelete];
462
0
        assert(infoDelete.nRefCount > 0);
463
0
        infoDelete.nRefCount--;
464
0
        vvNew[nUBucket][nUBucketPos] = -1;
465
0
        LogDebug(BCLog::ADDRMAN, "Removed %s from new[%i][%i]\n", infoDelete.ToStringAddrPort(), nUBucket, nUBucketPos);
Line
Count
Source
143
0
#define LogDebug(category, ...) detail_LogIfCategoryAndLevelEnabled(category, util::log::ShouldDebugLog, util::log::Level::Debug, __VA_ARGS__)
Line
Count
Source
136
0
    do {                                                                                      \
137
0
        if (shouldlog(category)) {                                                            \
138
0
            detail_LogWithSrcLoc((category), (level), util::log::NO_RATE_LIMIT, __VA_ARGS__); \
Line
Count
Source
119
0
#define detail_LogWithSrcLoc(category, level, ...) util::log::LogPrintFormatInternal(SourceLocation{__func__}, category, level, __VA_ARGS__)
139
0
        }                                                                                     \
140
0
    } while (0)
466
0
        if (infoDelete.nRefCount == 0) {
467
0
            Delete(nIdDelete);
468
0
        }
469
0
    }
470
0
}
471
472
void AddrManImpl::MakeTried(AddrInfo& info, nid_type nId)
473
0
{
474
0
    AssertLockHeld(cs);
Line
Count
Source
144
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
475
476
    // remove the entry from all new buckets
477
0
    const int start_bucket{info.GetNewBucket(nKey, m_netgroupman)};
478
0
    for (int n = 0; n < ADDRMAN_NEW_BUCKET_COUNT; ++n) {
479
0
        const int bucket{(start_bucket + n) % ADDRMAN_NEW_BUCKET_COUNT};
480
0
        const int pos{info.GetBucketPosition(nKey, true, bucket)};
481
0
        if (vvNew[bucket][pos] == nId) {
482
0
            vvNew[bucket][pos] = -1;
483
0
            info.nRefCount--;
484
0
            if (info.nRefCount == 0) break;
485
0
        }
486
0
    }
487
0
    nNew--;
488
0
    m_network_counts[info.GetNetwork()].n_new--;
489
490
0
    assert(info.nRefCount == 0);
491
492
    // which tried bucket to move the entry to
493
0
    int nKBucket = info.GetTriedBucket(nKey, m_netgroupman);
494
0
    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
0
    if (vvTried[nKBucket][nKBucketPos] != -1) {
498
        // find an item to evict
499
0
        nid_type nIdEvict = vvTried[nKBucket][nKBucketPos];
500
0
        assert(mapInfo.contains(nIdEvict));
501
0
        AddrInfo& infoOld = mapInfo[nIdEvict];
502
503
        // Remove the to-be-evicted item from the tried set.
504
0
        infoOld.fInTried = false;
505
0
        vvTried[nKBucket][nKBucketPos] = -1;
506
0
        nTried--;
507
0
        m_network_counts[infoOld.GetNetwork()].n_tried--;
508
509
        // find which new bucket it belongs to
510
0
        int nUBucket = infoOld.GetNewBucket(nKey, m_netgroupman);
511
0
        int nUBucketPos = infoOld.GetBucketPosition(nKey, true, nUBucket);
512
0
        ClearNew(nUBucket, nUBucketPos);
513
0
        assert(vvNew[nUBucket][nUBucketPos] == -1);
514
515
        // Enter it into the new set again.
516
0
        infoOld.nRefCount = 1;
517
0
        vvNew[nUBucket][nUBucketPos] = nIdEvict;
518
0
        nNew++;
519
0
        m_network_counts[infoOld.GetNetwork()].n_new++;
520
0
        LogDebug(BCLog::ADDRMAN, "Moved %s from tried[%i][%i] to new[%i][%i] to make space\n",
Line
Count
Source
143
0
#define LogDebug(category, ...) detail_LogIfCategoryAndLevelEnabled(category, util::log::ShouldDebugLog, util::log::Level::Debug, __VA_ARGS__)
Line
Count
Source
136
0
    do {                                                                                      \
137
0
        if (shouldlog(category)) {                                                            \
138
0
            detail_LogWithSrcLoc((category), (level), util::log::NO_RATE_LIMIT, __VA_ARGS__); \
Line
Count
Source
119
0
#define detail_LogWithSrcLoc(category, level, ...) util::log::LogPrintFormatInternal(SourceLocation{__func__}, category, level, __VA_ARGS__)
139
0
        }                                                                                     \
140
0
    } while (0)
521
0
                 infoOld.ToStringAddrPort(), nKBucket, nKBucketPos, nUBucket, nUBucketPos);
522
0
    }
523
0
    assert(vvTried[nKBucket][nKBucketPos] == -1);
524
525
0
    vvTried[nKBucket][nKBucketPos] = nId;
526
0
    nTried++;
527
0
    info.fInTried = true;
528
0
    m_network_counts[info.GetNetwork()].n_tried++;
529
0
}
530
531
bool AddrManImpl::AddSingle(const CAddress& addr, const CNetAddr& source, std::chrono::seconds time_penalty)
532
0
{
533
0
    AssertLockHeld(cs);
Line
Count
Source
144
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
534
535
0
    if (!addr.IsRoutable())
536
0
        return false;
537
538
0
    nid_type nId;
539
0
    AddrInfo* pinfo = Find(addr, &nId);
540
541
    // Do not set a penalty for a source's self-announcement
542
0
    if (addr == source) {
543
0
        time_penalty = 0s;
544
0
    }
545
546
0
    if (pinfo) {
547
        // periodically update nTime
548
0
        const bool currently_online{NodeClock::now() - addr.nTime < 24h};
549
0
        const auto update_interval{currently_online ? 1h : 24h};
550
0
        if (pinfo->nTime < addr.nTime - update_interval - time_penalty) {
551
0
            pinfo->nTime = std::max(NodeSeconds{0s}, addr.nTime - time_penalty);
552
0
        }
553
554
        // add services
555
0
        pinfo->nServices = ServiceFlags(pinfo->nServices | addr.nServices);
556
557
        // do not update if no new information is present
558
0
        if (addr.nTime <= pinfo->nTime) {
559
0
            return false;
560
0
        }
561
562
        // do not update if the entry was already in the "tried" table
563
0
        if (pinfo->fInTried)
564
0
            return false;
565
566
        // do not update if the max reference count is reached
567
0
        if (pinfo->nRefCount == ADDRMAN_NEW_BUCKETS_PER_ADDRESS)
568
0
            return false;
569
570
        // stochastic test: previous nRefCount == N: 2^N times harder to increase it
571
0
        if (pinfo->nRefCount > 0) {
572
0
            const int nFactor{1 << pinfo->nRefCount};
573
0
            if (insecure_rand.randrange(nFactor) != 0) return false;
574
0
        }
575
0
    } else {
576
0
        pinfo = Create(addr, source, &nId);
577
0
        pinfo->nTime = std::max(NodeSeconds{0s}, pinfo->nTime - time_penalty);
578
0
    }
579
580
0
    int nUBucket = pinfo->GetNewBucket(nKey, source, m_netgroupman);
581
0
    int nUBucketPos = pinfo->GetBucketPosition(nKey, true, nUBucket);
582
0
    bool fInsert = vvNew[nUBucket][nUBucketPos] == -1;
583
0
    if (vvNew[nUBucket][nUBucketPos] != nId) {
584
0
        if (!fInsert) {
585
0
            AddrInfo& infoExisting = mapInfo[vvNew[nUBucket][nUBucketPos]];
586
0
            if (infoExisting.IsTerrible() || (infoExisting.nRefCount > 1 && pinfo->nRefCount == 0)) {
587
                // Overwrite the existing new table entry.
588
0
                fInsert = true;
589
0
            }
590
0
        }
591
0
        if (fInsert) {
592
0
            ClearNew(nUBucket, nUBucketPos);
593
0
            pinfo->nRefCount++;
594
0
            vvNew[nUBucket][nUBucketPos] = nId;
595
0
            const auto mapped_as{m_netgroupman.GetMappedAS(addr)};
596
0
            LogDebug(BCLog::ADDRMAN, "Added %s%s to new[%i][%i]\n",
Line
Count
Source
143
0
#define LogDebug(category, ...) detail_LogIfCategoryAndLevelEnabled(category, util::log::ShouldDebugLog, util::log::Level::Debug, __VA_ARGS__)
Line
Count
Source
136
0
    do {                                                                                      \
137
0
        if (shouldlog(category)) {                                                            \
138
0
            detail_LogWithSrcLoc((category), (level), util::log::NO_RATE_LIMIT, __VA_ARGS__); \
Line
Count
Source
119
0
#define detail_LogWithSrcLoc(category, level, ...) util::log::LogPrintFormatInternal(SourceLocation{__func__}, category, level, __VA_ARGS__)
139
0
        }                                                                                     \
140
0
    } while (0)
597
0
                     addr.ToStringAddrPort(), (mapped_as ? strprintf(" mapped to AS%i", mapped_as) : ""), nUBucket, nUBucketPos);
598
0
        } else {
599
0
            if (pinfo->nRefCount == 0) {
600
0
                Delete(nId);
601
0
            }
602
0
        }
603
0
    }
604
0
    return fInsert;
605
0
}
606
607
bool AddrManImpl::Good_(const CService& addr, bool test_before_evict, NodeSeconds time)
608
0
{
609
0
    AssertLockHeld(cs);
Line
Count
Source
144
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
610
611
0
    nid_type nId;
612
613
0
    m_last_good = time;
614
615
0
    AddrInfo* pinfo = Find(addr, &nId);
616
617
    // if not found, bail out
618
0
    if (!pinfo) return false;
619
620
0
    AddrInfo& info = *pinfo;
621
622
    // update info
623
0
    info.m_last_success = time;
624
0
    info.m_last_try = time;
625
0
    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
0
    if (info.fInTried) return false;
631
632
    // if it is not in new, something bad happened
633
0
    if (!Assume(info.nRefCount > 0)) return false;
Line
Count
Source
128
0
#define Assume(val) inline_assertion_check<false>(val, std::source_location::current(), #val)
634
635
636
    // which tried bucket to move the entry to
637
0
    int tried_bucket = info.GetTriedBucket(nKey, m_netgroupman);
638
0
    int tried_bucket_pos = info.GetBucketPosition(nKey, false, tried_bucket);
639
640
    // Will moving this address into tried evict another entry?
641
0
    if (test_before_evict && (vvTried[tried_bucket][tried_bucket_pos] != -1)) {
642
0
        if (m_tried_collisions.size() < ADDRMAN_SET_TRIED_COLLISION_SIZE) {
643
0
            m_tried_collisions.insert(nId);
644
0
        }
645
        // Output the entry we'd be colliding with, for debugging purposes
646
0
        auto colliding_entry = mapInfo.find(vvTried[tried_bucket][tried_bucket_pos]);
647
0
        LogDebug(BCLog::ADDRMAN, "Collision with %s while attempting to move %s to tried table. Collisions=%d",
Line
Count
Source
143
0
#define LogDebug(category, ...) detail_LogIfCategoryAndLevelEnabled(category, util::log::ShouldDebugLog, util::log::Level::Debug, __VA_ARGS__)
Line
Count
Source
136
0
    do {                                                                                      \
137
0
        if (shouldlog(category)) {                                                            \
138
0
            detail_LogWithSrcLoc((category), (level), util::log::NO_RATE_LIMIT, __VA_ARGS__); \
Line
Count
Source
119
0
#define detail_LogWithSrcLoc(category, level, ...) util::log::LogPrintFormatInternal(SourceLocation{__func__}, category, level, __VA_ARGS__)
139
0
        }                                                                                     \
140
0
    } while (0)
648
0
                 colliding_entry != mapInfo.end() ? colliding_entry->second.ToStringAddrPort() : "<unknown-addr>",
649
0
                 addr.ToStringAddrPort(),
650
0
                 m_tried_collisions.size());
651
0
        return false;
652
0
    } else {
653
        // move nId to the tried tables
654
0
        MakeTried(info, nId);
655
0
        const auto mapped_as{m_netgroupman.GetMappedAS(addr)};
656
0
        LogDebug(BCLog::ADDRMAN, "Moved %s%s to tried[%i][%i]\n",
Line
Count
Source
143
0
#define LogDebug(category, ...) detail_LogIfCategoryAndLevelEnabled(category, util::log::ShouldDebugLog, util::log::Level::Debug, __VA_ARGS__)
Line
Count
Source
136
0
    do {                                                                                      \
137
0
        if (shouldlog(category)) {                                                            \
138
0
            detail_LogWithSrcLoc((category), (level), util::log::NO_RATE_LIMIT, __VA_ARGS__); \
Line
Count
Source
119
0
#define detail_LogWithSrcLoc(category, level, ...) util::log::LogPrintFormatInternal(SourceLocation{__func__}, category, level, __VA_ARGS__)
139
0
        }                                                                                     \
140
0
    } while (0)
657
0
                 addr.ToStringAddrPort(), (mapped_as ? strprintf(" mapped to AS%i", mapped_as) : ""), tried_bucket, tried_bucket_pos);
658
0
        return true;
659
0
    }
660
0
}
661
662
bool AddrManImpl::Add_(const std::vector<CAddress>& vAddr, const CNetAddr& source, std::chrono::seconds time_penalty)
663
0
{
664
0
    int added{0};
665
0
    for (std::vector<CAddress>::const_iterator it = vAddr.begin(); it != vAddr.end(); it++) {
666
0
        added += AddSingle(*it, source, time_penalty) ? 1 : 0;
667
0
    }
668
0
    if (added > 0) {
669
0
        LogDebug(BCLog::ADDRMAN, "Added %i addresses (of %i) from %s: %i tried, %i new\n", added, vAddr.size(), source.ToStringAddr(), nTried, nNew);
Line
Count
Source
143
0
#define LogDebug(category, ...) detail_LogIfCategoryAndLevelEnabled(category, util::log::ShouldDebugLog, util::log::Level::Debug, __VA_ARGS__)
Line
Count
Source
136
0
    do {                                                                                      \
137
0
        if (shouldlog(category)) {                                                            \
138
0
            detail_LogWithSrcLoc((category), (level), util::log::NO_RATE_LIMIT, __VA_ARGS__); \
Line
Count
Source
119
0
#define detail_LogWithSrcLoc(category, level, ...) util::log::LogPrintFormatInternal(SourceLocation{__func__}, category, level, __VA_ARGS__)
139
0
        }                                                                                     \
140
0
    } while (0)
670
0
    }
671
0
    return added > 0;
672
0
}
673
674
void AddrManImpl::Attempt_(const CService& addr, bool fCountFailure, NodeSeconds time)
675
0
{
676
0
    AssertLockHeld(cs);
Line
Count
Source
144
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
677
678
0
    AddrInfo* pinfo = Find(addr);
679
680
    // if not found, bail out
681
0
    if (!pinfo)
682
0
        return;
683
684
0
    AddrInfo& info = *pinfo;
685
686
    // update info
687
0
    info.m_last_try = time;
688
0
    if (fCountFailure && info.m_last_count_attempt < m_last_good) {
689
0
        info.m_last_count_attempt = time;
690
0
        info.nAttempts++;
691
0
    }
692
0
}
693
694
std::pair<CAddress, NodeSeconds> AddrManImpl::Select_(bool new_only, const std::unordered_set<Network>& networks) const
695
0
{
696
0
    AssertLockHeld(cs);
Line
Count
Source
144
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
697
698
0
    if (vRandom.empty()) return {};
699
700
0
    size_t new_count = nNew;
701
0
    size_t tried_count = nTried;
702
703
0
    if (!networks.empty()) {
704
0
        new_count = 0;
705
0
        tried_count = 0;
706
0
        for (auto& network : networks) {
707
0
            auto it = m_network_counts.find(network);
708
0
            if (it == m_network_counts.end()) {
709
0
                continue;
710
0
            }
711
0
            auto counts = it->second;
712
0
            new_count += counts.n_new;
713
0
            tried_count += counts.n_tried;
714
0
        }
715
0
    }
716
717
0
    if (new_only && new_count == 0) return {};
718
0
    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
0
    bool search_tried;
723
0
    if (new_only || tried_count == 0) {
724
0
        search_tried = false;
725
0
    } else if (new_count == 0) {
726
0
        search_tried = true;
727
0
    } else {
728
0
        search_tried = insecure_rand.randbool();
729
0
    }
730
731
0
    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
0
    double chance_factor = 1.0;
735
0
    while (1) {
736
        // Pick a bucket, and an initial position in that bucket.
737
0
        int bucket = insecure_rand.randrange(bucket_count);
738
0
        int initial_position = insecure_rand.randrange(ADDRMAN_BUCKET_SIZE);
739
740
        // Iterate over the positions of that bucket, starting at the initial one,
741
        // and looping around.
742
0
        int i, position;
743
0
        nid_type node_id;
744
0
        for (i = 0; i < ADDRMAN_BUCKET_SIZE; ++i) {
745
0
            position = (initial_position + i) % ADDRMAN_BUCKET_SIZE;
746
0
            node_id = GetEntry(search_tried, bucket, position);
747
0
            if (node_id != -1) {
748
0
                if (!networks.empty()) {
749
0
                    const auto it{mapInfo.find(node_id)};
750
0
                    if (Assume(it != mapInfo.end()) && networks.contains(it->second.GetNetwork())) break;
Line
Count
Source
128
0
#define Assume(val) inline_assertion_check<false>(val, std::source_location::current(), #val)
751
0
                } else {
752
0
                    break;
753
0
                }
754
0
            }
755
0
        }
756
757
        // If the bucket is entirely empty, start over with a (likely) different one.
758
0
        if (i == ADDRMAN_BUCKET_SIZE) continue;
759
760
        // Find the entry to return.
761
0
        const auto it_found{mapInfo.find(node_id)};
762
0
        assert(it_found != mapInfo.end());
763
0
        const AddrInfo& info{it_found->second};
764
765
        // With probability GetChance() * chance_factor, return the entry.
766
0
        if (insecure_rand.randbits<30>() < chance_factor * info.GetChance() * (1 << 30)) {
767
0
            LogDebug(BCLog::ADDRMAN, "Selected %s from %s\n", info.ToStringAddrPort(), search_tried ? "tried" : "new");
Line
Count
Source
143
0
#define LogDebug(category, ...) detail_LogIfCategoryAndLevelEnabled(category, util::log::ShouldDebugLog, util::log::Level::Debug, __VA_ARGS__)
Line
Count
Source
136
0
    do {                                                                                      \
137
0
        if (shouldlog(category)) {                                                            \
138
0
            detail_LogWithSrcLoc((category), (level), util::log::NO_RATE_LIMIT, __VA_ARGS__); \
Line
Count
Source
119
0
#define detail_LogWithSrcLoc(category, level, ...) util::log::LogPrintFormatInternal(SourceLocation{__func__}, category, level, __VA_ARGS__)
139
0
        }                                                                                     \
140
0
    } while (0)
768
0
            return {info, info.m_last_try};
769
0
        }
770
771
        // Otherwise start over with a (likely) different bucket, and increased chance factor.
772
0
        chance_factor *= 1.2;
773
0
    }
774
0
}
775
776
nid_type AddrManImpl::GetEntry(bool use_tried, size_t bucket, size_t position) const
777
0
{
778
0
    AssertLockHeld(cs);
Line
Count
Source
144
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
779
780
0
    if (use_tried) {
781
0
        if (Assume(position < ADDRMAN_BUCKET_SIZE) && Assume(bucket < ADDRMAN_TRIED_BUCKET_COUNT)) {
Line
Count
Source
128
0
#define Assume(val) inline_assertion_check<false>(val, std::source_location::current(), #val)
        if (Assume(position < ADDRMAN_BUCKET_SIZE) && Assume(bucket < ADDRMAN_TRIED_BUCKET_COUNT)) {
Line
Count
Source
128
0
#define Assume(val) inline_assertion_check<false>(val, std::source_location::current(), #val)
782
0
            return vvTried[bucket][position];
783
0
        }
784
0
    } else {
785
0
        if (Assume(position < ADDRMAN_BUCKET_SIZE) && Assume(bucket < ADDRMAN_NEW_BUCKET_COUNT)) {
Line
Count
Source
128
0
#define Assume(val) inline_assertion_check<false>(val, std::source_location::current(), #val)
        if (Assume(position < ADDRMAN_BUCKET_SIZE) && Assume(bucket < ADDRMAN_NEW_BUCKET_COUNT)) {
Line
Count
Source
128
0
#define Assume(val) inline_assertion_check<false>(val, std::source_location::current(), #val)
786
0
            return vvNew[bucket][position];
787
0
        }
788
0
    }
789
790
0
    return -1;
791
0
}
792
793
std::vector<CAddress> AddrManImpl::GetAddr_(size_t max_addresses, size_t max_pct, std::optional<Network> network, const bool filtered) const
794
0
{
795
0
    AssertLockHeld(cs);
Line
Count
Source
144
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
796
0
    Assume(max_pct <= 100);
Line
Count
Source
128
0
#define Assume(val) inline_assertion_check<false>(val, std::source_location::current(), #val)
797
798
0
    size_t nNodes = vRandom.size();
799
0
    if (max_pct != 0) {
800
0
        max_pct = std::min(max_pct, size_t{100});
801
0
        nNodes = max_pct * nNodes / 100;
802
0
    }
803
0
    if (max_addresses != 0) {
804
0
        nNodes = std::min(nNodes, max_addresses);
805
0
    }
806
807
    // gather a list of random nodes, skipping those of low quality
808
0
    const auto now{Now<NodeSeconds>()};
809
0
    std::vector<CAddress> addresses;
810
0
    addresses.reserve(nNodes);
811
0
    for (unsigned int n = 0; n < vRandom.size(); n++) {
812
0
        if (addresses.size() >= nNodes)
813
0
            break;
814
815
0
        int nRndPos = insecure_rand.randrange(vRandom.size() - n) + n;
816
0
        SwapRandom(n, nRndPos);
817
0
        const auto it{mapInfo.find(vRandom[n])};
818
0
        assert(it != mapInfo.end());
819
820
0
        const AddrInfo& ai{it->second};
821
822
        // Filter by network (optional)
823
0
        if (network != std::nullopt && ai.GetNetClass() != network) continue;
824
825
        // Filter for quality
826
0
        if (ai.IsTerrible(now) && filtered) continue;
827
828
0
        addresses.push_back(ai);
829
0
    }
830
0
    LogDebug(BCLog::ADDRMAN, "GetAddr returned %d random addresses\n", addresses.size());
Line
Count
Source
143
0
#define LogDebug(category, ...) detail_LogIfCategoryAndLevelEnabled(category, util::log::ShouldDebugLog, util::log::Level::Debug, __VA_ARGS__)
Line
Count
Source
136
0
    do {                                                                                      \
137
0
        if (shouldlog(category)) {                                                            \
138
0
            detail_LogWithSrcLoc((category), (level), util::log::NO_RATE_LIMIT, __VA_ARGS__); \
Line
Count
Source
119
0
#define detail_LogWithSrcLoc(category, level, ...) util::log::LogPrintFormatInternal(SourceLocation{__func__}, category, level, __VA_ARGS__)
139
0
        }                                                                                     \
140
0
    } while (0)
831
0
    return addresses;
832
0
}
833
834
std::vector<std::pair<AddrInfo, AddressPosition>> AddrManImpl::GetEntries_(bool from_tried) const
835
0
{
836
0
    AssertLockHeld(cs);
Line
Count
Source
144
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
837
838
0
    const int bucket_count = from_tried ? ADDRMAN_TRIED_BUCKET_COUNT : ADDRMAN_NEW_BUCKET_COUNT;
839
0
    std::vector<std::pair<AddrInfo, AddressPosition>> infos;
840
0
    for (int bucket = 0; bucket < bucket_count; ++bucket) {
841
0
        for (int position = 0; position < ADDRMAN_BUCKET_SIZE; ++position) {
842
0
            nid_type id = GetEntry(from_tried, bucket, position);
843
0
            if (id >= 0) {
844
0
                AddrInfo info = mapInfo.at(id);
845
0
                AddressPosition location = AddressPosition(
846
0
                    from_tried,
847
0
                    /*multiplicity_in=*/from_tried ? 1 : info.nRefCount,
848
0
                    bucket,
849
0
                    position);
850
0
                infos.emplace_back(info, location);
851
0
            }
852
0
        }
853
0
    }
854
855
0
    return infos;
856
0
}
857
858
void AddrManImpl::Connected_(const CService& addr, NodeSeconds time)
859
0
{
860
0
    AssertLockHeld(cs);
Line
Count
Source
144
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
861
862
0
    AddrInfo* pinfo = Find(addr);
863
864
    // if not found, bail out
865
0
    if (!pinfo)
866
0
        return;
867
868
0
    AddrInfo& info = *pinfo;
869
870
    // update info
871
0
    const auto update_interval{20min};
872
0
    if (time - info.nTime > update_interval) {
873
0
        info.nTime = time;
874
0
    }
875
0
}
876
877
void AddrManImpl::SetServices_(const CService& addr, ServiceFlags nServices)
878
0
{
879
0
    AssertLockHeld(cs);
Line
Count
Source
144
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
880
881
0
    AddrInfo* pinfo = Find(addr);
882
883
    // if not found, bail out
884
0
    if (!pinfo)
885
0
        return;
886
887
0
    AddrInfo& info = *pinfo;
888
889
    // update info
890
0
    info.nServices = nServices;
891
0
}
892
893
void AddrManImpl::ResolveCollisions_()
894
0
{
895
0
    AssertLockHeld(cs);
Line
Count
Source
144
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
896
897
0
    for (std::set<nid_type>::iterator it = m_tried_collisions.begin(); it != m_tried_collisions.end();) {
898
0
        nid_type id_new = *it;
899
900
0
        bool erase_collision = false;
901
902
        // If id_new not found in mapInfo remove it from m_tried_collisions
903
0
        if (!mapInfo.contains(id_new)) {
904
0
            erase_collision = true;
905
0
        } else {
906
0
            AddrInfo& info_new = mapInfo[id_new];
907
908
            // Which tried bucket to move the entry to.
909
0
            int tried_bucket = info_new.GetTriedBucket(nKey, m_netgroupman);
910
0
            int tried_bucket_pos = info_new.GetBucketPosition(nKey, false, tried_bucket);
911
0
            if (!info_new.IsValid()) { // id_new may no longer map to a valid address
912
0
                erase_collision = true;
913
0
            } else {
914
                // A pending tried collision implies that the destination tried slot
915
                // remains occupied until we resolve it.
916
0
                Assume(vvTried[tried_bucket][tried_bucket_pos] != -1);
Line
Count
Source
128
0
#define Assume(val) inline_assertion_check<false>(val, std::source_location::current(), #val)
917
918
                // Get the to-be-evicted address that is being tested
919
0
                nid_type id_old = vvTried[tried_bucket][tried_bucket_pos];
920
0
                AddrInfo& info_old = mapInfo[id_old];
921
922
0
                const auto current_time{Now<NodeSeconds>()};
923
924
                // Has successfully connected in last X hours
925
0
                if (current_time - info_old.m_last_success < ADDRMAN_REPLACEMENT) {
926
0
                    erase_collision = true;
927
0
                } else if (current_time - info_old.m_last_try < ADDRMAN_REPLACEMENT) { // attempted to connect and failed in last X hours
928
929
                    // Give address at least 60 seconds to successfully connect
930
0
                    if (current_time - info_old.m_last_try > 60s) {
931
0
                        LogDebug(BCLog::ADDRMAN, "Replacing %s with %s in tried table\n", info_old.ToStringAddrPort(), info_new.ToStringAddrPort());
Line
Count
Source
143
0
#define LogDebug(category, ...) detail_LogIfCategoryAndLevelEnabled(category, util::log::ShouldDebugLog, util::log::Level::Debug, __VA_ARGS__)
Line
Count
Source
136
0
    do {                                                                                      \
137
0
        if (shouldlog(category)) {                                                            \
138
0
            detail_LogWithSrcLoc((category), (level), util::log::NO_RATE_LIMIT, __VA_ARGS__); \
Line
Count
Source
119
0
#define detail_LogWithSrcLoc(category, level, ...) util::log::LogPrintFormatInternal(SourceLocation{__func__}, category, level, __VA_ARGS__)
139
0
        }                                                                                     \
140
0
    } while (0)
932
933
                        // Replaces an existing address already in the tried table with the new address
934
0
                        Good_(info_new, false, current_time);
935
0
                        erase_collision = true;
936
0
                    }
937
0
                } else if (current_time - info_new.m_last_success > ADDRMAN_TEST_WINDOW) {
938
                    // If the collision hasn't resolved in some reasonable amount of time,
939
                    // just evict the old entry -- we must not be able to
940
                    // connect to it for some reason.
941
0
                    LogDebug(BCLog::ADDRMAN, "Unable to test; replacing %s with %s in tried table anyway\n", info_old.ToStringAddrPort(), info_new.ToStringAddrPort());
Line
Count
Source
143
0
#define LogDebug(category, ...) detail_LogIfCategoryAndLevelEnabled(category, util::log::ShouldDebugLog, util::log::Level::Debug, __VA_ARGS__)
Line
Count
Source
136
0
    do {                                                                                      \
137
0
        if (shouldlog(category)) {                                                            \
138
0
            detail_LogWithSrcLoc((category), (level), util::log::NO_RATE_LIMIT, __VA_ARGS__); \
Line
Count
Source
119
0
#define detail_LogWithSrcLoc(category, level, ...) util::log::LogPrintFormatInternal(SourceLocation{__func__}, category, level, __VA_ARGS__)
139
0
        }                                                                                     \
140
0
    } while (0)
942
0
                    Good_(info_new, false, current_time);
943
0
                    erase_collision = true;
944
0
                }
945
0
            }
946
0
        }
947
948
0
        if (erase_collision) {
949
0
            m_tried_collisions.erase(it++);
950
0
        } else {
951
0
            it++;
952
0
        }
953
0
    }
954
0
}
955
956
std::pair<CAddress, NodeSeconds> AddrManImpl::SelectTriedCollision_()
957
0
{
958
0
    AssertLockHeld(cs);
Line
Count
Source
144
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
959
960
0
    if (m_tried_collisions.size() == 0) return {};
961
962
0
    std::set<nid_type>::iterator it = m_tried_collisions.begin();
963
964
    // Selects a random element from m_tried_collisions
965
0
    std::advance(it, insecure_rand.randrange(m_tried_collisions.size()));
966
0
    nid_type id_new = *it;
967
968
    // If id_new not found in mapInfo remove it from m_tried_collisions
969
0
    if (!mapInfo.contains(id_new)) {
970
0
        m_tried_collisions.erase(it);
971
0
        return {};
972
0
    }
973
974
0
    const AddrInfo& newInfo = mapInfo[id_new];
975
976
    // which tried bucket to move the entry to
977
0
    int tried_bucket = newInfo.GetTriedBucket(nKey, m_netgroupman);
978
0
    int tried_bucket_pos = newInfo.GetBucketPosition(nKey, false, tried_bucket);
979
980
0
    Assume(vvTried[tried_bucket][tried_bucket_pos] != -1);
Line
Count
Source
128
0
#define Assume(val) inline_assertion_check<false>(val, std::source_location::current(), #val)
981
0
    const AddrInfo& info_old = mapInfo[vvTried[tried_bucket][tried_bucket_pos]];
982
0
    return {info_old, info_old.m_last_try};
983
0
}
984
985
std::optional<AddressPosition> AddrManImpl::FindAddressEntry_(const CAddress& addr)
986
0
{
987
0
    AssertLockHeld(cs);
Line
Count
Source
144
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
988
989
0
    AddrInfo* addr_info = Find(addr);
990
991
0
    if (!addr_info) return std::nullopt;
992
993
0
    if(addr_info->fInTried) {
994
0
        int bucket{addr_info->GetTriedBucket(nKey, m_netgroupman)};
995
0
        return AddressPosition(/*tried_in=*/true,
996
0
                               /*multiplicity_in=*/1,
997
0
                               /*bucket_in=*/bucket,
998
0
                               /*position_in=*/addr_info->GetBucketPosition(nKey, false, bucket));
999
0
    } else {
1000
0
        int bucket{addr_info->GetNewBucket(nKey, m_netgroupman)};
1001
0
        return AddressPosition(/*tried_in=*/false,
1002
0
                               /*multiplicity_in=*/addr_info->nRefCount,
1003
0
                               /*bucket_in=*/bucket,
1004
0
                               /*position_in=*/addr_info->GetBucketPosition(nKey, true, bucket));
1005
0
    }
1006
0
}
1007
1008
size_t AddrManImpl::Size_(std::optional<Network> net, std::optional<bool> in_new) const
1009
0
{
1010
0
    AssertLockHeld(cs);
Line
Count
Source
144
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
1011
1012
0
    if (!net.has_value()) {
1013
0
        if (in_new.has_value()) {
1014
0
            return *in_new ? nNew : nTried;
1015
0
        } else {
1016
0
            return vRandom.size();
1017
0
        }
1018
0
    }
1019
0
    if (auto it = m_network_counts.find(*net); it != m_network_counts.end()) {
1020
0
        auto net_count = it->second;
1021
0
        if (in_new.has_value()) {
1022
0
            return *in_new ? net_count.n_new : net_count.n_tried;
1023
0
        } else {
1024
0
            return net_count.n_new + net_count.n_tried;
1025
0
        }
1026
0
    }
1027
0
    return 0;
1028
0
}
1029
1030
void AddrManImpl::Check() const
1031
0
{
1032
0
    AssertLockHeld(cs);
Line
Count
Source
144
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
1033
1034
    // Run consistency checks 1 in m_consistency_check_ratio times if enabled
1035
0
    if (m_consistency_check_ratio == 0) return;
1036
0
    if (insecure_rand.randrange(m_consistency_check_ratio) >= 1) return;
1037
1038
0
    const int err{CheckAddrman()};
1039
0
    if (err) {
1040
0
        LogError("ADDRMAN CONSISTENCY CHECK FAILED!!! err=%i", err);
Line
Count
Source
127
0
#define LogError(...) detail_LogWithSrcLoc(BCLog::LogFlags::ALL, util::log::Level::Error, __VA_ARGS__)
Line
Count
Source
119
0
#define detail_LogWithSrcLoc(category, level, ...) util::log::LogPrintFormatInternal(SourceLocation{__func__}, category, level, __VA_ARGS__)
1041
0
        assert(false);
1042
0
    }
1043
0
}
1044
1045
int AddrManImpl::CheckAddrman() const
1046
0
{
1047
0
    AssertLockHeld(cs);
Line
Count
Source
144
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
1048
1049
0
    LOG_TIME_MILLIS_WITH_CATEGORY_MSG_ONCE(
Line
Count
Source
106
0
    BCLog::Timer<std::chrono::milliseconds> BITCOIN_UNIQUE_NAME(logging_timer)(__func__, end_msg, log_category, /* msg_on_completion=*/false)
Line
Count
Source
11
0
#define BITCOIN_UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
1050
0
        strprintf("new %i, tried %i, total %u", nNew, nTried, vRandom.size()), BCLog::ADDRMAN);
1051
1052
0
    std::unordered_set<nid_type> setTried;
1053
0
    std::unordered_map<nid_type, int> mapNew;
1054
0
    std::unordered_map<Network, NewTriedCount> local_counts;
1055
1056
0
    if (vRandom.size() != (size_t)(nTried + nNew))
1057
0
        return -7;
1058
1059
0
    for (const auto& entry : mapInfo) {
1060
0
        nid_type n = entry.first;
1061
0
        const AddrInfo& info = entry.second;
1062
0
        if (info.fInTried) {
1063
0
            if (!TicksSinceEpoch<std::chrono::seconds>(info.m_last_success)) {
1064
0
                return -1;
1065
0
            }
1066
0
            if (info.nRefCount)
1067
0
                return -2;
1068
0
            setTried.insert(n);
1069
0
            local_counts[info.GetNetwork()].n_tried++;
1070
0
        } else {
1071
0
            if (info.nRefCount < 0 || info.nRefCount > ADDRMAN_NEW_BUCKETS_PER_ADDRESS)
1072
0
                return -3;
1073
0
            if (!info.nRefCount)
1074
0
                return -4;
1075
0
            mapNew[n] = info.nRefCount;
1076
0
            local_counts[info.GetNetwork()].n_new++;
1077
0
        }
1078
0
        const auto it{mapAddr.find(info)};
1079
0
        if (it == mapAddr.end() || it->second != n) {
1080
0
            return -5;
1081
0
        }
1082
0
        if (info.nRandomPos < 0 || (size_t)info.nRandomPos >= vRandom.size() || vRandom[info.nRandomPos] != n)
1083
0
            return -14;
1084
0
        if (info.m_last_try < NodeSeconds{0s}) {
1085
0
            return -6;
1086
0
        }
1087
0
        if (info.m_last_success < NodeSeconds{0s}) {
1088
0
            return -8;
1089
0
        }
1090
0
    }
1091
1092
0
    if (setTried.size() != (size_t)nTried)
1093
0
        return -9;
1094
0
    if (mapNew.size() != (size_t)nNew)
1095
0
        return -10;
1096
1097
0
    for (int n = 0; n < ADDRMAN_TRIED_BUCKET_COUNT; n++) {
1098
0
        for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) {
1099
0
            if (vvTried[n][i] != -1) {
1100
0
                if (!setTried.contains(vvTried[n][i]))
1101
0
                    return -11;
1102
0
                const auto it{mapInfo.find(vvTried[n][i])};
1103
0
                if (it == mapInfo.end() || it->second.GetTriedBucket(nKey, m_netgroupman) != n) {
1104
0
                    return -17;
1105
0
                }
1106
0
                if (it->second.GetBucketPosition(nKey, false, n) != i) {
1107
0
                    return -18;
1108
0
                }
1109
0
                setTried.erase(vvTried[n][i]);
1110
0
            }
1111
0
        }
1112
0
    }
1113
1114
0
    for (int n = 0; n < ADDRMAN_NEW_BUCKET_COUNT; n++) {
1115
0
        for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) {
1116
0
            if (vvNew[n][i] != -1) {
1117
0
                if (!mapNew.contains(vvNew[n][i]))
1118
0
                    return -12;
1119
0
                const auto it{mapInfo.find(vvNew[n][i])};
1120
0
                if (it == mapInfo.end() || it->second.GetBucketPosition(nKey, true, n) != i) {
1121
0
                    return -19;
1122
0
                }
1123
0
                if (--mapNew[vvNew[n][i]] == 0)
1124
0
                    mapNew.erase(vvNew[n][i]);
1125
0
            }
1126
0
        }
1127
0
    }
1128
1129
0
    if (setTried.size())
1130
0
        return -13;
1131
0
    if (mapNew.size())
1132
0
        return -15;
1133
0
    if (nKey.IsNull())
1134
0
        return -16;
1135
1136
    // It's possible that m_network_counts may have all-zero entries that local_counts
1137
    // doesn't have if addrs from a network were being added and then removed again in the past.
1138
0
    if (m_network_counts.size() < local_counts.size()) {
1139
0
        return -20;
1140
0
    }
1141
0
    for (const auto& [net, count] : m_network_counts) {
1142
0
        if (local_counts[net].n_new != count.n_new || local_counts[net].n_tried != count.n_tried) {
1143
0
            return -21;
1144
0
        }
1145
0
    }
1146
1147
0
    return 0;
1148
0
}
1149
1150
size_t AddrManImpl::Size(std::optional<Network> net, std::optional<bool> in_new) const
1151
0
{
1152
0
    LOCK(cs);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock BITCOIN_UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define BITCOIN_UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
1153
0
    Check();
1154
0
    auto ret = Size_(net, in_new);
1155
0
    Check();
1156
0
    return ret;
1157
0
}
1158
1159
bool AddrManImpl::Add(const std::vector<CAddress>& vAddr, const CNetAddr& source, std::chrono::seconds time_penalty)
1160
0
{
1161
0
    LOCK(cs);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock BITCOIN_UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define BITCOIN_UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
1162
0
    Check();
1163
0
    auto ret = Add_(vAddr, source, time_penalty);
1164
0
    Check();
1165
0
    return ret;
1166
0
}
1167
1168
bool AddrManImpl::Good(const CService& addr, NodeSeconds time)
1169
0
{
1170
0
    LOCK(cs);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock BITCOIN_UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define BITCOIN_UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
1171
0
    Check();
1172
0
    auto ret = Good_(addr, /*test_before_evict=*/true, time);
1173
0
    Check();
1174
0
    return ret;
1175
0
}
1176
1177
void AddrManImpl::Attempt(const CService& addr, bool fCountFailure, NodeSeconds time)
1178
0
{
1179
0
    LOCK(cs);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock BITCOIN_UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define BITCOIN_UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
1180
0
    Check();
1181
0
    Attempt_(addr, fCountFailure, time);
1182
0
    Check();
1183
0
}
1184
1185
void AddrManImpl::ResolveCollisions()
1186
0
{
1187
0
    LOCK(cs);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock BITCOIN_UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define BITCOIN_UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
1188
0
    Check();
1189
0
    ResolveCollisions_();
1190
0
    Check();
1191
0
}
1192
1193
std::pair<CAddress, NodeSeconds> AddrManImpl::SelectTriedCollision()
1194
0
{
1195
0
    LOCK(cs);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock BITCOIN_UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define BITCOIN_UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
1196
0
    Check();
1197
0
    auto ret = SelectTriedCollision_();
1198
0
    Check();
1199
0
    return ret;
1200
0
}
1201
1202
std::pair<CAddress, NodeSeconds> AddrManImpl::Select(bool new_only, const std::unordered_set<Network>& networks) const
1203
0
{
1204
0
    LOCK(cs);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock BITCOIN_UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define BITCOIN_UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
1205
0
    Check();
1206
0
    auto addrRet = Select_(new_only, networks);
1207
0
    Check();
1208
0
    return addrRet;
1209
0
}
1210
1211
std::vector<CAddress> AddrManImpl::GetAddr(size_t max_addresses, size_t max_pct, std::optional<Network> network, const bool filtered) const
1212
0
{
1213
0
    LOCK(cs);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock BITCOIN_UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define BITCOIN_UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
1214
0
    Check();
1215
0
    auto addresses = GetAddr_(max_addresses, max_pct, network, filtered);
1216
0
    Check();
1217
0
    return addresses;
1218
0
}
1219
1220
std::vector<std::pair<AddrInfo, AddressPosition>> AddrManImpl::GetEntries(bool from_tried) const
1221
0
{
1222
0
    LOCK(cs);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock BITCOIN_UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define BITCOIN_UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
1223
0
    Check();
1224
0
    auto addrInfos = GetEntries_(from_tried);
1225
0
    Check();
1226
0
    return addrInfos;
1227
0
}
1228
1229
void AddrManImpl::Connected(const CService& addr, NodeSeconds time)
1230
0
{
1231
0
    LOCK(cs);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock BITCOIN_UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define BITCOIN_UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
1232
0
    Check();
1233
0
    Connected_(addr, time);
1234
0
    Check();
1235
0
}
1236
1237
void AddrManImpl::SetServices(const CService& addr, ServiceFlags nServices)
1238
0
{
1239
0
    LOCK(cs);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock BITCOIN_UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define BITCOIN_UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
1240
0
    Check();
1241
0
    SetServices_(addr, nServices);
1242
0
    Check();
1243
0
}
1244
1245
std::optional<AddressPosition> AddrManImpl::FindAddressEntry(const CAddress& addr)
1246
0
{
1247
0
    LOCK(cs);
Line
Count
Source
268
0
#define LOCK(cs) UniqueLock BITCOIN_UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define BITCOIN_UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
1248
0
    Check();
1249
0
    auto entry = FindAddressEntry_(addr);
1250
0
    Check();
1251
0
    return entry;
1252
0
}
1253
1254
AddrMan::AddrMan(const NetGroupManager& netgroupman, bool deterministic, int32_t consistency_check_ratio)
1255
0
    : m_impl(std::make_unique<AddrManImpl>(netgroupman, deterministic, consistency_check_ratio)) {}
1256
1257
0
AddrMan::~AddrMan() = default;
1258
1259
template <typename Stream>
1260
void AddrMan::Serialize(Stream& s_) const
1261
0
{
1262
0
    m_impl->Serialize<Stream>(s_);
1263
0
}
Unexecuted instantiation: void AddrMan::Serialize<HashedSourceWriter<AutoFile>>(HashedSourceWriter<AutoFile>&) const
Unexecuted instantiation: void AddrMan::Serialize<DataStream>(DataStream&) const
1264
1265
template <typename Stream>
1266
void AddrMan::Unserialize(Stream& s_)
1267
0
{
1268
0
    m_impl->Unserialize<Stream>(s_);
1269
0
}
Unexecuted instantiation: void AddrMan::Unserialize<AutoFile>(AutoFile&)
Unexecuted instantiation: void AddrMan::Unserialize<HashVerifier<AutoFile>>(HashVerifier<AutoFile>&)
Unexecuted instantiation: void AddrMan::Unserialize<DataStream>(DataStream&)
Unexecuted instantiation: void AddrMan::Unserialize<HashVerifier<DataStream>>(HashVerifier<DataStream>&)
1270
1271
// explicit instantiation
1272
template void AddrMan::Serialize(HashedSourceWriter<AutoFile>&) const;
1273
template void AddrMan::Serialize(DataStream&) const;
1274
template void AddrMan::Unserialize(AutoFile&);
1275
template void AddrMan::Unserialize(HashVerifier<AutoFile>&);
1276
template void AddrMan::Unserialize(DataStream&);
1277
template void AddrMan::Unserialize(HashVerifier<DataStream>&);
1278
1279
size_t AddrMan::Size(std::optional<Network> net, std::optional<bool> in_new) const
1280
0
{
1281
0
    return m_impl->Size(net, in_new);
1282
0
}
1283
1284
bool AddrMan::Add(const std::vector<CAddress>& vAddr, const CNetAddr& source, std::chrono::seconds time_penalty)
1285
0
{
1286
0
    return m_impl->Add(vAddr, source, time_penalty);
1287
0
}
1288
1289
bool AddrMan::Good(const CService& addr, NodeSeconds time)
1290
0
{
1291
0
    return m_impl->Good(addr, time);
1292
0
}
1293
1294
void AddrMan::Attempt(const CService& addr, bool fCountFailure, NodeSeconds time)
1295
0
{
1296
0
    m_impl->Attempt(addr, fCountFailure, time);
1297
0
}
1298
1299
void AddrMan::ResolveCollisions()
1300
0
{
1301
0
    m_impl->ResolveCollisions();
1302
0
}
1303
1304
std::pair<CAddress, NodeSeconds> AddrMan::SelectTriedCollision()
1305
0
{
1306
0
    return m_impl->SelectTriedCollision();
1307
0
}
1308
1309
std::pair<CAddress, NodeSeconds> AddrMan::Select(bool new_only, const std::unordered_set<Network>& networks) const
1310
0
{
1311
0
    return m_impl->Select(new_only, networks);
1312
0
}
1313
1314
std::vector<CAddress> AddrMan::GetAddr(size_t max_addresses, size_t max_pct, std::optional<Network> network, const bool filtered) const
1315
0
{
1316
0
    return m_impl->GetAddr(max_addresses, max_pct, network, filtered);
1317
0
}
1318
1319
std::vector<std::pair<AddrInfo, AddressPosition>> AddrMan::GetEntries(bool use_tried) const
1320
0
{
1321
0
    return m_impl->GetEntries(use_tried);
1322
0
}
1323
1324
void AddrMan::Connected(const CService& addr, NodeSeconds time)
1325
0
{
1326
0
    m_impl->Connected(addr, time);
1327
0
}
1328
1329
void AddrMan::SetServices(const CService& addr, ServiceFlags nServices)
1330
0
{
1331
0
    m_impl->SetServices(addr, nServices);
1332
0
}
1333
1334
std::optional<AddressPosition> AddrMan::FindAddressEntry(const CAddress& addr)
1335
0
{
1336
0
    return m_impl->FindAddressEntry(addr);
1337
0
}