Inside Bitcoin
Opening the selected file…
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.
1// Copyright (c) 2009-2010 Satoshi Nakamoto2// Copyright (c) 2009-present The Bitcoin Core developers3// Distributed under the MIT software license, see the accompanying4// file COPYING or http://www.opensource.org/licenses/mit-license.php.6#ifndef BITCOIN_NET_H7#define BITCOIN_NET_H9#include <bip324.h>10#include <chainparams.h>11#include <common/bloom.h>12#include <compat/compat.h>13#include <consensus/amount.h>14#include <crypto/siphash.h>15#include <hash.h>16#include <i2p.h>17#include <kernel/messagestartchars.h>18#include <net_permissions.h>19#include <netaddress.h>20#include <netbase.h>21#include <netgroup.h>22#include <node/connection_types.h>23#include <node/protocol_version.h>24#include <policy/feerate.h>25#include <protocol.h>26#include <random.h>27#include <semaphore_grant.h>28#include <span.h>29#include <streams.h>30#include <sync.h>31#include <uint256.h>32#include <util/check.h>33#include <util/sock.h>34#include <util/threadinterrupt.h>36#include <atomic>37#include <condition_variable>38#include <cstdint>39#include <deque>40#include <functional>41#include <list>42#include <map>43#include <memory>44#include <optional>45#include <queue>46#include <string_view>47#include <thread>48#include <unordered_set>49#include <vector>51class AddrMan;52class BanMan;53class CChainParams;54class CNode;55class CScheduler;56struct bilingual_str;58/** Time after which to disconnect, after waiting for a ping response (or inactivity). */59inline constexpr std::chrono::minutes TIMEOUT_INTERVAL{20};60/** Run the feeler connection loop once every 2 minutes. **/61inline constexpr auto FEELER_INTERVAL = 2min;62/** Run the extra block-relay-only connection loop once every 5 minutes. **/63inline constexpr auto EXTRA_BLOCK_RELAY_ONLY_PEER_INTERVAL = 5min;64/** Maximum length of incoming protocol messages (no message over 4 MB is currently acceptable). */65inline constexpr unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 4 * 1000 * 1000;66/** Maximum length of the user agent string in `version` message */67inline constexpr unsigned int MAX_SUBVERSION_LENGTH = 256;68/** Maximum number of automatic outgoing nodes over which we'll relay everything (blocks, tx, addrs, etc) */69inline constexpr int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS = 8;70/** Maximum number of addnode outgoing nodes */71inline constexpr int MAX_ADDNODE_CONNECTIONS = 8;72/** Maximum number of block-relay-only outgoing connections */73inline constexpr int MAX_BLOCK_RELAY_ONLY_CONNECTIONS = 2;74/** Maximum number of feeler connections */75inline constexpr int MAX_FEELER_CONNECTIONS = 1;76/** Maximum number of private broadcast connections */77inline constexpr size_t MAX_PRIVATE_BROADCAST_CONNECTIONS{64};78/** -listen default */79inline constexpr bool DEFAULT_LISTEN = true;80/** The maximum number of peer connections to maintain. */81inline constexpr unsigned int DEFAULT_MAX_PEER_CONNECTIONS{200};82/** Maximum value of -maxconnections */83inline constexpr int MAX_PEER_CONNECTIONS{2'000};84/** Default percentage of inbound connection slots that tx-relaying peers can use */85inline constexpr int DEFAULT_FULL_RELAY_INBOUND_PCT{50};86/** The default for -maxuploadtarget. 0 = Unlimited */87inline const std::string DEFAULT_MAX_UPLOAD_TARGET{"0M"};88/** Default for blocks only*/89inline constexpr bool DEFAULT_BLOCKSONLY = false;90/** -peertimeout default */91inline constexpr int64_t DEFAULT_PEER_CONNECT_TIMEOUT = 60;92/** Default for -privatebroadcast. */93inline constexpr bool DEFAULT_PRIVATE_BROADCAST{false};94/** Number of file descriptors required for message capture **/95inline constexpr int NUM_FDS_MESSAGE_CAPTURE = 1;96/** Interval for ASMap Health Check **/97inline constexpr std::chrono::hours ASMAP_HEALTH_CHECK_INTERVAL{24};99inline constexpr bool DEFAULT_FORCEDNSSEED{false};100inline constexpr bool DEFAULT_DNSSEED{true};101inline constexpr bool DEFAULT_FIXEDSEEDS{true};102inline constexpr size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;103inline constexpr size_t DEFAULT_MAXSENDBUFFER = 1 * 1000;105inline constexpr bool DEFAULT_V2_TRANSPORT{true};107typedef int64_t NodeId;109struct AddedNodeParams {110std::string m_added_node;111bool m_use_v2transport;112};114struct AddedNodeInfo {115AddedNodeParams m_params;116CService resolvedAddress;117bool fConnected;118bool fInbound;119};121class CNodeStats;122class CClientUIInterface;124struct CSerializedNetMsg {125CSerializedNetMsg() = default;126CSerializedNetMsg(CSerializedNetMsg&&) = default;127CSerializedNetMsg& operator=(CSerializedNetMsg&&) = default;128// No implicit copying, only moves.129CSerializedNetMsg(const CSerializedNetMsg& msg) = delete;130CSerializedNetMsg& operator=(const CSerializedNetMsg&) = delete;132CSerializedNetMsg Copy() const133{134CSerializedNetMsg copy;135copy.data = data;136copy.m_type = m_type;137return copy;138}140std::vector<unsigned char> data;141std::string m_type;143/** Compute total memory usage of this object (own memory + any dynamic memory). */144size_t GetMemoryUsage() const noexcept;145};147/**148* Look up IP addresses from all interfaces on the machine and add them to the149* list of local addresses to self-advertise.150* The loopback interface is skipped.151*/152void Discover();154uint16_t GetListenPort();156enum157{158LOCAL_NONE, // unknown159LOCAL_IF, // address a local interface listens on160LOCAL_BIND, // address explicit bound to161LOCAL_MAPPED, // address reported by PCP162LOCAL_MANUAL, // address explicitly specified (-externalip=)164LOCAL_MAX165};167/** Returns a local address that we should advertise to this peer. */168std::optional<CService> GetLocalAddrForPeer(CNode& node);170void ClearLocal();171bool AddLocal(const CService& addr, int nScore = LOCAL_NONE, bool add_even_if_unreachable = false);172bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE, bool add_even_if_unreachable = false);173void RemoveLocal(const CService& addr);174bool SeenLocal(const CService& addr);175bool IsLocal(const CService& addr);176CService GetLocalAddress(const CNode& peer);178extern bool fDiscover;179extern bool fListen;181/** Subversion as sent to the P2P network in `version` messages */182extern std::string strSubVersion;184struct LocalServiceInfo {185int nScore;186uint16_t nPort;187};189extern GlobalMutex g_maplocalhost_mutex;190extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost GUARDED_BY(g_maplocalhost_mutex);192extern const std::string NET_MESSAGE_TYPE_OTHER;193using mapMsgTypeSize = std::map</* message type */ std::string, /* total bytes */ uint64_t>;195class CNodeStats196{197public:198NodeId nodeid;199NodeClock::time_point m_last_send;200NodeClock::time_point m_last_recv;201std::chrono::seconds m_last_tx_time;202std::chrono::seconds m_last_block_time;203NodeClock::time_point m_connected;204std::string m_addr_name;205int nVersion;206std::string cleanSubVer;207bool fInbound;208// We requested high bandwidth connection to peer209bool m_bip152_highbandwidth_to;210// Peer requested high bandwidth connection211bool m_bip152_highbandwidth_from;212uint64_t nSendBytes;213mapMsgTypeSize mapSendBytesPerMsgType;214uint64_t nRecvBytes;215mapMsgTypeSize mapRecvBytesPerMsgType;216NetPermissionFlags m_permission_flags;217NodeClock::duration m_last_ping_time;218NodeClock::duration m_min_ping_time;219// Our address, as reported by the peer220std::string addrLocal;221// Address of this peer222CAddress addr;223// Bind address of our side of the connection224CService addrBind;225// Network the peer connected through226Network m_network;227uint32_t m_mapped_as;228ConnectionType m_conn_type;229/** Transport protocol type. */230TransportProtocolType m_transport_type;231/** BIP324 session id string in hex, if any. */232std::string m_session_id;233};236/** Transport protocol agnostic message container.237* Ideally it should only contain receive time, payload,238* type and size.239*/240class CNetMessage241{242public:243DataStream m_recv; //!< received message data244/// time of message receipt245NodeClock::time_point m_time{NodeClock::epoch};246uint32_t m_message_size{0}; //!< size of the payload247uint32_t m_raw_message_size{0}; //!< used wire size of the message (including header/checksum)248std::string m_type;250explicit CNetMessage(DataStream&& recv_in) : m_recv(std::move(recv_in)) {}
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.