Coverage Report

Created: 2026-11-13 17:38

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