Coverage Report

Created: 2026-09-01 13:33

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/bitcoin/src/node/eviction.cpp
Line
Count
Source
1
// Copyright (c) 2022-present The Bitcoin Core developers
2
// Distributed under the MIT software license, see the accompanying
3
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5
#include <node/eviction.h>
6
7
#include <algorithm>
8
#include <array>
9
#include <chrono>
10
#include <cstdint>
11
#include <functional>
12
#include <map>
13
#include <vector>
14
15
16
static bool ReverseCompareNodeMinPingTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
17
21.4M
{
18
21.4M
    return a.m_min_ping_time > b.m_min_ping_time;
19
21.4M
}
20
21
static bool ReverseCompareNodeTimeConnected(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
22
15.7M
{
23
15.7M
    return a.m_connected > b.m_connected;
24
15.7M
}
25
26
28.3M
static bool CompareNetGroupKeyed(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b) {
27
28.3M
    return a.nKeyedNetGroup < b.nKeyedNetGroup;
28
28.3M
}
29
30
static bool CompareNodeBlockTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
31
20.3M
{
32
    // There is a fall-through here because it is common for a node to have many peers which have not yet relayed a block.
33
20.3M
    if (a.m_last_block_time != b.m_last_block_time) return a.m_last_block_time < b.m_last_block_time;
  Branch (33:9): [True: 2.37M, False: 17.9M]
34
17.9M
    if (a.fRelevantServices != b.fRelevantServices) return b.fRelevantServices;
  Branch (34:9): [True: 5.37k, False: 17.9M]
35
17.9M
    return a.m_connected > b.m_connected;
36
17.9M
}
37
38
static bool CompareNodeTXTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
39
20.1M
{
40
    // There is a fall-through here because it is common for a node to have more than a few peers that have not yet relayed txn.
41
20.1M
    if (a.m_last_tx_time != b.m_last_tx_time) return a.m_last_tx_time < b.m_last_tx_time;
  Branch (41:9): [True: 1.58M, False: 18.5M]
42
18.5M
    if (a.m_relay_txs != b.m_relay_txs) return b.m_relay_txs;
  Branch (42:9): [True: 3.12k, False: 18.5M]
43
18.5M
    if (a.fBloomFilter != b.fBloomFilter) return a.fBloomFilter;
  Branch (43:9): [True: 6.78k, False: 18.5M]
44
18.5M
    return a.m_connected > b.m_connected;
45
18.5M
}
46
47
// Pick out the potential block-relay only peers, and sort them by last block time.
48
static bool CompareNodeBlockRelayOnlyTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
49
19.4M
{
50
19.4M
    if (a.m_relay_txs != b.m_relay_txs) return a.m_relay_txs;
  Branch (50:9): [True: 10.1k, False: 19.4M]
51
19.4M
    if (a.m_last_block_time != b.m_last_block_time) return a.m_last_block_time < b.m_last_block_time;
  Branch (51:9): [True: 1.50M, False: 17.9M]
52
17.9M
    if (a.fRelevantServices != b.fRelevantServices) return b.fRelevantServices;
  Branch (52:9): [True: 4.77k, False: 17.9M]
53
17.9M
    return a.m_connected > b.m_connected;
54
17.9M
}
55
56
/**
57
 * Sort eviction candidates by network/localhost and connection uptime.
58
 * Candidates near the beginning are more likely to be evicted, and those
59
 * near the end are more likely to be protected, e.g. less likely to be evicted.
60
 * - First, nodes that are not `is_local` and that do not belong to `network`,
61
 *   sorted by increasing uptime (from most recently connected to connected longer).
62
 * - Then, nodes that are `is_local` or belong to `network`, sorted by increasing uptime.
63
 */
64
struct CompareNodeNetworkTime {
65
    const bool m_is_local;
66
    const Network m_network;
67
68.1k
    CompareNodeNetworkTime(bool is_local, Network network) : m_is_local(is_local), m_network(network) {}
68
    bool operator()(const NodeEvictionCandidate& a, const NodeEvictionCandidate& b) const
69
79.8M
    {
70
79.8M
        if (m_is_local && a.m_is_local != b.m_is_local) return b.m_is_local;
  Branch (70:13): [True: 17.2M, False: 62.6M]
  Branch (70:27): [True: 810k, False: 16.4M]
71
79.0M
        if ((a.m_network == m_network) != (b.m_network == m_network)) return b.m_network == m_network;
  Branch (71:13): [True: 3.21M, False: 75.8M]
72
75.8M
        return a.m_connected > b.m_connected;
73
79.0M
    };
74
};
75
76
//! Sort an array by the specified comparator, then erase the last K elements where predicate is true.
77
template <typename T, typename Comparator>
78
static void EraseLastKElements(
79
    std::vector<T>& elements, Comparator comparator, size_t k,
80
1.74M
    std::function<bool(const NodeEvictionCandidate&)> predicate = [](const NodeEvictionCandidate& n) { return true; })
81
270k
{
82
270k
    std::sort(elements.begin(), elements.end(), comparator);
83
270k
    size_t eraseSize = std::min(k, elements.size());
84
270k
    elements.erase(std::remove_if(elements.end() - eraseSize, elements.end(), predicate), elements.end());
85
270k
}
eviction.cpp:_ZL18EraseLastKElementsI21NodeEvictionCandidate22CompareNodeNetworkTimeEvRSt6vectorIT_SaIS3_EET0_mSt8functionIFbRKS0_EE
Line
Count
Source
81
68.1k
{
82
68.1k
    std::sort(elements.begin(), elements.end(), comparator);
83
68.1k
    size_t eraseSize = std::min(k, elements.size());
84
68.1k
    elements.erase(std::remove_if(elements.end() - eraseSize, elements.end(), predicate), elements.end());
85
68.1k
}
eviction.cpp:_ZL18EraseLastKElementsI21NodeEvictionCandidatePFbRKS0_S2_EEvRSt6vectorIT_SaIS6_EET0_mSt8functionIFbS2_EE
Line
Count
Source
81
202k
{
82
202k
    std::sort(elements.begin(), elements.end(), comparator);
83
202k
    size_t eraseSize = std::min(k, elements.size());
84
202k
    elements.erase(std::remove_if(elements.end() - eraseSize, elements.end(), predicate), elements.end());
85
202k
}
86
87
void ProtectNoBanConnections(std::vector<NodeEvictionCandidate>& eviction_candidates)
88
33.7k
{
89
33.7k
    eviction_candidates.erase(std::remove_if(eviction_candidates.begin(), eviction_candidates.end(),
90
5.77M
                                             [](NodeEvictionCandidate const& n) {
91
5.77M
                                                 return n.m_noban;
92
5.77M
                                             }),
93
33.7k
                              eviction_candidates.end());
94
33.7k
}
95
96
void ProtectOutboundConnections(std::vector<NodeEvictionCandidate>& eviction_candidates)
97
33.7k
{
98
33.7k
    eviction_candidates.erase(std::remove_if(eviction_candidates.begin(), eviction_candidates.end(),
99
4.31M
                                             [](NodeEvictionCandidate const& n) {
100
4.31M
                                                 return n.m_conn_type != ConnectionType::INBOUND;
101
4.31M
                                             }),
102
33.7k
                              eviction_candidates.end());
103
33.7k
}
104
105
void ProtectEvictionCandidatesByRatio(std::vector<NodeEvictionCandidate>& eviction_candidates)
106
33.7k
{
107
    // Protect the half of the remaining nodes which have been connected the longest.
108
    // This replicates the non-eviction implicit behavior, and precludes attacks that start later.
109
    // To favorise the diversity of our peer connections, reserve up to half of these protected
110
    // spots for Tor/onion, localhost, I2P, and CJDNS peers, even if they're not longest uptime
111
    // overall. This helps protect these higher-latency peers that tend to be otherwise
112
    // disadvantaged under our eviction criteria.
113
33.7k
    const size_t initial_size = eviction_candidates.size();
114
33.7k
    const size_t total_protect_size{initial_size / 2};
115
116
    // Disadvantaged networks to protect. In the case of equal counts, earlier array members
117
    // have the first opportunity to recover unused slots from the previous iteration.
118
33.7k
    struct Net { bool is_local; Network id; size_t count; };
119
33.7k
    std::array<Net, 4> networks{
120
33.7k
        {{false, NET_CJDNS, 0}, {false, NET_I2P, 0}, {/*localhost=*/true, NET_MAX, 0}, {false, NET_ONION, 0}}};
121
122
    // Count and store the number of eviction candidates per network.
123
134k
    for (Net& n : networks) {
  Branch (123:17): [True: 134k, False: 33.7k]
124
134k
        n.count = std::count_if(eviction_candidates.cbegin(), eviction_candidates.cend(),
125
12.9M
                                [&n](const NodeEvictionCandidate& c) {
126
12.9M
                                    return n.is_local ? c.m_is_local : c.m_network == n.id;
  Branch (126:44): [True: 3.24M, False: 9.73M]
127
12.9M
                                });
128
134k
    }
129
    // Sort `networks` by ascending candidate count, to give networks having fewer candidates
130
    // the first opportunity to recover unused protected slots from the previous iteration.
131
200k
    std::stable_sort(networks.begin(), networks.end(), [](Net a, Net b) { return a.count < b.count; });
132
133
    // Protect up to 25% of the eviction candidates by disadvantaged network.
134
33.7k
    const size_t max_protect_by_network{total_protect_size / 2};
135
33.7k
    size_t num_protected{0};
136
137
70.3k
    while (num_protected < max_protect_by_network) {
  Branch (137:12): [True: 50.4k, False: 19.8k]
138
        // Count the number of disadvantaged networks from which we have peers to protect.
139
201k
        auto num_networks = std::count_if(networks.begin(), networks.end(), [](const Net& n) { return n.count; });
140
50.4k
        if (num_networks == 0) {
  Branch (140:13): [True: 10.8k, False: 39.5k]
141
10.8k
            break;
142
10.8k
        }
143
39.5k
        const size_t disadvantaged_to_protect{max_protect_by_network - num_protected};
144
39.5k
        const size_t protect_per_network{std::max(disadvantaged_to_protect / num_networks, static_cast<size_t>(1))};
145
        // Early exit flag if there are no remaining candidates by disadvantaged network.
146
39.5k
        bool protected_at_least_one{false};
147
148
155k
        for (Net& n : networks) {
  Branch (148:21): [True: 155k, False: 27.4k]
149
155k
            if (n.count == 0) continue;
  Branch (149:17): [True: 87.8k, False: 68.1k]
150
68.1k
            const size_t before = eviction_candidates.size();
151
68.1k
            EraseLastKElements(eviction_candidates, CompareNodeNetworkTime(n.is_local, n.id),
152
1.03M
                               protect_per_network, [&n](const NodeEvictionCandidate& c) {
153
1.03M
                                   return n.is_local ? c.m_is_local : c.m_network == n.id;
  Branch (153:43): [True: 252k, False: 784k]
154
1.03M
                               });
155
68.1k
            const size_t after = eviction_candidates.size();
156
68.1k
            if (before > after) {
  Branch (156:17): [True: 62.9k, False: 5.20k]
157
62.9k
                protected_at_least_one = true;
158
62.9k
                const size_t delta{before - after};
159
62.9k
                num_protected += delta;
160
62.9k
                if (num_protected >= max_protect_by_network) {
  Branch (160:21): [True: 12.1k, False: 50.7k]
161
12.1k
                    break;
162
12.1k
                }
163
50.7k
                n.count -= delta;
164
50.7k
            }
165
68.1k
        }
166
39.5k
        if (!protected_at_least_one) {
  Branch (166:13): [True: 2.98k, False: 36.5k]
167
2.98k
            break;
168
2.98k
        }
169
39.5k
    }
170
171
    // Calculate how many we removed, and update our total number of peers that
172
    // we want to protect based on uptime accordingly.
173
33.7k
    assert(num_protected == initial_size - eviction_candidates.size());
  Branch (173:5): [True: 33.7k, False: 0]
174
33.7k
    const size_t remaining_to_protect{total_protect_size - num_protected};
175
33.7k
    EraseLastKElements(eviction_candidates, ReverseCompareNodeTimeConnected, remaining_to_protect);
176
33.7k
}
177
178
[[nodiscard]] std::optional<NodeId> SelectNodeToEvict(std::vector<NodeEvictionCandidate>&& vEvictionCandidates)
179
33.7k
{
180
    // Protect connections with certain characteristics
181
182
33.7k
    ProtectNoBanConnections(vEvictionCandidates);
183
184
33.7k
    ProtectOutboundConnections(vEvictionCandidates);
185
186
    // Deterministically select 4 peers to protect by netgroup.
187
    // An attacker cannot predict which netgroups will be protected
188
33.7k
    EraseLastKElements(vEvictionCandidates, CompareNetGroupKeyed, 4);
189
    // Protect the 8 nodes with the lowest minimum ping time.
190
    // An attacker cannot manipulate this metric without physically moving nodes closer to the target.
191
33.7k
    EraseLastKElements(vEvictionCandidates, ReverseCompareNodeMinPingTime, 8);
192
    // Protect 4 nodes that most recently sent us novel transactions accepted into our mempool.
193
    // An attacker cannot manipulate this metric without performing useful work.
194
33.7k
    EraseLastKElements(vEvictionCandidates, CompareNodeTXTime, 4);
195
    // Protect up to 8 non-tx-relay peers that have sent us novel blocks.
196
33.7k
    EraseLastKElements(vEvictionCandidates, CompareNodeBlockRelayOnlyTime, 8,
197
229k
                       [](const NodeEvictionCandidate& n) { return !n.m_relay_txs && n.fRelevantServices; });
  Branch (197:68): [True: 227k, False: 1.89k]
  Branch (197:86): [True: 129, False: 227k]
198
199
    // Protect 4 nodes that most recently sent us novel blocks.
200
    // An attacker cannot manipulate this metric without performing useful work.
201
33.7k
    EraseLastKElements(vEvictionCandidates, CompareNodeBlockTime, 4);
202
203
    // Protect some of the remaining eviction candidates by ratios of desirable
204
    // or disadvantaged characteristics.
205
33.7k
    ProtectEvictionCandidatesByRatio(vEvictionCandidates);
206
207
33.7k
    if (vEvictionCandidates.empty()) return std::nullopt;
  Branch (207:9): [True: 5.91k, False: 27.8k]
208
209
    // If any remaining peers are preferred for eviction consider only them.
210
    // This happens after the other preferences since if a peer is really the best by other criteria (esp relaying blocks)
211
    //  then we probably don't want to evict it no matter what.
212
1.60M
    if (std::any_of(vEvictionCandidates.begin(),vEvictionCandidates.end(),[](NodeEvictionCandidate const &n){return n.prefer_evict;})) {
  Branch (212:9): [True: 119, False: 27.7k]
213
119
        vEvictionCandidates.erase(std::remove_if(vEvictionCandidates.begin(),vEvictionCandidates.end(),
214
72.1k
                                  [](NodeEvictionCandidate const &n){return !n.prefer_evict;}),vEvictionCandidates.end());
215
119
    }
216
217
    // Identify the network group with the most connections and youngest member.
218
    // (vEvictionCandidates is already sorted by reverse connect time)
219
27.8k
    uint64_t naMostConnections;
220
27.8k
    unsigned int nMostConnections = 0;
221
27.8k
    NodeClock::time_point nMostConnectionsTime{NodeClock::epoch};
222
27.8k
    std::map<uint64_t, std::vector<NodeEvictionCandidate> > mapNetGroupNodes;
223
1.56M
    for (const NodeEvictionCandidate &node : vEvictionCandidates) {
  Branch (223:44): [True: 1.56M, False: 27.8k]
224
1.56M
        std::vector<NodeEvictionCandidate> &group = mapNetGroupNodes[node.nKeyedNetGroup];
225
1.56M
        group.push_back(node);
226
1.56M
        const auto grouptime{group[0].m_connected};
227
228
1.56M
        if (group.size() > nMostConnections || (group.size() == nMostConnections && grouptime > nMostConnectionsTime)) {
  Branch (228:13): [True: 614k, False: 947k]
  Branch (228:49): [True: 148k, False: 799k]
  Branch (228:85): [True: 87, False: 148k]
229
614k
            nMostConnections = group.size();
230
614k
            nMostConnectionsTime = grouptime;
231
614k
            naMostConnections = node.nKeyedNetGroup;
232
614k
        }
233
1.56M
    }
234
235
    // Reduce to the network group with the most connections
236
27.8k
    vEvictionCandidates = std::move(mapNetGroupNodes[naMostConnections]);
237
238
    // Disconnect from the network group with the most connections
239
27.8k
    return vEvictionCandidates.front().id;
240
33.7k
}