Bitcoin Core 32.99.0
P2P Digital Currency
Loading...
Searching...
No Matches
eviction.cpp
Go to the documentation of this file.
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
17{
18 return a.m_min_ping_time > b.m_min_ping_time;
19}
20
22{
23 return a.m_connected > b.m_connected;
24}
25
27 return a.nKeyedNetGroup < b.nKeyedNetGroup;
28}
29
31{
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 if (a.m_last_block_time != b.m_last_block_time) return a.m_last_block_time < b.m_last_block_time;
34 if (a.fRelevantServices != b.fRelevantServices) return b.fRelevantServices;
35 return a.m_connected > b.m_connected;
36}
37
39{
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 if (a.m_last_tx_time != b.m_last_tx_time) return a.m_last_tx_time < b.m_last_tx_time;
42 if (a.m_relay_txs != b.m_relay_txs) return b.m_relay_txs;
43 if (a.fBloomFilter != b.fBloomFilter) return a.fBloomFilter;
44 return a.m_connected > b.m_connected;
45}
46
47// Pick out the potential block-relay only peers, and sort them by last block time.
49{
50 if (a.m_relay_txs != b.m_relay_txs) return a.m_relay_txs;
51 if (a.m_last_block_time != b.m_last_block_time) return a.m_last_block_time < b.m_last_block_time;
52 if (a.fRelevantServices != b.fRelevantServices) return b.fRelevantServices;
53 return a.m_connected > b.m_connected;
54}
55
65 const bool m_is_local;
69 {
70 if (m_is_local && a.m_is_local != b.m_is_local) return b.m_is_local;
71 if ((a.m_network == m_network) != (b.m_network == m_network)) return b.m_network == m_network;
72 return a.m_connected > b.m_connected;
73 };
74};
75
77template <typename T, typename Comparator>
79 std::vector<T>& elements, Comparator comparator, size_t k,
80 std::function<bool(const NodeEvictionCandidate&)> predicate = [](const NodeEvictionCandidate& n) { return true; })
81{
82 std::sort(elements.begin(), elements.end(), comparator);
83 size_t eraseSize = std::min(k, elements.size());
84 elements.erase(std::remove_if(elements.end() - eraseSize, elements.end(), predicate), elements.end());
85}
86
87void ProtectNoBanConnections(std::vector<NodeEvictionCandidate>& eviction_candidates)
88{
89 std::erase_if(eviction_candidates, [](const NodeEvictionCandidate& n) { return n.m_noban; });
90}
91
92void ProtectOutboundConnections(std::vector<NodeEvictionCandidate>& eviction_candidates)
93{
94 std::erase_if(eviction_candidates, [](const NodeEvictionCandidate& n) { return n.m_conn_type != ConnectionType::INBOUND; });
95}
96
97void ProtectEvictionCandidatesByRatio(std::vector<NodeEvictionCandidate>& eviction_candidates)
98{
99 // Protect the half of the remaining nodes which have been connected the longest.
100 // This replicates the non-eviction implicit behavior, and precludes attacks that start later.
101 // To favorise the diversity of our peer connections, reserve up to half of these protected
102 // spots for Tor/onion, localhost, I2P, and CJDNS peers, even if they're not longest uptime
103 // overall. This helps protect these higher-latency peers that tend to be otherwise
104 // disadvantaged under our eviction criteria.
105 const size_t initial_size = eviction_candidates.size();
106 const size_t total_protect_size{initial_size / 2};
107
108 // Disadvantaged networks to protect. In the case of equal counts, earlier array members
109 // have the first opportunity to recover unused slots from the previous iteration.
110 struct Net { bool is_local; Network id; size_t count; };
111 std::array<Net, 4> networks{
112 {{false, NET_CJDNS, 0}, {false, NET_I2P, 0}, {/*localhost=*/true, NET_MAX, 0}, {false, NET_ONION, 0}}};
113
114 // Count and store the number of eviction candidates per network.
115 for (Net& n : networks) {
116 n.count = std::count_if(eviction_candidates.cbegin(), eviction_candidates.cend(),
117 [&n](const NodeEvictionCandidate& c) {
118 return n.is_local ? c.m_is_local : c.m_network == n.id;
119 });
120 }
121 // Sort `networks` by ascending candidate count, to give networks having fewer candidates
122 // the first opportunity to recover unused protected slots from the previous iteration.
123 std::stable_sort(networks.begin(), networks.end(), [](Net a, Net b) { return a.count < b.count; });
124
125 // Protect up to 25% of the eviction candidates by disadvantaged network.
127 size_t num_protected{0};
128
130 // Count the number of disadvantaged networks from which we have peers to protect.
131 auto num_networks = std::count_if(networks.begin(), networks.end(), [](const Net& n) { return n.count; });
132 if (num_networks == 0) {
133 break;
134 }
136 const size_t protect_per_network{std::max(disadvantaged_to_protect / num_networks, static_cast<size_t>(1))};
137 // Early exit flag if there are no remaining candidates by disadvantaged network.
138 bool protected_at_least_one{false};
139
140 for (Net& n : networks) {
141 if (n.count == 0) continue;
142 const size_t before = eviction_candidates.size();
145 return n.is_local ? c.m_is_local : c.m_network == n.id;
146 });
147 const size_t after = eviction_candidates.size();
148 if (before > after) {
150 const size_t delta{before - after};
151 num_protected += delta;
153 break;
154 }
155 n.count -= delta;
156 }
157 }
159 break;
160 }
161 }
162
163 // Calculate how many we removed, and update our total number of peers that
164 // we want to protect based on uptime accordingly.
168}
169
170[[nodiscard]] std::optional<NodeId> SelectNodeToEvict(std::vector<NodeEvictionCandidate>&& vEvictionCandidates)
171{
172 // Protect connections with certain characteristics
173
175
177
178 // Deterministically select 4 peers to protect by netgroup.
179 // An attacker cannot predict which netgroups will be protected
181 // Protect the 8 nodes with the lowest minimum ping time.
182 // An attacker cannot manipulate this metric without physically moving nodes closer to the target.
184 // Protect 4 nodes that most recently sent us novel transactions accepted into our mempool.
185 // An attacker cannot manipulate this metric without performing useful work.
187 // Protect up to 8 non-tx-relay peers that have sent us novel blocks.
189 [](const NodeEvictionCandidate& n) { return !n.m_relay_txs && n.fRelevantServices; });
190
191 // Protect 4 nodes that most recently sent us novel blocks.
192 // An attacker cannot manipulate this metric without performing useful work.
194
195 // Protect some of the remaining eviction candidates by ratios of desirable
196 // or disadvantaged characteristics.
198
199 if (vEvictionCandidates.empty()) return std::nullopt;
200
201 // If any remaining peers are preferred for eviction consider only them.
202 // This happens after the other preferences since if a peer is really the best by other criteria (esp relaying blocks)
203 // then we probably don't want to evict it no matter what.
204 if (std::any_of(vEvictionCandidates.begin(),vEvictionCandidates.end(),[](NodeEvictionCandidate const &n){return n.prefer_evict;})) {
205 std::erase_if(vEvictionCandidates, [](const NodeEvictionCandidate& n) { return !n.prefer_evict; });
206 }
207
208 // Identify the network group with the most connections and youngest member.
209 // (vEvictionCandidates is already sorted by reverse connect time)
211 unsigned int nMostConnections = 0;
213 std::map<uint64_t, std::vector<NodeEvictionCandidate> > mapNetGroupNodes;
215 std::vector<NodeEvictionCandidate> &group = mapNetGroupNodes[node.nKeyedNetGroup];
216 group.push_back(node);
217 const auto grouptime{group[0].m_connected};
218
219 if (group.size() > nMostConnections || (group.size() == nMostConnections && grouptime > nMostConnectionsTime)) {
220 nMostConnections = group.size();
222 naMostConnections = node.nKeyedNetGroup;
223 }
224 }
225
226 // Reduce to the network group with the most connections
228
229 // Disconnect from the network group with the most connections
230 return vEvictionCandidates.front().id;
231}
@ INBOUND
Inbound connections are those initiated by a peer.
static bool CompareNodeBlockTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
Definition eviction.cpp:30
static void EraseLastKElements(std::vector< T > &elements, Comparator comparator, size_t k, std::function< bool(const NodeEvictionCandidate &)> predicate=[](const NodeEvictionCandidate &n) { return true;})
Sort an array by the specified comparator, then erase the last K elements where predicate is true.
Definition eviction.cpp:78
static bool CompareNodeBlockRelayOnlyTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
Definition eviction.cpp:48
void ProtectNoBanConnections(std::vector< NodeEvictionCandidate > &eviction_candidates)
Definition eviction.cpp:87
static bool ReverseCompareNodeTimeConnected(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
Definition eviction.cpp:21
static bool CompareNetGroupKeyed(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
Definition eviction.cpp:26
void ProtectEvictionCandidatesByRatio(std::vector< NodeEvictionCandidate > &eviction_candidates)
Protect desirable or disadvantaged inbound peers from eviction by ratio.
Definition eviction.cpp:97
std::optional< NodeId > SelectNodeToEvict(std::vector< NodeEvictionCandidate > &&vEvictionCandidates)
Select an inbound peer to evict after filtering out (protecting) peers having distinct,...
Definition eviction.cpp:170
static bool CompareNodeTXTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
Definition eviction.cpp:38
void ProtectOutboundConnections(std::vector< NodeEvictionCandidate > &eviction_candidates)
Definition eviction.cpp:92
static bool ReverseCompareNodeMinPingTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
Definition eviction.cpp:16
Network
A network type.
Definition netaddress.h:33
@ NET_I2P
I2P.
Definition netaddress.h:47
@ NET_CJDNS
CJDNS.
Definition netaddress.h:50
@ NET_MAX
Dummy value to indicate the number of NET_* constants.
Definition netaddress.h:57
@ NET_ONION
TOR (v2 or v3)
Definition netaddress.h:44
Sort eviction candidates by network/localhost and connection uptime.
Definition eviction.cpp:64
CompareNodeNetworkTime(bool is_local, Network network)
Definition eviction.cpp:67
const Network m_network
Definition eviction.cpp:66
bool operator()(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b) const
Definition eviction.cpp:68
std::chrono::time_point< NodeClock > time_point
Definition time.h:28
static constexpr time_point epoch
Definition time.h:33
std::chrono::seconds m_last_tx_time
Definition eviction.h:23
NodeClock::duration m_min_ping_time
Definition eviction.h:21
std::chrono::seconds m_last_block_time
Definition eviction.h:22
ConnectionType m_conn_type
Definition eviction.h:32
uint64_t nKeyedNetGroup
Definition eviction.h:27
NodeClock::time_point m_connected
Definition eviction.h:20
static int count
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.
Definition time.h:82
assert(!tx.IsCoinBase())