Bitcoin Core  22.99.0
P2P Digital Currency
util.cpp
Go to the documentation of this file.
1 // Copyright (c) 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 <consensus/amount.h>
6 #include <net_processing.h>
7 #include <netmessagemaker.h>
8 #include <pubkey.h>
9 #include <test/fuzz/util.h>
10 #include <test/util/script.h>
11 #include <util/overflow.h>
12 #include <util/rbf.h>
13 #include <util/time.h>
14 #include <version.h>
15 
16 #include <memory>
17 
19  : m_fuzzed_data_provider{fuzzed_data_provider}
20 {
21  m_socket = fuzzed_data_provider.ConsumeIntegralInRange<SOCKET>(INVALID_SOCKET - 1, INVALID_SOCKET);
22 }
23 
25 {
26  // Sock::~Sock() will be called after FuzzedSock::~FuzzedSock() and it will call
27  // Sock::Reset() (not FuzzedSock::Reset()!) which will call CloseSocket(m_socket).
28  // Avoid closing an arbitrary file descriptor (m_socket is just a random very high number which
29  // theoretically may concide with a real opened file descriptor).
30  Reset();
31 }
32 
34 {
35  assert(false && "Move of Sock into FuzzedSock not allowed.");
36  return *this;
37 }
38 
40 {
42 }
43 
44 ssize_t FuzzedSock::Send(const void* data, size_t len, int flags) const
45 {
46  constexpr std::array send_errnos{
47  EACCES,
48  EAGAIN,
49  EALREADY,
50  EBADF,
51  ECONNRESET,
52  EDESTADDRREQ,
53  EFAULT,
54  EINTR,
55  EINVAL,
56  EISCONN,
57  EMSGSIZE,
58  ENOBUFS,
59  ENOMEM,
60  ENOTCONN,
61  ENOTSOCK,
62  EOPNOTSUPP,
63  EPIPE,
64  EWOULDBLOCK,
65  };
67  return len;
68  }
69  const ssize_t r = m_fuzzed_data_provider.ConsumeIntegralInRange<ssize_t>(-1, len);
70  if (r == -1) {
72  }
73  return r;
74 }
75 
76 ssize_t FuzzedSock::Recv(void* buf, size_t len, int flags) const
77 {
78  // Have a permanent error at recv_errnos[0] because when the fuzzed data is exhausted
79  // SetFuzzedErrNo() will always return the first element and we want to avoid Recv()
80  // returning -1 and setting errno to EAGAIN repeatedly.
81  constexpr std::array recv_errnos{
82  ECONNREFUSED,
83  EAGAIN,
84  EBADF,
85  EFAULT,
86  EINTR,
87  EINVAL,
88  ENOMEM,
89  ENOTCONN,
90  ENOTSOCK,
91  EWOULDBLOCK,
92  };
93  assert(buf != nullptr || len == 0);
94  if (len == 0 || m_fuzzed_data_provider.ConsumeBool()) {
95  const ssize_t r = m_fuzzed_data_provider.ConsumeBool() ? 0 : -1;
96  if (r == -1) {
98  }
99  return r;
100  }
101  std::vector<uint8_t> random_bytes;
102  bool pad_to_len_bytes{m_fuzzed_data_provider.ConsumeBool()};
103  if (m_peek_data.has_value()) {
104  // `MSG_PEEK` was used in the preceding `Recv()` call, return `m_peek_data`.
105  random_bytes.assign({m_peek_data.value()});
106  if ((flags & MSG_PEEK) == 0) {
107  m_peek_data.reset();
108  }
109  pad_to_len_bytes = false;
110  } else if ((flags & MSG_PEEK) != 0) {
111  // New call with `MSG_PEEK`.
112  random_bytes = m_fuzzed_data_provider.ConsumeBytes<uint8_t>(1);
113  if (!random_bytes.empty()) {
114  m_peek_data = random_bytes[0];
115  pad_to_len_bytes = false;
116  }
117  } else {
118  random_bytes = m_fuzzed_data_provider.ConsumeBytes<uint8_t>(
120  }
121  if (random_bytes.empty()) {
122  const ssize_t r = m_fuzzed_data_provider.ConsumeBool() ? 0 : -1;
123  if (r == -1) {
125  }
126  return r;
127  }
128  std::memcpy(buf, random_bytes.data(), random_bytes.size());
129  if (pad_to_len_bytes) {
130  if (len > random_bytes.size()) {
131  std::memset((char*)buf + random_bytes.size(), 0, len - random_bytes.size());
132  }
133  return len;
134  }
135  if (m_fuzzed_data_provider.ConsumeBool() && std::getenv("FUZZED_SOCKET_FAKE_LATENCY") != nullptr) {
136  std::this_thread::sleep_for(std::chrono::milliseconds{2});
137  }
138  return random_bytes.size();
139 }
140 
141 int FuzzedSock::Connect(const sockaddr*, socklen_t) const
142 {
143  // Have a permanent error at connect_errnos[0] because when the fuzzed data is exhausted
144  // SetFuzzedErrNo() will always return the first element and we want to avoid Connect()
145  // returning -1 and setting errno to EAGAIN repeatedly.
146  constexpr std::array connect_errnos{
147  ECONNREFUSED,
148  EAGAIN,
149  ECONNRESET,
150  EHOSTUNREACH,
151  EINPROGRESS,
152  EINTR,
153  ENETUNREACH,
154  ETIMEDOUT,
155  };
157  SetFuzzedErrNo(m_fuzzed_data_provider, connect_errnos);
158  return -1;
159  }
160  return 0;
161 }
162 
163 std::unique_ptr<Sock> FuzzedSock::Accept(sockaddr* addr, socklen_t* addr_len) const
164 {
165  constexpr std::array accept_errnos{
166  ECONNABORTED,
167  EINTR,
168  ENOMEM,
169  };
171  SetFuzzedErrNo(m_fuzzed_data_provider, accept_errnos);
172  return std::unique_ptr<FuzzedSock>();
173  }
174  return std::make_unique<FuzzedSock>(m_fuzzed_data_provider);
175 }
176 
177 int FuzzedSock::GetSockOpt(int level, int opt_name, void* opt_val, socklen_t* opt_len) const
178 {
179  constexpr std::array getsockopt_errnos{
180  ENOMEM,
181  ENOBUFS,
182  };
184  SetFuzzedErrNo(m_fuzzed_data_provider, getsockopt_errnos);
185  return -1;
186  }
187  if (opt_val == nullptr) {
188  return 0;
189  }
190  std::memcpy(opt_val,
192  *opt_len);
193  return 0;
194 }
195 
196 bool FuzzedSock::Wait(std::chrono::milliseconds timeout, Event requested, Event* occurred) const
197 {
198  constexpr std::array wait_errnos{
199  EBADF,
200  EINTR,
201  EINVAL,
202  };
205  return false;
206  }
207  if (occurred != nullptr) {
208  *occurred = m_fuzzed_data_provider.ConsumeBool() ? requested : 0;
209  }
210  return true;
211 }
212 
213 bool FuzzedSock::IsConnected(std::string& errmsg) const
214 {
216  return true;
217  }
218  errmsg = "disconnected at random by the fuzzer";
219  return false;
220 }
221 
222 void FillNode(FuzzedDataProvider& fuzzed_data_provider, ConnmanTestMsg& connman, PeerManager& peerman, CNode& node) noexcept
223 {
224  const bool successfully_connected{fuzzed_data_provider.ConsumeBool()};
225  const ServiceFlags remote_services = ConsumeWeakEnum(fuzzed_data_provider, ALL_SERVICE_FLAGS);
226  const NetPermissionFlags permission_flags = ConsumeWeakEnum(fuzzed_data_provider, ALL_NET_PERMISSION_FLAGS);
227  const int32_t version = fuzzed_data_provider.ConsumeIntegralInRange<int32_t>(MIN_PEER_PROTO_VERSION, std::numeric_limits<int32_t>::max());
228  const bool filter_txs = fuzzed_data_provider.ConsumeBool();
229 
230  const CNetMsgMaker mm{0};
231 
232  CSerializedNetMsg msg_version{
233  mm.Make(NetMsgType::VERSION,
234  version, //
235  Using<CustomUintFormatter<8>>(remote_services), //
236  int64_t{}, // dummy time
237  int64_t{}, // ignored service bits
238  CService{}, // dummy
239  int64_t{}, // ignored service bits
240  CService{}, // ignored
241  uint64_t{1}, // dummy nonce
242  std::string{}, // dummy subver
243  int32_t{}, // dummy starting_height
244  filter_txs),
245  };
246 
247  (void)connman.ReceiveMsgFrom(node, msg_version);
248  node.fPauseSend = false;
249  connman.ProcessMessagesOnce(node);
250  {
251  LOCK(node.cs_sendProcessing);
252  peerman.SendMessages(&node);
253  }
254  if (node.fDisconnect) return;
255  assert(node.nVersion == version);
256  assert(node.GetCommonVersion() == std::min(version, PROTOCOL_VERSION));
257  assert(node.nServices == remote_services);
258  if (node.m_tx_relay != nullptr) {
259  LOCK(node.m_tx_relay->cs_filter);
260  assert(node.m_tx_relay->fRelayTxes == filter_txs);
261  }
262  node.m_permissionFlags = permission_flags;
263  if (successfully_connected) {
264  CSerializedNetMsg msg_verack{mm.Make(NetMsgType::VERACK)};
265  (void)connman.ReceiveMsgFrom(node, msg_verack);
266  node.fPauseSend = false;
267  connman.ProcessMessagesOnce(node);
268  {
269  LOCK(node.cs_sendProcessing);
270  peerman.SendMessages(&node);
271  }
272  assert(node.fSuccessfullyConnected == true);
273  }
274 }
275 
276 CAmount ConsumeMoney(FuzzedDataProvider& fuzzed_data_provider, const std::optional<CAmount>& max) noexcept
277 {
278  return fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(0, max.value_or(MAX_MONEY));
279 }
280 
281 int64_t ConsumeTime(FuzzedDataProvider& fuzzed_data_provider, const std::optional<int64_t>& min, const std::optional<int64_t>& max) noexcept
282 {
283  // Avoid t=0 (1970-01-01T00:00:00Z) since SetMockTime(0) disables mocktime.
284  static const int64_t time_min{ParseISO8601DateTime("2000-01-01T00:00:01Z")};
285  static const int64_t time_max{ParseISO8601DateTime("2100-12-31T23:59:59Z")};
286  return fuzzed_data_provider.ConsumeIntegralInRange<int64_t>(min.value_or(time_min), max.value_or(time_max));
287 }
288 
289 CMutableTransaction ConsumeTransaction(FuzzedDataProvider& fuzzed_data_provider, const std::optional<std::vector<uint256>>& prevout_txids, const int max_num_in, const int max_num_out) noexcept
290 {
291  CMutableTransaction tx_mut;
292  const auto p2wsh_op_true = fuzzed_data_provider.ConsumeBool();
293  tx_mut.nVersion = fuzzed_data_provider.ConsumeBool() ?
295  fuzzed_data_provider.ConsumeIntegral<int32_t>();
296  tx_mut.nLockTime = fuzzed_data_provider.ConsumeIntegral<uint32_t>();
297  const auto num_in = fuzzed_data_provider.ConsumeIntegralInRange<int>(0, max_num_in);
298  const auto num_out = fuzzed_data_provider.ConsumeIntegralInRange<int>(0, max_num_out);
299  for (int i = 0; i < num_in; ++i) {
300  const auto& txid_prev = prevout_txids ?
301  PickValue(fuzzed_data_provider, *prevout_txids) :
302  ConsumeUInt256(fuzzed_data_provider);
303  const auto index_out = fuzzed_data_provider.ConsumeIntegralInRange<uint32_t>(0, max_num_out);
304  const auto sequence = ConsumeSequence(fuzzed_data_provider);
305  const auto script_sig = p2wsh_op_true ? CScript{} : ConsumeScript(fuzzed_data_provider);
306  CScriptWitness script_wit;
307  if (p2wsh_op_true) {
308  script_wit.stack = std::vector<std::vector<uint8_t>>{WITNESS_STACK_ELEM_OP_TRUE};
309  } else {
310  script_wit = ConsumeScriptWitness(fuzzed_data_provider);
311  }
312  CTxIn in;
313  in.prevout = COutPoint{txid_prev, index_out};
314  in.nSequence = sequence;
315  in.scriptSig = script_sig;
316  in.scriptWitness = script_wit;
317 
318  tx_mut.vin.push_back(in);
319  }
320  for (int i = 0; i < num_out; ++i) {
321  const auto amount = fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(-10, 50 * COIN + 10);
322  const auto script_pk = p2wsh_op_true ?
323  P2WSH_OP_TRUE :
324  ConsumeScript(fuzzed_data_provider, /*maybe_p2wsh=*/true);
325  tx_mut.vout.emplace_back(amount, script_pk);
326  }
327  return tx_mut;
328 }
329 
330 CScriptWitness ConsumeScriptWitness(FuzzedDataProvider& fuzzed_data_provider, const size_t max_stack_elem_size) noexcept
331 {
332  CScriptWitness ret;
333  const auto n_elements = fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, max_stack_elem_size);
334  for (size_t i = 0; i < n_elements; ++i) {
335  ret.stack.push_back(ConsumeRandomLengthByteVector(fuzzed_data_provider));
336  }
337  return ret;
338 }
339 
340 CScript ConsumeScript(FuzzedDataProvider& fuzzed_data_provider, const bool maybe_p2wsh) noexcept
341 {
342  CScript r_script{};
343  {
344  // Keep a buffer of bytes to allow the fuzz engine to produce smaller
345  // inputs to generate CScripts with repeated data.
346  static constexpr unsigned MAX_BUFFER_SZ{128};
347  std::vector<uint8_t> buffer(MAX_BUFFER_SZ, uint8_t{'a'});
348  while (fuzzed_data_provider.ConsumeBool()) {
349  CallOneOf(
350  fuzzed_data_provider,
351  [&] {
352  // Insert byte vector directly to allow malformed or unparsable scripts
353  r_script.insert(r_script.end(), buffer.begin(), buffer.begin() + fuzzed_data_provider.ConsumeIntegralInRange(0U, MAX_BUFFER_SZ));
354  },
355  [&] {
356  // Push a byte vector from the buffer
357  r_script << std::vector<uint8_t>{buffer.begin(), buffer.begin() + fuzzed_data_provider.ConsumeIntegralInRange(0U, MAX_BUFFER_SZ)};
358  },
359  [&] {
360  // Push multisig
361  // There is a special case for this to aid the fuzz engine
362  // navigate the highly structured multisig format.
363  r_script << fuzzed_data_provider.ConsumeIntegralInRange<int64_t>(0, 22);
364  int num_data{fuzzed_data_provider.ConsumeIntegralInRange(1, 22)};
365  std::vector<uint8_t> pubkey_comp{buffer.begin(), buffer.begin() + CPubKey::COMPRESSED_SIZE};
366  pubkey_comp.front() = fuzzed_data_provider.ConsumeIntegralInRange(2, 3); // Set first byte for GetLen() to pass
367  std::vector<uint8_t> pubkey_uncomp{buffer.begin(), buffer.begin() + CPubKey::SIZE};
368  pubkey_uncomp.front() = fuzzed_data_provider.ConsumeIntegralInRange(4, 7); // Set first byte for GetLen() to pass
369  while (num_data--) {
370  auto& pubkey{fuzzed_data_provider.ConsumeBool() ? pubkey_uncomp : pubkey_comp};
371  if (fuzzed_data_provider.ConsumeBool()) {
372  pubkey.back() = num_data; // Make each pubkey different
373  }
374  r_script << pubkey;
375  }
376  r_script << fuzzed_data_provider.ConsumeIntegralInRange<int64_t>(0, 22);
377  },
378  [&] {
379  // Mutate the buffer
380  const auto vec{ConsumeRandomLengthByteVector(fuzzed_data_provider, /*max_length=*/MAX_BUFFER_SZ)};
381  std::copy(vec.begin(), vec.end(), buffer.begin());
382  },
383  [&] {
384  // Push an integral
385  r_script << fuzzed_data_provider.ConsumeIntegral<int64_t>();
386  },
387  [&] {
388  // Push an opcode
389  r_script << ConsumeOpcodeType(fuzzed_data_provider);
390  },
391  [&] {
392  // Push a scriptnum
393  r_script << ConsumeScriptNum(fuzzed_data_provider);
394  });
395  }
396  }
397  if (maybe_p2wsh && fuzzed_data_provider.ConsumeBool()) {
398  uint256 script_hash;
399  CSHA256().Write(r_script.data(), r_script.size()).Finalize(script_hash.begin());
400  r_script.clear();
401  r_script << OP_0 << ToByteVector(script_hash);
402  }
403  return r_script;
404 }
405 
406 uint32_t ConsumeSequence(FuzzedDataProvider& fuzzed_data_provider) noexcept
407 {
408  return fuzzed_data_provider.ConsumeBool() ?
409  fuzzed_data_provider.PickValueInArray({
413  }) :
414  fuzzed_data_provider.ConsumeIntegral<uint32_t>();
415 }
416 
418 {
419  CTxDestination tx_destination;
420  const size_t call_size{CallOneOf(
421  fuzzed_data_provider,
422  [&] {
423  tx_destination = CNoDestination{};
424  },
425  [&] {
426  tx_destination = PKHash{ConsumeUInt160(fuzzed_data_provider)};
427  },
428  [&] {
429  tx_destination = ScriptHash{ConsumeUInt160(fuzzed_data_provider)};
430  },
431  [&] {
432  tx_destination = WitnessV0ScriptHash{ConsumeUInt256(fuzzed_data_provider)};
433  },
434  [&] {
435  tx_destination = WitnessV0KeyHash{ConsumeUInt160(fuzzed_data_provider)};
436  },
437  [&] {
438  tx_destination = WitnessV1Taproot{XOnlyPubKey{ConsumeUInt256(fuzzed_data_provider)}};
439  },
440  [&] {
441  WitnessUnknown witness_unknown{};
442  witness_unknown.version = fuzzed_data_provider.ConsumeIntegralInRange(2, 16);
443  std::vector<uint8_t> witness_unknown_program_1{fuzzed_data_provider.ConsumeBytes<uint8_t>(40)};
444  if (witness_unknown_program_1.size() < 2) {
445  witness_unknown_program_1 = {0, 0};
446  }
447  witness_unknown.length = witness_unknown_program_1.size();
448  std::copy(witness_unknown_program_1.begin(), witness_unknown_program_1.end(), witness_unknown.program);
449  tx_destination = witness_unknown;
450  })};
451  Assert(call_size == std::variant_size_v<CTxDestination>);
452  return tx_destination;
453 }
454 
455 CTxMemPoolEntry ConsumeTxMemPoolEntry(FuzzedDataProvider& fuzzed_data_provider, const CTransaction& tx) noexcept
456 {
457  // Avoid:
458  // policy/feerate.cpp:28:34: runtime error: signed integer overflow: 34873208148477500 * 1000 cannot be represented in type 'long'
459  //
460  // Reproduce using CFeeRate(348732081484775, 10).GetFeePerK()
461  const CAmount fee = std::min<CAmount>(ConsumeMoney(fuzzed_data_provider), std::numeric_limits<CAmount>::max() / static_cast<CAmount>(100000));
462  assert(MoneyRange(fee));
463  const int64_t time = fuzzed_data_provider.ConsumeIntegral<int64_t>();
464  const unsigned int entry_height = fuzzed_data_provider.ConsumeIntegral<unsigned int>();
465  const bool spends_coinbase = fuzzed_data_provider.ConsumeBool();
466  const unsigned int sig_op_cost = fuzzed_data_provider.ConsumeIntegralInRange<unsigned int>(0, MAX_BLOCK_SIGOPS_COST);
467  return CTxMemPoolEntry{MakeTransactionRef(tx), fee, time, entry_height, spends_coinbase, sig_op_cost, {}};
468 }
469 
470 bool ContainsSpentInput(const CTransaction& tx, const CCoinsViewCache& inputs) noexcept
471 {
472  for (const CTxIn& tx_in : tx.vin) {
473  const Coin& coin = inputs.AccessCoin(tx_in.prevout);
474  if (coin.IsSpent()) {
475  return true;
476  }
477  }
478  return false;
479 }
480 
481 CNetAddr ConsumeNetAddr(FuzzedDataProvider& fuzzed_data_provider) noexcept
482 {
483  const Network network = fuzzed_data_provider.PickValueInArray({Network::NET_IPV4, Network::NET_IPV6, Network::NET_INTERNAL, Network::NET_ONION});
484  CNetAddr net_addr;
485  if (network == Network::NET_IPV4) {
486  in_addr v4_addr = {};
487  v4_addr.s_addr = fuzzed_data_provider.ConsumeIntegral<uint32_t>();
488  net_addr = CNetAddr{v4_addr};
489  } else if (network == Network::NET_IPV6) {
490  if (fuzzed_data_provider.remaining_bytes() >= 16) {
491  in6_addr v6_addr = {};
492  memcpy(v6_addr.s6_addr, fuzzed_data_provider.ConsumeBytes<uint8_t>(16).data(), 16);
493  net_addr = CNetAddr{v6_addr, fuzzed_data_provider.ConsumeIntegral<uint32_t>()};
494  }
495  } else if (network == Network::NET_INTERNAL) {
496  net_addr.SetInternal(fuzzed_data_provider.ConsumeBytesAsString(32));
497  } else if (network == Network::NET_ONION) {
498  net_addr.SetSpecial(fuzzed_data_provider.ConsumeBytesAsString(32));
499  }
500  return net_addr;
501 }
502 
504 {
507  return nullptr;
508  }
509  std::string mode;
510  CallOneOf(
512  [&] {
513  mode = "r";
514  },
515  [&] {
516  mode = "r+";
517  },
518  [&] {
519  mode = "w";
520  },
521  [&] {
522  mode = "w+";
523  },
524  [&] {
525  mode = "a";
526  },
527  [&] {
528  mode = "a+";
529  });
530 #if defined _GNU_SOURCE && !defined __ANDROID__
531  const cookie_io_functions_t io_hooks = {
536  };
537  return fopencookie(this, mode.c_str(), io_hooks);
538 #else
539  (void)mode;
540  return nullptr;
541 #endif
542 }
543 
544 ssize_t FuzzedFileProvider::read(void* cookie, char* buf, size_t size)
545 {
546  FuzzedFileProvider* fuzzed_file = (FuzzedFileProvider*)cookie;
548  if (buf == nullptr || size == 0 || fuzzed_file->m_fuzzed_data_provider.ConsumeBool()) {
549  return fuzzed_file->m_fuzzed_data_provider.ConsumeBool() ? 0 : -1;
550  }
551  const std::vector<uint8_t> random_bytes = fuzzed_file->m_fuzzed_data_provider.ConsumeBytes<uint8_t>(size);
552  if (random_bytes.empty()) {
553  return 0;
554  }
555  std::memcpy(buf, random_bytes.data(), random_bytes.size());
556  if (AdditionOverflow(fuzzed_file->m_offset, (int64_t)random_bytes.size())) {
557  return fuzzed_file->m_fuzzed_data_provider.ConsumeBool() ? 0 : -1;
558  }
559  fuzzed_file->m_offset += random_bytes.size();
560  return random_bytes.size();
561 }
562 
563 ssize_t FuzzedFileProvider::write(void* cookie, const char* buf, size_t size)
564 {
565  FuzzedFileProvider* fuzzed_file = (FuzzedFileProvider*)cookie;
567  const ssize_t n = fuzzed_file->m_fuzzed_data_provider.ConsumeIntegralInRange<ssize_t>(0, size);
568  if (AdditionOverflow(fuzzed_file->m_offset, (int64_t)n)) {
569  return fuzzed_file->m_fuzzed_data_provider.ConsumeBool() ? 0 : -1;
570  }
571  fuzzed_file->m_offset += n;
572  return n;
573 }
574 
575 int FuzzedFileProvider::seek(void* cookie, int64_t* offset, int whence)
576 {
577  assert(whence == SEEK_SET || whence == SEEK_CUR || whence == SEEK_END);
578  FuzzedFileProvider* fuzzed_file = (FuzzedFileProvider*)cookie;
580  int64_t new_offset = 0;
581  if (whence == SEEK_SET) {
582  new_offset = *offset;
583  } else if (whence == SEEK_CUR) {
584  if (AdditionOverflow(fuzzed_file->m_offset, *offset)) {
585  return -1;
586  }
587  new_offset = fuzzed_file->m_offset + *offset;
588  } else if (whence == SEEK_END) {
589  const int64_t n = fuzzed_file->m_fuzzed_data_provider.ConsumeIntegralInRange<int64_t>(0, 4096);
590  if (AdditionOverflow(n, *offset)) {
591  return -1;
592  }
593  new_offset = n + *offset;
594  }
595  if (new_offset < 0) {
596  return -1;
597  }
598  fuzzed_file->m_offset = new_offset;
599  *offset = new_offset;
600  return fuzzed_file->m_fuzzed_data_provider.ConsumeIntegralInRange<int>(-1, 0);
601 }
602 
603 int FuzzedFileProvider::close(void* cookie)
604 {
605  FuzzedFileProvider* fuzzed_file = (FuzzedFileProvider*)cookie;
607  return fuzzed_file->m_fuzzed_data_provider.ConsumeIntegralInRange<int>(-1, 0);
608 }
CTxIn
An input of a transaction.
Definition: transaction.h:65
ConsumeUInt256
uint256 ConsumeUInt256(FuzzedDataProvider &fuzzed_data_provider) noexcept
Definition: util.h:195
CService
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:528
CMutableTransaction::vin
std::vector< CTxIn > vin
Definition: transaction.h:366
FillNode
void FillNode(FuzzedDataProvider &fuzzed_data_provider, ConnmanTestMsg &connman, PeerManager &peerman, CNode &node) noexcept
Definition: util.cpp:222
WitnessUnknown
CTxDestination subtype to encode any future Witness version.
Definition: standard.h:125
Sock::m_socket
SOCKET m_socket
Contained socket.
Definition: sock.h:185
assert
assert(!tx.IsCoinBase())
CSHA256::Write
CSHA256 & Write(const unsigned char *data, size_t len)
Definition: sha256.cpp:689
NET_IPV4
@ NET_IPV4
IPv4.
Definition: netaddress.h:50
flags
int flags
Definition: bitcoin-tx.cpp:529
FuzzedSock::Reset
void Reset() override
Close if non-empty.
Definition: util.cpp:39
NET_INTERNAL
@ NET_INTERNAL
A set of addresses that represent the hash of a string or FQDN.
Definition: netaddress.h:66
WitnessUnknown::version
unsigned int version
Definition: standard.h:127
FuzzedSock::Send
ssize_t Send(const void *data, size_t len, int flags) const override
send(2) wrapper.
Definition: util.cpp:44
ParseISO8601DateTime
int64_t ParseISO8601DateTime(const std::string &str)
Definition: time.cpp:158
CMutableTransaction::nVersion
int32_t nVersion
Definition: transaction.h:368
FuzzedSock
Definition: util.h:41
CNetAddr
Network address.
Definition: netaddress.h:118
CPubKey::SIZE
static constexpr unsigned int SIZE
secp256k1:
Definition: pubkey.h:39
FuzzedFileProvider::seek
static int seek(void *cookie, int64_t *offset, int whence)
Definition: util.cpp:575
ConsumeScript
CScript ConsumeScript(FuzzedDataProvider &fuzzed_data_provider, const bool maybe_p2wsh) noexcept
Definition: util.cpp:340
CNode
Information about a peer.
Definition: net.h:394
FuzzedFileProvider::write
static ssize_t write(void *cookie, const char *buf, size_t size)
Definition: util.cpp:563
util.h
FuzzedSock::m_fuzzed_data_provider
FuzzedDataProvider & m_fuzzed_data_provider
Definition: util.h:43
ALL_NET_PERMISSION_FLAGS
constexpr NetPermissionFlags ALL_NET_PERMISSION_FLAGS[]
Definition: net.h:57
MoneyRange
bool MoneyRange(const CAmount &nValue)
Definition: amount.h:27
MakeTransactionRef
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:407
XOnlyPubKey
Definition: pubkey.h:224
CTxIn::MAX_SEQUENCE_NONFINAL
static const uint32_t MAX_SEQUENCE_NONFINAL
This is the maximum sequence number that enables both nLockTime and OP_CHECKLOCKTIMEVERIFY (BIP 65).
Definition: transaction.h:86
MIN_PEER_PROTO_VERSION
static const int MIN_PEER_PROTO_VERSION
disconnect from peers older than this proto version
Definition: version.h:18
ServiceFlags
ServiceFlags
nServices flags
Definition: protocol.h:271
FuzzedSock::~FuzzedSock
~FuzzedSock() override
Definition: util.cpp:24
ConsumeNetAddr
CNetAddr ConsumeNetAddr(FuzzedDataProvider &fuzzed_data_provider) noexcept
Definition: util.cpp:481
pubkey.h
CustomUintFormatter
Serialization wrapper class for custom integers and enums.
Definition: serialize.h:465
Network
Network
A network type.
Definition: netaddress.h:45
version.h
ConsumeOpcodeType
opcodetype ConsumeOpcodeType(FuzzedDataProvider &fuzzed_data_provider) noexcept
Definition: util.h:164
Assert
#define Assert(val)
Identity function.
Definition: check.h:57
NetPermissionFlags
NetPermissionFlags
Definition: net_permissions.h:18
ConsumeTxDestination
CTxDestination ConsumeTxDestination(FuzzedDataProvider &fuzzed_data_provider) noexcept
Definition: util.cpp:417
CTransaction
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:279
rbf.h
CTxIn::SEQUENCE_FINAL
static const uint32_t SEQUENCE_FINAL
Setting nSequence to this value for every input in a transaction disables nLockTime/IsFinalTx().
Definition: transaction.h:80
Sock
RAII helper class that manages a socket.
Definition: sock.h:26
WitnessV0KeyHash
Definition: standard.h:109
CScriptWitness
Definition: script.h:557
ConnmanTestMsg
Definition: net.h:19
CTxIn::nSequence
uint32_t nSequence
Definition: transaction.h:70
CTxIn::scriptWitness
CScriptWitness scriptWitness
Only serialized through CTransaction.
Definition: transaction.h:71
SetFuzzedErrNo
void SetFuzzedErrNo(FuzzedDataProvider &fuzzed_data_provider, const std::array< T, size > &errnos)
Sets errno to a value selected from the given std::array errnos.
Definition: util.h:242
ConsumeTime
int64_t ConsumeTime(FuzzedDataProvider &fuzzed_data_provider, const std::optional< int64_t > &min, const std::optional< int64_t > &max) noexcept
Definition: util.cpp:281
WITNESS_STACK_ELEM_OP_TRUE
static const std::vector< uint8_t > WITNESS_STACK_ELEM_OP_TRUE
Definition: script.h:11
script.h
OP_0
@ OP_0
Definition: script.h:69
CMutableTransaction::nLockTime
uint32_t nLockTime
Definition: transaction.h:369
ToByteVector
std::vector< unsigned char > ToByteVector(const T &in)
Definition: script.h:60
MAX_BIP125_RBF_SEQUENCE
static constexpr uint32_t MAX_BIP125_RBF_SEQUENCE
Definition: rbf.h:12
CTxDestination
std::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:157
INVALID_SOCKET
#define INVALID_SOCKET
Definition: compat.h:53
CNetAddr::SetSpecial
bool SetSpecial(const std::string &addr)
Parse a Tor or I2P address and set this object to it.
Definition: netaddress.cpp:212
Coin
A UTXO entry.
Definition: coins.h:30
CallOneOf
size_t CallOneOf(FuzzedDataProvider &fuzzed_data_provider, Callables... callables)
Definition: util.h:82
MAX_BLOCK_SIGOPS_COST
static const int64_t MAX_BLOCK_SIGOPS_COST
The maximum allowed number of signature check operations in a block (network rule)
Definition: consensus.h:17
FuzzedSock::GetSockOpt
int GetSockOpt(int level, int opt_name, void *opt_val, socklen_t *opt_len) const override
getsockopt(2) wrapper.
Definition: util.cpp:177
ConsumeTxMemPoolEntry
CTxMemPoolEntry ConsumeTxMemPoolEntry(FuzzedDataProvider &fuzzed_data_provider, const CTransaction &tx) noexcept
Definition: util.cpp:455
CSerializedNetMsg
Definition: net.h:101
ALL_SERVICE_FLAGS
constexpr ServiceFlags ALL_SERVICE_FLAGS[]
Definition: net.h:48
time.h
ConsumeTransaction
CMutableTransaction ConsumeTransaction(FuzzedDataProvider &fuzzed_data_provider, const std::optional< std::vector< uint256 >> &prevout_txids, const int max_num_in, const int max_num_out) noexcept
Definition: util.cpp:289
CAmount
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
ConsumeRandomLengthByteVector
std::vector< uint8_t > ConsumeRandomLengthByteVector(FuzzedDataProvider &fuzzed_data_provider, const std::optional< size_t > &max_length=std::nullopt) noexcept
Definition: util.h:103
ConsumeUInt160
uint160 ConsumeUInt160(FuzzedDataProvider &fuzzed_data_provider) noexcept
Definition: util.h:186
ConsumeScriptWitness
CScriptWitness ConsumeScriptWitness(FuzzedDataProvider &fuzzed_data_provider, const size_t max_stack_elem_size) noexcept
Definition: util.cpp:330
CNetMsgMaker
Definition: netmessagemaker.h:12
PeerManager
Definition: net_processing.h:37
CPubKey::COMPRESSED_SIZE
static constexpr unsigned int COMPRESSED_SIZE
Definition: pubkey.h:40
FuzzedFileProvider::open
FILE * open()
Definition: util.cpp:503
uint256
256-bit opaque blob.
Definition: uint256.h:126
CSHA256::Finalize
void Finalize(unsigned char hash[OUTPUT_SIZE])
Definition: sha256.cpp:715
CScript
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:405
net_processing.h
CNoDestination
Definition: standard.h:73
FuzzedSock::IsConnected
bool IsConnected(std::string &errmsg) const override
Check if still connected.
Definition: util.cpp:213
AdditionOverflow
bool AdditionOverflow(const T i, const T j) noexcept
Definition: overflow.h:12
FuzzedFileProvider::read
static ssize_t read(void *cookie, char *buf, size_t size)
Definition: util.cpp:544
CTransaction::CURRENT_VERSION
static const int32_t CURRENT_VERSION
Definition: transaction.h:283
ContainsSpentInput
bool ContainsSpentInput(const CTransaction &tx, const CCoinsViewCache &inputs) noexcept
Definition: util.cpp:470
CMutableTransaction::vout
std::vector< CTxOut > vout
Definition: transaction.h:367
PKHash
Definition: standard.h:79
FuzzedFileProvider::close
static int close(void *cookie)
Definition: util.cpp:603
CCoinsViewCache
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:213
netmessagemaker.h
FuzzedSock::m_peek_data
std::optional< uint8_t > m_peek_data
Data to return when MSG_PEEK is used as a Recv() flag.
Definition: util.h:50
CTxMemPoolEntry
Definition: txmempool.h:85
LOCK
#define LOCK(cs)
Definition: sync.h:226
FuzzedDataProvider
Definition: FuzzedDataProvider.h:31
FuzzedSock::Accept
std::unique_ptr< Sock > Accept(sockaddr *addr, socklen_t *addr_len) const override
accept(2) wrapper.
Definition: util.cpp:163
NET_ONION
@ NET_ONION
TOR (v2 or v3)
Definition: netaddress.h:56
Sock::Event
uint8_t Event
Definition: sock.h:118
CTxIn::prevout
COutPoint prevout
Definition: transaction.h:68
CTxIn::scriptSig
CScript scriptSig
Definition: transaction.h:69
CSHA256
A hasher class for SHA-256.
Definition: sha256.h:13
FuzzedSock::FuzzedSock
FuzzedSock(FuzzedDataProvider &fuzzed_data_provider)
Definition: util.cpp:18
node
Definition: init.h:22
FuzzedSock::Recv
ssize_t Recv(void *buf, size_t len, int flags) const override
recv(2) wrapper.
Definition: util.cpp:76
FuzzedSock::Wait
bool Wait(std::chrono::milliseconds timeout, Event requested, Event *occurred=nullptr) const override
Wait for readiness for input (recv) or output (send).
Definition: util.cpp:196
NET_IPV6
@ NET_IPV6
IPv6.
Definition: netaddress.h:53
NetMsgType::VERACK
const char * VERACK
The verack message acknowledges a previously-received version message, informing the connecting node ...
Definition: protocol.cpp:14
FuzzedFileProvider::m_offset
int64_t m_offset
Definition: util.h:332
CNetAddr::SetInternal
bool SetInternal(const std::string &name)
Create an "internal" address that represents a name or FQDN.
Definition: netaddress.cpp:173
MAX_MONEY
static constexpr CAmount MAX_MONEY
No amount larger than this (in satoshi) is valid.
Definition: amount.h:26
ConsumeSequence
uint32_t ConsumeSequence(FuzzedDataProvider &fuzzed_data_provider) noexcept
Definition: util.cpp:406
COutPoint
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:26
ConsumeFixedLengthByteVector
std::vector< uint8_t > ConsumeFixedLengthByteVector(FuzzedDataProvider &fuzzed_data_provider, const size_t length) noexcept
Returns a byte vector of specified size regardless of the number of remaining bytes available from th...
Definition: util.h:261
Coin::IsSpent
bool IsSpent() const
Either this coin never existed (see e.g.
Definition: coins.h:79
FuzzedDataProvider::ConsumeBool
bool ConsumeBool()
Definition: FuzzedDataProvider.h:288
FuzzedFileProvider
Definition: util.h:329
COIN
static constexpr CAmount COIN
The amount of satoshis in one BTC.
Definition: amount.h:15
ConsumeWeakEnum
WeakEnumType ConsumeWeakEnum(FuzzedDataProvider &fuzzed_data_provider, const WeakEnumType(&all_types)[size]) noexcept
Definition: util.h:157
CMutableTransaction
A mutable version of CTransaction.
Definition: transaction.h:364
FuzzedSock::operator=
FuzzedSock & operator=(Sock &&other) override
Move assignment operator, grab the socket from another object and close ours (if set).
Definition: util.cpp:33
NetMsgType::VERSION
const char * VERSION
The version message provides information about the transmitting node to the receiving node at the beg...
Definition: protocol.cpp:13
WitnessV0ScriptHash
Definition: standard.h:102
FuzzedSock::Connect
int Connect(const sockaddr *, socklen_t) const override
connect(2) wrapper.
Definition: util.cpp:141
Using
static Wrapper< Formatter, T & > Using(T &&t)
Cause serialization/deserialization of an object to be done using a specified formatter class.
Definition: serialize.h:433
ConsumeMoney
CAmount ConsumeMoney(FuzzedDataProvider &fuzzed_data_provider, const std::optional< CAmount > &max) noexcept
Definition: util.cpp:276
ConsumeScriptNum
CScriptNum ConsumeScriptNum(FuzzedDataProvider &fuzzed_data_provider) noexcept
Definition: util.h:181
FuzzedFileProvider::m_fuzzed_data_provider
FuzzedDataProvider & m_fuzzed_data_provider
Definition: util.h:331
amount.h
overflow.h
ScriptHash
Definition: standard.h:89
FuzzedDataProvider::ConsumeIntegralInRange
T ConsumeIntegralInRange(T min, T max)
Definition: FuzzedDataProvider.h:204
base_blob::begin
unsigned char * begin()
Definition: uint256.h:60
CScriptWitness::stack
std::vector< std::vector< unsigned char > > stack
Definition: script.h:561
FuzzedDataProvider::ConsumeBytes
std::vector< T > ConsumeBytes(size_t num_bytes)
Definition: FuzzedDataProvider.h:108
PickValue
auto & PickValue(FuzzedDataProvider &fuzzed_data_provider, Collection &col)
Definition: util.h:94
PROTOCOL_VERSION
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:12
SOCKET
unsigned int SOCKET
Definition: compat.h:41
P2WSH_OP_TRUE
static const CScript P2WSH_OP_TRUE
Definition: script.h:12
WitnessV1Taproot
Definition: standard.h:118