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