Coverage Report

Created: 2026-07-14 18:13

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/bitcoin/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
314k
{
38
314k
    std::vector<unsigned char> vchSourceGroupKey = netgroupman.GetGroup(src);
39
314k
    uint64_t hash1 = (HashWriter{} << nKey << netgroupman.GetGroup(*this) << vchSourceGroupKey).GetCheapHash();
40
314k
    uint64_t hash2 = (HashWriter{} << nKey << vchSourceGroupKey << (hash1 % ADDRMAN_NEW_BUCKETS_PER_SOURCE_GROUP)).GetCheapHash();
41
314k
    return hash2 % ADDRMAN_NEW_BUCKET_COUNT;
42
314k
}
43
44
int AddrInfo::GetBucketPosition(const uint256& nKey, bool fNew, int bucket) const
45
314k
{
46
314k
    uint64_t hash1 = (HashWriter{} << nKey << (fNew ? uint8_t{'N'} : uint8_t{'K'}) << bucket << GetKey()).GetCheapHash();
  Branch (46:48): [True: 314k, False: 0]
47
314k
    return hash1 % ADDRMAN_BUCKET_SIZE;
48
314k
}
49
50
bool AddrInfo::IsTerrible(NodeSeconds now) const
51
21.2k
{
52
21.2k
    if (now - m_last_try <= 1min) { // never remove things tried in the last minute
  Branch (52:9): [True: 0, False: 21.2k]
53
0
        return false;
54
0
    }
55
56
21.2k
    if (nTime > now + 10min) { // came in a flying DeLorean
  Branch (56:9): [True: 2.01k, False: 19.2k]
57
2.01k
        return true;
58
2.01k
    }
59
60
19.2k
    if (now - nTime > ADDRMAN_HORIZON) { // not seen in recent history
  Branch (60:9): [True: 12.4k, False: 6.82k]
61
12.4k
        return true;
62
12.4k
    }
63
64
6.82k
    if (TicksSinceEpoch<std::chrono::seconds>(m_last_success) == 0 && nAttempts >= ADDRMAN_RETRIES) { // tried N times and never a success
  Branch (64:9): [True: 6.82k, False: 0]
  Branch (64:71): [True: 0, False: 6.82k]
65
0
        return true;
66
0
    }
67
68
6.82k
    if (now - m_last_success > ADDRMAN_MIN_FAIL && nAttempts >= ADDRMAN_MAX_FAILURES) { // N successive failures in the last week
  Branch (68:9): [True: 6.82k, False: 0]
  Branch (68:9): [True: 0, False: 6.82k]
  Branch (68:52): [True: 0, False: 6.82k]
69
0
        return true;
70
0
    }
71
72
6.82k
    return false;
73
6.82k
}
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) {
  Branch (80:9): [True: 0, False: 0]
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
54
    : insecure_rand{deterministic}
92
54
    , nKey{deterministic ? uint256{1} : insecure_rand.rand256()}
  Branch (92:12): [True: 0, False: 54]
93
54
    , m_consistency_check_ratio{consistency_check_ratio}
94
54
    , m_netgroupman{netgroupman}
95
54
{
96
55.2k
    for (auto& bucket : vvNew) {
  Branch (96:23): [True: 55.2k, False: 54]
97
3.53M
        for (auto& entry : bucket) {
  Branch (97:26): [True: 3.53M, False: 55.2k]
98
3.53M
            entry = -1;
99
3.53M
        }
100
55.2k
    }
101
13.8k
    for (auto& bucket : vvTried) {
  Branch (101:23): [True: 13.8k, False: 54]
102
884k
        for (auto& entry : bucket) {
  Branch (102:26): [True: 884k, False: 13.8k]
103
884k
            entry = -1;
104
884k
        }
105
13.8k
    }
106
54
}
107
108
AddrManImpl::~AddrManImpl()
109
150k
{
110
150k
    nKey.SetNull();
111
150k
}
112
113
template <typename Stream>
114
void AddrManImpl::Serialize(Stream& s_) const
115
215k
{
116
215k
    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
215k
    ParamsStream s{s_, CAddress::V2_DISK};
158
159
215k
    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
215k
    static constexpr uint8_t lowest_compatible = Format::V4_MULTIPORT;
164
215k
    s << static_cast<uint8_t>(INCOMPATIBILITY_BASE + lowest_compatible);
165
166
215k
    s << nKey;
167
215k
    s << nNew;
168
215k
    s << nTried;
169
170
215k
    int nUBuckets = ADDRMAN_NEW_BUCKET_COUNT ^ (1 << 30);
171
215k
    s << nUBuckets;
172
215k
    std::unordered_map<nid_type, int> mapUnkIds;
173
215k
    int nIds = 0;
174
578k
    for (const auto& entry : mapInfo) {
  Branch (174:28): [True: 578k, False: 215k]
  Branch (174:28): [True: 0, False: 0]
175
578k
        mapUnkIds[entry.first] = nIds;
176
578k
        const AddrInfo& info = entry.second;
177
578k
        if (info.nRefCount) {
  Branch (177:13): [True: 578k, False: 0]
  Branch (177:13): [True: 0, False: 0]
178
578k
            assert(nIds != nNew); // this means nNew was wrong, oh ow
  Branch (178:13): [True: 578k, False: 0]
  Branch (178:13): [True: 0, False: 0]
179
578k
            s << info;
180
578k
            nIds++;
181
578k
        }
182
578k
    }
183
215k
    nIds = 0;
184
578k
    for (const auto& entry : mapInfo) {
  Branch (184:28): [True: 578k, False: 215k]
  Branch (184:28): [True: 0, False: 0]
185
578k
        const AddrInfo& info = entry.second;
186
578k
        if (info.fInTried) {
  Branch (186:13): [True: 0, False: 578k]
  Branch (186:13): [True: 0, False: 0]
187
0
            assert(nIds != nTried); // this means nTried was wrong, oh ow
  Branch (187:13): [True: 0, False: 0]
  Branch (187:13): [True: 0, False: 0]
188
0
            s << info;
189
0
            nIds++;
190
0
        }
191
578k
    }
192
220M
    for (int bucket = 0; bucket < ADDRMAN_NEW_BUCKET_COUNT; bucket++) {
  Branch (192:26): [True: 220M, False: 215k]
  Branch (192:26): [True: 0, False: 0]
193
220M
        int nSize = 0;
194
14.3G
        for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) {
  Branch (194:25): [True: 14.1G, False: 220M]
  Branch (194:25): [True: 0, False: 0]
195
14.1G
            if (vvNew[bucket][i] != -1)
  Branch (195:17): [True: 578k, False: 14.1G]
  Branch (195:17): [True: 0, False: 0]
196
578k
                nSize++;
197
14.1G
        }
198
220M
        s << nSize;
199
14.3G
        for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) {
  Branch (199:25): [True: 14.1G, False: 220M]
  Branch (199:25): [True: 0, False: 0]
200
14.1G
            if (vvNew[bucket][i] != -1) {
  Branch (200:17): [True: 578k, False: 14.1G]
  Branch (200:17): [True: 0, False: 0]
201
578k
                int nIndex = mapUnkIds[vvNew[bucket][i]];
202
578k
                s << nIndex;
203
578k
            }
204
14.1G
        }
205
220M
    }
206
    // Store asmap version after bucket entries so that it
207
    // can be ignored by older clients for backward compatibility.
208
215k
    s << m_netgroupman.GetAsmapVersion();
209
215k
}
void AddrManImpl::Serialize<HashedSourceWriter<AutoFile> >(HashedSourceWriter<AutoFile>&) const
Line
Count
Source
115
215k
{
116
215k
    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
215k
    ParamsStream s{s_, CAddress::V2_DISK};
158
159
215k
    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
215k
    static constexpr uint8_t lowest_compatible = Format::V4_MULTIPORT;
164
215k
    s << static_cast<uint8_t>(INCOMPATIBILITY_BASE + lowest_compatible);
165
166
215k
    s << nKey;
167
215k
    s << nNew;
168
215k
    s << nTried;
169
170
215k
    int nUBuckets = ADDRMAN_NEW_BUCKET_COUNT ^ (1 << 30);
171
215k
    s << nUBuckets;
172
215k
    std::unordered_map<nid_type, int> mapUnkIds;
173
215k
    int nIds = 0;
174
578k
    for (const auto& entry : mapInfo) {
  Branch (174:28): [True: 578k, False: 215k]
175
578k
        mapUnkIds[entry.first] = nIds;
176
578k
        const AddrInfo& info = entry.second;
177
578k
        if (info.nRefCount) {
  Branch (177:13): [True: 578k, False: 0]
178
578k
            assert(nIds != nNew); // this means nNew was wrong, oh ow
  Branch (178:13): [True: 578k, False: 0]
179
578k
            s << info;
180
578k
            nIds++;
181
578k
        }
182
578k
    }
183
215k
    nIds = 0;
184
578k
    for (const auto& entry : mapInfo) {
  Branch (184:28): [True: 578k, False: 215k]
185
578k
        const AddrInfo& info = entry.second;
186
578k
        if (info.fInTried) {
  Branch (186:13): [True: 0, False: 578k]
187
0
            assert(nIds != nTried); // this means nTried was wrong, oh ow
  Branch (187:13): [True: 0, False: 0]
188
0
            s << info;
189
0
            nIds++;
190
0
        }
191
578k
    }
192
220M
    for (int bucket = 0; bucket < ADDRMAN_NEW_BUCKET_COUNT; bucket++) {
  Branch (192:26): [True: 220M, False: 215k]
193
220M
        int nSize = 0;
194
14.3G
        for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) {
  Branch (194:25): [True: 14.1G, False: 220M]
195
14.1G
            if (vvNew[bucket][i] != -1)
  Branch (195:17): [True: 578k, False: 14.1G]
196
578k
                nSize++;
197
14.1G
        }
198
220M
        s << nSize;
199
14.3G
        for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) {
  Branch (199:25): [True: 14.1G, False: 220M]
200
14.1G
            if (vvNew[bucket][i] != -1) {
  Branch (200:17): [True: 578k, False: 14.1G]
201
578k
                int nIndex = mapUnkIds[vvNew[bucket][i]];
202
578k
                s << nIndex;
203
578k
            }
204
14.1G
        }
205
220M
    }
206
    // Store asmap version after bucket entries so that it
207
    // can be ignored by older clients for backward compatibility.
208
215k
    s << m_netgroupman.GetAsmapVersion();
209
215k
}
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);
215
216
0
    assert(vRandom.empty());
  Branch (216:5): [True: 0, False: 0]
  Branch (216:5): [True: 0, False: 0]
  Branch (216:5): [True: 0, False: 0]
  Branch (216:5): [True: 0, False: 0]
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);
  Branch (221:30): [True: 0, False: 0]
  Branch (221:30): [True: 0, False: 0]
  Branch (221:30): [True: 0, False: 0]
  Branch (221:30): [True: 0, False: 0]
222
0
    ParamsStream s{s_, ser_params};
223
224
0
    uint8_t compat;
225
0
    s >> compat;
226
0
    if (compat < INCOMPATIBILITY_BASE) {
  Branch (226:9): [True: 0, False: 0]
  Branch (226:9): [True: 0, False: 0]
  Branch (226:9): [True: 0, False: 0]
  Branch (226:9): [True: 0, False: 0]
227
0
        throw std::ios_base::failure(strprintf(
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) {
  Branch (233:9): [True: 0, False: 0]
  Branch (233:9): [True: 0, False: 0]
  Branch (233:9): [True: 0, False: 0]
  Branch (233:9): [True: 0, False: 0]
234
0
        throw InvalidAddrManVersionError(strprintf(
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}));
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) {
  Branch (245:9): [True: 0, False: 0]
  Branch (245:9): [True: 0, False: 0]
  Branch (245:9): [True: 0, False: 0]
  Branch (245:9): [True: 0, False: 0]
246
0
        nUBuckets ^= (1 << 30);
247
0
    }
248
249
0
    if (nNew > ADDRMAN_NEW_BUCKET_COUNT * ADDRMAN_BUCKET_SIZE || nNew < 0) {
  Branch (249:9): [True: 0, False: 0]
  Branch (249:66): [True: 0, False: 0]
  Branch (249:9): [True: 0, False: 0]
  Branch (249:66): [True: 0, False: 0]
  Branch (249:9): [True: 0, False: 0]
  Branch (249:66): [True: 0, False: 0]
  Branch (249:9): [True: 0, False: 0]
  Branch (249:66): [True: 0, False: 0]
250
0
        throw std::ios_base::failure(
251
0
                strprintf("Corrupt AddrMan serialization: nNew=%d, should be in [0, %d]",
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) {
  Branch (256:9): [True: 0, False: 0]
  Branch (256:70): [True: 0, False: 0]
  Branch (256:9): [True: 0, False: 0]
  Branch (256:70): [True: 0, False: 0]
  Branch (256:9): [True: 0, False: 0]
  Branch (256:70): [True: 0, False: 0]
  Branch (256:9): [True: 0, False: 0]
  Branch (256:70): [True: 0, False: 0]
257
0
        throw std::ios_base::failure(
258
0
                strprintf("Corrupt AddrMan serialization: nTried=%d, should be in [0, %d]",
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++) {
  Branch (264:21): [True: 0, False: 0]
  Branch (264:21): [True: 0, False: 0]
  Branch (264:21): [True: 0, False: 0]
  Branch (264:21): [True: 0, False: 0]
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++) {
  Branch (276:21): [True: 0, False: 0]
  Branch (276:21): [True: 0, False: 0]
  Branch (276:21): [True: 0, False: 0]
  Branch (276:21): [True: 0, False: 0]
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()
  Branch (281:13): [True: 0, False: 0]
  Branch (281:13): [True: 0, False: 0]
  Branch (281:13): [True: 0, False: 0]
  Branch (281:13): [True: 0, False: 0]
282
0
                && vvTried[nKBucket][nKBucketPos] == -1) {
  Branch (282:20): [True: 0, False: 0]
  Branch (282:20): [True: 0, False: 0]
  Branch (282:20): [True: 0, False: 0]
  Branch (282:20): [True: 0, False: 0]
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) {
  Branch (302:26): [True: 0, False: 0]
  Branch (302:26): [True: 0, False: 0]
  Branch (302:26): [True: 0, False: 0]
  Branch (302:26): [True: 0, False: 0]
303
0
        int num_entries{0};
304
0
        s >> num_entries;
305
0
        for (int n = 0; n < num_entries; ++n) {
  Branch (305:25): [True: 0, False: 0]
  Branch (305:25): [True: 0, False: 0]
  Branch (305:25): [True: 0, False: 0]
  Branch (305:25): [True: 0, False: 0]
306
0
            int entry_index{0};
307
0
            s >> entry_index;
308
0
            if (entry_index >= 0 && entry_index < nNew) {
  Branch (308:17): [True: 0, False: 0]
  Branch (308:37): [True: 0, False: 0]
  Branch (308:17): [True: 0, False: 0]
  Branch (308:37): [True: 0, False: 0]
  Branch (308:17): [True: 0, False: 0]
  Branch (308:37): [True: 0, False: 0]
  Branch (308:17): [True: 0, False: 0]
  Branch (308:37): [True: 0, False: 0]
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) {
  Branch (319:9): [True: 0, False: 0]
  Branch (319:9): [True: 0, False: 0]
  Branch (319:9): [True: 0, False: 0]
  Branch (319:9): [True: 0, False: 0]
320
0
        s >> serialized_asmap_version;
321
0
    }
322
0
    const bool restore_bucketing{nUBuckets == ADDRMAN_NEW_BUCKET_COUNT &&
  Branch (322:34): [True: 0, False: 0]
  Branch (322:34): [True: 0, False: 0]
  Branch (322:34): [True: 0, False: 0]
  Branch (322:34): [True: 0, False: 0]
323
0
        serialized_asmap_version == supplied_asmap_version};
  Branch (323:9): [True: 0, False: 0]
  Branch (323:9): [True: 0, False: 0]
  Branch (323:9): [True: 0, False: 0]
  Branch (323:9): [True: 0, False: 0]
324
325
0
    if (!restore_bucketing) {
  Branch (325:9): [True: 0, False: 0]
  Branch (325:9): [True: 0, False: 0]
  Branch (325:9): [True: 0, False: 0]
  Branch (325:9): [True: 0, False: 0]
326
0
        LogDebug(BCLog::ADDRMAN, "Bucketing method was updated, re-bucketing addrman entries from disk\n");
327
0
    }
328
329
0
    for (auto bucket_entry : bucket_entries) {
  Branch (329:28): [True: 0, False: 0]
  Branch (329:28): [True: 0, False: 0]
  Branch (329:28): [True: 0, False: 0]
  Branch (329:28): [True: 0, False: 0]
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;
  Branch (335:13): [True: 0, False: 0]
  Branch (335:13): [True: 0, False: 0]
  Branch (335:13): [True: 0, False: 0]
  Branch (335:13): [True: 0, False: 0]
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;
  Branch (340:13): [True: 0, False: 0]
  Branch (340:13): [True: 0, False: 0]
  Branch (340:13): [True: 0, False: 0]
  Branch (340:13): [True: 0, False: 0]
341
342
0
        int bucket_position = info.GetBucketPosition(nKey, true, bucket);
343
0
        if (restore_bucketing && vvNew[bucket][bucket_position] == -1) {
  Branch (343:13): [True: 0, False: 0]
  Branch (343:34): [True: 0, False: 0]
  Branch (343:13): [True: 0, False: 0]
  Branch (343:34): [True: 0, False: 0]
  Branch (343:13): [True: 0, False: 0]
  Branch (343:34): [True: 0, False: 0]
  Branch (343:13): [True: 0, False: 0]
  Branch (343:34): [True: 0, False: 0]
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) {
  Branch (352:17): [True: 0, False: 0]
  Branch (352:17): [True: 0, False: 0]
  Branch (352:17): [True: 0, False: 0]
  Branch (352:17): [True: 0, False: 0]
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(); ) {
  Branch (361:38): [True: 0, False: 0]
  Branch (361:38): [True: 0, False: 0]
  Branch (361:38): [True: 0, False: 0]
  Branch (361:38): [True: 0, False: 0]
362
0
        if (it->second.fInTried == false && it->second.nRefCount == 0) {
  Branch (362:13): [True: 0, False: 0]
  Branch (362:45): [True: 0, False: 0]
  Branch (362:13): [True: 0, False: 0]
  Branch (362:45): [True: 0, False: 0]
  Branch (362:13): [True: 0, False: 0]
  Branch (362:45): [True: 0, False: 0]
  Branch (362:13): [True: 0, False: 0]
  Branch (362:45): [True: 0, False: 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) {
  Branch (370:9): [True: 0, False: 0]
  Branch (370:9): [True: 0, False: 0]
  Branch (370:9): [True: 0, False: 0]
  Branch (370:9): [True: 0, False: 0]
371
0
        LogDebug(BCLog::ADDRMAN, "addrman lost %i new and %i tried addresses due to collisions or invalid addresses\n", nLostUnk, nLost);
372
0
    }
373
374
0
    const int check_code{CheckAddrman()};
375
0
    if (check_code != 0) {
  Branch (375:9): [True: 0, False: 0]
  Branch (375:9): [True: 0, False: 0]
  Branch (375:9): [True: 0, False: 0]
  Branch (375:9): [True: 0, False: 0]
376
0
        throw std::ios_base::failure(strprintf(
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
936k
{
384
936k
    AssertLockHeld(cs);
385
386
936k
    const auto it = mapAddr.find(addr);
387
936k
    if (it == mapAddr.end())
  Branch (387:9): [True: 898k, False: 38.1k]
388
898k
        return nullptr;
389
38.1k
    if (pnId)
  Branch (389:9): [True: 38.1k, False: 18.4E]
390
38.1k
        *pnId = (*it).second;
391
38.1k
    const auto it2 = mapInfo.find((*it).second);
392
38.1k
    if (it2 != mapInfo.end())
  Branch (392:9): [True: 38.1k, False: 18.4E]
393
38.1k
        return &(*it2).second;
394
18.4E
    return nullptr;
395
38.1k
}
396
397
AddrInfo* AddrManImpl::Create(const CAddress& addr, const CNetAddr& addrSource, nid_type* pnId)
398
295k
{
399
295k
    AssertLockHeld(cs);
400
401
295k
    nid_type nId = nIdCount++;
402
295k
    mapInfo[nId] = AddrInfo(addr, addrSource);
403
295k
    mapAddr[addr] = nId;
404
295k
    mapInfo[nId].nRandomPos = vRandom.size();
405
295k
    vRandom.push_back(nId);
406
295k
    nNew++;
407
295k
    m_network_counts[addr.GetNetwork()].n_new++;
408
295k
    if (pnId)
  Branch (408:9): [True: 295k, False: 18.4E]
409
295k
        *pnId = nId;
410
295k
    return &mapInfo[nId];
411
295k
}
412
413
void AddrManImpl::SwapRandom(unsigned int nRndPos1, unsigned int nRndPos2) const
414
21.2k
{
415
21.2k
    AssertLockHeld(cs);
416
417
21.2k
    if (nRndPos1 == nRndPos2)
  Branch (417:9): [True: 3.02k, False: 18.2k]
418
3.02k
        return;
419
420
21.2k
    assert(nRndPos1 < vRandom.size() && nRndPos2 < vRandom.size());
  Branch (420:5): [True: 18.2k, False: 0]
  Branch (420:5): [True: 18.2k, False: 0]
  Branch (420:5): [True: 18.2k, False: 0]
421
422
18.2k
    nid_type nId1 = vRandom[nRndPos1];
423
18.2k
    nid_type nId2 = vRandom[nRndPos2];
424
425
18.2k
    const auto it_1{mapInfo.find(nId1)};
426
18.2k
    const auto it_2{mapInfo.find(nId2)};
427
18.2k
    assert(it_1 != mapInfo.end());
  Branch (427:5): [True: 18.2k, False: 0]
428
18.2k
    assert(it_2 != mapInfo.end());
  Branch (428:5): [True: 18.2k, False: 0]
429
430
18.2k
    it_1->second.nRandomPos = nRndPos2;
431
18.2k
    it_2->second.nRandomPos = nRndPos1;
432
433
18.2k
    vRandom[nRndPos1] = nId2;
434
18.2k
    vRandom[nRndPos2] = nId1;
435
18.2k
}
436
437
void AddrManImpl::Delete(nid_type nId)
438
862
{
439
862
    AssertLockHeld(cs);
440
441
862
    assert(mapInfo.contains(nId));
  Branch (441:5): [True: 862, False: 0]
442
862
    AddrInfo& info = mapInfo[nId];
443
862
    assert(!info.fInTried);
  Branch (443:5): [True: 862, False: 0]
444
862
    assert(info.nRefCount == 0);
  Branch (444:5): [True: 862, False: 0]
445
446
862
    SwapRandom(info.nRandomPos, vRandom.size() - 1);
447
862
    m_network_counts[info.GetNetwork()].n_new--;
448
862
    vRandom.pop_back();
449
862
    mapAddr.erase(info);
450
862
    mapInfo.erase(nId);
451
862
    nNew--;
452
862
}
453
454
void AddrManImpl::ClearNew(int nUBucket, int nUBucketPos)
455
295k
{
456
295k
    AssertLockHeld(cs);
457
458
    // if there is an entry in the specified bucket, delete it.
459
295k
    if (vvNew[nUBucket][nUBucketPos] != -1) {
  Branch (459:9): [True: 339, False: 294k]
460
339
        nid_type nIdDelete = vvNew[nUBucket][nUBucketPos];
461
339
        AddrInfo& infoDelete = mapInfo[nIdDelete];
462
339
        assert(infoDelete.nRefCount > 0);
  Branch (462:9): [True: 339, False: 0]
463
339
        infoDelete.nRefCount--;
464
339
        vvNew[nUBucket][nUBucketPos] = -1;
465
339
        LogDebug(BCLog::ADDRMAN, "Removed %s from new[%i][%i]\n", infoDelete.ToStringAddrPort(), nUBucket, nUBucketPos);
466
339
        if (infoDelete.nRefCount == 0) {
  Branch (466:13): [True: 339, False: 0]
467
339
            Delete(nIdDelete);
468
339
        }
469
339
    }
470
295k
}
471
472
void AddrManImpl::MakeTried(AddrInfo& info, nid_type nId)
473
0
{
474
0
    AssertLockHeld(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) {
  Branch (478:21): [True: 0, False: 0]
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) {
  Branch (481:13): [True: 0, False: 0]
482
0
            vvNew[bucket][pos] = -1;
483
0
            info.nRefCount--;
484
0
            if (info.nRefCount == 0) break;
  Branch (484:17): [True: 0, False: 0]
485
0
        }
486
0
    }
487
0
    nNew--;
488
0
    m_network_counts[info.GetNetwork()].n_new--;
489
490
0
    assert(info.nRefCount == 0);
  Branch (490:5): [True: 0, False: 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) {
  Branch (497:9): [True: 0, False: 0]
498
        // find an item to evict
499
0
        nid_type nIdEvict = vvTried[nKBucket][nKBucketPos];
500
0
        assert(mapInfo.contains(nIdEvict));
  Branch (500:9): [True: 0, False: 0]
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);
  Branch (513:9): [True: 0, False: 0]
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",
521
0
                 infoOld.ToStringAddrPort(), nKBucket, nKBucketPos, nUBucket, nUBucketPos);
522
0
    }
523
0
    assert(vvTried[nKBucket][nKBucketPos] == -1);
  Branch (523:5): [True: 0, False: 0]
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
529k
{
533
529k
    AssertLockHeld(cs);
534
535
529k
    if (!addr.IsRoutable())
  Branch (535:9): [True: 195k, False: 333k]
536
195k
        return false;
537
538
333k
    nid_type nId;
539
333k
    AddrInfo* pinfo = Find(addr, &nId);
540
541
    // Do not set a penalty for a source's self-announcement
542
333k
    if (addr == source) {
  Branch (542:9): [True: 0, False: 333k]
543
0
        time_penalty = 0s;
544
0
    }
545
546
333k
    if (pinfo) {
  Branch (546:9): [True: 38.1k, False: 295k]
547
        // periodically update nTime
548
38.1k
        const bool currently_online{NodeClock::now() - addr.nTime < 24h};
549
38.1k
        const auto update_interval{currently_online ? 1h : 24h};
  Branch (549:36): [True: 11.2k, False: 26.9k]
550
38.1k
        if (pinfo->nTime < addr.nTime - update_interval - time_penalty) {
  Branch (550:13): [True: 602, False: 37.5k]
551
602
            pinfo->nTime = std::max(NodeSeconds{0s}, addr.nTime - time_penalty);
552
602
        }
553
554
        // add services
555
38.1k
        pinfo->nServices = ServiceFlags(pinfo->nServices | addr.nServices);
556
557
        // do not update if no new information is present
558
38.1k
        if (addr.nTime <= pinfo->nTime) {
  Branch (558:13): [True: 285, False: 37.8k]
559
285
            return false;
560
285
        }
561
562
        // do not update if the entry was already in the "tried" table
563
37.8k
        if (pinfo->fInTried)
  Branch (563:13): [True: 0, False: 37.8k]
564
0
            return false;
565
566
        // do not update if the max reference count is reached
567
37.8k
        if (pinfo->nRefCount == ADDRMAN_NEW_BUCKETS_PER_ADDRESS)
  Branch (567:13): [True: 0, False: 37.8k]
568
0
            return false;
569
570
        // stochastic test: previous nRefCount == N: 2^N times harder to increase it
571
37.8k
        if (pinfo->nRefCount > 0) {
  Branch (571:13): [True: 37.8k, False: 0]
572
37.8k
            const int nFactor{1 << pinfo->nRefCount};
573
37.8k
            if (insecure_rand.randrange(nFactor) != 0) return false;
  Branch (573:17): [True: 18.8k, False: 19.0k]
574
37.8k
        }
575
295k
    } else {
576
295k
        pinfo = Create(addr, source, &nId);
577
295k
        pinfo->nTime = std::max(NodeSeconds{0s}, pinfo->nTime - time_penalty);
578
295k
    }
579
580
314k
    int nUBucket = pinfo->GetNewBucket(nKey, source, m_netgroupman);
581
314k
    int nUBucketPos = pinfo->GetBucketPosition(nKey, true, nUBucket);
582
314k
    bool fInsert = vvNew[nUBucket][nUBucketPos] == -1;
583
314k
    if (vvNew[nUBucket][nUBucketPos] != nId) {
  Branch (583:9): [True: 295k, False: 19.0k]
584
295k
        if (!fInsert) {
  Branch (584:13): [True: 862, False: 294k]
585
862
            AddrInfo& infoExisting = mapInfo[vvNew[nUBucket][nUBucketPos]];
586
862
            if (infoExisting.IsTerrible() || (infoExisting.nRefCount > 1 && pinfo->nRefCount == 0)) {
  Branch (586:17): [True: 339, False: 523]
  Branch (586:47): [True: 0, False: 523]
  Branch (586:77): [True: 0, False: 0]
587
                // Overwrite the existing new table entry.
588
339
                fInsert = true;
589
339
            }
590
862
        }
591
295k
        if (fInsert) {
  Branch (591:13): [True: 295k, False: 523]
592
295k
            ClearNew(nUBucket, nUBucketPos);
593
295k
            pinfo->nRefCount++;
594
295k
            vvNew[nUBucket][nUBucketPos] = nId;
595
295k
            const auto mapped_as{m_netgroupman.GetMappedAS(addr)};
596
295k
            LogDebug(BCLog::ADDRMAN, "Added %s%s to new[%i][%i]\n",
597
295k
                     addr.ToStringAddrPort(), (mapped_as ? strprintf(" mapped to AS%i", mapped_as) : ""), nUBucket, nUBucketPos);
598
295k
        } else {
599
523
            if (pinfo->nRefCount == 0) {
  Branch (599:17): [True: 523, False: 0]
600
523
                Delete(nId);
601
523
            }
602
523
        }
603
295k
    }
604
314k
    return fInsert;
605
333k
}
606
607
bool AddrManImpl::Good_(const CService& addr, bool test_before_evict, NodeSeconds time)
608
21
{
609
21
    AssertLockHeld(cs);
610
611
21
    nid_type nId;
612
613
21
    m_last_good = time;
614
615
21
    AddrInfo* pinfo = Find(addr, &nId);
616
617
    // if not found, bail out
618
21
    if (!pinfo) return false;
  Branch (618:9): [True: 21, False: 0]
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;
  Branch (630:9): [True: 0, False: 0]
631
632
    // if it is not in new, something bad happened
633
0
    if (!Assume(info.nRefCount > 0)) return false;
  Branch (633:9): [True: 0, False: 0]
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)) {
  Branch (641:9): [True: 0, False: 0]
  Branch (641:30): [True: 0, False: 0]
642
0
        if (m_tried_collisions.size() < ADDRMAN_SET_TRIED_COLLISION_SIZE) {
  Branch (642:13): [True: 0, False: 0]
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",
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",
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
69.2k
{
664
69.2k
    int added{0};
665
598k
    for (std::vector<CAddress>::const_iterator it = vAddr.begin(); it != vAddr.end(); it++) {
  Branch (665:68): [True: 529k, False: 69.2k]
666
529k
        added += AddSingle(*it, source, time_penalty) ? 1 : 0;
  Branch (666:18): [True: 295k, False: 233k]
667
529k
    }
668
69.2k
    if (added > 0) {
  Branch (668:9): [True: 55.9k, False: 13.3k]
669
55.9k
        LogDebug(BCLog::ADDRMAN, "Added %i addresses (of %i) from %s: %i tried, %i new\n", added, vAddr.size(), source.ToStringAddr(), nTried, nNew);
670
55.9k
    }
671
69.2k
    return added > 0;
672
69.2k
}
673
674
void AddrManImpl::Attempt_(const CService& addr, bool fCountFailure, NodeSeconds time)
675
2.74k
{
676
2.74k
    AssertLockHeld(cs);
677
678
2.74k
    AddrInfo* pinfo = Find(addr);
679
680
    // if not found, bail out
681
2.74k
    if (!pinfo)
  Branch (681:9): [True: 2.74k, False: 0]
682
2.74k
        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) {
  Branch (688:9): [True: 0, False: 0]
  Branch (688:26): [True: 0, False: 0]
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);
697
698
0
    if (vRandom.empty()) return {};
  Branch (698:9): [True: 0, False: 0]
699
700
0
    size_t new_count = nNew;
701
0
    size_t tried_count = nTried;
702
703
0
    if (!networks.empty()) {
  Branch (703:9): [True: 0, False: 0]
704
0
        new_count = 0;
705
0
        tried_count = 0;
706
0
        for (auto& network : networks) {
  Branch (706:28): [True: 0, False: 0]
707
0
            auto it = m_network_counts.find(network);
708
0
            if (it == m_network_counts.end()) {
  Branch (708:17): [True: 0, False: 0]
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 {};
  Branch (717:9): [True: 0, False: 0]
  Branch (717:21): [True: 0, False: 0]
718
0
    if (new_count + tried_count == 0) return {};
  Branch (718:9): [True: 0, False: 0]
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) {
  Branch (723:9): [True: 0, False: 0]
  Branch (723:21): [True: 0, False: 0]
724
0
        search_tried = false;
725
0
    } else if (new_count == 0) {
  Branch (725:16): [True: 0, False: 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};
  Branch (731:28): [True: 0, False: 0]
732
733
    // Loop through the addrman table until we find an appropriate entry
734
0
    double chance_factor = 1.0;
735
0
    while (1) {
  Branch (735:12): [Folded - Ignored]
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) {
  Branch (744:21): [True: 0, False: 0]
745
0
            position = (initial_position + i) % ADDRMAN_BUCKET_SIZE;
746
0
            node_id = GetEntry(search_tried, bucket, position);
747
0
            if (node_id != -1) {
  Branch (747:17): [True: 0, False: 0]
748
0
                if (!networks.empty()) {
  Branch (748:21): [True: 0, False: 0]
749
0
                    const auto it{mapInfo.find(node_id)};
750
0
                    if (Assume(it != mapInfo.end()) && networks.contains(it->second.GetNetwork())) break;
  Branch (750:25): [True: 0, False: 0]
  Branch (750:56): [True: 0, False: 0]
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;
  Branch (758:13): [True: 0, False: 0]
759
760
        // Find the entry to return.
761
0
        const auto it_found{mapInfo.find(node_id)};
762
0
        assert(it_found != mapInfo.end());
  Branch (762:9): [True: 0, False: 0]
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)) {
  Branch (766:13): [True: 0, False: 0]
767
0
            LogDebug(BCLog::ADDRMAN, "Selected %s from %s\n", info.ToStringAddrPort(), search_tried ? "tried" : "new");
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);
779
780
0
    if (use_tried) {
  Branch (780:9): [True: 0, False: 0]
781
0
        if (Assume(position < ADDRMAN_BUCKET_SIZE) && Assume(bucket < ADDRMAN_TRIED_BUCKET_COUNT)) {
  Branch (781:13): [True: 0, False: 0]
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)) {
  Branch (785:13): [True: 0, False: 0]
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
7.83k
{
795
7.83k
    AssertLockHeld(cs);
796
7.83k
    Assume(max_pct <= 100);
797
798
7.83k
    size_t nNodes = vRandom.size();
799
7.83k
    if (max_pct != 0) {
  Branch (799:9): [True: 7.83k, False: 0]
800
7.83k
        max_pct = std::min(max_pct, size_t{100});
801
7.83k
        nNodes = max_pct * nNodes / 100;
802
7.83k
    }
803
7.83k
    if (max_addresses != 0) {
  Branch (803:9): [True: 7.83k, False: 0]
804
7.83k
        nNodes = std::min(nNodes, max_addresses);
805
7.83k
    }
806
807
    // gather a list of random nodes, skipping those of low quality
808
7.83k
    const auto now{Now<NodeSeconds>()};
809
7.83k
    std::vector<CAddress> addresses;
810
7.83k
    addresses.reserve(nNodes);
811
28.2k
    for (unsigned int n = 0; n < vRandom.size(); n++) {
  Branch (811:30): [True: 23.0k, False: 5.18k]
812
23.0k
        if (addresses.size() >= nNodes)
  Branch (812:13): [True: 2.64k, False: 20.4k]
813
2.64k
            break;
814
815
20.4k
        int nRndPos = insecure_rand.randrange(vRandom.size() - n) + n;
816
20.4k
        SwapRandom(n, nRndPos);
817
20.4k
        const auto it{mapInfo.find(vRandom[n])};
818
20.4k
        assert(it != mapInfo.end());
  Branch (818:9): [True: 20.4k, False: 0]
819
820
20.4k
        const AddrInfo& ai{it->second};
821
822
        // Filter by network (optional)
823
20.4k
        if (network != std::nullopt && ai.GetNetClass() != network) continue;
  Branch (823:13): [True: 0, False: 20.4k]
  Branch (823:13): [True: 0, False: 20.4k]
  Branch (823:40): [True: 0, False: 0]
824
825
        // Filter for quality
826
20.4k
        if (ai.IsTerrible(now) && filtered) continue;
  Branch (826:13): [True: 14.1k, False: 6.30k]
  Branch (826:35): [True: 14.1k, False: 0]
827
828
6.30k
        addresses.push_back(ai);
829
6.30k
    }
830
7.83k
    LogDebug(BCLog::ADDRMAN, "GetAddr returned %d random addresses\n", addresses.size());
831
7.83k
    return addresses;
832
7.83k
}
833
834
std::vector<std::pair<AddrInfo, AddressPosition>> AddrManImpl::GetEntries_(bool from_tried) const
835
0
{
836
0
    AssertLockHeld(cs);
837
838
0
    const int bucket_count = from_tried ? ADDRMAN_TRIED_BUCKET_COUNT : ADDRMAN_NEW_BUCKET_COUNT;
  Branch (838:30): [True: 0, False: 0]
839
0
    std::vector<std::pair<AddrInfo, AddressPosition>> infos;
840
0
    for (int bucket = 0; bucket < bucket_count; ++bucket) {
  Branch (840:26): [True: 0, False: 0]
841
0
        for (int position = 0; position < ADDRMAN_BUCKET_SIZE; ++position) {
  Branch (841:32): [True: 0, False: 0]
842
0
            nid_type id = GetEntry(from_tried, bucket, position);
843
0
            if (id >= 0) {
  Branch (843:17): [True: 0, False: 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,
  Branch (847:41): [True: 0, False: 0]
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
599k
{
860
599k
    AssertLockHeld(cs);
861
862
599k
    AddrInfo* pinfo = Find(addr);
863
864
    // if not found, bail out
865
599k
    if (!pinfo)
  Branch (865:9): [True: 599k, False: 18.4E]
866
599k
        return;
867
868
18.4E
    AddrInfo& info = *pinfo;
869
870
    // update info
871
18.4E
    const auto update_interval{20min};
872
18.4E
    if (time - info.nTime > update_interval) {
  Branch (872:9): [True: 0, False: 18.4E]
873
0
        info.nTime = time;
874
0
    }
875
18.4E
}
876
877
void AddrManImpl::SetServices_(const CService& addr, ServiceFlags nServices)
878
150
{
879
150
    AssertLockHeld(cs);
880
881
150
    AddrInfo* pinfo = Find(addr);
882
883
    // if not found, bail out
884
150
    if (!pinfo)
  Branch (884:9): [True: 150, False: 0]
885
150
        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);
896
897
0
    for (std::set<nid_type>::iterator it = m_tried_collisions.begin(); it != m_tried_collisions.end();) {
  Branch (897:72): [True: 0, False: 0]
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)) {
  Branch (903:13): [True: 0, False: 0]
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
  Branch (911:17): [True: 0, False: 0]
912
0
                erase_collision = true;
913
0
            } else if (vvTried[tried_bucket][tried_bucket_pos] != -1) { // The position in the tried bucket is not empty
  Branch (913:24): [True: 0, False: 0]
914
915
                // Get the to-be-evicted address that is being tested
916
0
                nid_type id_old = vvTried[tried_bucket][tried_bucket_pos];
917
0
                AddrInfo& info_old = mapInfo[id_old];
918
919
0
                const auto current_time{Now<NodeSeconds>()};
920
921
                // Has successfully connected in last X hours
922
0
                if (current_time - info_old.m_last_success < ADDRMAN_REPLACEMENT) {
  Branch (922:21): [True: 0, False: 0]
923
0
                    erase_collision = true;
924
0
                } else if (current_time - info_old.m_last_try < ADDRMAN_REPLACEMENT) { // attempted to connect and failed in last X hours
  Branch (924:28): [True: 0, False: 0]
925
926
                    // Give address at least 60 seconds to successfully connect
927
0
                    if (current_time - info_old.m_last_try > 60s) {
  Branch (927:25): [True: 0, False: 0]
928
0
                        LogDebug(BCLog::ADDRMAN, "Replacing %s with %s in tried table\n", info_old.ToStringAddrPort(), info_new.ToStringAddrPort());
929
930
                        // Replaces an existing address already in the tried table with the new address
931
0
                        Good_(info_new, false, current_time);
932
0
                        erase_collision = true;
933
0
                    }
934
0
                } else if (current_time - info_new.m_last_success > ADDRMAN_TEST_WINDOW) {
  Branch (934:28): [True: 0, False: 0]
935
                    // If the collision hasn't resolved in some reasonable amount of time,
936
                    // just evict the old entry -- we must not be able to
937
                    // connect to it for some reason.
938
0
                    LogDebug(BCLog::ADDRMAN, "Unable to test; replacing %s with %s in tried table anyway\n", info_old.ToStringAddrPort(), info_new.ToStringAddrPort());
939
0
                    Good_(info_new, false, current_time);
940
0
                    erase_collision = true;
941
0
                }
942
0
            } else { // Collision is not actually a collision anymore
943
0
                Good_(info_new, false, Now<NodeSeconds>());
944
0
                erase_collision = true;
945
0
            }
946
0
        }
947
948
0
        if (erase_collision) {
  Branch (948:13): [True: 0, False: 0]
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);
959
960
0
    if (m_tried_collisions.size() == 0) return {};
  Branch (960:9): [True: 0, False: 0]
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)) {
  Branch (969:9): [True: 0, False: 0]
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
    const AddrInfo& info_old = mapInfo[vvTried[tried_bucket][tried_bucket_pos]];
981
0
    return {info_old, info_old.m_last_try};
982
0
}
983
984
std::optional<AddressPosition> AddrManImpl::FindAddressEntry_(const CAddress& addr)
985
0
{
986
0
    AssertLockHeld(cs);
987
988
0
    AddrInfo* addr_info = Find(addr);
989
990
0
    if (!addr_info) return std::nullopt;
  Branch (990:9): [True: 0, False: 0]
991
992
0
    if(addr_info->fInTried) {
  Branch (992:8): [True: 0, False: 0]
993
0
        int bucket{addr_info->GetTriedBucket(nKey, m_netgroupman)};
994
0
        return AddressPosition(/*tried_in=*/true,
995
0
                               /*multiplicity_in=*/1,
996
0
                               /*bucket_in=*/bucket,
997
0
                               /*position_in=*/addr_info->GetBucketPosition(nKey, false, bucket));
998
0
    } else {
999
0
        int bucket{addr_info->GetNewBucket(nKey, m_netgroupman)};
1000
0
        return AddressPosition(/*tried_in=*/false,
1001
0
                               /*multiplicity_in=*/addr_info->nRefCount,
1002
0
                               /*bucket_in=*/bucket,
1003
0
                               /*position_in=*/addr_info->GetBucketPosition(nKey, true, bucket));
1004
0
    }
1005
0
}
1006
1007
size_t AddrManImpl::Size_(std::optional<Network> net, std::optional<bool> in_new) const
1008
215k
{
1009
215k
    AssertLockHeld(cs);
1010
1011
215k
    if (!net.has_value()) {
  Branch (1011:9): [True: 215k, False: 0]
1012
215k
        if (in_new.has_value()) {
  Branch (1012:13): [True: 0, False: 215k]
1013
0
            return *in_new ? nNew : nTried;
  Branch (1013:20): [True: 0, False: 0]
1014
215k
        } else {
1015
215k
            return vRandom.size();
1016
215k
        }
1017
215k
    }
1018
0
    if (auto it = m_network_counts.find(*net); it != m_network_counts.end()) {
  Branch (1018:48): [True: 0, False: 0]
1019
0
        auto net_count = it->second;
1020
0
        if (in_new.has_value()) {
  Branch (1020:13): [True: 0, False: 0]
1021
0
            return *in_new ? net_count.n_new : net_count.n_tried;
  Branch (1021:20): [True: 0, False: 0]
1022
0
        } else {
1023
0
            return net_count.n_new + net_count.n_tried;
1024
0
        }
1025
0
    }
1026
0
    return 0;
1027
0
}
1028
1029
void AddrManImpl::Check() const
1030
1.79M
{
1031
1.79M
    AssertLockHeld(cs);
1032
1033
    // Run consistency checks 1 in m_consistency_check_ratio times if enabled
1034
1.79M
    if (m_consistency_check_ratio == 0) return;
  Branch (1034:9): [True: 1.79M, False: 0]
1035
0
    if (insecure_rand.randrange(m_consistency_check_ratio) >= 1) return;
  Branch (1035:9): [True: 0, False: 0]
1036
1037
0
    const int err{CheckAddrman()};
1038
0
    if (err) {
  Branch (1038:9): [True: 0, False: 0]
1039
0
        LogError("ADDRMAN CONSISTENCY CHECK FAILED!!! err=%i", err);
1040
0
        assert(false);
  Branch (1040:9): [Folded - Ignored]
1041
0
    }
1042
0
}
1043
1044
int AddrManImpl::CheckAddrman() const
1045
0
{
1046
0
    AssertLockHeld(cs);
1047
1048
0
    LOG_TIME_MILLIS_WITH_CATEGORY_MSG_ONCE(
1049
0
        strprintf("new %i, tried %i, total %u", nNew, nTried, vRandom.size()), BCLog::ADDRMAN);
1050
1051
0
    std::unordered_set<nid_type> setTried;
1052
0
    std::unordered_map<nid_type, int> mapNew;
1053
0
    std::unordered_map<Network, NewTriedCount> local_counts;
1054
1055
0
    if (vRandom.size() != (size_t)(nTried + nNew))
  Branch (1055:9): [True: 0, False: 0]
1056
0
        return -7;
1057
1058
0
    for (const auto& entry : mapInfo) {
  Branch (1058:28): [True: 0, False: 0]
1059
0
        nid_type n = entry.first;
1060
0
        const AddrInfo& info = entry.second;
1061
0
        if (info.fInTried) {
  Branch (1061:13): [True: 0, False: 0]
1062
0
            if (!TicksSinceEpoch<std::chrono::seconds>(info.m_last_success)) {
  Branch (1062:17): [True: 0, False: 0]
1063
0
                return -1;
1064
0
            }
1065
0
            if (info.nRefCount)
  Branch (1065:17): [True: 0, False: 0]
1066
0
                return -2;
1067
0
            setTried.insert(n);
1068
0
            local_counts[info.GetNetwork()].n_tried++;
1069
0
        } else {
1070
0
            if (info.nRefCount < 0 || info.nRefCount > ADDRMAN_NEW_BUCKETS_PER_ADDRESS)
  Branch (1070:17): [True: 0, False: 0]
  Branch (1070:39): [True: 0, False: 0]
1071
0
                return -3;
1072
0
            if (!info.nRefCount)
  Branch (1072:17): [True: 0, False: 0]
1073
0
                return -4;
1074
0
            mapNew[n] = info.nRefCount;
1075
0
            local_counts[info.GetNetwork()].n_new++;
1076
0
        }
1077
0
        const auto it{mapAddr.find(info)};
1078
0
        if (it == mapAddr.end() || it->second != n) {
  Branch (1078:13): [True: 0, False: 0]
  Branch (1078:13): [True: 0, False: 0]
  Branch (1078:36): [True: 0, False: 0]
1079
0
            return -5;
1080
0
        }
1081
0
        if (info.nRandomPos < 0 || (size_t)info.nRandomPos >= vRandom.size() || vRandom[info.nRandomPos] != n)
  Branch (1081:13): [True: 0, False: 0]
  Branch (1081:36): [True: 0, False: 0]
  Branch (1081:81): [True: 0, False: 0]
1082
0
            return -14;
1083
0
        if (info.m_last_try < NodeSeconds{0s}) {
  Branch (1083:13): [True: 0, False: 0]
1084
0
            return -6;
1085
0
        }
1086
0
        if (info.m_last_success < NodeSeconds{0s}) {
  Branch (1086:13): [True: 0, False: 0]
1087
0
            return -8;
1088
0
        }
1089
0
    }
1090
1091
0
    if (setTried.size() != (size_t)nTried)
  Branch (1091:9): [True: 0, False: 0]
1092
0
        return -9;
1093
0
    if (mapNew.size() != (size_t)nNew)
  Branch (1093:9): [True: 0, False: 0]
1094
0
        return -10;
1095
1096
0
    for (int n = 0; n < ADDRMAN_TRIED_BUCKET_COUNT; n++) {
  Branch (1096:21): [True: 0, False: 0]
1097
0
        for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) {
  Branch (1097:25): [True: 0, False: 0]
1098
0
            if (vvTried[n][i] != -1) {
  Branch (1098:17): [True: 0, False: 0]
1099
0
                if (!setTried.contains(vvTried[n][i]))
  Branch (1099:21): [True: 0, False: 0]
1100
0
                    return -11;
1101
0
                const auto it{mapInfo.find(vvTried[n][i])};
1102
0
                if (it == mapInfo.end() || it->second.GetTriedBucket(nKey, m_netgroupman) != n) {
  Branch (1102:21): [True: 0, False: 0]
  Branch (1102:21): [True: 0, False: 0]
  Branch (1102:44): [True: 0, False: 0]
1103
0
                    return -17;
1104
0
                }
1105
0
                if (it->second.GetBucketPosition(nKey, false, n) != i) {
  Branch (1105:21): [True: 0, False: 0]
1106
0
                    return -18;
1107
0
                }
1108
0
                setTried.erase(vvTried[n][i]);
1109
0
            }
1110
0
        }
1111
0
    }
1112
1113
0
    for (int n = 0; n < ADDRMAN_NEW_BUCKET_COUNT; n++) {
  Branch (1113:21): [True: 0, False: 0]
1114
0
        for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) {
  Branch (1114:25): [True: 0, False: 0]
1115
0
            if (vvNew[n][i] != -1) {
  Branch (1115:17): [True: 0, False: 0]
1116
0
                if (!mapNew.contains(vvNew[n][i]))
  Branch (1116:21): [True: 0, False: 0]
1117
0
                    return -12;
1118
0
                const auto it{mapInfo.find(vvNew[n][i])};
1119
0
                if (it == mapInfo.end() || it->second.GetBucketPosition(nKey, true, n) != i) {
  Branch (1119:21): [True: 0, False: 0]
  Branch (1119:21): [True: 0, False: 0]
  Branch (1119:44): [True: 0, False: 0]
1120
0
                    return -19;
1121
0
                }
1122
0
                if (--mapNew[vvNew[n][i]] == 0)
  Branch (1122:21): [True: 0, False: 0]
1123
0
                    mapNew.erase(vvNew[n][i]);
1124
0
            }
1125
0
        }
1126
0
    }
1127
1128
0
    if (setTried.size())
  Branch (1128:9): [True: 0, False: 0]
1129
0
        return -13;
1130
0
    if (mapNew.size())
  Branch (1130:9): [True: 0, False: 0]
1131
0
        return -15;
1132
0
    if (nKey.IsNull())
  Branch (1132:9): [True: 0, False: 0]
1133
0
        return -16;
1134
1135
    // It's possible that m_network_counts may have all-zero entries that local_counts
1136
    // doesn't have if addrs from a network were being added and then removed again in the past.
1137
0
    if (m_network_counts.size() < local_counts.size()) {
  Branch (1137:9): [True: 0, False: 0]
1138
0
        return -20;
1139
0
    }
1140
0
    for (const auto& [net, count] : m_network_counts) {
  Branch (1140:35): [True: 0, False: 0]
1141
0
        if (local_counts[net].n_new != count.n_new || local_counts[net].n_tried != count.n_tried) {
  Branch (1141:13): [True: 0, False: 0]
  Branch (1141:55): [True: 0, False: 0]
1142
0
            return -21;
1143
0
        }
1144
0
    }
1145
1146
0
    return 0;
1147
0
}
1148
1149
size_t AddrManImpl::Size(std::optional<Network> net, std::optional<bool> in_new) const
1150
215k
{
1151
215k
    LOCK(cs);
1152
215k
    Check();
1153
215k
    auto ret = Size_(net, in_new);
1154
215k
    Check();
1155
215k
    return ret;
1156
215k
}
1157
1158
bool AddrManImpl::Add(const std::vector<CAddress>& vAddr, const CNetAddr& source, std::chrono::seconds time_penalty)
1159
69.2k
{
1160
69.2k
    LOCK(cs);
1161
69.2k
    Check();
1162
69.2k
    auto ret = Add_(vAddr, source, time_penalty);
1163
69.2k
    Check();
1164
69.2k
    return ret;
1165
69.2k
}
1166
1167
bool AddrManImpl::Good(const CService& addr, NodeSeconds time)
1168
21
{
1169
21
    LOCK(cs);
1170
21
    Check();
1171
21
    auto ret = Good_(addr, /*test_before_evict=*/true, time);
1172
21
    Check();
1173
21
    return ret;
1174
21
}
1175
1176
void AddrManImpl::Attempt(const CService& addr, bool fCountFailure, NodeSeconds time)
1177
2.74k
{
1178
2.74k
    LOCK(cs);
1179
2.74k
    Check();
1180
2.74k
    Attempt_(addr, fCountFailure, time);
1181
2.74k
    Check();
1182
2.74k
}
1183
1184
void AddrManImpl::ResolveCollisions()
1185
0
{
1186
0
    LOCK(cs);
1187
0
    Check();
1188
0
    ResolveCollisions_();
1189
0
    Check();
1190
0
}
1191
1192
std::pair<CAddress, NodeSeconds> AddrManImpl::SelectTriedCollision()
1193
0
{
1194
0
    LOCK(cs);
1195
0
    Check();
1196
0
    auto ret = SelectTriedCollision_();
1197
0
    Check();
1198
0
    return ret;
1199
0
}
1200
1201
std::pair<CAddress, NodeSeconds> AddrManImpl::Select(bool new_only, const std::unordered_set<Network>& networks) const
1202
0
{
1203
0
    LOCK(cs);
1204
0
    Check();
1205
0
    auto addrRet = Select_(new_only, networks);
1206
0
    Check();
1207
0
    return addrRet;
1208
0
}
1209
1210
std::vector<CAddress> AddrManImpl::GetAddr(size_t max_addresses, size_t max_pct, std::optional<Network> network, const bool filtered) const
1211
7.83k
{
1212
7.83k
    LOCK(cs);
1213
7.83k
    Check();
1214
7.83k
    auto addresses = GetAddr_(max_addresses, max_pct, network, filtered);
1215
7.83k
    Check();
1216
7.83k
    return addresses;
1217
7.83k
}
1218
1219
std::vector<std::pair<AddrInfo, AddressPosition>> AddrManImpl::GetEntries(bool from_tried) const
1220
0
{
1221
0
    LOCK(cs);
1222
0
    Check();
1223
0
    auto addrInfos = GetEntries_(from_tried);
1224
0
    Check();
1225
0
    return addrInfos;
1226
0
}
1227
1228
void AddrManImpl::Connected(const CService& addr, NodeSeconds time)
1229
599k
{
1230
599k
    LOCK(cs);
1231
599k
    Check();
1232
599k
    Connected_(addr, time);
1233
599k
    Check();
1234
599k
}
1235
1236
void AddrManImpl::SetServices(const CService& addr, ServiceFlags nServices)
1237
150
{
1238
150
    LOCK(cs);
1239
150
    Check();
1240
150
    SetServices_(addr, nServices);
1241
150
    Check();
1242
150
}
1243
1244
std::optional<AddressPosition> AddrManImpl::FindAddressEntry(const CAddress& addr)
1245
0
{
1246
0
    LOCK(cs);
1247
0
    Check();
1248
0
    auto entry = FindAddressEntry_(addr);
1249
0
    Check();
1250
0
    return entry;
1251
0
}
1252
1253
AddrMan::AddrMan(const NetGroupManager& netgroupman, bool deterministic, int32_t consistency_check_ratio)
1254
54
    : m_impl(std::make_unique<AddrManImpl>(netgroupman, deterministic, consistency_check_ratio)) {}
1255
1256
150k
AddrMan::~AddrMan() = default;
1257
1258
template <typename Stream>
1259
void AddrMan::Serialize(Stream& s_) const
1260
215k
{
1261
215k
    m_impl->Serialize<Stream>(s_);
1262
215k
}
void AddrMan::Serialize<HashedSourceWriter<AutoFile> >(HashedSourceWriter<AutoFile>&) const
Line
Count
Source
1260
215k
{
1261
215k
    m_impl->Serialize<Stream>(s_);
1262
215k
}
Unexecuted instantiation: void AddrMan::Serialize<DataStream>(DataStream&) const
1263
1264
template <typename Stream>
1265
void AddrMan::Unserialize(Stream& s_)
1266
0
{
1267
0
    m_impl->Unserialize<Stream>(s_);
1268
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>&)
1269
1270
// explicit instantiation
1271
template void AddrMan::Serialize(HashedSourceWriter<AutoFile>&) const;
1272
template void AddrMan::Serialize(DataStream&) const;
1273
template void AddrMan::Unserialize(AutoFile&);
1274
template void AddrMan::Unserialize(HashVerifier<AutoFile>&);
1275
template void AddrMan::Unserialize(DataStream&);
1276
template void AddrMan::Unserialize(HashVerifier<DataStream>&);
1277
1278
size_t AddrMan::Size(std::optional<Network> net, std::optional<bool> in_new) const
1279
215k
{
1280
215k
    return m_impl->Size(net, in_new);
1281
215k
}
1282
1283
bool AddrMan::Add(const std::vector<CAddress>& vAddr, const CNetAddr& source, std::chrono::seconds time_penalty)
1284
69.2k
{
1285
69.2k
    return m_impl->Add(vAddr, source, time_penalty);
1286
69.2k
}
1287
1288
bool AddrMan::Good(const CService& addr, NodeSeconds time)
1289
21
{
1290
21
    return m_impl->Good(addr, time);
1291
21
}
1292
1293
void AddrMan::Attempt(const CService& addr, bool fCountFailure, NodeSeconds time)
1294
2.74k
{
1295
2.74k
    m_impl->Attempt(addr, fCountFailure, time);
1296
2.74k
}
1297
1298
void AddrMan::ResolveCollisions()
1299
0
{
1300
0
    m_impl->ResolveCollisions();
1301
0
}
1302
1303
std::pair<CAddress, NodeSeconds> AddrMan::SelectTriedCollision()
1304
0
{
1305
0
    return m_impl->SelectTriedCollision();
1306
0
}
1307
1308
std::pair<CAddress, NodeSeconds> AddrMan::Select(bool new_only, const std::unordered_set<Network>& networks) const
1309
0
{
1310
0
    return m_impl->Select(new_only, networks);
1311
0
}
1312
1313
std::vector<CAddress> AddrMan::GetAddr(size_t max_addresses, size_t max_pct, std::optional<Network> network, const bool filtered) const
1314
7.83k
{
1315
7.83k
    return m_impl->GetAddr(max_addresses, max_pct, network, filtered);
1316
7.83k
}
1317
1318
std::vector<std::pair<AddrInfo, AddressPosition>> AddrMan::GetEntries(bool use_tried) const
1319
0
{
1320
0
    return m_impl->GetEntries(use_tried);
1321
0
}
1322
1323
void AddrMan::Connected(const CService& addr, NodeSeconds time)
1324
599k
{
1325
599k
    m_impl->Connected(addr, time);
1326
599k
}
1327
1328
void AddrMan::SetServices(const CService& addr, ServiceFlags nServices)
1329
150
{
1330
150
    m_impl->SetServices(addr, nServices);
1331
150
}
1332
1333
std::optional<AddressPosition> AddrMan::FindAddressEntry(const CAddress& addr)
1334
0
{
1335
0
    return m_impl->FindAddressEntry(addr);
1336
0
}