Coverage Report

Created: 2026-11-13 17:38

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