Inside Bitcoin
Opening the selected file…
Inside Bitcoin
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
1501/** Return true if the peer is inactive and should be disconnected. */1502bool InactivityCheck(const CNode& node, NodeClock::time_point now) const;1504/**1505* Generate a collection of sockets to check for IO readiness.1506* @param[in] nodes Select from these nodes' sockets.1507* @return sockets to check for readiness1508*/1509Sock::EventsPerSock GenerateWaitSockets(std::span<CNode* const> nodes);1511/**1512* Check connected and listening sockets for IO readiness and process them accordingly.1513*/1514void SocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex, !m_total_bytes_sent_mutex, !mutexMsgProc);1516/**1517* Do the read/write for connected sockets that are ready for IO.1518* @param[in] nodes Nodes to process. The socket of each node is checked against `what`.1519* @param[in] events_per_sock Sockets that are ready for IO.1520*/1521void SocketHandlerConnected(const std::vector<CNode*>& nodes,1522const Sock::EventsPerSock& events_per_sock)1523EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex, !mutexMsgProc);1525/**1526* Accept incoming connections, one from each read-ready listening socket.1527* @param[in] events_per_sock Sockets that are ready for IO.1528*/1529void SocketHandlerListening(const Sock::EventsPerSock& events_per_sock)1530EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);1532/// \anchor net1533void ThreadSocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex, !mutexMsgProc, !m_nodes_mutex, !m_reconnections_mutex);1534/// \anchor dnsseed1535void ThreadDNSAddressSeed() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex, !m_nodes_mutex);1537uint64_t CalculateKeyedNetGroup(const CNetAddr& ad) const;1539/**1540* Determine whether we're already connected to a given "host:port".1541* Note that for inbound connections, the peer is likely using a random outbound1542* port on their side, so this will likely not match any inbound connections.1543* @param[in] host String of the form "host[:port]", e.g. "localhost" or "localhost:8333" or "1.2.3.4:8333".1544* @return true if connected to `host`.1545*/1546bool AlreadyConnectedToHost(std::string_view host) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);1548/**1549* Determine whether we're already connected to a given address:port.1550* Note that for inbound connections, the peer is likely using a random outbound1551* port on their side, so this will likely not match any inbound connections.1552* @param[in] addr_port Address and port to check.1553* @return true if connected to addr_port.1554*/1555bool AlreadyConnectedToAddressPort(const CService& addr_port) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);1557/**1558* Determine whether we're already connected to a given address.1559*/1560bool AlreadyConnectedToAddress(const CNetAddr& addr) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);1562/**1563* Try to find an inbound connection to evict.1564* @param[in] evict_tx_relay_peer_only Whether to only select full relay peers for eviction1565* @param[in] protect_peer Protect peer with node id1566* @return True if a node was marked for disconnect1567*/1568bool AttemptToEvictConnection(bool evict_tx_relay_peer_only, std::optional<NodeId> protect_peer = std::nullopt) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);1570/**1571* Open a new P2P connection.1572* @param[in] addrConnect Address to connect to, if `pszDest` is `nullptr`.1573* @param[in] pszDest Address to resolve and connect to.1574* @param[in] fCountFailure Increment the number of connection attempts to this address in Addrman.1575* @param[in] conn_type Type of the connection to open, must not be `ConnectionType::INBOUND`.1576* @param[in] use_v2transport Use P2P encryption, (aka V2 transport, BIP324).1577* @param[in] proxy_override Optional proxy to use and override normal proxy selection.1578* @return Newly created CNode object or nullptr if the connection failed.1579*/1580CNode* ConnectNode(CAddress addrConnect,1581const char* pszDest,1582bool fCountFailure,1583ConnectionType conn_type,1584bool use_v2transport,1585const std::optional<Proxy>& proxy_override)1586EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex, !m_unused_i2p_sessions_mutex);1588void AddWhitelistPermissionFlags(NetPermissionFlags& flags, std::optional<CNetAddr> addr, const std::vector<NetWhitelistPermissions>& ranges) const;1590void DeleteNode(CNode* pnode);1592NodeId GetNewNodeId();1594/** (Try to) send data from node's vSendMsg. Returns (bytes_sent, data_left). */1595std::pair<size_t, bool> SocketSendData(CNode& node) const EXCLUSIVE_LOCKS_REQUIRED(node.cs_vSend);1597void DumpAddresses();1599// Network stats1600void RecordBytesRecv(uint64_t bytes);1601void RecordBytesSent(uint64_t bytes) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);1603/**1604Return reachable networks for which we have no addresses in addrman and therefore1605may require loading fixed seeds.1606*/1607std::unordered_set<Network> GetReachableEmptyNetworks() const;1609/**1610* Return vector of current BLOCK_RELAY peers.1611*/1612std::vector<CAddress> GetCurrentBlockRelayOnlyConns() const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);1614/**1615* Search for a "preferred" network, a reachable network to which we1616* currently don't have any OUTBOUND_FULL_RELAY or MANUAL connections.1617* There needs to be at least one address in AddrMan for a preferred1618* network to be picked.1619*1620* @param[out] network Preferred network, if found.1621*1622* @return bool Whether a preferred network was found.1623*/1624bool MaybePickPreferredNetwork(std::optional<Network>& network) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);1626// Whether the node should be passed out in ForEach* callbacks1627static bool NodeFullyConnected(const CNode* pnode);1629uint16_t GetDefaultPort(Network net) const;1630uint16_t GetDefaultPort(const std::string& addr) const;1632// Network usage totals1633mutable Mutex m_total_bytes_sent_mutex;1634std::atomic<uint64_t> nTotalBytesRecv{0};1635uint64_t nTotalBytesSent GUARDED_BY(m_total_bytes_sent_mutex) {0};1637// outbound limit & stats1638uint64_t nMaxOutboundTotalBytesSentInCycle GUARDED_BY(m_total_bytes_sent_mutex) {0};1639std::chrono::seconds nMaxOutboundCycleStartTime GUARDED_BY(m_total_bytes_sent_mutex) {0};1640uint64_t nMaxOutboundLimit GUARDED_BY(m_total_bytes_sent_mutex);1642// P2P timeout in seconds1643std::chrono::seconds m_peer_connect_timeout;1645// Whitelisted ranges. Any node connecting from these is automatically1646// whitelisted (as well as those connecting to whitelisted binds).1647std::vector<NetWhitelistPermissions> vWhitelistedRangeIncoming;1648// Whitelisted ranges for outgoing connections.1649std::vector<NetWhitelistPermissions> vWhitelistedRangeOutgoing;1651unsigned int nSendBufferMaxSize{0};1652unsigned int nReceiveFloodSize{0};1654std::vector<ListenSocket> vhListenSocket;1655std::atomic<bool> fNetworkActive{true};1656bool fAddressesInitialized{false};1657std::reference_wrapper<AddrMan> addrman;1658const NetGroupManager& m_netgroupman;1659std::deque<std::string> m_addr_fetches GUARDED_BY(m_addr_fetches_mutex);1660Mutex m_addr_fetches_mutex;1662// connection string and whether to use v2 p2p1663std::vector<AddedNodeParams> m_added_node_params GUARDED_BY(m_added_nodes_mutex);1665mutable Mutex m_added_nodes_mutex;1666std::vector<CNode*> m_nodes GUARDED_BY(m_nodes_mutex);1667std::list<CNode*> m_nodes_disconnected;1668mutable Mutex m_nodes_mutex;1669std::atomic<NodeId> nLastNodeId{0};1670unsigned int nPrevNodeCount{0};1672// Stores number of full-tx connections (outbound and manual) per network1673std::array<unsigned int, Network::NET_MAX> m_network_conn_counts GUARDED_BY(m_nodes_mutex) = {};1675/**1676* Cache responses to addr requests to minimize privacy leak.1677* Attack example: scraping addrs in real-time may allow an attacker1678* to infer new connections of the victim by detecting new records1679* with fresh timestamps (per self-announcement).1680*/1681struct CachedAddrResponse {1682std::vector<CAddress> m_addrs_response_cache;1683std::chrono::microseconds m_cache_entry_expiration{0};1684};1686/**1687* Addr responses stored in different caches1688* per (network, local socket) prevent cross-network node identification.1689* If a node for example is multi-homed under Tor and IPv6,1690* a single cache (or no cache at all) would let an attacker1691* to easily detect that it is the same node by comparing responses.1692* Indexing by local socket prevents leakage when a node has multiple1693* listening addresses on the same network.1694*1695* The used memory equals to 1000 CAddress records (or around 40 bytes) per1696* distinct Network (up to 5) we have/had an inbound peer from,1697* resulting in at most ~196 KB. Every separate local socket may1698* add up to ~196 KB extra.1699*/1700std::map<uint64_t, CachedAddrResponse> m_addr_response_caches;1702/**1703* Services this node offers.1704*1705* This data is replicated in each Peer instance we create.1706*1707* This data is not marked const, but after being set it should not1708* change. Unless AssumeUTXO is started, in which case, the peer1709* will be limited until the background chain sync finishes.1710*1711* \sa Peer::our_services1712*/1713std::atomic<ServiceFlags> m_local_services;1715std::unique_ptr<std::counting_semaphore<>> semOutbound;1716std::unique_ptr<std::counting_semaphore<>> semAddnode;1718/**1719* Maximum number of automatic connections permitted, excluding manual1720* connections but including inbounds. May be changed by the user and is1721* potentially limited by the operating system (number of file descriptors).1722*/1723int m_max_automatic_connections;1725/*1726* Maximum number of peers by connection type. Might vary from defaults1727* based on -maxconnections init value.1728*/1730// How many full-relay (tx, block, addr) outbound peers we want1731int m_max_outbound_full_relay;1733// How many block-relay only outbound peers we want1734// We do not relay tx or addr messages with these peers1735int m_max_outbound_block_relay;1737int m_max_addnode{MAX_ADDNODE_CONNECTIONS};1738int m_max_feeler{MAX_FEELER_CONNECTIONS};1739int m_max_automatic_outbound;1740int m_max_inbound;1741int m_max_inbound_full_relay;1743bool m_use_addrman_outgoing;1744CClientUIInterface* m_client_interface;1745NetEventsInterface* m_msgproc;1746/** Pointer to this node's banman. May be nullptr - check existence before dereferencing. */1747BanMan* m_banman;1749/**1750* Addresses that were saved during the previous clean shutdown. We'll
Independent explanations by MyBitcoinExplorer. Not affiliated with or endorsed by Bitcoin Core. Guides are educational and do not replace the source or its tests.
Bitcoin Core source © its contributors, distributed under the MIT license. Original notices and bundled third-party licenses are retained in the source tree.