6#if defined(HAVE_CONFIG_H)
7#include <config/bitcoin-config.h>
55#include <unordered_map>
61 "MAX_BLOCK_RELAY_ONLY_ANCHORS must not exceed "
62 "MAX_BLOCK_RELAY_ONLY_CONNECTIONS.");
94#define FEELER_SLEEP_WINDOW 1
128std::map<CNetAddr, LocalServiceInfo>
134 m_addr_fetches.push_back(strDest);
140 for (
const std::string &bind_arg :
gArgs.
GetArgs(
"-bind")) {
142 constexpr uint16_t dummy_port = 0;
144 if (
Lookup(bind_arg, bind_addr, dummy_port,
false)) {
145 if (bind_addr.
GetPort() != dummy_port) {
154 for (
const std::string &whitebind_arg :
gArgs.
GetArgs(
"-whitebind")) {
168 return static_cast<uint16_t
>(
179 int nBestReachability = -1;
182 for (
const auto &entry : mapLocalHost) {
183 int nScore = entry.second.nScore;
184 int nReachability = entry.first.GetReachabilityFrom(paddrPeer);
185 if (nReachability > nBestReachability ||
186 (nReachability == nBestReachability && nScore > nBestScore)) {
187 addr =
CService(entry.first, entry.second.nPort);
188 nBestReachability = nReachability;
193 return nBestScore >= 0;
197static std::vector<CAddress>
202 const auto one_week{7 * 24h};
203 std::vector<CAddress> vSeedsOut;
204 vSeedsOut.reserve(vSeedsIn.size());
206 for (
const auto &seed_in : vSeedsIn) {
208 memcpy(&ip, seed_in.addr,
sizeof(ip));
213 vSeedsOut.push_back(addr);
232 const auto it = mapLocalHost.find(addr);
233 return (it != mapLocalHost.end()) ? it->second.nScore : 0;
254 (!addrLocal.IsRoutable() ||
256 if (
node.IsInboundConn()) {
265 addrLocal.SetIP(
node.GetAddrLocal());
268 if (addrLocal.IsRoutable() ||
gArgs.
GetBoolArg(
"-addrmantest",
false)) {
270 addrLocal.ToString(),
node.GetId());
295 const auto [it, is_newly_added] =
298 if (is_newly_added || nScore >= info.
nScore) {
299 info.
nScore = nScore + !is_newly_added;
314 mapLocalHost.erase(addr);
322 vfLimited[net] = !reachable;
327 return !vfLimited[net];
337 const auto it = mapLocalHost.find(addr);
338 if (it == mapLocalHost.end()) {
348 return mapLocalHost.count(addr) > 0;
353 for (
CNode *pnode : m_nodes) {
354 if (
static_cast<CNetAddr>(pnode->addr) == ip) {
363 for (
CNode *pnode : m_nodes) {
373 for (
CNode *pnode : m_nodes) {
374 if (pnode->m_addr_name == addrName) {
383 for (
CNode *pnode : m_nodes) {
384 if (
static_cast<CService>(pnode->addr) == addr) {
398 for (
const CNode *pnode : m_nodes) {
399 if (!pnode->fSuccessfullyConnected && !pnode->IsInboundConn() &&
400 pnode->GetLocalNonce() == nonce) {
410 struct sockaddr_storage sockaddr_bind;
411 socklen_t sockaddr_bind_len =
sizeof(sockaddr_bind);
413 if (!getsockname(sock, (
struct sockaddr *)&sockaddr_bind,
414 &sockaddr_bind_len)) {
415 addr_bind.
SetSockAddr((
const struct sockaddr *)&sockaddr_bind);
418 "getsockname failed\n");
428 if (pszDest ==
nullptr) {
436 LogPrintf(
"Failed to open new connection, already connected\n");
442 "trying connection %s lastseen=%.1fhrs\n",
443 pszDest ? pszDest : addrConnect.
ToString(),
445 pszDest ? 0h : Now<NodeSeconds>() - addrConnect.
nTime));
448 const uint16_t default_port{pszDest !=
nullptr
452 std::vector<CService> resolved;
453 if (
Lookup(pszDest, resolved, default_port,
460 "Resolver returned invalid address %s for %s\n",
470 LogPrintf(
"Failed to open new connection, already connected\n");
477 bool connected =
false;
478 std::unique_ptr<Sock> sock;
484 bool proxyConnectionFailed =
false;
490 proxyConnectionFailed)) {
492 sock = std::move(conn.
sock);
513 if (!proxyConnectionFailed) {
525 uint16_t port{default_port};
527 bool proxyConnectionFailed;
536 std::vector<NetWhitelistPermissions> whitelist_permissions =
539 : std::vector<NetWhitelistPermissions>{};
541 whitelist_permissions);
548 uint64_t extra_entropy =
557 nonce, extra_entropy, addr_bind, pszDest ? pszDest :
"", conn_type,
580 const std::vector<NetWhitelistPermissions> &ranges)
const {
581 for (
const auto &subnet : ranges) {
582 if (subnet.m_subnet.Match(addr)) {
608 return "outbound-full-relay";
610 return "block-relay-only";
629 if (addrLocal.IsValid()) {
630 error(
"Addr local already set for node: %i. Refusing to change from %s "
632 id, addrLocal.ToString(), addrLocalIn.
ToString());
634 addrLocal = addrLocalIn;
693 const auto time = GetTime<std::chrono::microseconds>();
695 m_last_recv = std::chrono::duration_cast<std::chrono::seconds>(time);
696 nRecvBytes += msg_bytes.
size();
697 while (msg_bytes.
size() > 0) {
710 mapMsgCmdSize::iterator i = mapRecvBytesPerMsgCmd.find(msg.
m_type);
711 if (i == mapRecvBytesPerMsgCmd.end()) {
715 assert(i != mapRecvBytesPerMsgCmd.end());
732 uint32_t nCopy = std::min<unsigned int>(nRemaining, msg_bytes.
size());
745 }
catch (
const std::exception &) {
763 unsigned int nCopy = std::min<unsigned int>(nRemaining, msg_bytes.
size());
788 const std::chrono::microseconds time) {
816 "CHECKSUM ERROR (%s, %u bytes), expected %s was %s\n",
832 std::vector<uint8_t> &header) {
847 size_t nSentSize = 0;
848 size_t nMsgCount = 0;
850 for (
const auto &data :
node.vSendMsg) {
860 nBytes =
node.m_sock->Send(
861 reinterpret_cast<const char *
>(data.data()) +
node.nSendOffset,
877 node.CloseSocketDisconnect();
884 node.m_last_send = GetTime<std::chrono::seconds>();
885 node.nSendBytes += nBytes;
886 node.nSendOffset += nBytes;
888 if (
node.nSendOffset != data.size()) {
893 node.nSendOffset = 0;
894 node.nSendSize -= data.size();
899 node.vSendMsg.erase(
node.vSendMsg.begin(),
900 node.vSendMsg.begin() + nMsgCount);
902 if (
node.vSendMsg.empty()) {
907 return {nSentSize, !
node.vSendMsg.empty()};
1030template <
typename T,
typename Comparator>
1032 std::vector<T> &
elements, Comparator comparator,
size_t k,
1036 size_t eraseSize = std::min(k,
elements.size());
1043 std::vector<NodeEvictionCandidate> &eviction_candidates) {
1052 const size_t initial_size = eviction_candidates.size();
1053 const size_t total_protect_size{initial_size / 2};
1063 std::array<Net, 3> networks{{{
false,
NET_I2P, 0},
1068 for (Net &n : networks) {
1069 n.count = std::count_if(
1070 eviction_candidates.cbegin(), eviction_candidates.cend(),
1072 return n.is_local ? c.m_is_local : c.m_network == n.id;
1078 std::stable_sort(networks.begin(), networks.end(),
1079 [](Net a, Net b) { return a.count < b.count; });
1082 const size_t max_protect_by_network{total_protect_size / 2};
1083 size_t num_protected{0};
1085 while (num_protected < max_protect_by_network) {
1088 auto num_networks = std::count_if(networks.begin(), networks.end(),
1089 [](
const Net &n) { return n.count; });
1090 if (num_networks == 0) {
1093 const size_t disadvantaged_to_protect{max_protect_by_network -
1095 const size_t protect_per_network{std::max(
1096 disadvantaged_to_protect / num_networks,
static_cast<size_t>(1))};
1100 bool protected_at_least_one{
false};
1102 for (Net &n : networks) {
1106 const size_t before = eviction_candidates.size();
1110 return n.is_local ? c.m_is_local : c.m_network == n.id;
1112 const size_t after = eviction_candidates.size();
1113 if (before > after) {
1114 protected_at_least_one =
true;
1115 const size_t delta{before - after};
1116 num_protected += delta;
1117 if (num_protected >= max_protect_by_network) {
1123 if (!protected_at_least_one) {
1130 assert(num_protected == initial_size - eviction_candidates.size());
1131 const size_t remaining_to_protect{total_protect_size - num_protected};
1133 remaining_to_protect);
1136[[nodiscard]] std::optional<NodeId>
1178 if (vEvictionCandidates.empty()) {
1179 return std::nullopt;
1187 vEvictionCandidates.begin(), vEvictionCandidates.end(),
1189 vEvictionCandidates.erase(
1191 vEvictionCandidates.begin(), vEvictionCandidates.end(),
1193 vEvictionCandidates.end());
1198 uint64_t naMostConnections;
1199 unsigned int nMostConnections = 0;
1200 std::chrono::seconds nMostConnectionsTime{0};
1201 std::map<uint64_t, std::vector<NodeEvictionCandidate>> mapNetGroupNodes;
1203 std::vector<NodeEvictionCandidate> &group =
1204 mapNetGroupNodes[
node.nKeyedNetGroup];
1205 group.push_back(
node);
1206 const auto grouptime{group[0].m_connected};
1207 size_t group_size = group.size();
1208 if (group_size > nMostConnections ||
1209 (group_size == nMostConnections &&
1210 grouptime > nMostConnectionsTime)) {
1211 nMostConnections = group_size;
1212 nMostConnectionsTime = grouptime;
1213 naMostConnections =
node.nKeyedNetGroup;
1218 vEvictionCandidates = std::move(mapNetGroupNodes[naMostConnections]);
1221 return vEvictionCandidates.front().id;
1233 std::vector<NodeEvictionCandidate> vEvictionCandidates;
1240 if (!
node->IsInboundConn()) {
1243 if (
node->fDisconnect) {
1250 node->m_min_ping_time,
1251 node->m_last_block_time,
1252 node->m_last_proof_time,
1253 node->m_last_tx_time,
1254 node->m_has_all_wanted_services,
1255 node->m_relays_txs.load(),
1256 node->m_bloom_filter_loaded.load(),
1257 node->nKeyedNetGroup,
1258 node->m_prefer_evict,
1259 node->addr.IsLocal(),
1260 node->ConnectedThroughNetwork(),
1261 node->m_avalanche_enabled
1262 ?
node->getAvailabilityScore()
1263 : -std::numeric_limits<double>::infinity()};
1264 vEvictionCandidates.push_back(candidate);
1267 const std::optional<NodeId> node_id_to_evict =
1269 if (!node_id_to_evict) {
1273 for (
CNode *pnode : m_nodes) {
1274 if (pnode->GetId() == *node_id_to_evict) {
1277 "selected %s connection for eviction peer=%d; disconnecting\n",
1278 pnode->ConnectionTypeAsString(), pnode->GetId());
1279 pnode->fDisconnect =
true;
1287 struct sockaddr_storage sockaddr;
1288 socklen_t len =
sizeof(sockaddr);
1289 auto sock = hListenSocket.
sock->Accept((
struct sockaddr *)&sockaddr, &len);
1295 LogPrintf(
"socket error accept failed: %s\n",
1301 if (!addr.
SetSockAddr((
const struct sockaddr *)&sockaddr)) {
1303 "Unknown socket family\n");
1327 for (
const CNode *pnode : m_nodes) {
1328 if (pnode->IsInboundConn()) {
1336 "connection from %s dropped: not accepting new connections\n",
1342 LogPrintf(
"connection from %s dropped: non-selectable socket\n",
1364 nInbound + 1 >= nMaxInbound && discouraged) {
1370 if (nInbound >= nMaxInbound) {
1374 "connection dropped (full)\n");
1383 uint64_t extra_entropy =
1388 const bool inbound_onion =
1396 .prefer_evict = discouraged,
1407 m_nodes.push_back(pnode);
1417 std::optional<int> max_connections;
1418 switch (conn_type) {
1440 int existing_connections =
1442 return std::count_if(
1443 m_nodes.begin(), m_nodes.end(), [conn_type](
CNode *
node) {
1444 return node->m_conn_type == conn_type;
1448 if (max_connections != std::nullopt &&
1449 existing_connections >= max_connections) {
1470 for (
CNode *pnode : m_nodes) {
1471 if (!pnode->fDisconnect) {
1473 "Network not active, dropping peer=%d\n",
1475 pnode->fDisconnect =
true;
1481 std::vector<CNode *> nodes_copy = m_nodes;
1482 for (
CNode *pnode : nodes_copy) {
1483 if (pnode->fDisconnect) {
1485 m_nodes.erase(remove(m_nodes.begin(), m_nodes.end(), pnode),
1489 pnode->grantOutbound.Release();
1492 pnode->CloseSocketDisconnect();
1503 for (
CNode *pnode : nodes_disconnected_copy) {
1506 if (pnode->GetRefCount() <= 0) {
1518 nodes_size = m_nodes.size();
1529 std::chrono::seconds now)
const {
1536 const auto now{GetTime<std::chrono::seconds>()};
1537 const auto last_send{
node.m_last_send.load()};
1538 const auto last_recv{
node.m_last_recv.load()};
1544 if (last_recv.count() == 0 || last_send.count() == 0) {
1546 "socket no message in first %i seconds, %d %d peer=%d\n",
1548 last_send.count() != 0,
node.GetId());
1564 if (!
node.fSuccessfullyConnected) {
1577 events_per_sock.emplace(hListenSocket.sock,
Sock::Events{Sock::RECV});
1580 for (
CNode *pnode : nodes) {
1581 bool select_recv = !pnode->fPauseRecv;
1583 WITH_LOCK(pnode->cs_vSend,
return !pnode->vSendMsg.empty());
1584 if (!select_recv && !select_send) {
1588 LOCK(pnode->m_sock_mutex);
1589 if (pnode->m_sock) {
1592 events_per_sock.emplace(pnode->m_sock,
Sock::Events{event});
1596 return events_per_sock;
1605 const auto timeout =
1613 if (events_per_sock.empty() ||
1614 !events_per_sock.begin()->first->WaitMany(timeout,
1628 const std::vector<CNode *> &nodes,
1630 for (
CNode *pnode : nodes) {
1638 bool recvSet =
false;
1639 bool sendSet =
false;
1640 bool errorSet =
false;
1642 LOCK(pnode->m_sock_mutex);
1643 if (!pnode->m_sock) {
1646 const auto it = events_per_sock.find(pnode->m_sock);
1647 if (it != events_per_sock.end()) {
1650 errorSet = it->second.occurred &
Sock::ERR;
1656 auto [bytes_sent, data_left] =
1675 if (recvSet || errorSet) {
1677 uint8_t pchBuf[0x10000];
1680 LOCK(pnode->m_sock_mutex);
1681 if (!pnode->m_sock) {
1685 pnode->m_sock->Recv(pchBuf,
sizeof(pchBuf),
MSG_DONTWAIT);
1688 bool notify =
false;
1689 if (!pnode->ReceiveMsgBytes(*
config, {pchBuf, (size_t)nBytes},
1691 pnode->CloseSocketDisconnect();
1695 size_t nSizeAdded = 0;
1696 auto it(pnode->vRecvMsg.begin());
1697 for (; it != pnode->vRecvMsg.end(); ++it) {
1701 nSizeAdded += it->m_raw_message_size;
1704 LOCK(pnode->cs_vProcessMsg);
1705 pnode->vProcessMsg.splice(pnode->vProcessMsg.end(),
1707 pnode->vRecvMsg.begin(), it);
1708 pnode->nProcessQueueSize += nSizeAdded;
1714 }
else if (nBytes == 0) {
1716 if (!pnode->fDisconnect) {
1720 pnode->CloseSocketDisconnect();
1721 }
else if (nBytes < 0) {
1726 if (!pnode->fDisconnect) {
1728 "socket recv error for peer=%d: %s\n",
1731 pnode->CloseSocketDisconnect();
1737 pnode->fDisconnect =
true;
1748 const auto it = events_per_sock.find(listen_socket.sock);
1749 if (it != events_per_sock.end() && it->second.occurred &
Sock::RECV) {
1766 fMsgProcWake =
true;
1773 std::vector<std::string> seeds =
1776 int seeds_right_now = 0;
1781 seeds_right_now = seeds.size();
1786 seeds_right_now = seeds.size();
1801 const std::chrono::seconds seeds_wait_time =
1806 for (
const std::string &seed : seeds) {
1807 if (seeds_right_now == 0) {
1811 LogPrintf(
"Waiting %d seconds before querying DNS seeds.\n",
1812 seeds_wait_time.count());
1813 std::chrono::seconds to_wait = seeds_wait_time;
1814 while (to_wait.count() > 0) {
1818 std::chrono::seconds w =
1828 for (
const CNode *pnode : m_nodes) {
1829 if (pnode->fSuccessfullyConnected &&
1830 pnode->IsFullOutboundConn()) {
1835 if (nRelevant >= 2) {
1837 LogPrintf(
"%d addresses found from DNS seeds\n",
1840 "P2P peers available. Finished DNS seeding.\n");
1843 "P2P peers available. Skipped DNS seeding.\n");
1857 LogPrintf(
"Waiting for network to be reactivated before querying "
1866 LogPrintf(
"Loading addresses from DNS seed %s\n", seed);
1870 std::vector<CNetAddr> vIPs;
1871 std::vector<CAddress> vAdd;
1874 std::string host =
strprintf(
"x%x.%s", requiredServiceBits, seed);
1881 unsigned int nMaxIPs = 256;
1886 requiredServiceBits);
1889 Now<NodeSeconds>() - 3 * 24h, -4 * 24h);
1890 vAdd.push_back(addr);
1903 LogPrintf(
"%d addresses found from DNS seeds\n", found);
1916 std::string strDest;
1919 if (m_addr_fetches.empty()) {
1922 strDest = m_addr_fetches.front();
1923 m_addr_fetches.pop_front();
1940 flag ?
"true" :
"false");
1950 int full_outbound_peers = 0;
1953 for (
const CNode *pnode : m_nodes) {
1954 if (pnode->fSuccessfullyConnected && !pnode->fDisconnect &&
1955 pnode->IsFullOutboundConn()) {
1956 ++full_outbound_peers;
1966 int block_relay_peers = 0;
1969 for (
const CNode *pnode : m_nodes) {
1970 if (pnode->fSuccessfullyConnected && !pnode->fDisconnect &&
1971 pnode->IsBlockOnlyConn()) {
1972 ++block_relay_peers;
1980 const std::vector<std::string> connect,
1983 if (!connect.empty()) {
1984 for (int64_t nLoop = 0;; nLoop++) {
1986 for (
const std::string &strAddr : connect) {
1990 for (
int i = 0; i < 10 && i < nLoop; i++) {
1992 std::chrono::milliseconds(500))) {
2004 auto start = GetTime<std::chrono::microseconds>();
2008 auto next_extra_block_relay =
2013 if (!add_fixed_seeds) {
2014 LogPrintf(
"Fixed seeds are disabled\n");
2021 if (!mockOpenConnection &&
2037 bool add_fixed_seeds_now =
false;
2039 if (GetTime<std::chrono::seconds>() >
2040 start + std::chrono::minutes{1}) {
2041 add_fixed_seeds_now =
true;
2042 LogPrintf(
"Adding fixed seeds as 60 seconds have passed and "
2043 "addrman is empty\n");
2047 if (!add_fixed_seeds_now && !dnsseed) {
2049 if (m_addr_fetches.empty() && m_added_nodes.empty()) {
2050 add_fixed_seeds_now =
true;
2052 "Adding fixed seeds as -dnsseed=0, -addnode is not "
2053 "provided and all -seednode(s) attempted\n");
2057 if (add_fixed_seeds_now) {
2062 add_fixed_seeds =
false;
2072 int nOutboundFullRelay = 0;
2073 int nOutboundBlockRelay = 0;
2074 int nOutboundAvalanche = 0;
2075 std::set<std::vector<uint8_t>> setConnected;
2079 for (
const CNode *pnode : m_nodes) {
2080 if (pnode->IsAvalancheOutboundConnection()) {
2081 nOutboundAvalanche++;
2082 }
else if (pnode->IsFullOutboundConn()) {
2083 nOutboundFullRelay++;
2084 }
else if (pnode->IsBlockOnlyConn()) {
2085 nOutboundBlockRelay++;
2095 switch (pnode->m_conn_type) {
2104 setConnected.insert(
2112 auto now = GetTime<std::chrono::microseconds>();
2113 bool anchor =
false;
2114 bool fFeeler =
false;
2142 }
else if (now > next_extra_block_relay &&
2166 next_extra_block_relay =
2169 }
else if (now > next_feeler) {
2193 "Trying to make an anchor connection to %s\n",
2252 if (current_time - addr_last_try < 10min && nTries < 30) {
2302 std::chrono::milliseconds(randsleep))) {
2311 if (mockOpenConnection) {
2312 mockOpenConnection(addrConnect, conn_type);
2315 int(setConnected.size()) >=
2317 &grant,
nullptr, conn_type);
2324 std::vector<CAddress> ret;
2326 for (
const CNode *pnode : m_nodes) {
2327 if (pnode->IsBlockOnlyConn()) {
2328 ret.push_back(pnode->addr);
2336 std::vector<AddedNodeInfo> ret;
2338 std::list<std::string> lAddresses(0);
2341 ret.reserve(m_added_nodes.size());
2342 std::copy(m_added_nodes.cbegin(), m_added_nodes.cend(),
2343 std::back_inserter(lAddresses));
2348 std::map<CService, bool> mapConnected;
2349 std::map<std::string, std::pair<bool, CService>> mapConnectedByName;
2352 for (
const CNode *pnode : m_nodes) {
2353 if (pnode->addr.IsValid()) {
2354 mapConnected[pnode->addr] = pnode->IsInboundConn();
2356 std::string addrName{pnode->m_addr_name};
2357 if (!addrName.empty()) {
2358 mapConnectedByName[std::move(addrName)] =
2359 std::make_pair(pnode->IsInboundConn(),
2360 static_cast<const CService &
>(pnode->addr));
2365 for (
const std::string &strAddNode : lAddresses) {
2371 auto it = mapConnected.find(service);
2372 if (it != mapConnected.end()) {
2373 addedNode.resolvedAddress = service;
2374 addedNode.fConnected =
true;
2375 addedNode.fInbound = it->second;
2379 auto it = mapConnectedByName.find(strAddNode);
2380 if (it != mapConnectedByName.end()) {
2381 addedNode.resolvedAddress = it->second.second;
2382 addedNode.fConnected =
true;
2383 addedNode.fInbound = it->second.first;
2386 ret.emplace_back(std::move(addedNode));
2398 if (!info.fConnected) {
2408 info.strAddedNode.c_str(),
2427 const char *pszDest,
2441 bool banned_or_discouraged =
2444 if (
IsLocal(addrConnect) || banned_or_discouraged ||
2448 }
else if (
FindNode(std::string(pszDest))) {
2452 CNode *pnode =
ConnectNode(addrConnect, pszDest, fCountFailure, conn_type);
2457 if (grantOutbound) {
2467 m_nodes.push_back(pnode);
2477 bool fMoreWork =
false;
2485 for (
CNode *pnode : snap.Nodes()) {
2486 if (pnode->fDisconnect) {
2490 bool fMoreNodeWork =
false;
2493 fMoreNodeWork |= interface->ProcessMessages(
2496 fMoreWork |= (fMoreNodeWork && !pnode->fPauseSend);
2503 interface->SendMessages(*
config, pnode);
2515 std::chrono::steady_clock::now() +
2516 std::chrono::milliseconds(100),
2520 fMsgProcWake =
false;
2525 static constexpr auto err_wait_begin = 1s;
2526 static constexpr auto err_wait_cap = 5min;
2527 auto err_wait = err_wait_begin;
2529 bool advertising_listen_addr =
false;
2534 if (advertising_listen_addr && conn.
me.
IsValid()) {
2536 advertising_listen_addr =
false;
2540 if (err_wait < err_wait_cap) {
2547 if (!advertising_listen_addr) {
2549 advertising_listen_addr =
true;
2567 struct sockaddr_storage sockaddr;
2568 socklen_t len =
sizeof(sockaddr);
2569 if (!addrBind.
GetSockAddr((
struct sockaddr *)&sockaddr, &len)) {
2578 std::unique_ptr<Sock> sock =
CreateSock(addrBind);
2582 "connections (socket returned error %s)"),
2599 setsockopt(sock->Get(), IPPROTO_IPV6, IPV6_V6ONLY,
2603 int nProtLevel = PROTECTION_LEVEL_UNRESTRICTED;
2604 setsockopt(sock->Get(), IPPROTO_IPV6, IPV6_PROTECTION_LEVEL,
2609 if (::bind(sock->Get(), (
struct sockaddr *)&sockaddr, len) ==
2613 strError =
strprintf(
_(
"Unable to bind to %s on this computer. %s "
2614 "is probably already running."),
2615 addrBind.
ToString(), PACKAGE_NAME);
2617 strError =
strprintf(
_(
"Unable to bind to %s on this computer "
2618 "(bind returned error %s)"),
2630 strError =
strprintf(
_(
"Listening for incoming connections "
2631 "failed (listen returned error %s)"),
2649 char pszHostName[256] =
"";
2650 if (gethostname(pszHostName,
sizeof(pszHostName)) !=
SOCKET_ERROR) {
2651 std::vector<CNetAddr> vaddr;
2652 if (
LookupHost(pszHostName, vaddr, 0,
true)) {
2653 for (
const CNetAddr &addr : vaddr) {
2655 LogPrintf(
"%s: %s - %s\n", __func__, pszHostName,
2661#elif (HAVE_DECL_GETIFADDRS && HAVE_DECL_FREEIFADDRS)
2663 struct ifaddrs *myaddrs;
2664 if (getifaddrs(&myaddrs) == 0) {
2665 for (
struct ifaddrs *ifa = myaddrs; ifa !=
nullptr;
2666 ifa = ifa->ifa_next) {
2667 if (ifa->ifa_addr ==
nullptr || (ifa->ifa_flags & IFF_UP) == 0 ||
2668 strcmp(ifa->ifa_name,
"lo") == 0 ||
2669 strcmp(ifa->ifa_name,
"lo0") == 0) {
2672 if (ifa->ifa_addr->sa_family == AF_INET) {
2673 struct sockaddr_in *s4 =
2674 reinterpret_cast<struct sockaddr_in *
>(ifa->ifa_addr);
2677 LogPrintf(
"%s: IPv4 %s: %s\n", __func__, ifa->ifa_name,
2680 }
else if (ifa->ifa_addr->sa_family == AF_INET6) {
2681 struct sockaddr_in6 *s6 =
2682 reinterpret_cast<struct sockaddr_in6 *
>(ifa->ifa_addr);
2685 LogPrintf(
"%s: IPv6 %s: %s\n", __func__, ifa->ifa_name,
2690 freeifaddrs(myaddrs);
2696 LogPrintf(
"%s: %s\n", __func__, active);
2710 AddrMan &addrmanIn,
bool network_active)
2711 : config(&configIn), addrman(addrmanIn), nSeed0(nSeed0In),
2747 bool fBound =
false;
2748 for (
const auto &addrBind : options.
vBinds) {
2752 for (
const auto &addrBind : options.
vWhiteBinds) {
2756 for (
const auto &addr_bind : options.
onion_binds) {
2761 struct in_addr inaddr_any;
2762 inaddr_any.s_addr = htonl(INADDR_ANY);
2763 struct in6_addr inaddr6_any = IN6ADDR_ANY_INIT;
2779 _(
"Failed to listen on any port. Use -listen=0 if you want "
2793 for (
const auto &strDest : connOptions.
vSeedNodes) {
2806 "%i block-relay-only anchors will be tried for connections.\n",
2812 _(
"Starting network threads...").translated);
2837 fMsgProcWake =
false;
2859 _(
"Cannot provide specific connections and have addrman find "
2860 "outgoing connections at the same."),
2870 ThreadOpenConnections(connect, nullptr);
2960 std::vector<CAddress> anchors_to_dump =
2972 std::vector<CNode *> nodes;
2974 for (
CNode *pnode : nodes) {
2975 pnode->CloseSocketDisconnect();
2991 interface->FinalizeNode(*
config, *pnode);
3001std::vector<CAddress>
3003 std::optional<Network> network)
const {
3004 std::vector<CAddress> addresses =
3007 addresses.erase(std::remove_if(addresses.begin(), addresses.end(),
3009 return m_banman->IsDiscouraged(
3011 m_banman->IsBanned(addr);
3018std::vector<CAddress>
3024 .
Write(local_socket_bytes.data(), local_socket_bytes.size())
3026 const auto current_time = GetTime<std::chrono::microseconds>();
3062 current_time + std::chrono::hours(21) +
3070 for (
const std::string &it : m_added_nodes) {
3071 if (strNode == it) {
3076 m_added_nodes.push_back(strNode);
3082 for (std::vector<std::string>::iterator it = m_added_nodes.begin();
3083 it != m_added_nodes.end(); ++it) {
3084 if (strNode == *it) {
3085 m_added_nodes.erase(it);
3096 return m_nodes.size();
3100 for (
const auto &pnode : m_nodes) {
3113 vstats.reserve(m_nodes.size());
3114 for (
CNode *pnode : m_nodes) {
3115 vstats.emplace_back();
3116 pnode->copyStats(vstats.back());
3117 vstats.back().m_mapped_as = pnode->addr.GetMappedAS(
addrman.
GetAsmap());
3125 "disconnect by address%s matched peer=%d; disconnecting\n",
3127 pnode->fDisconnect =
true;
3134 bool disconnected =
false;
3136 for (
CNode *pnode : m_nodes) {
3137 if (subnet.
Match(pnode->addr)) {
3139 "disconnect by subnet%s matched peer=%d; disconnecting\n",
3142 pnode->fDisconnect =
true;
3143 disconnected =
true;
3146 return disconnected;
3155 for (
CNode *pnode : m_nodes) {
3156 if (
id == pnode->GetId()) {
3159 pnode->fDisconnect =
true;
3172 nTotalBytesSent += bytes;
3174 const auto now = GetTime<std::chrono::seconds>();
3177 nMaxOutboundCycleStartTime = now;
3178 nMaxOutboundTotalBytesSentInCycle = 0;
3182 nMaxOutboundTotalBytesSentInCycle += bytes;
3187 return nMaxOutboundLimit;
3196 if (nMaxOutboundLimit == 0) {
3200 if (nMaxOutboundCycleStartTime.count() == 0) {
3204 const std::chrono::seconds cycleEndTime =
3206 const auto now = GetTime<std::chrono::seconds>();
3207 return (cycleEndTime < now) ? 0s : cycleEndTime - now;
3212 if (nMaxOutboundLimit == 0) {
3216 if (historicalBlockServingLimit) {
3218 const std::chrono::seconds timeLeftInCycle =
3220 const uint64_t buffer =
3221 timeLeftInCycle / std::chrono::minutes{10} *
ONE_MEGABYTE;
3222 if (buffer >= nMaxOutboundLimit ||
3223 nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit - buffer) {
3226 }
else if (nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit) {
3235 if (nMaxOutboundLimit == 0) {
3239 return (nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit)
3241 : nMaxOutboundLimit - nMaxOutboundTotalBytesSentInCycle;
3250 return nTotalBytesSent;
3274 uint64_t windowInvCounters =
invCounters.exchange(0);
3277 int64_t polls = windowInvCounters & std::numeric_limits<uint32_t>::max();
3278 int64_t votes = windowInvCounters >> 32;
3281 decayFactor * (2 * votes - polls) + (1. - decayFactor) * previousScore;
3291 uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn,
3292 uint64_t nLocalExtraEntropyIn,
const CAddress &addrBindIn,
3295 : m_permission_flags{node_opts.permission_flags}, m_sock{sock},
3296 m_connected(
GetTime<
std::chrono::seconds>()), addr(addrIn),
3297 addrBind(addrBindIn),
3298 m_addr_name{addrNameIn.empty() ? addr.ToStringIPPort() : addrNameIn},
3299 m_inbound_onion(inbound_onion), m_prefer_evict{node_opts.prefer_evict},
3300 nKeyedNetGroup(nKeyedNetGroupIn),
3304 id(idIn), nLocalHostNonce(nLocalHostNonceIn),
3305 nLocalExtraEntropy(nLocalExtraEntropyIn), m_conn_type(conn_type_in) {
3306 if (inbound_onion) {
3311 mapRecvBytesPerMsgCmd[msg] = 0;
3334 size_t nMessageSize = msg.data.size();
3336 nMessageSize, pnode->
GetId());
3344 msg.data.size(), msg.data.data());
3347 std::vector<uint8_t> serializedHeader;
3349 size_t nTotalSize = nMessageSize + serializedHeader.size();
3351 size_t nBytesSent = 0;
3354 bool optimisticSend(pnode->vSendMsg.empty());
3357 pnode->mapSendBytesPerMsgCmd[msg.m_type] += nTotalSize;
3358 pnode->nSendSize += nTotalSize;
3363 pnode->vSendMsg.push_back(std::move(serializedHeader));
3365 pnode->vSendMsg.push_back(std::move(msg.data));
3370 if (optimisticSend) {
3380 CNode *found =
nullptr;
3382 for (
auto &&pnode : m_nodes) {
3383 if (pnode->
GetId() ==
id) {
3399 .
Write(vchNetGroup.data(), vchNetGroup.size())
3421 std::stringstream ebMBs;
3423 std::string eb = ebMBs.str();
3424 eb.insert(eb.size() - 1,
".", 1);
3425 if (eb.substr(0, 1) ==
".") {
3434 std::vector<std::string> uacomments;
3435 uacomments.push_back(
"EB" + eb);
3439 for (
const std::string &cmt :
gArgs.
GetArgs(
"-uacomment")) {
3440 uacomments.push_back(cmt);
3444 const std::string client_version =
3457 auto now = GetTime<std::chrono::microseconds>();
3460 std::string clean_addr = addr.
ToString();
3461 std::replace(clean_addr.begin(), clean_addr.end(),
':',
'_');
3467 base_path / (is_incoming ?
"msgs_recv.dat" :
"msgs_sent.dat");
3475 uint32_t size = data.
size();
3480std::function<void(
const CAddress &addr,
const std::string &msg_type,
std::vector< CAddress > ReadAnchors(const CChainParams &chainParams, const fs::path &anchors_db_path)
Read the anchor IP address database (anchors.dat)
bool DumpPeerAddresses(const CChainParams &chainParams, const ArgsManager &args, const AddrMan &addr)
void DumpAnchors(const CChainParams &chainParams, const fs::path &anchors_db_path, const std::vector< CAddress > &anchors)
Dump the anchor IP address database (anchors.dat)
const CChainParams & Params()
Return the currently selected parameters.
Stochastic address manager.
std::vector< CAddress > GetAddr(size_t max_addresses, size_t max_pct, std::optional< Network > network) const
Return all or many randomly selected addresses, optionally by network.
const std::vector< bool > & GetAsmap() const
void Attempt(const CService &addr, bool fCountFailure, NodeSeconds time=Now< NodeSeconds >())
Mark an entry as connection attempted to.
std::pair< CAddress, NodeSeconds > Select(bool newOnly=false) const
Choose an address to connect to.
void ResolveCollisions()
See if any to-be-evicted tried table entries have been tested and if so resolve the collisions.
size_t size() const
Return the number of (unique) addresses in all tables.
void Good(const CService &addr, bool test_before_evict=true, NodeSeconds time=Now< NodeSeconds >())
Mark an entry as accessible, possibly moving it from "new" to "tried".
std::pair< CAddress, NodeSeconds > SelectTriedCollision()
Randomly select an address in the tried table that another address is attempting to evict.
bool Add(const std::vector< CAddress > &vAddr, const CNetAddr &source, std::chrono::seconds time_penalty=0s)
Attempt to add one or more addresses to addrman's new table.
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
fs::path GetDataDirNet() const
Get data directory path with appended network identifier.
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Non-refcounted RAII wrapper for FILE*.
bool IsBanned(const CNetAddr &net_addr)
Return whether net_addr is banned.
bool IsDiscouraged(const CNetAddr &net_addr)
Return whether net_addr is discouraged.
A CService with information about it as peer.
ServiceFlags nServices
Serialized as uint64_t in V1, and as CompactSize in V2.
NodeSeconds nTime
Always included in serialization, except in the network format on INIT_PROTO_VERSION.
const CMessageHeader::MessageMagic & NetMagic() const
const std::vector< SeedSpec6 > & FixedSeeds() const
uint16_t GetDefaultPort() const
RAII helper to atomically create a copy of m_nodes and add a reference to each of the nodes.
bool whitelist_relay
flag for adding 'relay' permission to whitelisted inbound and manual peers with default permissions.
std::condition_variable condMsgProc
std::thread threadMessageHandler
std::chrono::seconds GetMaxOutboundTimeLeftInCycle() const
returns the time in second left in the current max outbound cycle in case of no limit,...
bool OutboundTargetReached(bool historicalBlockServingLimit) const
check if the outbound target is reached.
std::vector< NetWhitelistPermissions > vWhitelistedRangeIncoming
CClientUIInterface * m_client_interface
void ThreadMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func)
bool AddConnection(const std::string &address, ConnectionType conn_type)
Attempts to open a connection.
CNode * ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type)
void DeleteNode(CNode *pnode)
bool RemoveAddedNode(const std::string &node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
bool AttemptToEvictConnection()
Try to find a connection to evict when the node is full.
bool AlreadyConnectedToAddress(const CAddress &addr)
Determine whether we're already connected to a given address, in order to avoid initiating duplicate ...
ServiceFlags nLocalServices
Services this node offers.
bool GetTryNewOutboundPeer() const
int m_max_outbound_block_relay
std::thread threadI2PAcceptIncoming
void SetTryNewOutboundPeer(bool flag)
std::atomic< bool > flagInterruptMsgProc
unsigned int GetReceiveFloodSize() const
void ThreadOpenAddedConnections() EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
void Interrupt() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
void ThreadDNSAddressSeed() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Sock::EventsPerSock GenerateWaitSockets(Span< CNode *const > nodes)
Generate a collection of sockets to check for IO readiness.
void SocketHandlerConnected(const std::vector< CNode * > &nodes, const Sock::EventsPerSock &events_per_sock) EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Do the read/write for connected sockets that are ready for IO.
CThreadInterrupt interruptNet
This is signaled when network activity should cease.
std::unique_ptr< CSemaphore > semAddnode
bool Start(CScheduler &scheduler, const Options &options) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex
std::atomic< NodeId > nLastNodeId
void RecordBytesSent(uint64_t bytes)
int GetExtraBlockRelayCount() const
void WakeMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
BanMan * m_banman
Pointer to this node's banman.
uint64_t GetOutboundTargetBytesLeft() const
response the bytes left in the current max outbound cycle in case of no limit, it will always respons...
std::thread threadDNSAddressSeed
void ThreadI2PAcceptIncoming()
std::vector< CAddress > m_anchors
Addresses that were saved during the previous clean shutdown.
std::chrono::seconds GetMaxOutboundTimeframe() const
bool whitelist_forcerelay
flag for adding 'forcerelay' permission to whitelisted inbound and manual peers with default permissi...
unsigned int nPrevNodeCount
void NotifyNumConnectionsChanged()
ServiceFlags GetLocalServices() const
Used to convey which local services we are offering peers during node connection.
bool DisconnectNode(const std::string &node)
std::chrono::seconds m_peer_connect_timeout
std::atomic_bool m_try_another_outbound_peer
flag for deciding to connect to an extra outbound peer, in excess of m_max_outbound_full_relay.
bool InitBinds(const Options &options)
void AddAddrFetch(const std::string &strDest) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex)
std::vector< ListenSocket > vhListenSocket
std::vector< CAddress > GetCurrentBlockRelayOnlyConns() const
Return vector of current BLOCK_RELAY peers.
CSipHasher GetDeterministicRandomizer(uint64_t id) const
Get a unique deterministic randomizer.
uint64_t GetMaxOutboundTarget() const
std::unique_ptr< CSemaphore > semOutbound
RecursiveMutex cs_totalBytesSent
bool Bind(const CService &addr, unsigned int flags, NetPermissionFlags permissions)
std::thread threadOpenConnections
size_t GetNodeCount(ConnectionDirection) const
Mutex m_addr_fetches_mutex
bool InactivityCheck(const CNode &node) const
Return true if the peer is inactive and should be disconnected.
CNode * FindNode(const CNetAddr &ip)
void GetNodeStats(std::vector< CNodeStats > &vstats) const
std::vector< AddedNodeInfo > GetAddedNodeInfo() const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
const uint64_t nSeed0
SipHasher seeds for deterministic randomness.
unsigned int nReceiveFloodSize
int GetExtraFullOutboundCount() const
uint64_t GetTotalBytesRecv() const
std::pair< size_t, bool > SocketSendData(CNode &node) const EXCLUSIVE_LOCKS_REQUIRED(node.cs_vSend)
(Try to) send data from node's vSendMsg.
RecursiveMutex m_nodes_mutex
static bool NodeFullyConnected(const CNode *pnode)
void ProcessAddrFetch() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex)
CConnman(const Config &configIn, uint64_t seed0, uint64_t seed1, AddrMan &addrmanIn, bool network_active=true)
std::vector< CAddress > GetAddresses(size_t max_addresses, size_t max_pct, std::optional< Network > network) const
Return all or many randomly selected addresses, optionally by network.
void SetNetworkActive(bool active)
std::list< CNode * > m_nodes_disconnected
void OpenNetworkConnection(const CAddress &addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound, const char *strDest, ConnectionType conn_type)
void SocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
Check connected and listening sockets for IO readiness and process them accordingly.
uint64_t CalculateKeyedNetGroup(const CAddress &ad) const
bool fAddressesInitialized
bool AddNode(const std::string &node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
std::thread threadOpenAddedConnections
Mutex m_added_nodes_mutex
void AddWhitelistPermissionFlags(NetPermissionFlags &flags, const CNetAddr &addr, const std::vector< NetWhitelistPermissions > &ranges) const
void Init(const Options &connOptions) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
bool CheckIncomingNonce(uint64_t nonce)
int m_max_outbound_full_relay
void RecordBytesRecv(uint64_t bytes)
bool ShouldRunInactivityChecks(const CNode &node, std::chrono::seconds now) const
Return true if we should disconnect the peer for failing an inactivity check.
void ThreadSocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
void CreateNodeFromAcceptedSocket(std::unique_ptr< Sock > &&sock, NetPermissionFlags permission_flags, const CAddress &addr_bind, const CAddress &addr)
Create a CNode object from a socket that has just been accepted and add the node to the m_nodes membe...
void PushMessage(CNode *pnode, CSerializedNetMsg &&msg)
unsigned int nSendBufferMaxSize
std::unique_ptr< i2p::sam::Session > m_i2p_sam_session
I2P SAM session.
bool m_use_addrman_outgoing
std::vector< NetWhitelistPermissions > vWhitelistedRangeOutgoing
std::map< uint64_t, CachedAddrResponse > m_addr_response_caches
Addr responses stored in different caches per (network, local socket) prevent cross-network node iden...
std::atomic< uint64_t > nTotalBytesRecv
std::atomic< bool > fNetworkActive
std::atomic_bool m_start_extra_block_relay_peers
flag for initiating extra block-relay-only peer connections.
void SocketHandlerListening(const Sock::EventsPerSock &events_per_sock)
Accept incoming connections, one from each read-ready listening socket.
std::vector< CService > m_onion_binds
A vector of -bind=<address>:<port>=onion arguments each of which is an address and port that are desi...
std::vector< NetEventsInterface * > m_msgproc
std::thread threadSocketHandler
uint64_t GetTotalBytesSent() const
void ThreadOpenConnections(std::vector< std::string > connect, std::function< void(const CAddress &, ConnectionType)> mockOpenConnection) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
void AcceptConnection(const ListenSocket &hListenSocket)
bool BindListenPort(const CService &bindAddr, bilingual_str &strError, NetPermissionFlags permissions)
int m_max_avalanche_outbound
void resize(size_type n, value_type c=value_type{})
CHash256 & Write(Span< const uint8_t > input)
void Finalize(Span< uint8_t > output)
Network GetNetClass() const
std::string ToStringIP() const
std::string ToString() const
std::vector< uint8_t > GetGroup(const std::vector< bool > &asmap) const
Get the canonical identifier of our network group.
std::vector< uint8_t > GetAddrBytes() const
bool SetInternal(const std::string &name)
Create an "internal" address that represents a name or FQDN.
enum Network GetNetwork() const
Transport protocol agnostic message container.
uint32_t m_message_size
size of the payload
std::chrono::microseconds m_time
time of message receipt
uint32_t m_raw_message_size
used wire size of the message (including header/checksum)
Information about a peer.
const std::chrono::seconds m_connected
Unix epoch time at peer connection.
std::atomic< int > nVersion
std::atomic< double > availabilityScore
The last computed score.
bool IsInboundConn() const
std::atomic< int64_t > nTimeOffset
const std::string m_addr_name
std::string ConnectionTypeAsString() const
std::atomic< bool > m_bip152_highbandwidth_to
std::list< CNetMessage > vRecvMsg
std::atomic< bool > m_bip152_highbandwidth_from
std::atomic_bool fSuccessfullyConnected
CNode(NodeId id, std::shared_ptr< Sock > sock, const CAddress &addrIn, uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn, uint64_t nLocalExtraEntropyIn, const CAddress &addrBindIn, const std::string &addrNameIn, ConnectionType conn_type_in, bool inbound_onion, CNodeOptions &&node_opts={})
void SetAddrLocal(const CService &addrLocalIn) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex)
May not be called more than once.
CSemaphoreGrant grantOutbound
std::unique_ptr< TransportSerializer > m_serializer
Mutex m_subver_mutex
cleanSubVer is a sanitized string of the user agent byte array we read from the wire.
std::atomic_bool fPauseSend
std::unique_ptr< TransportDeserializer > m_deserializer
double getAvailabilityScore() const
const ConnectionType m_conn_type
Network ConnectedThroughNetwork() const
Get network the peer connected through.
void copyStats(CNodeStats &stats) EXCLUSIVE_LOCKS_REQUIRED(!m_subver_mutex
std::atomic< std::chrono::microseconds > m_last_ping_time
Last measured round-trip time.
void updateAvailabilityScore(double decayFactor)
The availability score is calculated using an exponentially weighted average.
const NetPermissionFlags m_permission_flags
bool ReceiveMsgBytes(const Config &config, Span< const uint8_t > msg_bytes, bool &complete) EXCLUSIVE_LOCKS_REQUIRED(!cs_vRecv)
Receive bytes from the buffer and deserialize them into messages.
void invsPolled(uint32_t count)
The node was polled for count invs.
const bool m_inbound_onion
Whether this peer is an inbound onion, i.e.
std::atomic< std::chrono::microseconds > m_min_ping_time
Lowest measured round-trip time.
std::atomic< std::chrono::seconds > m_last_proof_time
UNIX epoch time of the last proof received from this peer that we had not yet seen (e....
std::atomic< bool > m_avalanche_enabled
std::atomic< std::chrono::seconds > m_last_block_time
UNIX epoch time of the last block received from this peer that we had not yet seen (e....
std::atomic< uint64_t > invCounters
The inventories polled and voted counters since last score computation, stored as a pair of uint32_t ...
std::atomic_bool fDisconnect
std::atomic< std::chrono::seconds > m_last_recv
std::atomic< std::chrono::seconds > m_last_tx_time
UNIX epoch time of the last transaction received from this peer that we had not yet seen (e....
CService GetAddrLocal() const EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex)
void invsVoted(uint32_t count)
The node voted for count invs.
void CloseSocketDisconnect() EXCLUSIVE_LOCKS_REQUIRED(!m_sock_mutex)
std::atomic< std::chrono::seconds > m_last_send
Simple class for background tasks that should be run periodically or once "after a while".
void scheduleEvery(Predicate p, std::chrono::milliseconds delta) EXCLUSIVE_LOCKS_REQUIRED(!newTaskMutex)
Repeat p until it return false.
RAII-style semaphore lock.
void MoveTo(CSemaphoreGrant &grant)
A combination of a network address (CNetAddr) and a (TCP) port.
std::string ToStringIPPort() const
std::string ToString() const
bool SetSockAddr(const struct sockaddr *paddr)
bool GetSockAddr(struct sockaddr *paddr, socklen_t *addrlen) const
Obtain the IPv4/6 socket address this represents.
uint64_t Finalize() const
Compute the 64-bit SipHash-2-4 of the data written so far.
CSipHasher & Write(uint64_t data)
Hash a 64-bit integer worth of data.
std::string ToString() const
bool Match(const CNetAddr &addr) const
bool sleep_for(std::chrono::milliseconds rel_time) EXCLUSIVE_LOCKS_REQUIRED(!mut)
Minimal stream for overwriting and/or appending to an existing byte vector.
virtual uint64_t GetMaxBlockSize() const =0
virtual const CChainParams & GetChainParams() const =0
Tp rand_uniform_delay(const Tp &time, typename Tp::duration range)
Return the time point advanced by a uniform random duration.
uint64_t randbits(int bits) noexcept
Generate a random (bits)-bit integer.
Different type to mark Mutex at global scope.
static Mutex g_msgproc_mutex
Mutex for anything that is only accessed via the msg processing thread.
NetPermissionFlags m_flags
static void AddFlag(NetPermissionFlags &flags, NetPermissionFlags f)
static void ClearFlag(NetPermissionFlags &flags, NetPermissionFlags f)
ClearFlag is only called with f == NetPermissionFlags::Implicit.
static bool HasFlag(NetPermissionFlags flags, NetPermissionFlags f)
static bool TryParse(const std::string &str, NetWhitebindPermissions &output, bilingual_str &error)
static constexpr Event SEND
If passed to Wait(), then it will wait for readiness to send to the socket.
static constexpr Event ERR
Ignored if passed to Wait(), but could be set in the occurred events if an exceptional condition has ...
static constexpr Event RECV
If passed to Wait(), then it will wait for readiness to read from the socket.
std::unordered_map< std::shared_ptr< const Sock >, Events, HashSharedPtrSock, EqualSharedPtrSock > EventsPerSock
On which socket to wait for what events in WaitMany().
constexpr std::size_t size() const noexcept
CONSTEXPR_IF_NOT_DEBUG Span< C > first(std::size_t count) const noexcept
constexpr C * data() const noexcept
CNetMessage GetMessage(const Config &config, std::chrono::microseconds time) override
const uint256 & GetMessageHash() const
int readData(Span< const uint8_t > msg_bytes)
bool Complete() const override
int readHeader(const Config &config, Span< const uint8_t > msg_bytes)
void prepareForTransport(const Config &config, CSerializedNetMsg &msg, std::vector< uint8_t > &header) override
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
std::string FormatVersion(int nVersion)
std::string FormatUserAgent(const std::string &name, const std::string &version, const std::vector< std::string > &comments)
Format the subversion field according to BIP 14 spec.
static constexpr int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
const std::string CLIENT_NAME
#define WSAGetLastError()
static bool IsSelectableSocket(const SOCKET &s)
const Config & GetConfig()
static const uint64_t ONE_MEGABYTE
1MB
static uint32_t ReadLE32(const uint8_t *ptr)
const std::vector< std::string > GetRandomizedDNSSeeds(const CChainParams ¶ms)
Return the list of hostnames to look up for DNS seeds.
uint256 Hash(const T &in1)
Compute the 256-bit hash of an object.
bool error(const char *fmt, const Args &...args)
#define LogPrintLevel(category, level,...)
#define LogPrint(category,...)
static unsigned char elements[DATACOUNT][DATALEN]
static bool create_directories(const std::filesystem::path &p)
Create directory (and if necessary its parents), unless the leaf directory already exists or is a sym...
FILE * fopen(const fs::path &p, const char *mode)
Implement std::hash so RCUPtr can be used as a key for maps or sets.
void TraceThread(const char *thread_name, std::function< void()> thread_func)
A wrapper for do-something-once thread functions.
static bool CompareNodeBlockTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
bool IsPeerAddrLocalGood(CNode *pnode)
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.
static constexpr int DNSSEEDS_TO_QUERY_AT_ONCE
Number of DNS seeds to query when the number of connections is low.
bool IsLocal(const CService &addr)
check whether a given address is potentially local
static const uint64_t RANDOMIZER_ID_NETGROUP
CService GetLocalAddress(const CNetAddr &addrPeer)
static const uint64_t SELECT_TIMEOUT_MILLISECONDS
static bool CompareNodeBlockRelayOnlyTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
void RemoveLocal(const CService &addr)
BindFlags
Used to pass flags to the Bind() function.
@ BF_DONT_ADVERTISE
Do not call AddLocal() for our special addresses, e.g., for incoming Tor connections,...
static const uint64_t RANDOMIZER_ID_LOCALHOSTNONCE
static constexpr std::chrono::minutes DUMP_PEERS_INTERVAL
static constexpr int DNSSEEDS_DELAY_PEER_THRESHOLD
static constexpr size_t MAX_BLOCK_RELAY_ONLY_ANCHORS
Maximum number of block-relay-only anchor connections.
bool GetLocal(CService &addr, const CNetAddr *paddrPeer)
static bool ReverseCompareNodeTimeConnected(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
static bool CompareNodeAvailabilityScore(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
static bool CompareNetGroupKeyed(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
static CAddress GetBindAddress(SOCKET sock)
Get the bind address for a socket as CAddress.
static constexpr std::chrono::seconds DNSSEEDS_DELAY_FEW_PEERS
How long to delay before querying DNS seeds.
static const uint64_t RANDOMIZER_ID_ADDRCACHE
void ProtectEvictionCandidatesByRatio(std::vector< NodeEvictionCandidate > &eviction_candidates)
Protect desirable or disadvantaged inbound peers from eviction by ratio.
const std::string NET_MESSAGE_COMMAND_OTHER
std::optional< CService > GetLocalAddrForPeer(CNode &node)
Returns a local address that we should advertise to this peer.
std::optional< NodeId > SelectNodeToEvict(std::vector< NodeEvictionCandidate > &&vEvictionCandidates)
Select an inbound peer to evict after filtering out (protecting) peers having distinct,...
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
static bool CompareNodeTXTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
std::function< void(const CAddress &addr, const std::string &msg_type, Span< const uint8_t > data, bool is_incoming)> CaptureMessage
Defaults to CaptureMessageToFile(), but can be overridden by unit tests.
const char *const ANCHORS_DATABASE_FILENAME
Anchor IP address database file name.
std::string getSubVersionEB(uint64_t MaxBlockSize)
This function convert MaxBlockSize from byte to MB with a decimal precision one digit rounded down E....
GlobalMutex g_maplocalhost_mutex
std::map< CNetAddr, LocalServiceInfo > mapLocalHost GUARDED_BY(g_maplocalhost_mutex)
bool AddLocal(const CService &addr, int nScore)
static bool CompareNodeProofTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
#define FEELER_SLEEP_WINDOW
void CaptureMessageToFile(const CAddress &addr, const std::string &msg_type, Span< const uint8_t > data, bool is_incoming)
Dump binary message to file, with timestamp.
static constexpr std::chrono::minutes DNSSEEDS_DELAY_MANY_PEERS
static int GetnScore(const CService &addr)
std::string ConnectionTypeAsString(ConnectionType conn_type)
Convert ConnectionType enum to a string value.
static const uint64_t RANDOMIZER_ID_EXTRAENTROPY
static std::vector< CAddress > convertSeed6(const std::vector< SeedSpec6 > &vSeedsIn)
Convert the pnSeed6 array into usable address objects.
static bool ReverseCompareNodeMinPingTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
static CNetCleanup instance_of_cnetcleanup
std::string userAgent(const Config &config)
static constexpr std::chrono::seconds MAX_UPLOAD_TIMEFRAME
The default timeframe for -maxuploadtarget.
void Discover()
Look up IP addresses from all interfaces on the machine and add them to the list of local addresses t...
bool IsReachable(enum Network net)
bool SeenLocal(const CService &addr)
vote for a local address
static constexpr std::chrono::minutes TIMEOUT_INTERVAL
Time after which to disconnect, after waiting for a ping response (or inactivity).
static const bool DEFAULT_FORCEDNSSEED
static constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL
Run the extra block-relay-only connection loop once every 5 minutes.
static const bool DEFAULT_FIXEDSEEDS
ConnectionType
Different types of connections to a peer.
@ BLOCK_RELAY
We use block-relay-only connections to help prevent against partition attacks.
@ MANUAL
We open manual connections to addresses that users explicitly inputted via the addnode RPC,...
@ OUTBOUND_FULL_RELAY
These are the default connections that we use to connect with the network.
@ FEELER
Feeler connections are short-lived connections made to check that a node is alive.
@ INBOUND
Inbound connections are those initiated by a peer.
@ AVALANCHE_OUTBOUND
Special case of connection to a full relay outbound with avalanche service enabled.
@ ADDR_FETCH
AddrFetch connections are short lived connections used to solicit addresses from peers.
static constexpr auto FEELER_INTERVAL
Run the feeler connection loop once every 2 minutes.
static const bool DEFAULT_DNSSEED
static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
@ NET_MAX
Dummy value to indicate the number of NET_* constants.
@ NET_ONION
TOR (v2 or v3)
@ NET_UNROUTABLE
Addresses from these networks are not publicly routable on the global Internet.
@ NET_INTERNAL
A set of addresses that represent the hash of a string or FQDN.
bool GetNameProxy(proxyType &nameProxyOut)
bool GetProxy(enum Network net, proxyType &proxyInfoOut)
bool SetSocketNoDelay(const SOCKET &hSocket)
Set the TCP_NODELAY flag on a socket.
bool ConnectThroughProxy(const proxyType &proxy, const std::string &strDest, uint16_t port, const Sock &sock, int nTimeout, bool &outProxyConnectionFailed)
Connect to a specified destination service through a SOCKS5 proxy by first connecting to the SOCKS5 p...
void InterruptSocks5(bool interrupt)
std::function< std::unique_ptr< Sock >(const CService &)> CreateSock
Socket factory.
bool ConnectSocketDirectly(const CService &addrConnect, const Sock &sock, int nTimeout, bool manual_connection)
Try to connect to the specified service on the specified socket.
bool Lookup(const std::string &name, std::vector< CService > &vAddr, uint16_t portDefault, bool fAllowLookup, unsigned int nMaxSolutions, DNSLookupFn dns_lookup_function)
Resolve a service string to its corresponding service.
CService LookupNumeric(const std::string &name, uint16_t portDefault, DNSLookupFn dns_lookup_function)
Resolve a service string with a numeric IP to its first corresponding service.
bool IsBadPort(uint16_t port)
Determine if a port is "bad" from the perspective of attempting to connect to a node on that port.
bool LookupHost(const std::string &name, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function)
Resolve a host string to its corresponding network addresses.
const std::vector< std::string > & getAllNetMessageTypes()
Get a vector of all valid message types (see above)
ServiceFlags GetDesirableServiceFlags(ServiceFlags services)
Gets the set of service flags which are "desirable" for a given peer.
static bool HasAllDesirableServiceFlags(ServiceFlags services)
A shortcut for (services & GetDesirableServiceFlags(services)) == GetDesirableServiceFlags(services),...
ServiceFlags
nServices flags.
static bool MayHaveUsefulAddressDB(ServiceFlags services)
Checks if a peer with the given service flags may be capable of having a robust address-storage DB.
std::chrono::microseconds GetExponentialRand(std::chrono::microseconds now, std::chrono::seconds average_interval)
Return a timestamp in the future sampled from an exponential distribution (https://en....
void RandAddEvent(const uint32_t event_info) noexcept
Gathers entropy from the low bits of the time at which events occur.
constexpr auto GetRandMillis
T GetRand(T nMax=std::numeric_limits< T >::max()) noexcept
Generate a uniform random integer of type T in the range [0..nMax) nMax defaults to std::numeric_limi...
static uint16_t GetDefaultPort()
void ser_writedata32(Stream &s, uint32_t obj)
void ser_writedata64(Stream &s, uint64_t obj)
std::string NetworkErrorString(int err)
Return readable error string for a network error code.
Span< const std::byte > MakeByteSpan(V &&v) noexcept
Span< const std::byte > AsBytes(Span< T > s) noexcept
Cache responses to addr requests to minimize privacy leak.
std::chrono::microseconds m_cache_entry_expiration
std::vector< CAddress > m_addrs_response_cache
void AddSocketPermissionFlags(NetPermissionFlags &flags) const
std::shared_ptr< Sock > sock
std::vector< NetWhitebindPermissions > vWhiteBinds
std::vector< CService > onion_binds
std::vector< std::string > m_specified_outgoing
std::vector< CService > vBinds
bool m_i2p_accept_incoming
std::vector< std::string > vSeedNodes
bool m_use_addrman_outgoing
bool bind_on_any
True if the user did not specify -bind= or -whitebind= and thus we should bind on 0....
NetPermissionFlags permission_flags
POD that contains various stats about a node.
mapMsgCmdSize mapSendBytesPerMsgCmd
std::chrono::microseconds m_last_ping_time
std::chrono::seconds m_last_recv
std::optional< double > m_availabilityScore
std::chrono::seconds m_last_proof_time
ConnectionType m_conn_type
std::chrono::seconds m_last_send
std::chrono::seconds m_last_tx_time
std::chrono::microseconds m_min_ping_time
std::chrono::seconds m_connected
bool m_bip152_highbandwidth_from
bool m_bip152_highbandwidth_to
mapMsgCmdSize mapRecvBytesPerMsgCmd
std::chrono::seconds m_last_block_time
NetPermissionFlags m_permission_flags
std::vector< uint8_t > data
Sort eviction candidates by network/localhost and connection uptime.
CompareNodeNetworkTime(bool is_local, Network network)
bool operator()(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b) const
static time_point now() noexcept
Return current system time or mocked time, if set.
std::chrono::seconds m_last_tx_time
std::chrono::seconds m_connected
std::chrono::seconds m_last_block_time
std::chrono::microseconds m_min_ping_time
std::chrono::seconds m_last_proof_time
Auxiliary requested/occurred events to wait for in WaitMany().
An established connection with another peer.
std::unique_ptr< Sock > sock
Connected socket.
CService me
Our I2P address.
#define WAIT_LOCK(cs, name)
#define AssertLockNotHeld(cs)
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
#define EXCLUSIVE_LOCKS_REQUIRED(...)
int64_t GetTimeMillis()
Returns the system time (not mockable)
int64_t GetTime()
DEPRECATED Use either ClockType::now() or Now<TimePointType>() if a cast is needed.
constexpr int64_t count_seconds(std::chrono::seconds t)
std::chrono::time_point< NodeClock, std::chrono::seconds > NodeSeconds
#define TRACE6(context, event, a, b, c, d, e, f)
bilingual_str _(const char *psz)
Translation function.
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
void SplitHostPort(std::string_view in, uint16_t &portOut, std::string &hostOut)
std::string SanitizeString(std::string_view str, int rule)
Remove unsafe chars.
static const int INIT_PROTO_VERSION
initial proto version, to be increased after version/verack negotiation