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.
1251void NumToOpenAdd(size_t n);1253/**1254* Decrement the number of new connections of type `ConnectionType::PRIVATE_BROADCAST`1255* to be opened by `CConnman::ThreadPrivateBroadcast()`.1256* @param[in] n Decrement by this number.1257* @return The number of connections that remain to be opened after the operation.1258*/1259size_t NumToOpenSub(size_t n);1261/// Wait for the number of needed connections to become greater than 0.1262void NumToOpenWait() const;1264protected:1265/**1266* Check if private broadcast can be done to IPv4 or IPv6 peers and if so via which proxy.1267* If private broadcast connections should not be opened to IPv4 or IPv6, then this will1268* return an empty optional.1269*/1270std::optional<Proxy> ProxyForIPv4or6() const;1272/// Number of `ConnectionType::PRIVATE_BROADCAST` connections to open.1273std::atomic_size_t m_num_to_open{0};1275friend struct ConnmanTestMsg;1276} m_private_broadcast;1278bool CheckIncomingNonce(uint64_t nonce) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);1279void ASMapHealthCheck();1281// alias for thread safety annotations only, not defined1282Mutex& GetNodesMutex() const LOCK_RETURNED(m_nodes_mutex);1284bool ForNode(NodeId id, std::function<bool(CNode* pnode)> func) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);1286void PushMessage(CNode* pnode, CSerializedNetMsg&& msg) EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);1288using NodeFn = std::function<void(CNode*)>;1289void ForEachNode(const NodeFn& func) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)1290{1291LOCK(m_nodes_mutex);1292for (auto&& node : m_nodes) {1293if (NodeFullyConnected(node))1294func(node);1295}1296};1298void ForEachNode(const NodeFn& func) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex)1299{1300LOCK(m_nodes_mutex);1301for (auto&& node : m_nodes) {1302if (NodeFullyConnected(node))1303func(node);1304}1305};1307// Addrman functions1308/**1309* Return randomly selected addresses. This function does not use the address response cache and1310* should only be used in trusted contexts.1311*1312* An untrusted caller (e.g. from p2p) should instead use @ref GetAddresses to use the cache.1313*1314* @param[in] max_addresses Maximum number of addresses to return (0 = all).1315* @param[in] max_pct Maximum percentage of addresses to return (0 = all). Value must be from 0 to 100.1316* @param[in] network Select only addresses of this network (nullopt = all).1317* @param[in] filtered Select only addresses that are considered high quality (false = all).1318*/1319std::vector<CAddress> GetAddressesUnsafe(size_t max_addresses, size_t max_pct, std::optional<Network> network, bool filtered = true) const;1320/**1321* Return addresses from the per-requestor cache. If no cache entry exists, it is populated with1322* randomly selected addresses. This function can be used in untrusted contexts.1323*1324* A trusted caller (e.g. from RPC or a peer with addr permission) can use1325* @ref GetAddressesUnsafe to avoid using the cache.1326*1327* @param[in] requestor The requesting peer. Used to key the cache to prevent privacy leaks.1328* @param[in] max_addresses Maximum number of addresses to return (0 = all). Ignored when cache1329* already contains an entry for requestor.1330* @param[in] max_pct Maximum percentage of addresses to return (0 = all). Value must be1331* from 0 to 100. Ignored when cache already contains an entry for1332* requestor.1333*/1334std::vector<CAddress> GetAddresses(CNode& requestor, size_t max_addresses, size_t max_pct);1336// This allows temporarily exceeding m_max_outbound_full_relay, with the goal of finding1337// a peer that is better than all our current peers.1338void SetTryNewOutboundPeer(bool flag);1339bool GetTryNewOutboundPeer() const;1341void StartExtraBlockRelayPeers();1343// Count the number of full-relay peer we have.1344int GetFullOutboundConnCount() const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);1345// Return the number of outbound peers we have in excess of our target (eg,1346// if we previously called SetTryNewOutboundPeer(true), and have since set1347// to false, we may have extra peers that we wish to disconnect). This may1348// return a value less than (num_outbound_connections - num_outbound_slots)1349// in cases where some outbound connections are not yet fully connected, or1350// not yet fully disconnected.1351int GetExtraFullOutboundCount() const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);1352// Count the number of block-relay-only peers we have over our limit.1353int GetExtraBlockRelayCount() const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);1354/**1355* If we are at capacity for inbound tx-relay peers, attempt to evict one.1356* @param[in] protect_peer NodeId of a peer we want to protect1357* @return bool Returns true if successful (either there is1358* no need for eviction, or a peer was evicted).1359* Returns false, if we are full but couldn't find1360* a peer to evict (all eligible peers are protected)1361* so that the caller can deal with this.1362*/1363bool EvictTxPeerIfFull(std::optional<NodeId> protect_peer = std::nullopt) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);1365bool AddNode(const AddedNodeParams& add) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex);1366bool RemoveAddedNode(std::string_view node) EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex);1367bool AddedNodesContain(const CAddress& addr) const EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex);1368std::vector<AddedNodeInfo> GetAddedNodeInfo(bool include_connected) const1369EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex, !m_nodes_mutex);1371/**1372* Attempts to open a connection. Currently only used from tests.1373*1374* @param[in] address Address of node to try connecting to1375* @param[in] conn_type ConnectionType::OUTBOUND, ConnectionType::BLOCK_RELAY,1376* ConnectionType::ADDR_FETCH or ConnectionType::FEELER1377* @param[in] use_v2transport Set to true if node attempts to connect using BIP 324 v2 transport protocol.1378* @return bool Returns false if there are no available1379* slots for this connection:1380* - conn_type not a supported ConnectionType1381* - Max total outbound connection capacity filled1382* - Max connection capacity for type is filled1383*/1384bool AddConnection(const std::string& address, ConnectionType conn_type, bool use_v2transport)1385EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex, !m_unused_i2p_sessions_mutex);1387size_t GetNodeCount(ConnectionDirection) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);1388std::map<CNetAddr, LocalServiceInfo> getNetLocalAddresses() const;1389uint32_t GetMappedAS(const CNetAddr& addr) const;1390void GetNodeStats(std::vector<CNodeStats>& vstats) const EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);1391bool DisconnectNode(std::string_view node) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);1392bool DisconnectNode(const CSubNet& subnet, bool disconnect_private_broadcast = true) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);1393bool DisconnectNode(const CNetAddr& addr) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);1394bool DisconnectNode(NodeId id) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);1396//! Used to convey which local services we are offering peers during node1397//! connection.1398//!1399//! The data returned by this is used in CNode construction,1400//! which is used to advertise which services we are offering1401//! that peer during `net_processing.cpp:PushNodeVersion()`.1402ServiceFlags GetLocalServices() const;1404//! Updates the local services that this node advertises to other peers1405//! during connection handshake.1406void AddLocalServices(ServiceFlags services) { m_local_services = ServiceFlags(m_local_services | services); };1407void RemoveLocalServices(ServiceFlags services) { m_local_services = ServiceFlags(m_local_services & ~services); }1409uint64_t GetMaxOutboundTarget() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);1410std::chrono::seconds GetMaxOutboundTimeframe() const;1412//! check if the outbound target is reached1413//! if param historicalBlockServingLimit is set true, the function will1414//! response true if the limit for serving historical blocks has been reached1415bool OutboundTargetReached(bool historicalBlockServingLimit) const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);1417//! response the bytes left in the current max outbound cycle1418//! in case of no limit, it will always response 01419uint64_t GetOutboundTargetBytesLeft() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);1421std::chrono::seconds GetMaxOutboundTimeLeftInCycle() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);1423uint64_t GetTotalBytesRecv() const;1424uint64_t GetTotalBytesSent() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex);1426/** Get a unique deterministic randomizer. */1427CSipHasher GetDeterministicRandomizer(uint64_t id) const;1429void WakeMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!mutexMsgProc);1431/** Return true if we should disconnect the peer for failing an inactivity check. */1432bool ShouldRunInactivityChecks(const CNode& node, NodeClock::time_point now) const;1434bool MultipleManualOrFullOutboundConns(Network net) const EXCLUSIVE_LOCKS_REQUIRED(m_nodes_mutex);1436private:1437struct ListenSocket {1438public:1439std::shared_ptr<Sock> sock;1440inline void AddSocketPermissionFlags(NetPermissionFlags& flags) const { NetPermissions::AddFlag(flags, m_permissions); }1441ListenSocket(std::shared_ptr<Sock> sock_, NetPermissionFlags permissions_)1442: sock{sock_}, m_permissions{permissions_}1443{1444}1446private:1447NetPermissionFlags m_permissions;1448};1450//! returns the time left in the current max outbound cycle1451//! in case of no limit, it will always return 01452std::chrono::seconds GetMaxOutboundTimeLeftInCycle_() const EXCLUSIVE_LOCKS_REQUIRED(m_total_bytes_sent_mutex);1454bool BindListenPort(const CService& bindAddr, bilingual_str& strError, NetPermissionFlags permissions);1455bool Bind(const CService& addr, unsigned int flags, NetPermissionFlags permissions);1456bool InitBinds(const Options& options);1458/// \anchor addcon1459void ThreadOpenAddedConnections() EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex,1460!m_nodes_mutex,1461!m_reconnections_mutex,1462!m_unused_i2p_sessions_mutex);1464void AddAddrFetch(const std::string& strDest) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex);1466void ProcessAddrFetch() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex,1467!m_nodes_mutex,1468!m_unused_i2p_sessions_mutex);1470/// \anchor opencon1471void ThreadOpenConnections(std::vector<std::string> connect, std::span<const std::string> seed_nodes)1472EXCLUSIVE_LOCKS_REQUIRED(!m_added_nodes_mutex,1473!m_addr_fetches_mutex,1474!m_nodes_mutex,1475!m_reconnections_mutex,1476!m_unused_i2p_sessions_mutex);1478/// \anchor msghand1479void ThreadMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex, !mutexMsgProc);1480/// \anchor i2paccept1481void ThreadI2PAcceptIncoming() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);1482void ThreadPrivateBroadcast() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex, !m_unused_i2p_sessions_mutex);1483void AcceptConnection(const ListenSocket& hListenSocket) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);1485/**1486* Create a `CNode` object from a socket that has just been accepted and add the node to1487* the `m_nodes` member.1488* @param[in] sock Connected socket to communicate with the peer.1489* @param[in] permission_flags The peer's permissions.1490* @param[in] addr_bind The address and port at our side of the connection.1491* @param[in] addr The address and port at the peer's side of the connection.1492*/1493void CreateNodeFromAcceptedSocket(std::unique_ptr<Sock>&& sock,1494NetPermissionFlags permission_flags,1495const CService& addr_bind,1496const CService& addr)1497EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);1499void DisconnectNodes() EXCLUSIVE_LOCKS_REQUIRED(!m_reconnections_mutex, !m_nodes_mutex);1500void NotifyNumConnectionsChanged() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex);
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.