Bitcoin Core 32.99.0
P2P Digital Currency
Loading...
Searching...
No Matches
util.h
Go to the documentation of this file.
1// Copyright (c) 2009-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#ifndef BITCOIN_TEST_FUZZ_UTIL_H
6#define BITCOIN_TEST_FUZZ_UTIL_H
7
8#include <addresstype.h>
9#include <arith_uint256.h>
10#include <coins.h>
11#include <compat/compat.h>
12#include <consensus/amount.h>
13#include <consensus/consensus.h>
14#include <key.h>
15#include <merkleblock.h>
16#include <pow.h>
18#include <script/script.h>
19#include <serialize.h>
20#include <streams.h>
22#include <test/fuzz/fuzz.h>
23#include <uint256.h>
24#include <util/check.h>
25#include <validation.h>
26
27#include <algorithm>
28#include <array>
29#include <cstdint>
30#include <cstdio>
31#include <optional>
32#include <string>
33#include <vector>
34
35class PeerManager;
36
37template <typename... Callables>
39{
40 constexpr size_t call_size{sizeof...(callables)};
41 static_assert(call_size >= 1);
43
44 size_t i{0};
45 ((i++ == call_index ? callables() : void()), ...);
46 return call_size;
47}
48
49template <typename Collection>
51{
52 const auto sz{col.size()};
53 assert(sz >= 1);
54 return std::next(col.begin(), fuzzed_data_provider.ConsumeIntegralInRange<decltype(sz)>(0, sz - 1));
55}
56
57template <typename Collection>
62
63template<typename B = uint8_t>
64[[nodiscard]] inline std::vector<B> ConsumeRandomLengthByteVector(FuzzedDataProvider& fuzzed_data_provider, const std::optional<size_t>& max_length = std::nullopt) noexcept
65{
66 static_assert(sizeof(B) == 1);
67 const std::string s = max_length ?
70 std::vector<B> ret(s.size());
71 std::copy(s.begin(), s.end(), reinterpret_cast<char*>(ret.data()));
72 return ret;
73}
74
79
80[[nodiscard]] inline std::vector<std::string> ConsumeRandomLengthStringVector(FuzzedDataProvider& fuzzed_data_provider, const size_t max_vector_size = 16, const size_t max_string_length = 16) noexcept
81{
83 std::vector<std::string> r;
84 r.reserve(n_elements);
85 for (size_t i = 0; i < n_elements; ++i) {
87 }
88 return r;
89}
90
91template <typename T>
93{
95 std::vector<T> r;
96 r.reserve(n_elements);
97 for (size_t i = 0; i < n_elements; ++i) {
99 }
100 return r;
101}
102
103template <typename P>
105
106template <typename T, typename P>
107[[nodiscard]] std::optional<T> ConsumeDeserializable(FuzzedDataProvider& fuzzed_data_provider, const P& params, const std::optional<size_t>& max_length = std::nullopt) noexcept
108{
109 const std::vector<uint8_t> buffer{ConsumeRandomLengthByteVector(fuzzed_data_provider, max_length)};
110 SpanReader ds{buffer};
111 T obj;
112 try {
113 ds >> params(obj);
114 } catch (const std::ios_base::failure&) {
115 return std::nullopt;
116 }
117 return obj;
118}
119
120template <typename T>
121[[nodiscard]] inline std::optional<T> ConsumeDeserializable(FuzzedDataProvider& fuzzed_data_provider, const std::optional<size_t>& max_length = std::nullopt) noexcept
122{
123 const std::vector<uint8_t> buffer = ConsumeRandomLengthByteVector(fuzzed_data_provider, max_length);
124 SpanReader ds{buffer};
125 T obj;
126 try {
127 ds >> obj;
128 } catch (const std::ios_base::failure&) {
129 return std::nullopt;
130 }
131 return obj;
132}
133
134template <typename T>
135[[nodiscard]] inline std::optional<T> ConsumeDeserializableConstructor(FuzzedDataProvider& fuzzed_data_provider, const std::optional<size_t>& max_length = std::nullopt) noexcept
136{
137 const std::vector<uint8_t> buffer = ConsumeRandomLengthByteVector(fuzzed_data_provider, max_length);
138 SpanReader ds{buffer};
139 try {
141 return obj;
142 } catch (const std::ios_base::failure&) {
143 return std::nullopt;
144 }
145}
146
147template <typename WeakEnumType, size_t size>
154
159
160[[nodiscard]] CAmount ConsumeMoney(FuzzedDataProvider& fuzzed_data_provider, const std::optional<CAmount>& max = std::nullopt) noexcept;
161
162[[nodiscard]] NodeSeconds ConsumeTime(FuzzedDataProvider& fuzzed_data_provider, const std::optional<int64_t>& min = std::nullopt, const std::optional<int64_t>& max = std::nullopt) noexcept;
163
164template <class Dur>
165// Having the compiler infer the template argument from the function argument
166// is dangerous, because the desired return value generally has a different
167// type than the function argument. So std::common_type is used to force the
168// call site to specify the type of the return value.
169[[nodiscard]] Dur ConsumeDuration(FuzzedDataProvider& fuzzed_data_provider, std::common_type_t<Dur> min, std::common_type_t<Dur> max) noexcept
170{
171 return Dur{fuzzed_data_provider.ConsumeIntegralInRange(min.count(), max.count())};
172}
173
174[[nodiscard]] CMutableTransaction ConsumeTransaction(FuzzedDataProvider& fuzzed_data_provider, const std::optional<std::vector<Txid>>& prevout_txids, int max_num_in = 10, int max_num_out = 10) noexcept;
175
177
179
181
186
188{
189 const std::vector<uint8_t> v160 = fuzzed_data_provider.ConsumeBytes<uint8_t>(160 / 8);
190 if (v160.size() != 160 / 8) {
191 return {};
192 }
193 return uint160{v160};
194}
195
197{
198 const std::vector<uint8_t> v256 = fuzzed_data_provider.ConsumeBytes<uint8_t>(256 / 8);
199 if (v256.size() != 256 / 8) {
200 return {};
201 }
202 return uint256{v256};
203}
204
209
211{
212 assert(min <= max);
213 const arith_uint256 range = max - min;
215 arith_uint256 result = value;
216 // Avoid division by 0, in case range + 1 results in overflow.
217 if (range != ~arith_uint256(0)) {
218 const arith_uint256 quotient = value / (range + 1);
219 result = value - (quotient * (range + 1));
220 }
221 result += min;
222 assert(result >= min && result <= max);
223 return result;
224}
225
226[[nodiscard]] std::map<COutPoint, Coin> ConsumeCoins(FuzzedDataProvider& fuzzed_data_provider) noexcept;
227
229
230[[nodiscard]] CKey ConsumePrivateKey(FuzzedDataProvider& fuzzed_data_provider, std::optional<bool> compressed = std::nullopt) noexcept;
231
232template <typename T>
233[[nodiscard]] bool MultiplicationOverflow(const T i, const T j) noexcept
234{
235 static_assert(std::is_integral_v<T>, "Integral required.");
236 if (std::numeric_limits<T>::is_signed) {
237 if (i > 0) {
238 if (j > 0) {
239 return i > (std::numeric_limits<T>::max() / j);
240 } else {
241 return j < (std::numeric_limits<T>::min() / i);
242 }
243 } else {
244 if (j > 0) {
245 return i < (std::numeric_limits<T>::min() / j);
246 } else {
247 return i != 0 && (j < (std::numeric_limits<T>::max() / i));
248 }
249 }
250 } else {
251 return j != 0 && i > std::numeric_limits<T>::max() / j;
252 }
253}
254
255[[nodiscard]] bool ContainsSpentInput(const CTransaction& tx, const CCoinsViewCache& inputs) noexcept;
256
260template <typename T, size_t size>
265
266/*
267 * Sets a fuzzed errno in the range [0, 133 (EHWPOISON)]. Can be used from functions emulating
268 * standard library functions that set errno, or in other contexts where the value of errno
269 * might be relevant for the execution path that will be taken.
270 */
275
280template<typename B = uint8_t>
281[[nodiscard]] inline std::vector<B> ConsumeFixedLengthByteVector(FuzzedDataProvider& fuzzed_data_provider, const size_t length) noexcept
282{
283 static_assert(sizeof(B) == 1);
285 random_bytes.resize(length);
286 return random_bytes;
287}
288
290{
293
294public:
298
299 FILE* open();
300
301 static ssize_t read(void* cookie, char* buf, size_t size);
302
303 static ssize_t write(void* cookie, const char* buf, size_t size);
304
305 static int seek(void* cookie, int64_t* offset, int whence);
306
307 static int close(void* cookie);
308};
309
310#define WRITE_TO_STREAM_CASE(type, consume) \
311 [&] { \
312 type o = consume; \
313 stream << o; \
314 }
315template <typename Stream>
338
339#define READ_FROM_STREAM_CASE(type) \
340 [&] { \
341 type o; \
342 stream >> o; \
343 }
344template <typename Stream>
367
368inline void FinalizeHeader(CBlockHeader& header, const ChainstateManager& chainman)
369{
370 while (!CheckProofOfWork(header.GetHash(), header.nBits, chainman.GetParams().GetConsensus())) {
371 ++(header.nNonce);
372 }
373}
374
375#endif // BITCOIN_TEST_FUZZ_UTIL_H
std::variant< CNoDestination, PubKeyDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, PayToAnchor, WitnessUnknown > CTxDestination
A txout script categorized into standard templates.
int64_t CAmount
Amount in satoshis (Can be negative)
Definition amount.h:12
arith_uint256 UintToArith256(const uint256 &a)
int ret
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition block.h:27
uint32_t nNonce
Definition block.h:35
uint32_t nBits
Definition block.h:34
uint256 GetHash() const
Definition block.cpp:14
const Consensus::Params & GetConsensus() const
Definition chainparams.h:89
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition coins.h:437
An encapsulated private key.
Definition key.h:46
Serialized script, used inside transaction inputs and outputs.
Definition script.h:406
The basic transaction that is broadcasted on the network and contained in blocks.
Interface for managing multiple Chainstate objects, where each chainstate is associated with chainsta...
Definition validation.h:950
const CChainParams & GetParams() const
Double ended buffer combining vector and stream-like interfaces.
Definition streams.h:165
std::string ConsumeRandomLengthString(size_t max_length)
std::vector< T > ConsumeBytes(size_t num_bytes)
T ConsumeIntegralInRange(T min, T max)
T PickValueInArray(const T(&array)[size])
static ssize_t write(void *cookie, const char *buf, size_t size)
Definition util.cpp:311
FuzzedDataProvider & m_fuzzed_data_provider
Definition util.h:291
int64_t m_offset
Definition util.h:292
static int seek(void *cookie, int64_t *offset, int whence)
Definition util.cpp:323
static int close(void *cookie)
Definition util.cpp:351
FuzzedFileProvider(FuzzedDataProvider &fuzzed_data_provider)
Definition util.h:295
static ssize_t read(void *cookie, char *buf, size_t size)
Definition util.cpp:292
FILE * open()
Definition util.cpp:251
Minimal stream for reading from an existing byte array by std::span.
Definition streams.h:83
256-bit unsigned big integer.
160-bit opaque blob.
Definition uint256.h:184
256-bit opaque blob.
Definition uint256.h:196
#define T(expected, seed, data)
bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params &params)
Check whether a block hash satisfies the proof-of-work requirement specified by nBits.
Definition pow.cpp:140
constexpr unsigned int MAX_OPCODE
Definition script.h:217
opcodetype
Script opcodes.
Definition script.h:75
constexpr deserialize_type deserialize
Definition serialize.h:52
A mutable version of CTransaction.
CScriptNum ConsumeScriptNum(FuzzedDataProvider &fuzzed_data_provider) noexcept
Definition util.h:182
WeakEnumType ConsumeWeakEnum(FuzzedDataProvider &fuzzed_data_provider, const WeakEnumType(&all_types)[size]) noexcept
Definition util.h:148
uint32_t ConsumeSequence(FuzzedDataProvider &fuzzed_data_provider) noexcept
Definition util.cpp:155
DataStream ConsumeDataStream(FuzzedDataProvider &fuzzed_data_provider, const std::optional< size_t > &max_length=std::nullopt) noexcept
Definition util.h:75
NodeSeconds ConsumeTime(FuzzedDataProvider &fuzzed_data_provider, const std::optional< int64_t > &min=std::nullopt, const std::optional< int64_t > &max=std::nullopt) noexcept
Definition util.cpp:34
auto & PickValue(FuzzedDataProvider &fuzzed_data_provider, Collection &col)
Definition util.h:58
void ReadFromStream(FuzzedDataProvider &fuzzed_data_provider, Stream &stream) noexcept
Definition util.h:345
std::optional< T > ConsumeDeserializableConstructor(FuzzedDataProvider &fuzzed_data_provider, const std::optional< size_t > &max_length=std::nullopt) noexcept
Definition util.h:135
P ConsumeDeserializationParams(FuzzedDataProvider &fuzzed_data_provider) noexcept
Definition net.cpp:94
std::vector< B > 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:281
bool ContainsSpentInput(const CTransaction &tx, const CCoinsViewCache &inputs) noexcept
Definition util.cpp:240
uint256 ConsumeUInt256(FuzzedDataProvider &fuzzed_data_provider) noexcept
Definition util.h:196
#define READ_FROM_STREAM_CASE(type)
Definition util.h:339
arith_uint256 ConsumeArithUInt256(FuzzedDataProvider &fuzzed_data_provider) noexcept
Definition util.h:205
size_t CallOneOf(FuzzedDataProvider &fuzzed_data_provider, Callables... callables)
Definition util.h:38
std::vector< B > ConsumeRandomLengthByteVector(FuzzedDataProvider &fuzzed_data_provider, const std::optional< size_t > &max_length=std::nullopt) noexcept
Definition util.h:64
std::vector< T > ConsumeRandomLengthIntegralVector(FuzzedDataProvider &fuzzed_data_provider, const size_t max_vector_size=16) noexcept
Definition util.h:92
CScriptWitness ConsumeScriptWitness(FuzzedDataProvider &fuzzed_data_provider, size_t max_stack_elem_size=32) noexcept
Definition util.cpp:83
void WriteToStream(FuzzedDataProvider &fuzzed_data_provider, Stream &stream) noexcept
Definition util.h:316
CScript ConsumeScript(FuzzedDataProvider &fuzzed_data_provider, bool maybe_p2wsh=false) noexcept
Definition util.cpp:93
std::optional< T > ConsumeDeserializable(FuzzedDataProvider &fuzzed_data_provider, const P &params, const std::optional< size_t > &max_length=std::nullopt) noexcept
Definition util.h:107
std::vector< std::string > ConsumeRandomLengthStringVector(FuzzedDataProvider &fuzzed_data_provider, const size_t max_vector_size=16, const size_t max_string_length=16) noexcept
Definition util.h:80
CMutableTransaction ConsumeTransaction(FuzzedDataProvider &fuzzed_data_provider, const std::optional< std::vector< Txid > > &prevout_txids, int max_num_in=10, int max_num_out=10) noexcept
Definition util.cpp:42
CKey ConsumePrivateKey(FuzzedDataProvider &fuzzed_data_provider, std::optional< bool > compressed=std::nullopt) noexcept
Definition util.cpp:230
bool MultiplicationOverflow(const T i, const T j) noexcept
Definition util.h:233
Dur ConsumeDuration(FuzzedDataProvider &fuzzed_data_provider, std::common_type_t< Dur > min, std::common_type_t< Dur > max) noexcept
Definition util.h:169
opcodetype ConsumeOpcodeType(FuzzedDataProvider &fuzzed_data_provider) noexcept
Definition util.h:155
void FinalizeHeader(CBlockHeader &header, const ChainstateManager &chainman)
Definition util.h:368
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:261
uint160 ConsumeUInt160(FuzzedDataProvider &fuzzed_data_provider) noexcept
Definition util.h:187
#define WRITE_TO_STREAM_CASE(type, consume)
Definition util.h:310
CTxDestination ConsumeTxDestination(FuzzedDataProvider &fuzzed_data_provider) noexcept
Definition util.cpp:184
arith_uint256 ConsumeArithUInt256InRange(FuzzedDataProvider &fuzzed_data_provider, const arith_uint256 &min, const arith_uint256 &max) noexcept
Definition util.h:210
std::map< COutPoint, Coin > ConsumeCoins(FuzzedDataProvider &fuzzed_data_provider) noexcept
Definition util.cpp:166
CAmount ConsumeMoney(FuzzedDataProvider &fuzzed_data_provider, const std::optional< CAmount > &max=std::nullopt) noexcept
Definition util.cpp:29
auto PickIterator(FuzzedDataProvider &fuzzed_data_provider, Collection &col)
Definition util.h:50
std::chrono::time_point< NodeClock, std::chrono::seconds > NodeSeconds
Definition time.h:35
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.
Definition time.h:82
#define B
assert(!tx.IsCoinBase())
FuzzedDataProvider & fuzzed_data_provider
Definition fees.cpp:46