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.
1// Copyright (c) 2020-present The Bitcoin Core developers2// Distributed under the MIT software license, see the accompanying3// file COPYING or http://www.opensource.org/licenses/mit-license.php.5#ifndef BITCOIN_TEST_UTIL_NET_H6#define BITCOIN_TEST_UTIL_NET_H8#include <attributes.h>9#include <compat/compat.h>10#include <netmessagemaker.h>11#include <net.h>12#include <net_permissions.h>13#include <net_processing.h>14#include <netaddress.h>15#include <node/connection_types.h>16#include <node/eviction.h>17#include <span.h>18#include <sync.h>19#include <util/sock.h>21#include <algorithm>22#include <array>23#include <cassert>24#include <chrono>25#include <condition_variable>26#include <cstdint>27#include <cstring>28#include <memory>29#include <optional>30#include <string>31#include <unordered_map>32#include <vector>34class FastRandomContext;36struct ConnmanTestMsg : public CConnman {37using CConnman::CConnman;39void SetMsgProc(NetEventsInterface* msgproc)40{41m_msgproc = msgproc;42}44void SetAddrman(AddrMan& in) { addrman = in; }46void SetPeerConnectTimeout(std::chrono::seconds timeout)47{48m_peer_connect_timeout = timeout;49}51void ResetAddrCache();52void ResetMaxOutboundCycle();53/// Reset the internal state.54void Reset();56std::vector<CNode*> TestNodes()57{58LOCK(m_nodes_mutex);59return m_nodes;60}62void AddTestNode(CNode& node)63{64LOCK(m_nodes_mutex);65m_nodes.push_back(&node);67if (node.IsManualOrFullOutboundConn()) ++m_network_conn_counts[node.addr.GetNetwork()];68}70void ClearTestNodes()71{72LOCK(m_nodes_mutex);73for (CNode* node : m_nodes) {74delete node;75}76m_nodes.clear();77}79void CreateNodeFromAcceptedSocketPublic(std::unique_ptr<Sock> sock,80NetPermissionFlags permissions,81const CAddress& addr_bind,82const CAddress& addr_peer)83{84CreateNodeFromAcceptedSocket(std::move(sock), permissions, addr_bind, addr_peer);85}87bool InitBindsPublic(const CConnman::Options& options)88{89return InitBinds(options);90}92void SocketHandlerPublic()93{94SocketHandler();95}97void Handshake(CNode& node,98bool successfully_connected,99ServiceFlags remote_services,100ServiceFlags local_services,101int32_t version,102bool relay_txs)103EXCLUSIVE_LOCKS_REQUIRED(NetEventsInterface::g_msgproc_mutex);105bool ProcessMessagesOnce(CNode& node) EXCLUSIVE_LOCKS_REQUIRED(NetEventsInterface::g_msgproc_mutex)106{107return m_msgproc->ProcessMessages(node, flagInterruptMsgProc);108}110void NodeReceiveMsgBytes(CNode& node, std::span<const uint8_t> msg_bytes, bool& complete) const;112bool ReceiveMsgFrom(CNode& node, CSerializedNetMsg&& ser_msg) const;113void FlushSendBuffer(CNode& node) const;115bool AlreadyConnectedToAddressPublic(const CNetAddr& addr) { return AlreadyConnectedToAddress(addr); };117CNode* ConnectNodePublic(PeerManager& peerman, const char* pszDest, ConnectionType conn_type)118EXCLUSIVE_LOCKS_REQUIRED(!m_unused_i2p_sessions_mutex);119};121inline constexpr ServiceFlags ALL_SERVICE_FLAGS[]{122NODE_NONE,123NODE_NETWORK,124NODE_BLOOM,125NODE_WITNESS,126NODE_COMPACT_FILTERS,127NODE_NETWORK_LIMITED,128NODE_P2P_V2,129};131inline constexpr NetPermissionFlags ALL_NET_PERMISSION_FLAGS[]{132NetPermissionFlags::None,133NetPermissionFlags::BloomFilter,134NetPermissionFlags::Relay,135NetPermissionFlags::ForceRelay,136NetPermissionFlags::NoBan,137NetPermissionFlags::Mempool,138NetPermissionFlags::Addr,139NetPermissionFlags::Download,140NetPermissionFlags::Implicit,141NetPermissionFlags::All,142};144inline constexpr ConnectionType ALL_CONNECTION_TYPES[]{145ConnectionType::INBOUND,146ConnectionType::OUTBOUND_FULL_RELAY,147ConnectionType::MANUAL,148ConnectionType::FEELER,149ConnectionType::BLOCK_RELAY,150ConnectionType::ADDR_FETCH,151ConnectionType::PRIVATE_BROADCAST,152};154inline constexpr auto ALL_NETWORKS = std::array{155Network::NET_UNROUTABLE,156Network::NET_IPV4,157Network::NET_IPV6,158Network::NET_ONION,159Network::NET_I2P,160Network::NET_CJDNS,161Network::NET_INTERNAL,162};164/**165* A mocked Sock alternative that succeeds on all operations.166* Returns infinite amount of 0x0 bytes on reads.167*/168class ZeroSock : public Sock169{170public:171ZeroSock();173~ZeroSock() override;175ssize_t Send(const void*, size_t len, int) const override;177ssize_t Recv(void* buf, size_t len, int flags) const override;179int Connect(const sockaddr*, socklen_t) const override;181int Bind(const sockaddr*, socklen_t) const override;183int Listen(int) const override;185std::unique_ptr<Sock> Accept(sockaddr* addr, socklen_t* addr_len) const override;187int GetSockOpt(int level, int opt_name, void* opt_val, socklen_t* opt_len) const override;189int SetSockOpt(int, int, const void*, socklen_t) const override;191int GetSockName(sockaddr* name, socklen_t* name_len) const override;193bool SetNonBlocking() const override;195bool IsSelectable() const override;197bool Wait(std::chrono::milliseconds timeout,198Event requested,199Event* occurred = nullptr) const override;201bool WaitMany(std::chrono::milliseconds timeout, EventsPerSock& events_per_sock) const override;203private:204ZeroSock& operator=(Sock&& other) override;205};207/**208* A mocked Sock alternative that returns a statically contained data upon read and succeeds209* and ignores all writes. The data to be returned is given to the constructor and when it is210* exhausted an EOF is returned by further reads.211*/212class StaticContentsSock : public ZeroSock213{214public:215explicit StaticContentsSock(const std::string& contents);217/**218* Return parts of the contents that was provided at construction until it is exhausted219* and then return 0 (EOF).220*/221ssize_t Recv(void* buf, size_t len, int flags) const override;223bool IsConnected(std::string&) const override224{225return true;226}228private:229StaticContentsSock& operator=(Sock&& other) override;231const std::string m_contents;232mutable size_t m_consumed{0};233};235/**236* A mocked Sock alternative that allows providing the data to be returned by Recv()237* and inspecting the data that has been supplied to Send().238*/239class DynSock : public ZeroSock240{241public:242/**243* Unidirectional bytes or CNetMessage queue (FIFO).244*/245class Pipe246{247public:248/**249* Get bytes and remove them from the pipe.250* @param[in] buf Destination to write bytes to.
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.