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_TEST_FUZZ_UTIL_NET_H6#define BITCOIN_TEST_FUZZ_UTIL_NET_H8#include <addrman.h>9#include <addrman_impl.h>10#include <net.h>11#include <net_permissions.h>12#include <netaddress.h>13#include <node/connection_types.h>14#include <node/eviction.h>15#include <protocol.h>16#include <sync.h>17#include <test/fuzz/FuzzedDataProvider.h>18#include <test/fuzz/util.h>19#include <test/util/net.h>20#include <test/util/time.h>21#include <util/asmap.h>22#include <util/sock.h>24#include <chrono>25#include <cstddef>26#include <cstdint>27#include <limits>28#include <memory>29#include <optional>30#include <string>32/**33* Create a CNetAddr. It may have `addr.IsValid() == false`.34* @param[in,out] fuzzed_data_provider Take data for the address from this, if `rand` is `nullptr`.35* @param[in,out] rand If not nullptr, take data from it instead of from `fuzzed_data_provider`.36* Prefer generating addresses using `fuzzed_data_provider` because it is not uniform. Only use37* `rand` if `fuzzed_data_provider` is exhausted or its data is needed for other things.38* @return a "random" network address.39*/40CNetAddr ConsumeNetAddr(FuzzedDataProvider& fuzzed_data_provider, FastRandomContext* rand = nullptr) noexcept;42class AddrManDeterministic : public AddrMan43{44public:45explicit AddrManDeterministic(const NetGroupManager& netgroupman, FuzzedDataProvider& fuzzed_data_provider, int32_t check_ratio)46: AddrMan(netgroupman, /*deterministic=*/true, check_ratio)47{48WITH_LOCK(m_impl->cs, m_impl->insecure_rand.Reseed(ConsumeUInt256(fuzzed_data_provider)));49}51/**52* Compare with another AddrMan.53* This compares:54* - the values in `mapInfo` (the keys aka ids are ignored)55* - vvNew entries refer to the same addresses56* - vvTried entries refer to the same addresses57*/58bool operator==(const AddrManDeterministic& other) const59{60LOCK2(m_impl->cs, other.m_impl->cs);62if (m_impl->mapInfo.size() != other.m_impl->mapInfo.size() || m_impl->nNew != other.m_impl->nNew ||63m_impl->nTried != other.m_impl->nTried) {64return false;65}67// Check that all values in `mapInfo` are equal to all values in `other.mapInfo`.68// Keys may be different.70auto addrinfo_hasher = [](const AddrInfo& a) {71CSipHasher hasher(0, 0);72auto addr_key = a.GetKey();73auto source_key = a.source.GetAddrBytes();74hasher.Write(TicksSinceEpoch<std::chrono::seconds>(a.m_last_success));75hasher.Write(a.nAttempts);76hasher.Write(a.nRefCount);77hasher.Write(a.fInTried);78hasher.Write(a.GetNetwork());79hasher.Write(a.source.GetNetwork());80hasher.Write(addr_key.size());81hasher.Write(source_key.size());82hasher.Write(addr_key);83hasher.Write(source_key);84return (size_t)hasher.Finalize();85};87auto addrinfo_eq = [](const AddrInfo& lhs, const AddrInfo& rhs) {88return std::tie(static_cast<const CService&>(lhs), lhs.source, lhs.m_last_success, lhs.nAttempts, lhs.nRefCount, lhs.fInTried) ==89std::tie(static_cast<const CService&>(rhs), rhs.source, rhs.m_last_success, rhs.nAttempts, rhs.nRefCount, rhs.fInTried);90};92using Addresses = std::unordered_set<AddrInfo, decltype(addrinfo_hasher), decltype(addrinfo_eq)>;94const size_t num_addresses{m_impl->mapInfo.size()};96Addresses addresses{num_addresses, addrinfo_hasher, addrinfo_eq};97for (const auto& [id, addr] : m_impl->mapInfo) {98addresses.insert(addr);99}101Addresses other_addresses{num_addresses, addrinfo_hasher, addrinfo_eq};102for (const auto& [id, addr] : other.m_impl->mapInfo) {103other_addresses.insert(addr);104}106if (addresses != other_addresses) {107return false;108}110auto IdsReferToSameAddress = [&](nid_type id, nid_type other_id) EXCLUSIVE_LOCKS_REQUIRED(m_impl->cs, other.m_impl->cs) {111if (id == -1 && other_id == -1) {112return true;113}114if ((id == -1 && other_id != -1) || (id != -1 && other_id == -1)) {115return false;116}117return m_impl->mapInfo.at(id) == other.m_impl->mapInfo.at(other_id);118};120// Check that `vvNew` contains the same addresses as `other.vvNew`. Notice - `vvNew[i][j]`121// contains just an id and the address is to be found in `mapInfo.at(id)`. The ids122// themselves may differ between `vvNew` and `other.vvNew`.123for (size_t i = 0; i < ADDRMAN_NEW_BUCKET_COUNT; ++i) {124for (size_t j = 0; j < ADDRMAN_BUCKET_SIZE; ++j) {125if (!IdsReferToSameAddress(m_impl->vvNew[i][j], other.m_impl->vvNew[i][j])) {126return false;127}128}129}131// Same for `vvTried`.132for (size_t i = 0; i < ADDRMAN_TRIED_BUCKET_COUNT; ++i) {133for (size_t j = 0; j < ADDRMAN_BUCKET_SIZE; ++j) {134if (!IdsReferToSameAddress(m_impl->vvTried[i][j], other.m_impl->vvTried[i][j])) {135return false;136}137}138}140return true;141}142};144class FuzzedNetEvents : public NetEventsInterface145{146public:147FuzzedNetEvents(FuzzedDataProvider& fdp) : m_fdp(fdp) {}149virtual void InitializeNode(const CNode&, ServiceFlags) override {}151virtual void FinalizeNode(const CNode&) override {}153virtual bool HasAllDesirableServiceFlags(ServiceFlags) const override { return m_fdp.ConsumeBool(); }155virtual bool ProcessMessages(CNode&, std::atomic<bool>&) override { return m_fdp.ConsumeBool(); }157virtual bool SendMessages(CNode&) override { return m_fdp.ConsumeBool(); }159private:160FuzzedDataProvider& m_fdp;161};163class FuzzedSock : public Sock164{165FuzzedDataProvider& m_fuzzed_data_provider;167/**168* Data to return when `MSG_PEEK` is used as a `Recv()` flag.169* If `MSG_PEEK` is used, then our `Recv()` returns some random data as usual, but on the next170* `Recv()` call we must return the same data, thus we remember it here.171*/172mutable std::vector<uint8_t> m_peek_data;174/**175* Whether to pretend that the socket is select(2)-able. This is randomly set in the176* constructor. It should remain constant so that repeated calls to `IsSelectable()`177* return the same value.178*/179const bool m_selectable;181/**182* Externally-provided context used to mock the steady clock in methods183* waiting for a given duration. It is a reference (rather than an owned184* member) so that several FuzzedSock instances sharing a test case (e.g.185* one per peer, or one created from Accept()) advance a single mocked186* clock.187*/188FakeSteadyClock& m_clock;190public:191explicit FuzzedSock(FuzzedDataProvider& fuzzed_data_provider, FakeSteadyClock& clock);193~FuzzedSock() override;195FuzzedSock& operator=(Sock&& other) override;197ssize_t Send(const void* data, size_t len, int flags) const override;199ssize_t Recv(void* buf, size_t len, int flags) const override;201int Connect(const sockaddr*, socklen_t) const override;203int Bind(const sockaddr*, socklen_t) const override;205int Listen(int backlog) const override;207std::unique_ptr<Sock> Accept(sockaddr* addr, socklen_t* addr_len) const override;209int GetSockOpt(int level, int opt_name, void* opt_val, socklen_t* opt_len) const override;211int SetSockOpt(int level, int opt_name, const void* opt_val, socklen_t opt_len) const override;213int GetSockName(sockaddr* name, socklen_t* name_len) const override;215bool SetNonBlocking() const override;217bool IsSelectable() const override;219bool Wait(std::chrono::milliseconds timeout, Event requested, Event* occurred = nullptr) const override;221bool WaitMany(std::chrono::milliseconds timeout, EventsPerSock& events_per_sock) const override;223bool IsConnected(std::string& errmsg) const override;224};226[[nodiscard]] inline FuzzedNetEvents ConsumeNetEvents(FuzzedDataProvider& fdp) noexcept227{228return FuzzedNetEvents{fdp};229}231[[nodiscard]] inline FuzzedSock ConsumeSock(FuzzedDataProvider& fuzzed_data_provider, FakeSteadyClock& clock)232{233return FuzzedSock{fuzzed_data_provider, clock};234}236[[nodiscard]] inline NetGroupManager ConsumeNetGroupManager(FuzzedDataProvider& fuzzed_data_provider) noexcept237{238std::vector<std::byte> asmap{ConsumeRandomLengthByteVector<std::byte>(fuzzed_data_provider)};239if (!CheckStandardAsmap(asmap)) {240return NetGroupManager::NoAsmap();241}242return NetGroupManager::WithLoadedAsmap(std::move(asmap));243}245inline CSubNet ConsumeSubNet(FuzzedDataProvider& fuzzed_data_provider) noexcept246{247return {ConsumeNetAddr(fuzzed_data_provider), fuzzed_data_provider.ConsumeIntegral<uint8_t>()};248}250inline CService ConsumeService(FuzzedDataProvider& fuzzed_data_provider) noexcept
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.