Bitcoin Core 31.99.0
P2P Digital Currency
addrman.cpp
Go to the documentation of this file.
1// Copyright (c) 2020-present The Bitcoin Core developers
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5#include <addrdb.h>
6#include <addrman.h>
7#include <addrman_impl.h>
8#include <chainparams.h>
9#include <common/args.h>
10#include <merkleblock.h>
11#include <random.h>
13#include <test/fuzz/fuzz.h>
14#include <test/fuzz/util.h>
15#include <test/fuzz/util/net.h>
17#include <test/util/time.h>
18#include <util/asmap.h>
19#include <util/chaintype.h>
20
21#include <cassert>
22#include <cstdint>
23#include <ctime>
24#include <optional>
25#include <string>
26#include <vector>
27
28namespace {
30
31int32_t GetCheckRatio()
32{
33 return std::clamp<int32_t>(g_setup->m_node.args->GetIntArg("-checkaddrman", 0), 0, 1000000);
34}
35} // namespace
36
38{
39 static const auto testing_setup = MakeNoLogFileContext<>(ChainType::REGTEST);
40 g_setup = testing_setup.get();
41}
42
43FUZZ_TARGET(data_stream_addr_man, .init = initialize_addrman)
44{
46 FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
49 AddrMan addr_man(netgroupman, /*deterministic=*/false, GetCheckRatio());
50 try {
51 ReadFromStream(addr_man, data_stream);
52 } catch (const std::exception&) {
53 }
54}
55
60{
61 CNetAddr addr;
62 assert(!addr.IsValid());
63 for (size_t i = 0; i < 8 && !addr.IsValid(); ++i) {
66 } else {
67 addr = ConsumeNetAddr(fuzzed_data_provider, &fast_random_context);
68 }
69 }
70
71 // Return a dummy IPv4 5.5.5.5 if we generated an invalid address.
72 if (!addr.IsValid()) {
73 in_addr v4_addr = {};
74 v4_addr.s_addr = 0x05050505;
75 addr = CNetAddr{v4_addr};
76 }
77
78 return addr;
79}
80
83{
84 // Add a fraction of the addresses to the "tried" table.
85 // 0, 1, 2, 3 corresponding to 0%, 100%, 50%, 33%
86 const size_t n = fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, 3);
87
88 const size_t num_sources = fuzzed_data_provider.ConsumeIntegralInRange<size_t>(1, 50);
89 CNetAddr prev_source;
90 // Generate a FastRandomContext seed to use inside the loops instead of
91 // fuzzed_data_provider. When fuzzed_data_provider is exhausted it
92 // just returns 0.
94 for (size_t i = 0; i < num_sources; ++i) {
95 const auto source = RandAddr(fuzzed_data_provider, fast_random_context);
96 const size_t num_addresses = fast_random_context.randrange(500) + 1; // [1..500]
97
98 for (size_t j = 0; j < num_addresses; ++j) {
99 const auto addr = CAddress{CService{RandAddr(fuzzed_data_provider, fast_random_context), 8333}, NODE_NETWORK};
100 const std::chrono::seconds time_penalty{fast_random_context.randrange(100000001)};
101 addrman.Add({addr}, source, time_penalty);
102
103 if (n > 0 && addrman.Size() % n == 0) {
104 addrman.Good(addr, Now<NodeSeconds>());
105 }
106
107 // Add 10% of the addresses from more than one source.
108 if (fast_random_context.randrange(10) == 0 && prev_source.IsValid()) {
109 addrman.Add({addr}, prev_source, time_penalty);
110 }
111 }
112 prev_source = source;
113 }
114}
115
117{
119 FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
122 auto addr_man_ptr = std::make_unique<AddrManDeterministic>(netgroupman, fuzzed_data_provider, GetCheckRatio());
124 const std::vector<uint8_t> serialized_data{ConsumeRandomLengthByteVector(fuzzed_data_provider)};
125 DataStream ds{serialized_data};
126 try {
127 ds >> *addr_man_ptr;
128 } catch (const std::ios_base::failure&) {
129 addr_man_ptr = std::make_unique<AddrManDeterministic>(netgroupman, fuzzed_data_provider, GetCheckRatio());
130 }
131 }
132 AddrManDeterministic& addr_man = *addr_man_ptr;
134 CallOneOf(
136 [&] {
137 addr_man.ResolveCollisions();
138 },
139 [&] {
140 (void)addr_man.SelectTriedCollision();
141 },
142 [&] {
143 std::vector<CAddress> addresses;
145 addresses.push_back(ConsumeAddress(fuzzed_data_provider));
146 }
147 auto net_addr = ConsumeNetAddr(fuzzed_data_provider);
148 auto time_penalty = ConsumeDuration<std::chrono::seconds>(fuzzed_data_provider, /*min=*/0s, /*max=*/100000000s);
149 addr_man.Add(addresses, net_addr, time_penalty);
150 },
151 [&] {
154 addr_man.Good(addr, time);
155 },
156 [&] {
158 auto count_failure = fuzzed_data_provider.ConsumeBool();
160 addr_man.Attempt(addr, count_failure, time);
161 },
162 [&] {
165 addr_man.Connected(addr, time);
166 },
167 [&] {
170 addr_man.SetServices(addr, n_services);
171 });
172 }
173 const AddrMan& const_addr_man{addr_man};
174 std::optional<Network> network;
177 }
178 auto max_addresses = fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, 4096);
179 auto max_pct = fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, 100);
180 auto filtered = fuzzed_data_provider.ConsumeBool();
181 (void)const_addr_man.GetAddr(max_addresses, max_pct, network, filtered);
182
183 std::unordered_set<Network> nets;
184 for (const auto& net : ALL_NETWORKS) {
186 nets.insert(net);
187 }
188 }
189 (void)const_addr_man.Select(fuzzed_data_provider.ConsumeBool(), nets);
190
191 std::optional<bool> in_new;
194 }
195 (void)const_addr_man.Size(network, in_new);
196 DataStream data_stream{};
197 data_stream << const_addr_man;
198}
199
200// Check that serialize followed by unserialize produces the same addrman.
202{
204 FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
206
210
211 DataStream data_stream{};
212
214 data_stream << addr_man1;
215 data_stream >> addr_man2;
216 assert(addr_man1 == addr_man2);
217}
void ReadFromStream(AddrMan &addr, DataStream &ssPeers)
Only used by tests.
Definition: addrdb.cpp:191
static int32_t GetCheckRatio(const NodeContext &node_ctx)
const TestingSetup * g_setup
Stochastic address manager.
Definition: addrman.h:110
void Connected(const CService &addr, NodeSeconds time=Now< NodeSeconds >())
We have successfully connected to this peer.
Definition: addrman.cpp:1322
void Attempt(const CService &addr, bool fCountFailure, NodeSeconds time=Now< NodeSeconds >())
Mark an entry as connection attempted to.
Definition: addrman.cpp:1292
size_t Size(std::optional< Network > net=std::nullopt, std::optional< bool > in_new=std::nullopt) const
Return size information about addrman.
Definition: addrman.cpp:1277
void ResolveCollisions()
See if any to-be-evicted tried table entries have been tested and if so resolve the collisions.
Definition: addrman.cpp:1297
bool Good(const CService &addr, NodeSeconds time=Now< NodeSeconds >())
Mark an address record as accessible and attempt to move it to addrman's tried table.
Definition: addrman.cpp:1287
std::pair< CAddress, NodeSeconds > SelectTriedCollision()
Randomly select an address in the tried table that another address is attempting to evict.
Definition: addrman.cpp:1302
bool Add(const std::vector< CAddress > &vAddr, const CNetAddr &source, std::chrono::seconds time_penalty=0s)
Attempt to add one or more addresses to addrman's new table.
Definition: addrman.cpp:1282
void SetServices(const CService &addr, ServiceFlags nServices)
Update an entry's service bits.
Definition: addrman.cpp:1327
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Definition: args.h:308
A CService with information about it as peer.
Definition: protocol.h:367
Network address.
Definition: netaddress.h:113
bool IsValid() const
Definition: netaddress.cpp:424
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:530
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:133
Fast randomness source.
Definition: random.h:386
T ConsumeIntegralInRange(T min, T max)
T PickValueInArray(const T(&array)[size])
Netgroup manager.
Definition: netgroup.h:17
Helper to initialize the global NodeClock, let a duration elapse, and reset it after use in a test.
Definition: time.h:40
#define LIMITED_WHILE(condition, limit)
Can be used to limit a theoretically unbounded loop.
Definition: fuzz.h:22
Definition: basic.cpp:8
@ NODE_NETWORK
Definition: protocol.h:315
const char * source
Definition: rpcconsole.cpp:62
Basic testing setup.
Definition: setup_common.h:61
node::NodeContext m_node
Definition: setup_common.h:63
ArgsManager * args
Definition: context.h:76
FUZZ_TARGET(data_stream_addr_man,.init=initialize_addrman)
Definition: addrman.cpp:43
void FillAddrman(AddrMan &addrman, FuzzedDataProvider &fuzzed_data_provider)
Fill addrman with lots of addresses from lots of sources.
Definition: addrman.cpp:82
CNetAddr RandAddr(FuzzedDataProvider &fuzzed_data_provider, FastRandomContext &fast_random_context)
Generate a random address.
Definition: addrman.cpp:59
void initialize_addrman()
Definition: addrman.cpp:37
CAddress ConsumeAddress(FuzzedDataProvider &fuzzed_data_provider) noexcept
Definition: net.cpp:88
CNetAddr ConsumeNetAddr(FuzzedDataProvider &fuzzed_data_provider, FastRandomContext *rand) noexcept
Create a CNetAddr.
Definition: net.cpp:29
CService ConsumeService(FuzzedDataProvider &fuzzed_data_provider) noexcept
Definition: net.h:250
NetGroupManager ConsumeNetGroupManager(FuzzedDataProvider &fuzzed_data_provider) noexcept
Definition: net.h:236
NodeSeconds ConsumeTime(FuzzedDataProvider &fuzzed_data_provider, const std::optional< int64_t > &min, const std::optional< int64_t > &max) noexcept
Definition: util.cpp:34
WeakEnumType ConsumeWeakEnum(FuzzedDataProvider &fuzzed_data_provider, const WeakEnumType(&all_types)[size]) noexcept
Definition: util.h:128
DataStream ConsumeDataStream(FuzzedDataProvider &fuzzed_data_provider, const std::optional< size_t > &max_length=std::nullopt) noexcept
Definition: util.h:68
uint256 ConsumeUInt256(FuzzedDataProvider &fuzzed_data_provider) noexcept
Definition: util.h:176
size_t CallOneOf(FuzzedDataProvider &fuzzed_data_provider, Callables... callables)
Definition: util.h:35
std::vector< B > ConsumeRandomLengthByteVector(FuzzedDataProvider &fuzzed_data_provider, const std::optional< size_t > &max_length=std::nullopt) noexcept
Definition: util.h:57
constexpr ServiceFlags ALL_SERVICE_FLAGS[]
Definition: net.h:121
constexpr auto ALL_NETWORKS
Definition: net.h:154
void SeedRandomStateForTest(SeedRand seedtype)
Seed the global RNG state for testing and log the seed value.
Definition: random.cpp:19
@ ZEROS
Seed with a compile time constant of zeros.
assert(!tx.IsCoinBase())
FuzzedDataProvider & fuzzed_data_provider
Definition: fees.cpp:39