Bitcoin Core  24.1.0
P2P Digital Currency
addrman.cpp
Go to the documentation of this file.
1 // Copyright (c) 2020-2021 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 <merkleblock.h>
10 #include <random.h>
12 #include <test/fuzz/fuzz.h>
13 #include <test/fuzz/util.h>
14 #include <test/util/setup_common.h>
15 #include <time.h>
16 #include <util/asmap.h>
17 #include <util/system.h>
18 
19 #include <cassert>
20 #include <cstdint>
21 #include <optional>
22 #include <string>
23 #include <vector>
24 
25 namespace {
26 const BasicTestingSetup* g_setup;
27 
28 int32_t GetCheckRatio()
29 {
30  return std::clamp<int32_t>(g_setup->m_node.args->GetIntArg("-checkaddrman", 0), 0, 1000000);
31 }
32 } // namespace
33 
35 {
36  static const auto testing_setup = MakeNoLogFileContext<>(CBaseChainParams::REGTEST);
37  g_setup = testing_setup.get();
38 }
39 
40 [[nodiscard]] inline NetGroupManager ConsumeNetGroupManager(FuzzedDataProvider& fuzzed_data_provider) noexcept
41 {
42  std::vector<bool> asmap = ConsumeRandomLengthBitVector(fuzzed_data_provider);
43  if (!SanityCheckASMap(asmap, 128)) asmap.clear();
44  return NetGroupManager(asmap);
45 }
46 
47 FUZZ_TARGET_INIT(data_stream_addr_man, initialize_addrman)
48 {
49  FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
50  CDataStream data_stream = ConsumeDataStream(fuzzed_data_provider);
51  NetGroupManager netgroupman{ConsumeNetGroupManager(fuzzed_data_provider)};
52  AddrMan addr_man(netgroupman, /*deterministic=*/false, GetCheckRatio());
53  try {
54  ReadFromStream(addr_man, data_stream);
55  } catch (const std::exception&) {
56  }
57 }
58 
62 CNetAddr RandAddr(FuzzedDataProvider& fuzzed_data_provider, FastRandomContext& fast_random_context)
63 {
64  CNetAddr addr;
65  if (fuzzed_data_provider.remaining_bytes() > 1 && fuzzed_data_provider.ConsumeBool()) {
66  addr = ConsumeNetAddr(fuzzed_data_provider);
67  } else {
68  // The networks [1..6] correspond to CNetAddr::BIP155Network (private).
69  static const std::map<uint8_t, uint8_t> net_len_map = {{1, ADDR_IPV4_SIZE},
70  {2, ADDR_IPV6_SIZE},
71  {4, ADDR_TORV3_SIZE},
72  {5, ADDR_I2P_SIZE},
73  {6, ADDR_CJDNS_SIZE}};
74  uint8_t net = fast_random_context.randrange(5) + 1; // [1..5]
75  if (net == 3) {
76  net = 6;
77  }
78 
80 
81  s << net;
82  s << fast_random_context.randbytes(net_len_map.at(net));
83 
84  s >> addr;
85  }
86 
87  // Return a dummy IPv4 5.5.5.5 if we generated an invalid address.
88  if (!addr.IsValid()) {
89  in_addr v4_addr = {};
90  v4_addr.s_addr = 0x05050505;
91  addr = CNetAddr{v4_addr};
92  }
93 
94  return addr;
95 }
96 
98 void FillAddrman(AddrMan& addrman, FuzzedDataProvider& fuzzed_data_provider)
99 {
100  // Add a fraction of the addresses to the "tried" table.
101  // 0, 1, 2, 3 corresponding to 0%, 100%, 50%, 33%
102  const size_t n = fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, 3);
103 
104  const size_t num_sources = fuzzed_data_provider.ConsumeIntegralInRange<size_t>(1, 50);
105  CNetAddr prev_source;
106  // Generate a FastRandomContext seed to use inside the loops instead of
107  // fuzzed_data_provider. When fuzzed_data_provider is exhausted it
108  // just returns 0.
109  FastRandomContext fast_random_context{ConsumeUInt256(fuzzed_data_provider)};
110  for (size_t i = 0; i < num_sources; ++i) {
111  const auto source = RandAddr(fuzzed_data_provider, fast_random_context);
112  const size_t num_addresses = fast_random_context.randrange(500) + 1; // [1..500]
113 
114  for (size_t j = 0; j < num_addresses; ++j) {
115  const auto addr = CAddress{CService{RandAddr(fuzzed_data_provider, fast_random_context), 8333}, NODE_NETWORK};
116  const std::chrono::seconds time_penalty{fast_random_context.randrange(100000001)};
117  addrman.Add({addr}, source, time_penalty);
118 
119  if (n > 0 && addrman.size() % n == 0) {
120  addrman.Good(addr, Now<NodeSeconds>());
121  }
122 
123  // Add 10% of the addresses from more than one source.
124  if (fast_random_context.randrange(10) == 0 && prev_source.IsValid()) {
125  addrman.Add({addr}, prev_source, time_penalty);
126  }
127  }
128  prev_source = source;
129  }
130 }
131 
133 {
134 public:
135  explicit AddrManDeterministic(const NetGroupManager& netgroupman, FuzzedDataProvider& fuzzed_data_provider)
136  : AddrMan(netgroupman, /*deterministic=*/true, GetCheckRatio())
137  {
138  WITH_LOCK(m_impl->cs, m_impl->insecure_rand = FastRandomContext{ConsumeUInt256(fuzzed_data_provider)});
139  }
140 
148  bool operator==(const AddrManDeterministic& other) const
149  {
150  LOCK2(m_impl->cs, other.m_impl->cs);
151 
152  if (m_impl->mapInfo.size() != other.m_impl->mapInfo.size() || m_impl->nNew != other.m_impl->nNew ||
153  m_impl->nTried != other.m_impl->nTried) {
154  return false;
155  }
156 
157  // Check that all values in `mapInfo` are equal to all values in `other.mapInfo`.
158  // Keys may be different.
159 
160  auto addrinfo_hasher = [](const AddrInfo& a) {
161  CSipHasher hasher(0, 0);
162  auto addr_key = a.GetKey();
163  auto source_key = a.source.GetAddrBytes();
164  hasher.Write(TicksSinceEpoch<std::chrono::seconds>(a.m_last_success));
165  hasher.Write(a.nAttempts);
166  hasher.Write(a.nRefCount);
167  hasher.Write(a.fInTried);
168  hasher.Write(a.GetNetwork());
169  hasher.Write(a.source.GetNetwork());
170  hasher.Write(addr_key.size());
171  hasher.Write(source_key.size());
172  hasher.Write(addr_key.data(), addr_key.size());
173  hasher.Write(source_key.data(), source_key.size());
174  return (size_t)hasher.Finalize();
175  };
176 
177  auto addrinfo_eq = [](const AddrInfo& lhs, const AddrInfo& rhs) {
178  return std::tie(static_cast<const CService&>(lhs), lhs.source, lhs.m_last_success, lhs.nAttempts, lhs.nRefCount, lhs.fInTried) ==
179  std::tie(static_cast<const CService&>(rhs), rhs.source, rhs.m_last_success, rhs.nAttempts, rhs.nRefCount, rhs.fInTried);
180  };
181 
182  using Addresses = std::unordered_set<AddrInfo, decltype(addrinfo_hasher), decltype(addrinfo_eq)>;
183 
184  const size_t num_addresses{m_impl->mapInfo.size()};
185 
186  Addresses addresses{num_addresses, addrinfo_hasher, addrinfo_eq};
187  for (const auto& [id, addr] : m_impl->mapInfo) {
188  addresses.insert(addr);
189  }
190 
191  Addresses other_addresses{num_addresses, addrinfo_hasher, addrinfo_eq};
192  for (const auto& [id, addr] : other.m_impl->mapInfo) {
193  other_addresses.insert(addr);
194  }
195 
196  if (addresses != other_addresses) {
197  return false;
198  }
199 
200  auto IdsReferToSameAddress = [&](int id, int other_id) EXCLUSIVE_LOCKS_REQUIRED(m_impl->cs, other.m_impl->cs) {
201  if (id == -1 && other_id == -1) {
202  return true;
203  }
204  if ((id == -1 && other_id != -1) || (id != -1 && other_id == -1)) {
205  return false;
206  }
207  return m_impl->mapInfo.at(id) == other.m_impl->mapInfo.at(other_id);
208  };
209 
210  // Check that `vvNew` contains the same addresses as `other.vvNew`. Notice - `vvNew[i][j]`
211  // contains just an id and the address is to be found in `mapInfo.at(id)`. The ids
212  // themselves may differ between `vvNew` and `other.vvNew`.
213  for (size_t i = 0; i < ADDRMAN_NEW_BUCKET_COUNT; ++i) {
214  for (size_t j = 0; j < ADDRMAN_BUCKET_SIZE; ++j) {
215  if (!IdsReferToSameAddress(m_impl->vvNew[i][j], other.m_impl->vvNew[i][j])) {
216  return false;
217  }
218  }
219  }
220 
221  // Same for `vvTried`.
222  for (size_t i = 0; i < ADDRMAN_TRIED_BUCKET_COUNT; ++i) {
223  for (size_t j = 0; j < ADDRMAN_BUCKET_SIZE; ++j) {
224  if (!IdsReferToSameAddress(m_impl->vvTried[i][j], other.m_impl->vvTried[i][j])) {
225  return false;
226  }
227  }
228  }
229 
230  return true;
231  }
232 };
233 
235 {
236  FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
237  SetMockTime(ConsumeTime(fuzzed_data_provider));
238  NetGroupManager netgroupman{ConsumeNetGroupManager(fuzzed_data_provider)};
239  auto addr_man_ptr = std::make_unique<AddrManDeterministic>(netgroupman, fuzzed_data_provider);
240  if (fuzzed_data_provider.ConsumeBool()) {
241  const std::vector<uint8_t> serialized_data{ConsumeRandomLengthByteVector(fuzzed_data_provider)};
242  CDataStream ds(serialized_data, SER_DISK, INIT_PROTO_VERSION);
243  const auto ser_version{fuzzed_data_provider.ConsumeIntegral<int32_t>()};
244  ds.SetVersion(ser_version);
245  try {
246  ds >> *addr_man_ptr;
247  } catch (const std::ios_base::failure&) {
248  addr_man_ptr = std::make_unique<AddrManDeterministic>(netgroupman, fuzzed_data_provider);
249  }
250  }
251  AddrManDeterministic& addr_man = *addr_man_ptr;
252  LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 10000) {
253  CallOneOf(
254  fuzzed_data_provider,
255  [&] {
256  addr_man.ResolveCollisions();
257  },
258  [&] {
259  (void)addr_man.SelectTriedCollision();
260  },
261  [&] {
262  std::vector<CAddress> addresses;
263  LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 10000) {
264  const std::optional<CAddress> opt_address = ConsumeDeserializable<CAddress>(fuzzed_data_provider);
265  if (!opt_address) {
266  break;
267  }
268  addresses.push_back(*opt_address);
269  }
270  const std::optional<CNetAddr> opt_net_addr = ConsumeDeserializable<CNetAddr>(fuzzed_data_provider);
271  if (opt_net_addr) {
272  addr_man.Add(addresses, *opt_net_addr, std::chrono::seconds{ConsumeTime(fuzzed_data_provider, 0, 100000000)});
273  }
274  },
275  [&] {
276  const std::optional<CService> opt_service = ConsumeDeserializable<CService>(fuzzed_data_provider);
277  if (opt_service) {
278  addr_man.Good(*opt_service, NodeSeconds{std::chrono::seconds{ConsumeTime(fuzzed_data_provider)}});
279  }
280  },
281  [&] {
282  const std::optional<CService> opt_service = ConsumeDeserializable<CService>(fuzzed_data_provider);
283  if (opt_service) {
284  addr_man.Attempt(*opt_service, fuzzed_data_provider.ConsumeBool(), NodeSeconds{std::chrono::seconds{ConsumeTime(fuzzed_data_provider)}});
285  }
286  },
287  [&] {
288  const std::optional<CService> opt_service = ConsumeDeserializable<CService>(fuzzed_data_provider);
289  if (opt_service) {
290  addr_man.Connected(*opt_service, NodeSeconds{std::chrono::seconds{ConsumeTime(fuzzed_data_provider)}});
291  }
292  },
293  [&] {
294  const std::optional<CService> opt_service = ConsumeDeserializable<CService>(fuzzed_data_provider);
295  if (opt_service) {
296  addr_man.SetServices(*opt_service, ConsumeWeakEnum(fuzzed_data_provider, ALL_SERVICE_FLAGS));
297  }
298  });
299  }
300  const AddrMan& const_addr_man{addr_man};
301  (void)const_addr_man.GetAddr(
302  /*max_addresses=*/fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, 4096),
303  /*max_pct=*/fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, 4096),
304  /*network=*/std::nullopt);
305  (void)const_addr_man.Select(fuzzed_data_provider.ConsumeBool());
306  (void)const_addr_man.size();
308  data_stream << const_addr_man;
309 }
310 
311 // Check that serialize followed by unserialize produces the same addrman.
313 {
314  FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
315  SetMockTime(ConsumeTime(fuzzed_data_provider));
316 
317  NetGroupManager netgroupman{ConsumeNetGroupManager(fuzzed_data_provider)};
318  AddrManDeterministic addr_man1{netgroupman, fuzzed_data_provider};
319  AddrManDeterministic addr_man2{netgroupman, fuzzed_data_provider};
320 
322 
323  FillAddrman(addr_man1, fuzzed_data_provider);
324  data_stream << addr_man1;
325  data_stream >> addr_man2;
326  assert(addr_man1 == addr_man2);
327 }
const std::unique_ptr< AddrManImpl > m_impl
Definition: addrman.h:89
void ReadFromStream(AddrMan &addr, CDataStream &ssPeers)
Only used by tests.
Definition: addrdb.cpp:179
assert(!tx.IsCoinBase())
CSipHasher & Write(uint64_t data)
Hash a 64-bit integer worth of data It is treated as if this was the little-endian interpretation of ...
Definition: siphash.cpp:28
static const std::string REGTEST
CDataStream ConsumeDataStream(FuzzedDataProvider &fuzzed_data_provider, const std::optional< size_t > &max_length=std::nullopt) noexcept
Definition: util.h:123
static constexpr int ADDRMAN_BUCKET_SIZE
Definition: addrman_impl.h:34
WeakEnumType ConsumeWeakEnum(FuzzedDataProvider &fuzzed_data_provider, const WeakEnumType(&all_types)[size]) noexcept
Definition: util.h:164
bool SanityCheckASMap(const std::vector< bool > &asmap, int bits)
Definition: asmap.cpp:133
static constexpr size_t ADDR_TORV3_SIZE
Size of TORv3 address (in bytes).
Definition: netaddress.h:100
static constexpr int ADDRMAN_TRIED_BUCKET_COUNT
Definition: addrman_impl.h:28
static constexpr size_t ADDR_IPV4_SIZE
Size of IPv4 address (in bytes).
Definition: netaddress.h:93
#define LIMITED_WHILE(condition, limit)
Can be used to limit a theoretically unbounded loop.
Definition: fuzz.h:18
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:185
Netgroup manager.
Definition: netgroup.h:16
void ResolveCollisions()
See if any to-be-evicted tried table entries have been tested and if so resolve the collisions...
Definition: addrman.cpp:1208
Stochastic address manager.
Definition: addrman.h:86
Basic testing setup.
Definition: setup_common.h:83
bool IsValid() const
Definition: netaddress.cpp:445
static constexpr size_t ADDR_CJDNS_SIZE
Size of CJDNS address (in bytes).
Definition: netaddress.h:106
static constexpr int ADDRV2_FORMAT
A flag that is ORed into the protocol version to designate that addresses should be serialized in (un...
Definition: netaddress.h:33
std::chrono::time_point< NodeClock, std::chrono::seconds > NodeSeconds
Definition: time.h:25
constexpr ServiceFlags ALL_SERVICE_FLAGS[]
Definition: net.h:56
void SetMockTime(int64_t nMockTimeIn)
DEPRECATED Use SetMockTime with chrono type.
Definition: time.cpp:91
int nAttempts
connection attempts since last successful attempt
Definition: addrman_impl.h:55
#define LOCK2(cs1, cs2)
Definition: sync.h:262
const char * source
Definition: rpcconsole.cpp:59
static constexpr size_t ADDR_IPV6_SIZE
Size of IPv6 address (in bytes).
Definition: netaddress.h:96
void initialize_addrman()
Definition: addrman.cpp:34
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&#39;s new table.
Definition: addrman.cpp:1193
int nRefCount
reference count in new sets (memory only)
Definition: addrman_impl.h:58
static constexpr size_t ADDR_I2P_SIZE
Size of I2P address (in bytes).
Definition: netaddress.h:103
void FillAddrman(AddrMan &addrman, FuzzedDataProvider &fuzzed_data_provider)
Fill addrman with lots of addresses from lots of sources.
Definition: addrman.cpp:98
ArgsManager * args
Definition: context.h:56
static const int INIT_PROTO_VERSION
initial proto version, to be increased after version/verack negotiation
Definition: version.h:15
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:520
Fast randomness source.
Definition: random.h:142
Extended statistics about a CAddress.
Definition: addrman_impl.h:39
void Attempt(const CService &addr, bool fCountFailure, NodeSeconds time=Now< NodeSeconds >())
Mark an entry as connection attempted to.
Definition: addrman.cpp:1203
CNetAddr ConsumeNetAddr(FuzzedDataProvider &fuzzed_data_provider) noexcept
Definition: util.cpp:507
A CService with information about it as peer.
Definition: protocol.h:354
void Connected(const CService &addr, NodeSeconds time=Now< NodeSeconds >())
We have successfully connected to this peer.
Definition: addrman.cpp:1228
std::vector< bool > ConsumeRandomLengthBitVector(FuzzedDataProvider &fuzzed_data_provider, const std::optional< size_t > &max_length=std::nullopt) noexcept
Definition: util.h:118
std::vector< uint8_t > ConsumeRandomLengthByteVector(FuzzedDataProvider &fuzzed_data_provider, const std::optional< size_t > &max_length=std::nullopt) noexcept
Definition: util.h:110
uint64_t Finalize() const
Compute the 64-bit SipHash-2-4 of the data written so far.
Definition: siphash.cpp:76
std::vector< CAddress > GetAddr(size_t max_addresses, size_t max_pct, std::optional< Network > network) const
Return all or many randomly selected addresses, optionally by network.
Definition: addrman.cpp:1223
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:305
NetGroupManager ConsumeNetGroupManager(FuzzedDataProvider &fuzzed_data_provider) noexcept
Definition: addrman.cpp:40
CNetAddr source
where knowledge about this address first came from
Definition: addrman_impl.h:49
Network address.
Definition: netaddress.h:117
std::pair< CAddress, NodeSeconds > SelectTriedCollision()
Randomly select an address in the tried table that another address is attempting to evict...
Definition: addrman.cpp:1213
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
int64_t ConsumeTime(FuzzedDataProvider &fuzzed_data_provider, const std::optional< int64_t > &min, const std::optional< int64_t > &max) noexcept
Definition: util.cpp:307
static constexpr int ADDRMAN_NEW_BUCKET_COUNT
Definition: addrman_impl.h:31
bool operator==(const AddrManDeterministic &other) const
Compare with another AddrMan.
Definition: addrman.cpp:148
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:12
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Definition: system.cpp:629
AddrManDeterministic(const NetGroupManager &netgroupman, FuzzedDataProvider &fuzzed_data_provider)
Definition: addrman.cpp:135
void SetServices(const CService &addr, ServiceFlags nServices)
Update an entry&#39;s service bits.
Definition: addrman.cpp:1233
static int32_t GetCheckRatio(const NodeContext &node_ctx)
SipHash-2-4.
Definition: siphash.h:13
size_t size() const
Return the number of (unique) addresses in all tables.
Definition: addrman.cpp:1188
bool fInTried
in tried set? (memory only)
Definition: addrman_impl.h:61
size_t CallOneOf(FuzzedDataProvider &fuzzed_data_provider, Callables... callables)
Definition: util.h:89
CNetAddr RandAddr(FuzzedDataProvider &fuzzed_data_provider, FastRandomContext &fast_random_context)
Generate a random address.
Definition: addrman.cpp:62
T ConsumeIntegralInRange(T min, T max)
bool Good(const CService &addr, NodeSeconds time=Now< NodeSeconds >())
Mark an address record as accessible and attempt to move it to addrman&#39;s tried table.
Definition: addrman.cpp:1198
uint256 ConsumeUInt256(FuzzedDataProvider &fuzzed_data_provider) noexcept
Definition: util.h:202
void SetVersion(int n)
Definition: streams.h:277
node::NodeContext m_node
Definition: setup_common.h:84
NodeSeconds m_last_success
last successful connection by us
Definition: addrman_impl.h:52
uint64_t randrange(uint64_t range) noexcept
Generate a random integer in the range [0..range).
Definition: random.h:213
std::vector< unsigned char > randbytes(size_t len)
Generate random bytes.
Definition: random.cpp:617
FUZZ_TARGET_INIT(data_stream_addr_man, initialize_addrman)
Definition: addrman.cpp:47