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) 2009-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_NETBASE_H6#define BITCOIN_NETBASE_H8#include <compat/compat.h>9#include <netaddress.h>10#include <serialize.h>11#include <util/sock.h>12#include <util/threadinterrupt.h>14#include <chrono>15#include <cstdint>16#include <functional>17#include <memory>18#include <optional>19#include <string>20#include <type_traits>21#include <unordered_set>22#include <vector>24extern int nConnectTimeout;25extern bool fNameLookup;27//! -timeout default28inline constexpr int DEFAULT_CONNECT_TIMEOUT = 5000;29//! -dns default30inline constexpr int DEFAULT_NAME_LOOKUP = true;32/** Prefix for unix domain socket addresses (which are local filesystem paths) */33inline const std::string ADDR_PREFIX_UNIX = "unix:";35enum class ConnectionDirection {36None = 0,37In = (1U << 0),38Out = (1U << 1),39Both = (In | Out),40};41static inline ConnectionDirection& operator|=(ConnectionDirection& a, ConnectionDirection b) {42using underlying = std::underlying_type_t<ConnectionDirection>;43a = ConnectionDirection(underlying(a) | underlying(b));44return a;45}46static inline bool operator&(ConnectionDirection a, ConnectionDirection b) {47using underlying = std::underlying_type_t<ConnectionDirection>;48return (underlying(a) & underlying(b));49}51/**52* Check if a string is a valid UNIX domain socket path53*54* @param name The string provided by the user representing a local path55*56* @returns Whether the string has proper format, length, and points to an existing file path57*/58bool IsUnixSocketPath(const std::string& name);60class Proxy61{62public:63Proxy() : m_is_unix_socket(false), m_tor_stream_isolation(false) {}64explicit Proxy(const CService& _proxy, bool tor_stream_isolation = false) : proxy(_proxy), m_is_unix_socket(false), m_tor_stream_isolation(tor_stream_isolation) {}65explicit Proxy(std::string path, bool tor_stream_isolation = false)66: m_unix_socket_path(std::move(path)), m_is_unix_socket(true), m_tor_stream_isolation(tor_stream_isolation) {}68CService proxy;69std::string m_unix_socket_path;70bool m_is_unix_socket;71bool m_tor_stream_isolation;73bool IsValid() const74{75if (m_is_unix_socket) return IsUnixSocketPath(m_unix_socket_path);76return proxy.IsValid();77}79sa_family_t GetFamily() const80{81if (m_is_unix_socket) return AF_UNIX;82return proxy.GetSAFamily();83}85std::string ToString() const86{87if (m_is_unix_socket) return m_unix_socket_path;88return proxy.ToStringAddrPort();89}91std::unique_ptr<Sock> Connect() const;92};94/** Credentials for proxy authentication */95struct ProxyCredentials96{97std::string username;98std::string password;99};101/**102* List of reachable networks. Everything is reachable by default.103*/104class ReachableNets {105public:106void Add(Network net) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)107{108AssertLockNotHeld(m_mutex);109LOCK(m_mutex);110m_reachable.insert(net);111}113void Remove(Network net) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)114{115AssertLockNotHeld(m_mutex);116LOCK(m_mutex);117m_reachable.erase(net);118}120void RemoveAll() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)121{122AssertLockNotHeld(m_mutex);123LOCK(m_mutex);124m_reachable.clear();125}127void Reset() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)128{129AssertLockNotHeld(m_mutex);130LOCK(m_mutex);131m_reachable = DefaultNets();132}134[[nodiscard]] bool Contains(Network net) const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)135{136AssertLockNotHeld(m_mutex);137LOCK(m_mutex);138return m_reachable.contains(net);139}141[[nodiscard]] bool Contains(const CNetAddr& addr) const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)142{143AssertLockNotHeld(m_mutex);144return Contains(addr.GetNetwork());145}147[[nodiscard]] std::unordered_set<Network> All() const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)148{149AssertLockNotHeld(m_mutex);150LOCK(m_mutex);151return m_reachable;152}154private:155static std::unordered_set<Network> DefaultNets()156{157return {158NET_UNROUTABLE,159NET_IPV4,160NET_IPV6,161NET_ONION,162NET_I2P,163NET_CJDNS,164NET_INTERNAL165};166};168mutable Mutex m_mutex;169std::unordered_set<Network> m_reachable GUARDED_BY(m_mutex){DefaultNets()};170};172extern ReachableNets g_reachable_nets;174/**175* Wrapper for getaddrinfo(3). Do not use directly: call Lookup/LookupHost/LookupNumeric/LookupSubNet.176*/177std::vector<CNetAddr> WrappedGetAddrInfo(const std::string& name, bool allow_lookup);179enum Network ParseNetwork(const std::string& net);180std::string GetNetworkName(enum Network net);181/** Return a vector of publicly routable Network names; optionally append NET_UNROUTABLE. */182std::vector<std::string> GetNetworkNames(bool append_unroutable = false);183bool SetProxy(enum Network net, const Proxy &addrProxy);184std::optional<Proxy> GetProxy(enum Network net);185bool IsProxy(const CNetAddr &addr);186/**187* Set the name proxy to use for all connections to nodes specified by a188* hostname. After setting this proxy, connecting to a node specified by a189* hostname won't result in a local lookup of said hostname, rather, connect to190* the node by asking the name proxy for a proxy connection to the hostname,191* effectively delegating the hostname lookup to the specified proxy.192*193* This delegation increases privacy for those who set the name proxy as they no194* longer leak their external hostname queries to their DNS servers.195*196* @returns Whether or not the operation succeeded.197*198* @note SOCKS5's support for UDP-over-SOCKS5 has been considered, but no SOCK5199* server in common use (most notably Tor) actually implements UDP200* support, and a DNS resolver is beyond the scope of this project.201*/202bool SetNameProxy(const Proxy &addrProxy);203bool HaveNameProxy();204std::optional<Proxy> GetNameProxy();206using DNSLookupFn = std::function<std::vector<CNetAddr>(const std::string&, bool)>;207extern DNSLookupFn g_dns_lookup;209/**210* Resolve a host string to its corresponding network addresses.211*212* @param name The string representing a host. Could be a name or a numerical213* IP address (IPv6 addresses in their bracketed form are214* allowed).215*216* @returns The resulting network addresses to which the specified host217* string resolved.218*219* @see Lookup(const std::string&, uint16_t, bool, unsigned int, DNSLookupFn)220* for additional parameter descriptions.221*/222std::vector<CNetAddr> LookupHost(const std::string& name, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function = g_dns_lookup);224/**225* Resolve a host string to its first corresponding network address.226*227* @returns The resulting network address to which the specified host228* string resolved or std::nullopt if host does not resolve to an address.229*230* @see LookupHost(const std::string&, unsigned int, bool, DNSLookupFn)231* for additional parameter descriptions.232*/233std::optional<CNetAddr> LookupHost(const std::string& name, bool fAllowLookup, DNSLookupFn dns_lookup_function = g_dns_lookup);235/**236* Resolve a service string to its corresponding service.237*238* @param name The string representing a service. Could be a name or a239* numerical IP address (IPv6 addresses should be in their240* disambiguated bracketed form), optionally followed by a uint16_t port241* number. (e.g. example.com:8333 or242* [2001:db8:85a3:8d3:1319:8a2e:370:7348]:420)243* @param portDefault The default port for resulting services if not specified244* by the service string.245* @param fAllowLookup Whether or not hostname lookups are permitted. If yes,246* external queries may be performed.247* @param nMaxSolutions The maximum number of results we want, specifying 0248* means "as many solutions as we get."249*250* @returns The resulting services to which the specified service string
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.