Skip to content

Commit 0101d2b

Browse files
committed
[net] Move eviction logic to its own file
1 parent c741d74 commit 0101d2b

File tree

7 files changed

+314
-278
lines changed

7 files changed

+314
-278
lines changed

src/Makefile.am

+2
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,7 @@ BITCOIN_CORE_H = \
149149
dbwrapper.h \
150150
deploymentinfo.h \
151151
deploymentstatus.h \
152+
node/eviction.h \
152153
external_signer.h \
153154
flatfile.h \
154155
fs.h \
@@ -371,6 +372,7 @@ libbitcoin_node_a_SOURCES = \
371372
node/coin.cpp \
372373
node/connection_types.cpp \
373374
node/context.cpp \
375+
node/eviction.cpp \
374376
node/interfaces.cpp \
375377
node/miner.cpp \
376378
node/minisketchwrapper.cpp \

src/net.cpp

+1-226
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
#include <compat.h>
1717
#include <consensus/consensus.h>
1818
#include <crypto/sha256.h>
19+
#include <node/eviction.h>
1920
#include <fs.h>
2021
#include <i2p.h>
2122
#include <net_permissions.h>
@@ -857,232 +858,6 @@ size_t CConnman::SocketSendData(CNode& node) const
857858
return nSentSize;
858859
}
859860

860-
static bool ReverseCompareNodeMinPingTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
861-
{
862-
return a.m_min_ping_time > b.m_min_ping_time;
863-
}
864-
865-
static bool ReverseCompareNodeTimeConnected(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
866-
{
867-
return a.m_connected > b.m_connected;
868-
}
869-
870-
static bool CompareNetGroupKeyed(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b) {
871-
return a.nKeyedNetGroup < b.nKeyedNetGroup;
872-
}
873-
874-
static bool CompareNodeBlockTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
875-
{
876-
// There is a fall-through here because it is common for a node to have many peers which have not yet relayed a block.
877-
if (a.m_last_block_time != b.m_last_block_time) return a.m_last_block_time < b.m_last_block_time;
878-
if (a.fRelevantServices != b.fRelevantServices) return b.fRelevantServices;
879-
return a.m_connected > b.m_connected;
880-
}
881-
882-
static bool CompareNodeTXTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
883-
{
884-
// 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.
885-
if (a.m_last_tx_time != b.m_last_tx_time) return a.m_last_tx_time < b.m_last_tx_time;
886-
if (a.m_relay_txs != b.m_relay_txs) return b.m_relay_txs;
887-
if (a.fBloomFilter != b.fBloomFilter) return a.fBloomFilter;
888-
return a.m_connected > b.m_connected;
889-
}
890-
891-
// Pick out the potential block-relay only peers, and sort them by last block time.
892-
static bool CompareNodeBlockRelayOnlyTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
893-
{
894-
if (a.m_relay_txs != b.m_relay_txs) return a.m_relay_txs;
895-
if (a.m_last_block_time != b.m_last_block_time) return a.m_last_block_time < b.m_last_block_time;
896-
if (a.fRelevantServices != b.fRelevantServices) return b.fRelevantServices;
897-
return a.m_connected > b.m_connected;
898-
}
899-
900-
/**
901-
* Sort eviction candidates by network/localhost and connection uptime.
902-
* Candidates near the beginning are more likely to be evicted, and those
903-
* near the end are more likely to be protected, e.g. less likely to be evicted.
904-
* - First, nodes that are not `is_local` and that do not belong to `network`,
905-
* sorted by increasing uptime (from most recently connected to connected longer).
906-
* - Then, nodes that are `is_local` or belong to `network`, sorted by increasing uptime.
907-
*/
908-
struct CompareNodeNetworkTime {
909-
const bool m_is_local;
910-
const Network m_network;
911-
CompareNodeNetworkTime(bool is_local, Network network) : m_is_local(is_local), m_network(network) {}
912-
bool operator()(const NodeEvictionCandidate& a, const NodeEvictionCandidate& b) const
913-
{
914-
if (m_is_local && a.m_is_local != b.m_is_local) return b.m_is_local;
915-
if ((a.m_network == m_network) != (b.m_network == m_network)) return b.m_network == m_network;
916-
return a.m_connected > b.m_connected;
917-
};
918-
};
919-
920-
//! Sort an array by the specified comparator, then erase the last K elements where predicate is true.
921-
template <typename T, typename Comparator>
922-
static void EraseLastKElements(
923-
std::vector<T>& elements, Comparator comparator, size_t k,
924-
std::function<bool(const NodeEvictionCandidate&)> predicate = [](const NodeEvictionCandidate& n) { return true; })
925-
{
926-
std::sort(elements.begin(), elements.end(), comparator);
927-
size_t eraseSize = std::min(k, elements.size());
928-
elements.erase(std::remove_if(elements.end() - eraseSize, elements.end(), predicate), elements.end());
929-
}
930-
931-
void ProtectNoBanConnections(std::vector<NodeEvictionCandidate>& eviction_candidates)
932-
{
933-
eviction_candidates.erase(std::remove_if(eviction_candidates.begin(), eviction_candidates.end(),
934-
[](NodeEvictionCandidate const& n) {
935-
return n.m_noban;
936-
}),
937-
eviction_candidates.end());
938-
}
939-
940-
void ProtectOutboundConnections(std::vector<NodeEvictionCandidate>& eviction_candidates)
941-
{
942-
eviction_candidates.erase(std::remove_if(eviction_candidates.begin(), eviction_candidates.end(),
943-
[](NodeEvictionCandidate const& n) {
944-
return n.m_conn_type != ConnectionType::INBOUND;
945-
}),
946-
eviction_candidates.end());
947-
}
948-
949-
void ProtectEvictionCandidatesByRatio(std::vector<NodeEvictionCandidate>& eviction_candidates)
950-
{
951-
// Protect the half of the remaining nodes which have been connected the longest.
952-
// This replicates the non-eviction implicit behavior, and precludes attacks that start later.
953-
// To favorise the diversity of our peer connections, reserve up to half of these protected
954-
// spots for Tor/onion, localhost, I2P, and CJDNS peers, even if they're not longest uptime
955-
// overall. This helps protect these higher-latency peers that tend to be otherwise
956-
// disadvantaged under our eviction criteria.
957-
const size_t initial_size = eviction_candidates.size();
958-
const size_t total_protect_size{initial_size / 2};
959-
960-
// Disadvantaged networks to protect. In the case of equal counts, earlier array members
961-
// have the first opportunity to recover unused slots from the previous iteration.
962-
struct Net { bool is_local; Network id; size_t count; };
963-
std::array<Net, 4> networks{
964-
{{false, NET_CJDNS, 0}, {false, NET_I2P, 0}, {/*localhost=*/true, NET_MAX, 0}, {false, NET_ONION, 0}}};
965-
966-
// Count and store the number of eviction candidates per network.
967-
for (Net& n : networks) {
968-
n.count = std::count_if(eviction_candidates.cbegin(), eviction_candidates.cend(),
969-
[&n](const NodeEvictionCandidate& c) {
970-
return n.is_local ? c.m_is_local : c.m_network == n.id;
971-
});
972-
}
973-
// Sort `networks` by ascending candidate count, to give networks having fewer candidates
974-
// the first opportunity to recover unused protected slots from the previous iteration.
975-
std::stable_sort(networks.begin(), networks.end(), [](Net a, Net b) { return a.count < b.count; });
976-
977-
// Protect up to 25% of the eviction candidates by disadvantaged network.
978-
const size_t max_protect_by_network{total_protect_size / 2};
979-
size_t num_protected{0};
980-
981-
while (num_protected < max_protect_by_network) {
982-
// Count the number of disadvantaged networks from which we have peers to protect.
983-
auto num_networks = std::count_if(networks.begin(), networks.end(), [](const Net& n) { return n.count; });
984-
if (num_networks == 0) {
985-
break;
986-
}
987-
const size_t disadvantaged_to_protect{max_protect_by_network - num_protected};
988-
const size_t protect_per_network{std::max(disadvantaged_to_protect / num_networks, static_cast<size_t>(1))};
989-
// Early exit flag if there are no remaining candidates by disadvantaged network.
990-
bool protected_at_least_one{false};
991-
992-
for (Net& n : networks) {
993-
if (n.count == 0) continue;
994-
const size_t before = eviction_candidates.size();
995-
EraseLastKElements(eviction_candidates, CompareNodeNetworkTime(n.is_local, n.id),
996-
protect_per_network, [&n](const NodeEvictionCandidate& c) {
997-
return n.is_local ? c.m_is_local : c.m_network == n.id;
998-
});
999-
const size_t after = eviction_candidates.size();
1000-
if (before > after) {
1001-
protected_at_least_one = true;
1002-
const size_t delta{before - after};
1003-
num_protected += delta;
1004-
if (num_protected >= max_protect_by_network) {
1005-
break;
1006-
}
1007-
n.count -= delta;
1008-
}
1009-
}
1010-
if (!protected_at_least_one) {
1011-
break;
1012-
}
1013-
}
1014-
1015-
// Calculate how many we removed, and update our total number of peers that
1016-
// we want to protect based on uptime accordingly.
1017-
assert(num_protected == initial_size - eviction_candidates.size());
1018-
const size_t remaining_to_protect{total_protect_size - num_protected};
1019-
EraseLastKElements(eviction_candidates, ReverseCompareNodeTimeConnected, remaining_to_protect);
1020-
}
1021-
1022-
[[nodiscard]] std::optional<NodeId> SelectNodeToEvict(std::vector<NodeEvictionCandidate>&& vEvictionCandidates)
1023-
{
1024-
// Protect connections with certain characteristics
1025-
1026-
ProtectNoBanConnections(vEvictionCandidates);
1027-
1028-
ProtectOutboundConnections(vEvictionCandidates);
1029-
1030-
// Deterministically select 4 peers to protect by netgroup.
1031-
// An attacker cannot predict which netgroups will be protected
1032-
EraseLastKElements(vEvictionCandidates, CompareNetGroupKeyed, 4);
1033-
// Protect the 8 nodes with the lowest minimum ping time.
1034-
// An attacker cannot manipulate this metric without physically moving nodes closer to the target.
1035-
EraseLastKElements(vEvictionCandidates, ReverseCompareNodeMinPingTime, 8);
1036-
// Protect 4 nodes that most recently sent us novel transactions accepted into our mempool.
1037-
// An attacker cannot manipulate this metric without performing useful work.
1038-
EraseLastKElements(vEvictionCandidates, CompareNodeTXTime, 4);
1039-
// Protect up to 8 non-tx-relay peers that have sent us novel blocks.
1040-
EraseLastKElements(vEvictionCandidates, CompareNodeBlockRelayOnlyTime, 8,
1041-
[](const NodeEvictionCandidate& n) { return !n.m_relay_txs && n.fRelevantServices; });
1042-
1043-
// Protect 4 nodes that most recently sent us novel blocks.
1044-
// An attacker cannot manipulate this metric without performing useful work.
1045-
EraseLastKElements(vEvictionCandidates, CompareNodeBlockTime, 4);
1046-
1047-
// Protect some of the remaining eviction candidates by ratios of desirable
1048-
// or disadvantaged characteristics.
1049-
ProtectEvictionCandidatesByRatio(vEvictionCandidates);
1050-
1051-
if (vEvictionCandidates.empty()) return std::nullopt;
1052-
1053-
// If any remaining peers are preferred for eviction consider only them.
1054-
// This happens after the other preferences since if a peer is really the best by other criteria (esp relaying blocks)
1055-
// then we probably don't want to evict it no matter what.
1056-
if (std::any_of(vEvictionCandidates.begin(),vEvictionCandidates.end(),[](NodeEvictionCandidate const &n){return n.prefer_evict;})) {
1057-
vEvictionCandidates.erase(std::remove_if(vEvictionCandidates.begin(),vEvictionCandidates.end(),
1058-
[](NodeEvictionCandidate const &n){return !n.prefer_evict;}),vEvictionCandidates.end());
1059-
}
1060-
1061-
// Identify the network group with the most connections and youngest member.
1062-
// (vEvictionCandidates is already sorted by reverse connect time)
1063-
uint64_t naMostConnections;
1064-
unsigned int nMostConnections = 0;
1065-
std::chrono::seconds nMostConnectionsTime{0};
1066-
std::map<uint64_t, std::vector<NodeEvictionCandidate> > mapNetGroupNodes;
1067-
for (const NodeEvictionCandidate &node : vEvictionCandidates) {
1068-
std::vector<NodeEvictionCandidate> &group = mapNetGroupNodes[node.nKeyedNetGroup];
1069-
group.push_back(node);
1070-
const auto grouptime{group[0].m_connected};
1071-
1072-
if (group.size() > nMostConnections || (group.size() == nMostConnections && grouptime > nMostConnectionsTime)) {
1073-
nMostConnections = group.size();
1074-
nMostConnectionsTime = grouptime;
1075-
naMostConnections = node.nKeyedNetGroup;
1076-
}
1077-
}
1078-
1079-
// Reduce to the network group with the most connections
1080-
vEvictionCandidates = std::move(mapNetGroupNodes[naMostConnections]);
1081-
1082-
// Disconnect from the network group with the most connections
1083-
return vEvictionCandidates.front().id;
1084-
}
1085-
1086861
/** Try to find a connection to evict when the node is full.
1087862
* Extreme care must be taken to avoid opening the node to attacker
1088863
* triggered network partitioning.

src/net.h

-52
Original file line numberDiff line numberDiff line change
@@ -1176,56 +1176,4 @@ extern std::function<void(const CAddress& addr,
11761176
bool is_incoming)>
11771177
CaptureMessage;
11781178

1179-
struct NodeEvictionCandidate
1180-
{
1181-
NodeId id;
1182-
std::chrono::seconds m_connected;
1183-
std::chrono::microseconds m_min_ping_time;
1184-
std::chrono::seconds m_last_block_time;
1185-
std::chrono::seconds m_last_tx_time;
1186-
bool fRelevantServices;
1187-
bool m_relay_txs;
1188-
bool fBloomFilter;
1189-
uint64_t nKeyedNetGroup;
1190-
bool prefer_evict;
1191-
bool m_is_local;
1192-
Network m_network;
1193-
bool m_noban;
1194-
ConnectionType m_conn_type;
1195-
};
1196-
1197-
/**
1198-
* Select an inbound peer to evict after filtering out (protecting) peers having
1199-
* distinct, difficult-to-forge characteristics. The protection logic picks out
1200-
* fixed numbers of desirable peers per various criteria, followed by (mostly)
1201-
* ratios of desirable or disadvantaged peers. If any eviction candidates
1202-
* remain, the selection logic chooses a peer to evict.
1203-
*/
1204-
[[nodiscard]] std::optional<NodeId> SelectNodeToEvict(std::vector<NodeEvictionCandidate>&& vEvictionCandidates);
1205-
1206-
/** Protect desirable or disadvantaged inbound peers from eviction by ratio.
1207-
*
1208-
* This function protects half of the peers which have been connected the
1209-
* longest, to replicate the non-eviction implicit behavior and preclude attacks
1210-
* that start later.
1211-
*
1212-
* Half of these protected spots (1/4 of the total) are reserved for the
1213-
* following categories of peers, sorted by longest uptime, even if they're not
1214-
* longest uptime overall:
1215-
*
1216-
* - onion peers connected via our tor control service
1217-
*
1218-
* - localhost peers, as manually configured hidden services not using
1219-
* `-bind=addr[:port]=onion` will not be detected as inbound onion connections
1220-
*
1221-
* - I2P peers
1222-
*
1223-
* - CJDNS peers
1224-
*
1225-
* This helps protect these privacy network peers, which tend to be otherwise
1226-
* disadvantaged under our eviction criteria for their higher min ping times
1227-
* relative to IPv4/IPv6 peers, and favorise the diversity of peer connections.
1228-
*/
1229-
void ProtectEvictionCandidatesByRatio(std::vector<NodeEvictionCandidate>& vEvictionCandidates);
1230-
12311179
#endif // BITCOIN_NET_H

0 commit comments

Comments
 (0)