Skip to content

Commit 38a81a8

Browse files
committed
p2p: add CompareNodeNetworkTime() comparator struct
to compare and sort peer eviction candidates by the passed-in is_local (localhost status) and network arguments, and by longest uptime.
1 parent 4ee7aec commit 38a81a8

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

src/net.cpp

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -883,6 +883,26 @@ static bool CompareNodeBlockRelayOnlyTime(const NodeEvictionCandidate &a, const
883883
return a.nTimeConnected > b.nTimeConnected;
884884
}
885885

886+
/**
887+
* Sort eviction candidates by network/localhost and connection uptime.
888+
* Candidates near the beginning are more likely to be evicted, and those
889+
* near the end are more likely to be protected, e.g. less likely to be evicted.
890+
* - First, nodes that are not `is_local` and that do not belong to `network`,
891+
* sorted by increasing uptime (from most recently connected to connected longer).
892+
* - Then, nodes that are `is_local` or belong to `network`, sorted by increasing uptime.
893+
*/
894+
struct CompareNodeNetworkTime {
895+
const bool m_is_local;
896+
const Network m_network;
897+
CompareNodeNetworkTime(bool is_local, Network network) : m_is_local(is_local), m_network(network) {}
898+
bool operator()(const NodeEvictionCandidate& a, const NodeEvictionCandidate& b) const
899+
{
900+
if (m_is_local && a.m_is_local != b.m_is_local) return b.m_is_local;
901+
if ((a.m_network == m_network) != (b.m_network == m_network)) return b.m_network == m_network;
902+
return a.nTimeConnected > b.nTimeConnected;
903+
};
904+
};
905+
886906
//! Sort an array by the specified comparator, then erase the last K elements where predicate is true.
887907
template <typename T, typename Comparator>
888908
static void EraseLastKElements(

0 commit comments

Comments
 (0)