6#include <bitcoin-build-config.h>
44#include <util/threadinterrupt.h>
63#include <unordered_map>
183 if (!
fListen)
return std::nullopt;
185 std::optional<CService> addr;
245 return (it !=
mapLocalHost.end()) ? it->second.nScore : 0;
268 if (
node.IsInboundConn()) {
277 addrLocal.SetIP(
node.GetAddrLocal());
280 if (addrLocal.IsRoutable()) {
299 if (!addr.IsRoutable())
309 LogInfo(
"AddLocal(%s,%i)\n", addr.ToStringAddrPort(), nScore);
318 info.
nPort = addr.GetPort();
361 return std::ranges::any_of(
m_nodes, [&host](
CNode*
node) {
return node->m_addr_name == host; });
388 if (!
pnode->fSuccessfullyConnected && !
pnode->IsInboundConn() && !
pnode->IsPrivateBroadcastConn() &&
399 bool use_v2transport,
400 const std::optional<Proxy>& proxy_override)
412 LogInfo(
"Failed to open new connection to %s, already connected",
addrConnect.ToStringAddrPort());
431 if (!resolved.empty()) {
435 for (
const auto& r : resolved) {
460 std::unique_ptr<Sock> sock;
474 bool connected{
false};
502 sock = std::move(
conn.sock);
563 .proxy_override = proxy_override,
594 m_i2p_sam_session.reset();
598 for (
const auto& subnet :
ranges) {
599 if (addr.has_value() && subnet.m_subnet.Match(addr.value())) {
638#define X(name) stats.name = name
661 X(mapSendBytesPerMsgType);
666 X(mapRecvBytesPerMsgType);
712 auto i = mapRecvBytesPerMsgType.find(msg.m_type);
713 if (i == mapRecvBytesPerMsgType.end()) {
716 assert(i != mapRecvBytesPerMsgType.end());
717 i->second += msg.m_raw_message_size;
774 catch (
const std::exception&) {
836 msg.m_type =
hdr.GetMessageType();
838 msg.m_message_size =
hdr.nMessageSize;
848 LogDebug(
BCLog::NET,
"Header error: Wrong checksum (%s, %u bytes), expected %s was %s, peer=%d\n",
854 }
else if (!
hdr.IsMessageTypeValid()) {
942const std::array<std::string, BIP324_SHORTIDS_IMPLEMENTED>
V2_MESSAGE_IDS = {
980 std::unordered_map<std::string, uint8_t> m_map;
983 V2MessageMap() noexcept
990 std::optional<uint8_t> operator()(
const std::string&
message_name)
const noexcept
993 if (it == m_map.end())
return std::nullopt;
1002 std::vector<uint8_t>
ret;
1024 : m_cipher{key,
ent32},
1025 m_initiating{initiating},
1027 m_v1_fallback{nodeid},
1028 m_recv_state{initiating ? RecvState::KEY : RecvState::KEY_MAYBE_V1},
1030 m_send_state{initiating ? SendState::AWAITING_KEY : SendState::MAYBE_V1}
1036 StartSendingHandshake();
1049 case RecvState::KEY_MAYBE_V1:
1052 case RecvState::KEY:
1055 case RecvState::GARB_GARBTERM:
1058 case RecvState::VERSION:
1061 case RecvState::APP:
1064 case RecvState::APP_READY:
1080 case SendState::MAYBE_V1:
1083 case SendState::AWAITING_KEY:
1086 case SendState::READY:
1113 std::array<uint8_t, V1_PREFIX_LEN>
v1_prefix = {0, 0, 0, 0,
'v',
'e',
'r',
's',
'i',
'o',
'n', 0, 0, 0, 0, 0};
1114 std::copy(std::begin(
Params().MessageStart()), std::end(
Params().MessageStart()),
v1_prefix.begin());
1116 if (!std::equal(m_recv_buffer.begin(), m_recv_buffer.end(),
v1_prefix.begin())) {
1123 }
else if (m_recv_buffer.size() ==
v1_prefix.size()) {
1126 std::span<const uint8_t>
feedback{m_recv_buffer};
1155 static constexpr std::array<uint8_t, 12> MATCH = {
'v',
'e',
'r',
's',
'i',
'o',
'n', 0, 0, 0, 0, 0};
1156 static constexpr size_t OFFSET = std::tuple_size_v<MessageStartChars>;
1158 if (std::equal(MATCH.begin(), MATCH.end(), m_recv_buffer.begin() +
OFFSET)) {
1176 m_recv_buffer.clear();
1212 m_recv_buffer.clear();
1362 size_t max_read = GetMaxBytesToProcess();
1365 if (m_recv_buffer.size() + std::min(
msg_bytes.size(),
max_read) > m_recv_buffer.capacity()) {
1367 case RecvState::KEY_MAYBE_V1:
1368 case RecvState::KEY:
1369 case RecvState::GARB_GARBTERM:
1374 case RecvState::VERSION:
1375 case RecvState::APP: {
1382 m_recv_buffer.reserve(m_recv_buffer.size() +
alloc_add);
1385 case RecvState::APP_READY:
1387 Assume(m_recv_buffer.empty());
1404 case RecvState::KEY_MAYBE_V1:
1405 ProcessReceivedMaybeV1Bytes();
1409 case RecvState::KEY:
1410 if (!ProcessReceivedKeyBytes())
return false;
1413 case RecvState::GARB_GARBTERM:
1414 if (!ProcessReceivedGarbageBytes())
return false;
1417 case RecvState::VERSION:
1418 case RecvState::APP:
1419 if (!ProcessReceivedPacketBytes())
return false;
1422 case RecvState::APP_READY:
1439 if (
contents.size() == 0)
return std::nullopt;
1450 return std::nullopt;
1455 return std::nullopt;
1494 msg.m_message_size =
contents.size();
1495 msg.m_recv.resize(
contents.size());
1502 SetReceiveState(RecvState::APP);
1511 if (
m_send_state == SendState::V1)
return m_v1_fallback.SetMessageToSend(msg);
1520 contents.resize(1 + msg.data.size());
1522 std::copy(msg.data.begin(), msg.data.end(),
contents.begin() + 1);
1527 std::copy(msg.m_type.begin(), msg.m_type.end(),
contents.data() + 1);
1589 if (!m_recv_buffer.empty())
return false;
1627 auto it =
node.vSendMsg.begin();
1633 if (it !=
node.vSendMsg.end()) {
1637 size_t memusage = it->GetMemoryUsage();
1638 if (
node.m_transport->SetMessageToSend(*it)) {
1652 if (!
data.empty()) {
1688 node.CloseSocketDisconnect();
1701 if (it ==
node.vSendMsg.end()) {
1704 node.vSendMsg.erase(
node.vSendMsg.begin(), it);
1725 if (
node->fDisconnect)
1735 .m_connected =
node->m_connected,
1736 .m_min_ping_time =
node->m_min_ping_time,
1737 .m_last_block_time =
node->m_last_block_time,
1738 .m_last_tx_time =
node->m_last_tx_time,
1739 .fRelevantServices =
node->m_has_all_wanted_services,
1740 .m_relay_txs =
node->m_relays_txs.load(),
1741 .fBloomFilter =
node->m_bloom_filter_loaded.load(),
1742 .nKeyedNetGroup =
node->nKeyedNetGroup,
1743 .prefer_evict =
node->m_prefer_evict,
1744 .m_is_local =
node->addr.IsLocal(),
1745 .m_network =
node->ConnectedThroughNetwork(),
1747 .m_conn_type =
node->m_conn_type,
1762 pnode->m_addr_name.c_str(),
1763 pnode->ConnectionTypeAsString().c_str(),
1764 pnode->ConnectedThroughNetwork(),
1766 pnode->fDisconnect =
true;
1830 if (!sock->IsSelectable()) {
1839 LogDebug(
BCLog::NET,
"connection from %s: unable to set TCP_NODELAY, continuing anyway\n",
1863 LogDebug(
BCLog::NET,
"failed to find an eviction candidate - connection dropped (full)\n");
1906 pnode->m_addr_name.c_str(),
1907 pnode->ConnectionTypeAsString().c_str(),
1908 pnode->ConnectedThroughNetwork(),
1919 std::optional<int> max_connections;
1920 switch (conn_type) {
1943 return std::count_if(
m_nodes.begin(),
m_nodes.end(), [conn_type](
CNode*
node) { return node->m_conn_type == conn_type; }););
1950 if (!grant)
return false;
1978 if (!
pnode->fDisconnect) {
1980 pnode->fDisconnect =
true;
1989 if (
pnode->fDisconnect)
1999 .proxy_override =
pnode->m_proxy_override,
2000 .addr_connect =
pnode->addr,
2001 .grant = std::move(
pnode->grantOutbound),
2002 .destination =
pnode->m_dest,
2003 .conn_type =
pnode->m_conn_type,
2004 .use_v2transport =
false});
2009 pnode->grantOutbound.Release();
2012 pnode->CloseSocketDisconnect();
2029 if (
pnode->GetRefCount() <= 0) {
2068 const auto last_send{
node.m_last_send.load()};
2069 const auto last_recv{
node.m_last_recv.load()};
2081 "socket no message in first %i seconds%s, %s",
2084 node.DisconnectMsg()
2092 node.DisconnectMsg()
2100 node.DisconnectMsg()
2105 if (
node.fPauseSend) {
2110 node.DisconnectMsg()
2116 if (!
node.fSuccessfullyConnected) {
2150 if (
pnode->m_sock) {
2156 return events_per_sock;
2176 if (events_per_sock.empty() || !events_per_sock.begin()->first->WaitMany(timeout, events_per_sock)) {
2208 if (!
pnode->m_sock) {
2211 const auto it = events_per_sock.find(
pnode->m_sock);
2212 if (it != events_per_sock.end()) {
2243 if (!
pnode->m_sock) {
2250 bool notify =
false;
2251 if (!
pnode->ReceiveMsgBytes({pchBuf, (size_t)nBytes}, notify)) {
2253 "receiving message bytes failed, %s",
2254 pnode->DisconnectMsg()
2256 pnode->CloseSocketDisconnect();
2260 pnode->MarkReceivedMsgsForProcessing();
2267 if (!
pnode->fDisconnect) {
2270 pnode->CloseSocketDisconnect();
2278 if (!
pnode->fDisconnect) {
2281 pnode->CloseSocketDisconnect();
2299 if (it != events_per_sock.end() && it->second.occurred &
Sock::RecvEvent) {
2332 LogInfo(
"-seednode enabled. Trying the provided seeds for %d seconds before defaulting to the dnsseeds.\n",
SEEDNODE_TIMEOUT.count());
2341 LogInfo(
"Couldn't connect to enough peers via seed nodes. Handing fetch logic to the DNS seeds.\n");
2347 LogInfo(
"P2P peers available. Finished fetching data from seed nodes.\n");
2355 std::shuffle(seeds.begin(), seeds.end(),
rng);
2361 }
else if (
addrman.get().Size() == 0) {
2385 for (
const std::string& seed : seeds) {
2389 if (
addrman.get().Size() > 0) {
2402 LogInfo(
"%d addresses found from DNS seeds\n", found);
2403 LogInfo(
"P2P peers available. Finished DNS seeding.\n");
2405 LogInfo(
"P2P peers available. Skipped DNS seeding.\n");
2417 LogInfo(
"Waiting for network to be reactivated before querying DNS seeds.\n");
2423 LogInfo(
"Loading addresses from DNS seed %s\n", seed);
2429 std::vector<CAddress>
vAdd;
2446 vAdd.push_back(addr);
2459 LogInfo(
"%d addresses found from DNS seeds\n", found);
2461 LogInfo(
"Skipping DNS seeds. Enough peers have been found\n");
2467 const auto start{SteadyClock::now()};
2511 LogDebug(
BCLog::NET,
"setting try another outbound peer=%s\n", flag ?
"true" :
"false");
2549 if (
pnode->fSuccessfullyConnected && !
pnode->fDisconnect &&
pnode->IsFullOutboundConn()) {
2565 if (
pnode->fSuccessfullyConnected && !
pnode->fDisconnect &&
pnode->IsBlockOnlyConn()) {
2579 if (!
pnode->fDisconnect &&
pnode->IsInboundConn() &&
pnode->m_relays_txs) {
2592 std::unordered_set<Network>
networks{};
2593 for (
int n = 0; n <
NET_MAX; n++) {
2635 if (!connect.empty())
2642 for (
const std::string&
strAddr : connect)
2651 for (
int i = 0; i < 10 && i <
nLoop; i++)
2681 LogInfo(
"Fixed seeds are disabled\n");
2690 if (
addrman.get().Size() == 0) {
2691 LogInfo(
"Empty addrman, adding seednode (%s) to addrfetch\n", seed);
2693 LogInfo(
"Couldn't connect to peers from addrman after %d seconds. Adding seednode (%s) to addrfetch\n",
ADD_NEXT_SEEDNODE.count(), seed);
2720 LogInfo(
"Adding fixed seeds as 60 seconds have passed and addrman is empty for at least one reachable network\n");
2728 LogInfo(
"Adding fixed seeds as -dnsseed=0 (or IPv4/IPv6 connections are disabled via -onlynet) and neither -addnode nor -seednode are provided\n");
2767 switch (
pnode->m_conn_type) {
2782 if (address.IsTor() || address.IsI2P() || address.IsCJDNS()) {
2879 addrman.get().ResolveCollisions();
2981 LogDebug(
BCLog::NET,
"Not making automatic %s%s connection to %s peer selected for manual (addnode) connection%s\n",
3024 std::vector<CAddress>
ret;
3027 if (
pnode->IsBlockOnlyConn()) {
3039 std::vector<AddedNodeInfo>
ret;
3055 if (
pnode->addr.IsValid()) {
3086 addedNode.resolvedAddress = it->second.second;
3118 info.m_params.m_added_node.c_str(),
3120 info.m_params.m_use_v2transport,
3140 bool use_v2transport,
3141 const std::optional<Proxy>& proxy_override)
3182 pnode->m_addr_name.c_str(),
3183 pnode->ConnectionTypeAsString().c_str(),
3184 pnode->ConnectedThroughNetwork(),
3213 return std::nullopt;
3225 return m_num_to_open;
3231 m_num_to_open.notify_all();
3246 m_num_to_open.wait(0);
3251 if (m_outbound_tor_ok_at_least_once.load()) {
3256 return std::nullopt;
3278 if (
pnode->fDisconnect)
3368 std::optional<Proxy> proxy;
3370 if (!
net.has_value()) {
3371 LogWarning(
"Unable to open -privatebroadcast connections: neither Tor nor I2P is reachable");
3376 const auto [addr,
_] =
addrman.get().Select(
false, {
net.value()});
3378 if (!addr.IsValid() ||
IsLocal(addr)) {
3389 if (proxy.has_value()) {
3390 target_str +=
" through the proxy at " + proxy->ToString();
3562 return nLastNodeId.fetch_add(1, std::memory_order_relaxed);
3597 for (
const auto& addrBind : options.
vBinds) {
3602 for (
const auto& addrBind : options.
vWhiteBinds) {
3637 _(
"Failed to listen on any port. Use -listen=0 if you want this."),
3664 LogInfo(
"%i block-relay-only anchors will be tried for connections.\n",
m_anchors.size());
3699 LogInfo(
"DNS seeding disabled\n");
3709 _(
"Cannot provide specific connections and have addrman find outgoing connections at the same time."),
3768 (*m_interrupt_net)();
3834 std::vector<CNode*>
nodes;
3838 pnode->CloseSocketDisconnect();
3930 if (
node == it->m_added_node) {
3946 [&](
const auto&
p) { return p.m_added_node == addr_str || p.m_added_node == addr_port_str; }));
3998 node->fDisconnect =
true;
4007 bool disconnected =
false;
4012 pnode->fDisconnect =
true;
4013 disconnected =
true;
4016 return disconnected;
4029 if (
id ==
pnode->GetId()) {
4031 pnode->fDisconnect =
true;
4145 if (use_v2transport) {
4153 std::shared_ptr<Sock> sock,
4164 m_permission_flags{
node_opts.permission_flags},
4179 m_recv_flood_size{
node_opts.recv_flood_size},
4180 m_i2p_sam_session{
std::move(
node_opts.i2p_sam_session)}
4185 mapRecvBytesPerMsgType[msg] = 0;
4218 std::list<CNetMessage> msgs;
4259 size_t nMessageSize = msg.data.size();
4267 pnode->m_addr_name.c_str(),
4268 pnode->ConnectionTypeAsString().c_str(),
4280 pnode->m_transport->GetBytesToSend(
true);
4284 pnode->m_send_memusage += msg.GetMemoryUsage();
4287 pnode->fPauseSend =
true;
4290 pnode->vSendMsg.push_back(std::move(msg));
4310 CNode* found =
nullptr;
4313 if(
pnode->GetId() == id) {
4354 std::move(
item.grant),
4355 item.destination.empty() ?
nullptr :
item.destination.c_str(),
4357 item.use_v2transport,
4358 item.proxy_override);
4369 [](
const CAddress& addr) { return static_cast<CNetAddr>(addr); });
4371 [](
const CAddress& addr) { return static_cast<CNetAddr>(addr); });
4378 std::span<const unsigned char>
data,
4406 if (
f.fclose() != 0) {
4407 throw std::ios_base::failure(
4414 std::span<const unsigned char>
data,
bool DumpPeerAddresses(const ArgsManager &args, const AddrMan &addr)
std::vector< CAddress > ReadAnchors(const fs::path &anchors_db_path)
Read the anchor IP address database (anchors.dat)
void DumpAnchors(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.
#define Assume(val)
Assume is the identity function.
Stochastic address manager.
std::vector< std::string > GetArgs(const std::string &strArg) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Return a vector of strings of the given argument.
fs::path GetDataDirNet() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Get data directory path with appended network identifier.
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
bool GetBoolArg(const std::string &strArg, bool fDefault) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Return boolean argument or default value.
Non-refcounted RAII wrapper for FILE*.
bool Decrypt(std::span< const std::byte > input, std::span< const std::byte > aad, bool &ignore, std::span< std::byte > contents) noexcept
Decrypt a packet.
std::span< const std::byte > GetSendGarbageTerminator() const noexcept
Get the Garbage Terminator to send.
static constexpr unsigned GARBAGE_TERMINATOR_LEN
unsigned DecryptLength(std::span< const std::byte > input) noexcept
Decrypt the length of a packet.
std::span< const std::byte > GetSessionID() const noexcept
Get the Session ID.
const EllSwiftPubKey & GetOurPubKey() const noexcept
Retrieve our public key.
std::span< const std::byte > GetReceiveGarbageTerminator() const noexcept
Get the expected Garbage Terminator to receive.
static constexpr unsigned LENGTH_LEN
static constexpr unsigned EXPANSION
void Initialize(const EllSwiftPubKey &their_pubkey, bool initiator, bool self_decrypt=false) noexcept
Initialize when the other side's public key is received.
void Encrypt(std::span< const std::byte > contents, std::span< const std::byte > aad, bool ignore, std::span< std::byte > output) noexcept
Encrypt a packet.
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. The behavior is unspecified if the value is not representable as ui...
static constexpr SerParams V2_NETWORK
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
const MessageStartChars & MessageStart() const
uint16_t GetDefaultPort() const
const std::vector< std::string > & DNSSeeds() const
Return the list of hostnames to look up for DNS seeds.
const std::vector< uint8_t > & FixedSeeds() const
RAII helper to atomically create a copy of m_nodes and add a reference to each of the nodes.
std::atomic_bool m_outbound_tor_ok_at_least_once
Remember if we ever established at least one outbound connection to a Tor peer, including sending and...
void NumToOpenAdd(size_t n)
Increment the number of new connections of type ConnectionType::PRIVATE_BROADCAST to be opened by CCo...
std::optional< Proxy > ProxyForIPv4or6() const
Check if private broadcast can be done to IPv4 or IPv6 peers and if so via which proxy.
size_t NumToOpenSub(size_t n)
Decrement the number of new connections of type ConnectionType::PRIVATE_BROADCAST to be opened by CCo...
void NumToOpenWait() const
Wait for the number of needed connections to become greater than 0.
size_t NumToOpen() const
Get the pending number of connections to open.
std::optional< Network > PickNetwork(std::optional< Proxy > &proxy) const
Choose a network to open a connection to.
std::counting_semaphore m_sem_conn_max
Semaphore used to guard against opening too many connections.
void AcceptConnection(const ListenSocket &hListenSocket) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
std::unordered_set< Network > GetReachableEmptyNetworks() const
Return reachable networks for which we have no addresses in addrman and therefore may require loading...
std::condition_variable condMsgProc
std::thread threadMessageHandler
void PerformReconnections() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex
Attempt reconnections, if m_reconnections non-empty.
bool MaybePickPreferredNetwork(std::optional< Network > &network) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Search for a "preferred" network, a reachable network to which we currently don't have any OUTBOUND_F...
std::reference_wrapper< AddrMan > addrman
void StopNodes() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex
void DisconnectNodes() EXCLUSIVE_LOCKS_REQUIRED(!m_reconnections_mutex
m_max_outbound_full_relay
void DeleteNode(CNode *pnode)
void ThreadI2PAcceptIncoming() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
void Stop() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex
static constexpr size_t MAX_UNUSED_I2P_SESSIONS_SIZE
Cap on the size of m_unused_i2p_sessions, to ensure it does not unexpectedly use too much memory.
bool GetTryNewOutboundPeer() const
const bool use_v2transport(GetLocalServices() &NODE_P2P_V2)
class CConnman::PrivateBroadcast m_private_broadcast
uint16_t GetDefaultPort(Network net) const
bool AlreadyConnectedToAddress(const CNetAddr &addr) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Determine whether we're already connected to a given address.
bool ShouldRunInactivityChecks(const CNode &node, NodeClock::time_point now) const
Return true if we should disconnect the peer for failing an inactivity check.
std::thread threadI2PAcceptIncoming
std::vector< CAddress > GetAddresses(CNode &requestor, size_t max_addresses, size_t max_pct)
Return addresses from the per-requestor cache.
void SetTryNewOutboundPeer(bool flag)
std::atomic< bool > flagInterruptMsgProc
void Interrupt() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
std::map< CNetAddr, LocalServiceInfo > getNetLocalAddresses() const
void ThreadDNSAddressSeed() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
std::vector< CAddress > GetCurrentBlockRelayOnlyConns() const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Return vector of current BLOCK_RELAY peers.
bool AlreadyConnectedToAddressPort(const CService &addr_port) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Determine whether we're already connected to a given address:port.
std::atomic< NodeId > nLastNodeId
bool AlreadyConnectedToHost(std::string_view host) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Determine whether we're already connected to a given "host:port".
void WakeMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc)
bool OutboundTargetReached(bool historicalBlockServingLimit) const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
check if the outbound target is reached if param historicalBlockServingLimit is set true,...
void SocketHandlerListening(const Sock::EventsPerSock &events_per_sock) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Accept incoming connections, one from each read-ready listening socket.
uint64_t GetMaxOutboundTarget() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
std::thread threadDNSAddressSeed
bool AddConnection(const std::string &address, ConnectionType conn_type, bool use_v2transport) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex
Attempts to open a connection.
void SocketHandlerConnected(const std::vector< CNode * > &nodes, const Sock::EventsPerSock &events_per_sock) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex
Do the read/write for connected sockets that are ready for IO.
void StartExtraBlockRelayPeers()
const NetGroupManager & m_netgroupman
std::chrono::seconds GetMaxOutboundTimeframe() const
uint64_t CalculateKeyedNetGroup(const CNetAddr &ad) const
unsigned int nPrevNodeCount
void AddWhitelistPermissionFlags(NetPermissionFlags &flags, std::optional< CNetAddr > addr, const std::vector< NetWhitelistPermissions > &ranges) const
ServiceFlags GetLocalServices() const
Used to convey which local services we are offering peers during node connection.
bool AddNode(const AddedNodeParams &add) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
std::vector< AddedNodeInfo > GetAddedNodeInfo(bool include_connected) const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex
CNode * ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, ConnectionType conn_type, bool use_v2transport, const std::optional< Proxy > &proxy_override) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex
Open a new P2P connection.
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 This t...
bool InitBinds(const Options &options)
vWhitelistedRangeOutgoing
void AddAddrFetch(const std::string &strDest) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex)
std::vector< ListenSocket > vhListenSocket
CSipHasher GetDeterministicRandomizer(uint64_t id) const
Get a unique deterministic randomizer.
Mutex m_total_bytes_sent_mutex
void ThreadOpenAddedConnections() EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex
bool Bind(const CService &addr, unsigned int flags, NetPermissionFlags permissions)
void SetNetworkActive(bool active) EXCLUSIVE_LOCKS_REQUIRED(!m_anchors_mutex
bool EvictTxPeerIfFull(std::optional< NodeId > protect_peer=std::nullopt) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
If we are at capacity for inbound tx-relay peers, attempt to evict one.
std::thread threadOpenConnections
void ThreadPrivateBroadcast() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex
uint32_t GetMappedAS(const CNetAddr &addr) const
void ProcessAddrFetch() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex
Mutex m_addr_fetches_mutex
Mutex m_reconnections_mutex
Mutex protecting m_reconnections.
bool Start(CScheduler &scheduler, const Options &options) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex
const uint64_t nSeed0
SipHasher seeds for deterministic randomness.
std::chrono::seconds GetMaxOutboundTimeLeftInCycle_() const EXCLUSIVE_LOCKS_REQUIRED(m_total_bytes_sent_mutex)
returns the time left in the current max outbound cycle in case of no limit, it will always return 0
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.
bool OpenNetworkConnection(const CAddress &addrConnect, bool fCountFailure, CountingSemaphoreGrant<> &&grant_outbound, const char *pszDest, ConnectionType conn_type, bool use_v2transport, const std::optional< Proxy > &proxy_override) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex
Open a new P2P connection and initialize it with the PeerManager at m_msgproc.
m_max_outbound_block_relay
static bool NodeFullyConnected(const CNode *pnode)
std::unique_ptr< std::counting_semaphore<> > semOutbound
const CChainParams & m_params
bool MultipleManualOrFullOutboundConns(Network net) const EXCLUSIVE_LOCKS_REQUIRED(m_nodes_mutex)
bool AddedNodesContain(const CAddress &addr) const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
bool InactivityCheck(const CNode &node, NodeClock::time_point now) const
Return true if the peer is inactive and should be disconnected.
std::chrono::seconds GetMaxOutboundTimeLeftInCycle() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
const std::shared_ptr< CThreadInterrupt > m_interrupt_net
This is signaled when network activity should cease.
void CreateNodeFromAcceptedSocket(std::unique_ptr< Sock > &&sock, NetPermissionFlags permission_flags, const CService &addr_bind, const CService &addr) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Create a CNode object from a socket that has just been accepted and add the node to the m_nodes membe...
void ThreadOpenConnections(std::vector< std::string > connect, std::span< const std::string > seed_nodes) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex
bool AttemptToEvictConnection(bool evict_tx_relay_peer_only, std::optional< NodeId > protect_peer=std::nullopt) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Try to find an inbound connection to evict.
void GetNodeStats(std::vector< CNodeStats > &vstats) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
m_max_automatic_connections
std::thread threadPrivateBroadcast
bool RemoveAddedNode(std::string_view node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex)
bool fAddressesInitialized
std::vector< CAddress > GetAddressesUnsafe(size_t max_addresses, size_t max_pct, std::optional< Network > network, bool filtered=true) const
Return randomly selected addresses.
void NotifyNumConnectionsChanged() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
int GetExtraBlockRelayCount() const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
std::thread threadOpenAddedConnections
bool DisconnectNode(std::string_view node) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Mutex m_added_nodes_mutex
vWhitelistedRangeIncoming
void ThreadSocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex
void RecordBytesSent(uint64_t bytes) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
void ThreadMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex
Mutex m_unused_i2p_sessions_mutex
Mutex protecting m_i2p_sam_sessions.
uint64_t GetTotalBytesSent() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
std::unique_ptr< std::counting_semaphore<> > semAddnode
Mutex m_anchors_mutex
Addresses that were saved during the previous clean shutdown or when the network was deactivated.
size_t GetNodeCount(ConnectionDirection) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
void RecordBytesRecv(uint64_t bytes)
int GetExtraFullOutboundCount() const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
uint64_t GetOutboundTargetBytesLeft() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
response the bytes left in the current max outbound cycle in case of no limit, it will always respons...
void SocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex
Check connected and listening sockets for IO readiness and process them accordingly.
void PushMessage(CNode *pnode, CSerializedNetMsg &&msg) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex)
std::list< CNode * > m_nodes_disconnected
std::unique_ptr< i2p::sam::Session > m_i2p_sam_session
I2P SAM session.
std::map< uint64_t, CachedAddrResponse > m_addr_response_caches
Addr responses stored in different caches per (network, local socket) prevent cross-network node iden...
bool CheckIncomingNonce(uint64_t nonce) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
Sock::EventsPerSock GenerateWaitSockets(std::span< CNode *const > nodes)
Generate a collection of sockets to check for IO readiness.
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.
CConnman(uint64_t seed0, uint64_t seed1, AddrMan &addrman, const NetGroupManager &netgroupman, const CChainParams ¶ms, bool network_active=true, std::shared_ptr< CThreadInterrupt > interrupt_net=std::make_shared< CThreadInterrupt >())
std::thread threadSocketHandler
int GetFullOutboundConnCount() const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)
bool BindListenPort(const CService &bindAddr, bilingual_str &strError, NetPermissionFlags permissions)
An encapsulated private key.
Network GetNetClass() const
std::string ToStringAddr() const
bool IsPrivacyNet() const
Whether this object is a privacy network.
bool SetSpecial(std::string_view addr)
Parse a Tor or I2P address and set this object to it.
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.
size_t GetMemoryUsage() const noexcept
Compute total memory usage of this object (own memory + any dynamic memory).
DataStream m_recv
received message data time of message receipt
Information about a peer.
std::atomic< int > nVersion
bool IsInboundConn() const
std::atomic_bool fPauseRecv
std::string LogPeer() const
Helper function to log the peer id, optionally including IP address.
std::atomic< NodeClock::duration > m_last_ping_time
Last measured round-trip duration. Used only for stats.
const std::string m_addr_name
bool IsConnectedThroughPrivacyNet() const
Whether this peer connected through a privacy network.
void CopyStats(CNodeStats &stats) EXCLUSIVE_LOCKS_REQUIRED(!m_subver_mutex
std::string ConnectionTypeAsString() const
std::atomic< bool > m_bip152_highbandwidth_to
std::list< CNetMessage > vRecvMsg
std::atomic< bool > m_bip152_highbandwidth_from
bool ReceiveMsgBytes(std::span< const uint8_t > msg_bytes, bool &complete) EXCLUSIVE_LOCKS_REQUIRED(!cs_vRecv)
Receive bytes from the buffer and deserialize them into messages.
void SetAddrLocal(const CService &addrLocalIn) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_local_mutex)
May not be called more than once.
const NodeClock::time_point m_connected
Unix epoch time at peer connection.
std::atomic< NodeClock::time_point > m_last_recv
CNode(NodeId id, std::shared_ptr< Sock > sock, const CAddress &addrIn, uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn, const CService &addrBindIn, const std::string &addrNameIn, ConnectionType conn_type_in, bool inbound_onion, uint64_t network_key, CNodeOptions &&node_opts={})
void MarkReceivedMsgsForProcessing() EXCLUSIVE_LOCKS_REQUIRED(!m_msg_process_queue_mutex)
Move all messages from the received queue to the processing queue.
std::string DisconnectMsg() const
Helper function to log disconnects.
std::atomic< NodeClock::duration > m_min_ping_time
Lowest measured round-trip duration.
std::optional< std::pair< CNetMessage, bool > > PollMessage() EXCLUSIVE_LOCKS_REQUIRED(!m_msg_process_queue_mutex)
Poll the next message from the processing queue of this connection.
const util::NotNullUniquePtr< Transport > m_transport
Transport serializer/deserializer.
Mutex m_msg_process_queue_mutex
std::atomic< NodeClock::time_point > m_last_send
const ConnectionType m_conn_type
Network ConnectedThroughNetwork() const
Get network the peer connected through.
const size_t m_recv_flood_size
const NetPermissionFlags m_permission_flags
const bool m_inbound_onion
Whether this peer is an inbound onion, i.e. connected via our Tor onion service.
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_bool fDisconnect
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 CloseSocketDisconnect() EXCLUSIVE_LOCKS_REQUIRED(!m_sock_mutex)
std::string m_session_id
BIP324 session id string in hex, if any.
TransportProtocolType m_transport_type
Transport protocol type.
Simple class for background tasks that should be run periodically or once "after a while".
void scheduleEvery(Function f, std::chrono::milliseconds delta) EXCLUSIVE_LOCKS_REQUIRED(!newTaskMutex)
Repeat f until the scheduler is stopped.
A combination of a network address (CNetAddr) and a (TCP) port.
bool SetSockAddr(const struct sockaddr *paddr, socklen_t addrlen)
Set CService from a network sockaddr.
sa_family_t GetSAFamily() const
Get the address family.
bool GetSockAddr(struct sockaddr *paddr, socklen_t *addrlen) const
Obtain the IPv4/6 socket address this represents.
std::string ToStringAddrPort() const
General SipHash-2-4 implementation.
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
std::chrono::steady_clock Clock
RAII-style semaphore lock.
Double ended buffer combining vector and stream-like interfaces.
size_t GetMemoryUsage() const noexcept
Compute total memory usage of this object (own memory + any dynamic memory).
void fillrand(std::span< std::byte > output) noexcept
Fill a byte span with random bytes.
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.
bool UsingASMap() const
Indicates whether ASMap is being used for clearnet bucketing.
void ASMapHealthCheck(const std::vector< CNetAddr > &clearnet_addrs) const
Analyze and log current health of ASMap based buckets.
std::vector< unsigned char > GetGroup(const CNetAddr &address) const
Get the canonical identifier of the network group for address.
uint32_t GetMappedAS(const CNetAddr &address) const
Get the autonomous system on the BGP path to address.
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)
Wrapper that overrides the GetParams() function of a stream.
Tp rand_uniform_delay(const Tp &time, typename Tp::duration range) noexcept
Return the time point advanced by a uniform random duration.
Chrono::duration rand_uniform_duration(typename Chrono::duration range) noexcept
Generate a uniform random duration in the range from 0 (inclusive) to range (exclusive).
I randrange(I range) noexcept
Generate a random integer in the range [0..range), with range > 0.
std::chrono::microseconds rand_exp_duration(std::chrono::microseconds mean) noexcept
Return a duration sampled from an exponential distribution (https://en.wikipedia.org/wiki/Exponential...
uint64_t randbits(int bits) noexcept
Generate a random (bits)-bit integer.
std::unordered_set< Network > All() const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
bool Contains(Network net) const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
static constexpr Event RecvEvent
If passed to Wait(), then it will wait for readiness to read from the socket.
static constexpr Event SendEvent
If passed to Wait(), then it will wait for readiness to send to the socket.
static constexpr Event ErrorEvent
Ignored if passed to Wait(), but could be set in the occurred events if an exceptional condition has ...
std::unordered_map< std::shared_ptr< const Sock >, Events, HashSharedPtrSock, EqualSharedPtrSock > EventsPerSock
On which socket to wait for what events in WaitMany().
Minimal stream for reading from an existing byte array by std::span.
std::tuple< std::span< const uint8_t >, bool, const std::string & > BytesToSend
Return type for GetBytesToSend, consisting of:
CNetMessage GetReceivedMessage(NodeClock::time_point time, bool &reject_message) override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
Retrieve a completed message from transport.
bool SetMessageToSend(CSerializedNetMsg &msg) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex)
Set the next message to send.
Info GetInfo() const noexcept override
Retrieve information about this transport.
int readData(std::span< const uint8_t > msg_bytes) EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
Mutex m_send_mutex
Lock for sending state.
const MessageStartChars m_magic_bytes
size_t GetSendMemoryUsage() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex)
Return the memory usage of this transport attributable to buffered data to send.
const uint256 & GetMessageHash() const EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
void MarkBytesSent(size_t bytes_sent) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex)
Report how many bytes returned by the last GetBytesToSend() have been sent.
int readHeader(std::span< const uint8_t > msg_bytes) EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
bool CompleteInternal() const noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
bool ReceivedBytes(std::span< const uint8_t > &msg_bytes) override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
Feed wire bytes to the transport.
V1Transport(NodeId node_id) noexcept
BytesToSend GetBytesToSend(bool have_next_message) const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex)
Get bytes to send on the wire, if any, along with other information about it.
void Reset() EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
Mutex m_recv_mutex
Lock for receive state.
bool ReceivedMessageComplete() const override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
Returns true if the current message is complete (so GetReceivedMessage can be called).
void MarkBytesSent(size_t bytes_sent) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex)
Report how many bytes returned by the last GetBytesToSend() have been sent.
static constexpr uint32_t MAX_GARBAGE_LEN
const NodeId m_nodeid
NodeId (for debug logging).
size_t GetMaxBytesToProcess() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
Determine how many received bytes can be processed in one go (not allowed in V1 state).
BIP324Cipher m_cipher
Cipher state.
size_t GetSendMemoryUsage() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex)
Return the memory usage of this transport attributable to buffered data to send.
void ProcessReceivedMaybeV1Bytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex
Process bytes in m_recv_buffer, while in KEY_MAYBE_V1 state.
SendState
State type that controls the sender side.
@ READY
Normal sending state.
@ AWAITING_KEY
Waiting for the other side's public key.
@ V1
This transport is using v1 fallback.
V1Transport m_v1_fallback
Encapsulate a V1Transport to fall back to.
static constexpr size_t V1_PREFIX_LEN
The length of the V1 prefix to match bytes initially received by responders with to determine if thei...
void StartSendingHandshake() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_send_mutex)
Put our public key + garbage in the send buffer.
bool ProcessReceivedPacketBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
Process bytes in m_recv_buffer, while in VERSION/APP state.
CNetMessage GetReceivedMessage(NodeClock::time_point time, bool &reject_message) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
Retrieve a completed message from transport.
bool ProcessReceivedKeyBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex
Process bytes in m_recv_buffer, while in KEY state.
const bool m_initiating
Whether we are the initiator side.
Info GetInfo() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
Retrieve information about this transport.
BytesToSend GetBytesToSend(bool have_next_message) const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex)
Get bytes to send on the wire, if any, along with other information about it.
void SetReceiveState(RecvState recv_state) noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
Change the receive state.
bool ProcessReceivedGarbageBytes() noexcept EXCLUSIVE_LOCKS_REQUIRED(m_recv_mutex)
Process bytes in m_recv_buffer, while in GARB_GARBTERM state.
bool ReceivedMessageComplete() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex)
Returns true if the current message is complete (so GetReceivedMessage can be called).
static constexpr std::array< std::byte, 0 > VERSION_CONTENTS
Contents of the version packet to send.
static std::optional< std::string > GetMessageType(std::span< const uint8_t > &contents) noexcept
Given a packet's contents, find the message type (if valid), and strip it from contents.
bool ReceivedBytes(std::span< const uint8_t > &msg_bytes) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex
Feed wire bytes to the transport.
bool ShouldReconnectV1() const noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_recv_mutex
Whether upon disconnections, a reconnect with V1 is warranted.
bool SetMessageToSend(CSerializedNetMsg &msg) noexcept override EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex)
Set the next message to send.
V2Transport(NodeId nodeid, bool initiating) noexcept
Construct a V2 transport with securely generated random keys.
RecvState
State type that defines the current contents of the receive buffer and/or how the next received bytes...
@ GARB_GARBTERM
Garbage and garbage terminator.
@ V1
Nothing (this transport is using v1 fallback).
@ KEY_MAYBE_V1
(Responder only) either v2 public key or v1 header.
@ APP_READY
Nothing (an application packet is available for GetMessage()).
void SetSendState(SendState send_state) noexcept EXCLUSIVE_LOCKS_REQUIRED(m_send_mutex)
Change the send state.
constexpr unsigned char * begin()
Implements a drop-in replacement for std::vector<T> which stores up to N elements directly (without h...
void push_back(const T &value)
NotNull is intended to be used to denote that a smart pointer type can not hold a nullptr value.
static const PrecomputedData data
Precomputed COutPoint and CCoins values.
#define WSAGetLastError()
#define COMPAT_IN6ADDR_ANY_INIT
std::string ConnectionTypeAsString(ConnectionType conn_type)
Convert ConnectionType enum to a string value.
ConnectionType
Different types of connections to a peer.
@ PRIVATE_BROADCAST
Private broadcast connections are short-lived and only opened to privacy networks (Tor,...
@ BLOCK_RELAY
We use block-relay-only connections to help prevent against partition attacks.
@ MANUAL
We open manual connections to addresses that users explicitly requested via the addnode RPC or the -a...
@ 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.
@ ADDR_FETCH
AddrFetch connections are short lived connections used to solicit addresses from peers.
@ V1
Unencrypted, plaintext protocol.
@ DETECTING
Peer could be v1 or v2.
constexpr unsigned int MAX_BLOCK_SERIALIZED_SIZE
The maximum allowed size for a serialized block, in bytes (only for buffer size limits)
uint32_t ReadLE32(const B *ptr)
static CService ip(uint32_t i)
std::optional< NodeId > SelectNodeToEvict(std::vector< NodeEvictionCandidate > &&vEvictionCandidates)
Select an inbound peer to evict after filtering out (protecting) peers having distinct,...
static path u8path(std::string_view utf8_str)
static std::string PathToString(const path &path)
Convert path object to a byte string.
uint256 Hash(const T &in1)
Compute the 256-bit hash of an object.
std::string HexStr(const std::span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
CKey GenerateRandomKey(bool compressed) noexcept
#define LogDebug(category,...)
constexpr const char * FILTERCLEAR
The filterclear message tells the receiving peer to remove a previously-set bloom filter.
constexpr const char * FEEFILTER
The feefilter message tells the receiving peer not to inv us any txs which do not meet the specified ...
constexpr const char * GETBLOCKS
The getblocks message requests an inv message that provides block header hashes starting from a parti...
constexpr const char * HEADERS
The headers message sends one or more block headers to a node which previously requested certain head...
constexpr const char * ADDR
The addr (IP address) message relays connection information for peers on the network.
constexpr const char * GETBLOCKTXN
Contains a BlockTransactionsRequest Peer should respond with "blocktxn" message.
constexpr const char * CMPCTBLOCK
Contains a CBlockHeaderAndShortTxIDs object - providing a header and list of "short txids".
constexpr const char * CFCHECKPT
cfcheckpt is a response to a getcfcheckpt request containing a vector of evenly spaced filter headers...
constexpr const char * GETCFILTERS
getcfilters requests compact filters for a range of blocks.
constexpr const char * PONG
The pong message replies to a ping message, proving to the pinging node that the ponging node is stil...
constexpr const char * BLOCKTXN
Contains a BlockTransactions.
constexpr const char * CFHEADERS
cfheaders is a response to a getcfheaders request containing a filter header and a vector of filter h...
constexpr const char * PING
The ping message is sent periodically to help confirm that the receiving peer is still connected.
constexpr const char * FILTERLOAD
The filterload message tells the receiving peer to filter all relayed transactions and requested merk...
constexpr const char * ADDRV2
The addrv2 message relays connection information for peers on the network just like the addr message,...
constexpr const char * VERACK
The verack message acknowledges a previously-received version message, informing the connecting node ...
constexpr const char * GETHEADERS
The getheaders message requests a headers message that provides block headers starting from a particu...
constexpr const char * FILTERADD
The filteradd message tells the receiving peer to add a single element to a previously-set bloom filt...
constexpr const char * CFILTER
cfilter is a response to a getcfilters request containing a single compact filter.
constexpr const char * FEATURE
BIP 434 Peer feature negotiation.
constexpr const char * GETDATA
The getdata message requests one or more data objects from another node.
constexpr const char * SENDCMPCT
Contains a 1-byte bool and 8-byte LE version number.
constexpr const char * GETCFCHECKPT
getcfcheckpt requests evenly spaced compact filter headers, enabling parallelized download and valida...
constexpr const char * INV
The inv message (inventory message) transmits one or more inventories of objects known to the transmi...
constexpr const char * TX
The tx message transmits a single transaction.
constexpr const char * MEMPOOL
The mempool message requests the TXIDs of transactions that the receiving node has verified as valid ...
constexpr const char * NOTFOUND
The notfound message is a reply to a getdata message which requested an object the receiving node doe...
constexpr const char * MERKLEBLOCK
The merkleblock message is a reply to a getdata message which requested a block using the inventory t...
constexpr const char * BLOCK
The block message transmits a single serialized block.
constexpr const char * GETCFHEADERS
getcfheaders requests a compact filter header and the filter hashes for a range of blocks,...
constexpr const char * VERSION
The version message provides information about the transmitting node to the receiving node at the beg...
FILE * fopen(const fs::path &p, const char *mode)
static size_t DynamicUsage(const int8_t &v)
Dynamic memory usage for built-in types is zero.
void TraceThread(std::string_view thread_name, std::function< void()> thread_func)
A wrapper for do-something-once thread functions.
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
static const uint64_t SELECT_TIMEOUT_MILLISECONDS
static util::NotNullUniquePtr< Transport > MakeTransport(NodeId id, bool use_v2transport, bool inbound) noexcept
static const uint64_t RANDOMIZER_ID_NETWORKKEY
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 auto EXTRA_NETWORK_PEER_INTERVAL
Frequency to attempt extra connections to reachable networks we're not connected to yet.
static constexpr int SEED_OUTBOUND_CONNECTION_THRESHOLD
Minimum number of outbound connections under which we will keep fetching our address seeds.
static constexpr auto FEELER_SLEEP_WINDOW
static constexpr int DNSSEEDS_DELAY_PEER_THRESHOLD
static constexpr size_t MAX_BLOCK_RELAY_ONLY_ANCHORS
Maximum number of block-relay-only anchor connections.
static bool IsPeerAddrLocalGood(CNode *pnode)
static constexpr std::chrono::seconds DNSSEEDS_DELAY_FEW_PEERS
How long to delay before querying DNS seeds.
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
std::optional< CService > GetLocalAddrForPeer(CNode &node)
Returns a local address that we should advertise to this peer.
const std::string NET_MESSAGE_TYPE_OTHER
const char *const ANCHORS_DATABASE_FILENAME
Anchor IP address database file name.
static std::vector< CAddress > ConvertSeeds(const std::vector< uint8_t > &vSeedsIn)
Convert the serialized seeds into usable address objects.
static void CaptureMessageToFile(const CAddress &addr, const std::string &msg_type, std::span< const unsigned char > data, bool is_incoming)
CService GetLocalAddress(const CNode &peer)
GlobalMutex g_maplocalhost_mutex
static std::optional< CService > GetLocal(const CNode &peer)
std::function< void(const CAddress &addr, const std::string &msg_type, std::span< const unsigned char > data, bool is_incoming)> CaptureMessage
Defaults to CaptureMessageToFile(), but can be overridden by unit tests.
static constexpr std::chrono::minutes DNSSEEDS_DELAY_MANY_PEERS
bool AddLocal(const CService &addr_, int nScore, bool add_even_if_unreachable)
static int GetnScore(const CService &addr)
static bool IsOutboundMessageAllowedInPrivateBroadcast(std::string_view type) noexcept
Private broadcast connections only need to send certain message types.
static CNetCleanup instance_of_cnetcleanup
static constexpr std::chrono::seconds MAX_UPLOAD_TIMEFRAME
The default timeframe for -maxuploadtarget.
bool SeenLocal(const CService &addr)
vote for a local address
constexpr bool DEFAULT_PRIVATE_BROADCAST
Default for -privatebroadcast.
bool IsLocal(const CService &addr)
check whether a given address is potentially local
void RemoveLocal(const CService &addr)
constexpr std::chrono::minutes TIMEOUT_INTERVAL
Time after which to disconnect, after waiting for a ping response (or inactivity).
constexpr bool DEFAULT_FIXEDSEEDS
constexpr unsigned int MAX_PROTOCOL_MESSAGE_LENGTH
Maximum length of incoming protocol messages (no message over 4 MB is currently acceptable).
constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL
Run the extra block-relay-only connection loop once every 5 minutes.
const std::string NET_MESSAGE_TYPE_OTHER
constexpr bool DEFAULT_FORCEDNSSEED
constexpr bool DEFAULT_DNSSEED
constexpr int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
GlobalMutex g_maplocalhost_mutex
constexpr std::chrono::hours ASMAP_HEALTH_CHECK_INTERVAL
Interval for ASMap Health Check.
bool AddLocal(const CService &addr, int nScore=LOCAL_NONE, bool add_even_if_unreachable=false)
constexpr auto FEELER_INTERVAL
Run the feeler connection loop once every 2 minutes.
std::function< void(const CAddress &addr, const std::string &msg_type, std::span< const unsigned char > data, bool is_incoming)> CaptureMessage
Defaults to CaptureMessageToFile(), but can be overridden by unit tests.
constexpr int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS
Maximum number of automatic outgoing nodes over which we'll relay everything (blocks,...
void Discover()
Look up IP addresses from all interfaces on the machine and add them to the list of local addresses t...
int64_t NodeId
Identifier of a peer connection.
constexpr uint16_t I2P_SAM31_PORT
SAM 3.1 and earlier do not support specifying ports and force the port to 0.
@ 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.
std::optional< Proxy > GetNameProxy()
std::unique_ptr< Sock > ConnectDirectly(const CService &dest, bool manual_connection)
Create a socket and try to connect to the specified service.
std::vector< CNetAddr > LookupHost(const std::string &name, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function)
Resolve a host string to its corresponding network addresses.
std::string GetNetworkName(enum Network net)
CThreadInterrupt g_socks5_interrupt
Interrupt SOCKS5 reads or writes.
CService GetBindAddress(const Sock &sock)
Get the bind address for a socket as CService.
std::vector< CService > Lookup(const std::string &name, uint16_t portDefault, bool fAllowLookup, unsigned int nMaxSolutions, DNSLookupFn dns_lookup_function)
Resolve a service string to its corresponding service.
CService MaybeFlipIPv6toCJDNS(const CService &service)
If an IPv6 address belongs to the address range used by the CJDNS network and the CJDNS network is re...
ReachableNets g_reachable_nets
std::unique_ptr< Sock > ConnectThroughProxy(const Proxy &proxy, const std::string &dest, uint16_t port, bool &proxy_connection_failed)
Connect to a specified destination service through a SOCKS5 proxy by first connecting to the SOCKS5 p...
std::function< std::unique_ptr< Sock >(int, int, int)> CreateSock
Socket factory.
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.
std::optional< Proxy > GetProxy(enum Network net)
std::vector< CNetAddr > GetLocalAddresses()
Return all local non-loopback IPv4 and IPv6 network addresses.
T SaturatingAdd(const T i, const T j) noexcept
const std::array ALL_NET_MESSAGE_TYPES
All known message types (see above).
constexpr ServiceFlags SeedsServiceFlags()
State independent service flags.
ServiceFlags
nServices flags
constexpr ServiceFlags SeedsAssumedServiceFlags()
Service flags we assume for addresses obtained from the DNS seeds and the fixed seeds,...
static bool MayHaveUsefulAddressDB(ServiceFlags services)
Checks if a peer with the given service flags may be capable of having a robust address-storage DB.
void RandAddEvent(const uint32_t event_info) noexcept
Gathers entropy from the low bits of the time at which events occur.
uint256 GetRandHash() noexcept
Generate a random uint256.
void ser_writedata32(Stream &s, uint32_t obj)
constexpr uint64_t MAX_SIZE
The maximum size of a serialized object in bytes or number of elements (for eg vectors) when the size...
void ser_writedata64(Stream &s, uint64_t obj)
std::string NetworkErrorString(int err)
Return readable error string for a network error code.
auto MakeByteSpan(const V &v) noexcept
constexpr auto MakeUCharSpan(const V &v) -> decltype(UCharSpanCast(std::span{v}))
Like the std::span constructor, but for (const) unsigned char member types only.
T & SpanPopBack(std::span< T > &span)
A span is an object that can refer to a contiguous sequence of objects.
auto MakeWritableByteSpan(V &&v) noexcept
unsigned char * UCharCast(char *c)
Utilities for converting data from/to strings.
Cache responses to addr requests to minimize privacy leak.
std::vector< CAddress > m_addrs_response_cache
std::vector< NetWhitebindPermissions > vWhiteBinds
std::vector< CService > onion_binds
std::vector< CService > vBinds
bool bind_on_any
True if the user did not specify -bind= or -whitebind= and thus we should bind on 0....
NetPermissionFlags permission_flags
std::vector< unsigned char > data
size_t GetMemoryUsage() const noexcept
Compute total memory usage of this object (own memory + any dynamic memory).
An ElligatorSwift-encoded public key.
static constexpr size_t size()
Version of the system clock that is mockable in the context of tests (via FakeNodeClock or SetMockTim...
static time_point now() noexcept
Return current system time or mocked time, if set.
std::chrono::time_point< NodeClock > time_point
static constexpr time_point epoch
Auxiliary requested/occurred events to wait for in WaitMany().
std::optional< uint256 > session_id
TransportProtocolType transport_type
An established connection with another peer.
#define WAIT_LOCK(cs, name)
#define AssertLockNotHeld(cs)
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
#define AssertLockHeld(cs)
#define EXCLUSIVE_LOCKS_REQUIRED(...)
#define TRACEPOINT(context,...)
#define TRACEPOINT_SEMAPHORE(context, event)
consteval auto _(util::TranslatedLiteral str)
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
bool SplitHostPort(std::string_view in, uint16_t &portOut, std::string &hostOut)
Splits socket address string into host string and port value.
std::string SanitizeString(std::string_view str, int rule)
Remove unsafe chars.
constexpr int64_t count_seconds(std::chrono::seconds t)
std::chrono::time_point< NodeClock, std::chrono::seconds > NodeSeconds
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.
void ClearShrink(V &v) noexcept
Clear a vector (or std::deque) and release its allocated memory.