Bitcoin Core 31.99.0
P2P Digital Currency
deserialize.cpp
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#include <addrdb.h>
6#include <addrman.h>
7#include <addrman_impl.h>
8#include <blockencodings.h>
9#include <blockfilter.h>
10#include <chain.h>
11#include <coins.h>
12#include <common/args.h>
13#include <compressor.h>
14#include <consensus/merkle.h>
15#include <key.h>
16#include <merkleblock.h>
17#include <net.h>
18#include <netbase.h>
19#include <netgroup.h>
20#include <node/blockstorage.h>
21#include <node/utxo_snapshot.h>
22#include <primitives/block.h>
23#include <protocol.h>
24#include <psbt.h>
25#include <pubkey.h>
26#include <script/keyorigin.h>
27#include <streams.h>
28#include <test/fuzz/fuzz.h>
29#include <test/fuzz/util.h>
31#include <undo.h>
32
33#include <cstdint>
34#include <exception>
35#include <optional>
36#include <stdexcept>
37
40
42{
43 static const auto testing_setup = MakeNoLogFileContext<>();
44}
45
46#define FUZZ_TARGET_DESERIALIZE(name, code) \
47 FUZZ_TARGET(name, .init = initialize_deserialize) \
48 { \
49 try { \
50 code \
51 } catch (const invalid_fuzzing_input_exception&) { \
52 } \
53 }
54
55namespace {
56
57struct invalid_fuzzing_input_exception : public std::exception {
58};
59
60template <typename T, typename P>
61T Deserialize(DataStream&& ds, const P& params)
62{
63 T obj;
64 ds >> params(obj);
65 return obj;
66}
67
68template <typename T>
69DataStream Serialize(const T& obj)
70{
71 DataStream ds{};
72 ds << obj;
73 return ds;
74}
75
76template <typename T>
77T Deserialize(DataStream ds)
78{
79 T obj;
80 ds >> obj;
81 return obj;
82}
83
84template <typename T>
85void DeserializeFromFuzzingInput(FuzzBufferType buffer, T&& obj)
86{
87 try {
88 SpanReader{buffer} >> obj;
89 } catch (const std::ios_base::failure&) {
90 throw invalid_fuzzing_input_exception();
91 }
92 assert(buffer.empty() || !Serialize(obj).empty());
93}
94
95template <typename T>
96T DeserializeConstructFromFuzzingInput(FuzzBufferType buffer)
97{
98 try {
99 SpanReader reader{buffer};
100 T obj(deserialize, reader);
101 assert(buffer.empty() || !Serialize(obj).empty());
102 return obj;
103 } catch (const std::ios_base::failure&) {
104 throw invalid_fuzzing_input_exception();
105 }
106}
107
108template <typename T, typename P>
109void AssertEqualAfterSerializeDeserialize(const T& obj, const P& params)
110{
111 assert(Deserialize<T>(Serialize(params(obj)), params) == obj);
112}
113template <typename T>
114void AssertEqualAfterSerializeDeserialize(const T& obj)
115{
116 assert(Deserialize<T>(Serialize(obj)) == obj);
117}
118
119} // namespace
120
121FUZZ_TARGET_DESERIALIZE(block_filter_deserialize, {
122 BlockFilter block_filter;
123 DeserializeFromFuzzingInput(buffer, block_filter);
124})
125FUZZ_TARGET(addr_info_deserialize, .init = initialize_deserialize)
126{
127 FuzzedDataProvider fdp{buffer.data(), buffer.size()};
128 (void)ConsumeDeserializable<AddrInfo>(fdp, ConsumeDeserializationParams<CAddress::SerParams>(fdp));
129}
130FUZZ_TARGET_DESERIALIZE(block_file_info_deserialize, {
131 CBlockFileInfo block_file_info;
132 DeserializeFromFuzzingInput(buffer, block_file_info);
133})
134FUZZ_TARGET_DESERIALIZE(block_header_and_short_txids_deserialize, {
135 CBlockHeaderAndShortTxIDs block_header_and_short_txids;
136 DeserializeFromFuzzingInput(buffer, block_header_and_short_txids);
137})
138FUZZ_TARGET_DESERIALIZE(fee_rate_deserialize, {
139 CFeeRate fee_rate;
140 DeserializeFromFuzzingInput(buffer, fee_rate);
141 AssertEqualAfterSerializeDeserialize(fee_rate);
142})
143FUZZ_TARGET_DESERIALIZE(merkle_block_deserialize, {
144 CMerkleBlock merkle_block;
145 DeserializeFromFuzzingInput(buffer, merkle_block);
146})
147FUZZ_TARGET_DESERIALIZE(out_point_deserialize, {
148 COutPoint out_point;
149 DeserializeFromFuzzingInput(buffer, out_point);
150 AssertEqualAfterSerializeDeserialize(out_point);
151})
152FUZZ_TARGET_DESERIALIZE(partial_merkle_tree_deserialize, {
153 CPartialMerkleTree partial_merkle_tree;
154 DeserializeFromFuzzingInput(buffer, partial_merkle_tree);
155})
156FUZZ_TARGET_DESERIALIZE(pub_key_deserialize, {
157 CPubKey pub_key;
158 DeserializeFromFuzzingInput(buffer, pub_key);
159 AssertEqualAfterSerializeDeserialize(pub_key);
160})
161FUZZ_TARGET_DESERIALIZE(script_deserialize, {
163 DeserializeFromFuzzingInput(buffer, script);
164})
165FUZZ_TARGET_DESERIALIZE(tx_in_deserialize, {
166 CTxIn tx_in;
167 DeserializeFromFuzzingInput(buffer, tx_in);
168 AssertEqualAfterSerializeDeserialize(tx_in);
169})
170FUZZ_TARGET_DESERIALIZE(flat_file_pos_deserialize, {
171 FlatFilePos flat_file_pos;
172 DeserializeFromFuzzingInput(buffer, flat_file_pos);
173 AssertEqualAfterSerializeDeserialize(flat_file_pos);
174})
175FUZZ_TARGET_DESERIALIZE(key_origin_info_deserialize, {
176 KeyOriginInfo key_origin_info;
177 DeserializeFromFuzzingInput(buffer, key_origin_info);
178 AssertEqualAfterSerializeDeserialize(key_origin_info);
179})
180FUZZ_TARGET_DESERIALIZE(partially_signed_transaction_deserialize, {
181 PartiallySignedTransaction partially_signed_transaction = DeserializeConstructFromFuzzingInput<PartiallySignedTransaction>(buffer);
182})
183FUZZ_TARGET_DESERIALIZE(prefilled_transaction_deserialize, {
184 PrefilledTransaction prefilled_transaction;
185 DeserializeFromFuzzingInput(buffer, prefilled_transaction);
186})
187FUZZ_TARGET_DESERIALIZE(psbt_input_deserialize, {
188 PSBTInput psbt_input(0, Txid{}, 0);
189 DeserializeFromFuzzingInput(buffer, psbt_input);
190})
191FUZZ_TARGET_DESERIALIZE(psbt_output_deserialize, {
192 PSBTOutput psbt_output(0, 0, CScript());
193 DeserializeFromFuzzingInput(buffer, psbt_output);
194})
195FUZZ_TARGET_DESERIALIZE(block_deserialize, {
196 CBlock block;
197 DeserializeFromFuzzingInput(buffer, TX_WITH_WITNESS(block));
198})
199FUZZ_TARGET_DESERIALIZE(blocklocator_deserialize, {
200 CBlockLocator bl;
201 DeserializeFromFuzzingInput(buffer, bl);
202})
203FUZZ_TARGET_DESERIALIZE(blockmerkleroot, {
204 CBlock block;
205 DeserializeFromFuzzingInput(buffer, TX_WITH_WITNESS(block));
206 bool mutated;
207 BlockMerkleRoot(block, &mutated);
208})
209FUZZ_TARGET_DESERIALIZE(blockheader_deserialize, {
210 CBlockHeader bh;
211 DeserializeFromFuzzingInput(buffer, bh);
212})
213FUZZ_TARGET_DESERIALIZE(txundo_deserialize, {
214 CTxUndo tu;
215 DeserializeFromFuzzingInput(buffer, tu);
216})
217FUZZ_TARGET_DESERIALIZE(blockundo_deserialize, {
218 CBlockUndo bu;
219 DeserializeFromFuzzingInput(buffer, bu);
220})
221FUZZ_TARGET_DESERIALIZE(coins_deserialize, {
222 Coin coin;
223 DeserializeFromFuzzingInput(buffer, coin);
224})
225FUZZ_TARGET(netaddr_deserialize, .init = initialize_deserialize)
226{
227 FuzzedDataProvider fdp{buffer.data(), buffer.size()};
228 const auto maybe_na{ConsumeDeserializable<CNetAddr>(fdp, ConsumeDeserializationParams<CNetAddr::SerParams>(fdp))};
229 if (!maybe_na) return;
230 const CNetAddr& na{*maybe_na};
231 if (na.IsAddrV1Compatible()) {
232 AssertEqualAfterSerializeDeserialize(na, CNetAddr::V1);
233 }
234 AssertEqualAfterSerializeDeserialize(na, CNetAddr::V2);
235}
236FUZZ_TARGET(service_deserialize, .init = initialize_deserialize)
237{
238 FuzzedDataProvider fdp{buffer.data(), buffer.size()};
239 const auto ser_params{ConsumeDeserializationParams<CNetAddr::SerParams>(fdp)};
240 const auto maybe_s{ConsumeDeserializable<CService>(fdp, ser_params)};
241 if (!maybe_s) return;
242 const CService& s{*maybe_s};
243 if (s.IsAddrV1Compatible()) {
244 AssertEqualAfterSerializeDeserialize(s, CNetAddr::V1);
245 }
246 AssertEqualAfterSerializeDeserialize(s, CNetAddr::V2);
247 if (ser_params.enc == CNetAddr::Encoding::V1) {
248 assert(s.IsAddrV1Compatible());
249 }
250}
251FUZZ_TARGET_DESERIALIZE(messageheader_deserialize, {
253 DeserializeFromFuzzingInput(buffer, mh);
254 (void)mh.IsMessageTypeValid();
255})
256FUZZ_TARGET(address_deserialize, .init = initialize_deserialize)
257{
258 FuzzedDataProvider fdp{buffer.data(), buffer.size()};
259 const auto ser_enc{ConsumeDeserializationParams<CAddress::SerParams>(fdp)};
260 const auto maybe_a{ConsumeDeserializable<CAddress>(fdp, ser_enc)};
261 if (!maybe_a) return;
262 const CAddress& a{*maybe_a};
263 // A CAddress in V1 mode will roundtrip
264 // in all 4 formats (v1/v2, network/disk)
265 if (ser_enc.enc == CNetAddr::Encoding::V1) {
266 AssertEqualAfterSerializeDeserialize(a, CAddress::V1_NETWORK);
267 AssertEqualAfterSerializeDeserialize(a, CAddress::V1_DISK);
268 AssertEqualAfterSerializeDeserialize(a, CAddress::V2_NETWORK);
269 AssertEqualAfterSerializeDeserialize(a, CAddress::V2_DISK);
270 } else {
271 // A CAddress in V2 mode will roundtrip in both V2 formats, and also in the V1 formats
272 // if it's V1 compatible.
273 if (a.IsAddrV1Compatible()) {
274 AssertEqualAfterSerializeDeserialize(a, CAddress::V1_DISK);
275 AssertEqualAfterSerializeDeserialize(a, CAddress::V1_NETWORK);
276 }
277 AssertEqualAfterSerializeDeserialize(a, CAddress::V2_NETWORK);
278 AssertEqualAfterSerializeDeserialize(a, CAddress::V2_DISK);
279 }
280}
281FUZZ_TARGET_DESERIALIZE(inv_deserialize, {
282 CInv i;
283 DeserializeFromFuzzingInput(buffer, i);
284})
285FUZZ_TARGET_DESERIALIZE(bloomfilter_deserialize, {
286 CBloomFilter bf;
287 DeserializeFromFuzzingInput(buffer, bf);
288})
289FUZZ_TARGET_DESERIALIZE(diskblockindex_deserialize, {
290 CDiskBlockIndex dbi;
291 DeserializeFromFuzzingInput(buffer, dbi);
292})
293FUZZ_TARGET_DESERIALIZE(txoutcompressor_deserialize, {
294 CTxOut to;
295 auto toc = Using<TxOutCompression>(to);
296 DeserializeFromFuzzingInput(buffer, toc);
297})
298FUZZ_TARGET_DESERIALIZE(blocktransactions_deserialize, {
300 DeserializeFromFuzzingInput(buffer, bt);
301})
302FUZZ_TARGET_DESERIALIZE(blocktransactionsrequest_deserialize, {
304 DeserializeFromFuzzingInput(buffer, btr);
305})
306FUZZ_TARGET_DESERIALIZE(snapshotmetadata_deserialize, {
307 auto msg_start = Params().MessageStart();
308 SnapshotMetadata snapshot_metadata{msg_start};
309 DeserializeFromFuzzingInput(buffer, snapshot_metadata);
310})
311FUZZ_TARGET_DESERIALIZE(uint160_deserialize, {
312 uint160 u160;
313 DeserializeFromFuzzingInput(buffer, u160);
314 AssertEqualAfterSerializeDeserialize(u160);
315})
316FUZZ_TARGET_DESERIALIZE(uint256_deserialize, {
317 uint256 u256;
318 DeserializeFromFuzzingInput(buffer, u256);
319 AssertEqualAfterSerializeDeserialize(u256);
320})
321// Classes intentionally not covered in this file since their deserialization code is
322// fuzzed elsewhere:
323// * Deserialization of CTxOut is fuzzed in test/fuzz/tx_out.cpp
324// * Deserialization of CMutableTransaction is fuzzed in src/test/fuzz/transaction.cpp
const CChainParams & Params()
Return the currently selected parameters.
Complete block filter struct as defined in BIP 157.
Definition: blockfilter.h:116
A CService with information about it as peer.
Definition: protocol.h:387
static constexpr SerParams V1_NETWORK
Definition: protocol.h:428
static constexpr SerParams V2_NETWORK
Definition: protocol.h:429
static constexpr SerParams V1_DISK
Definition: protocol.h:430
static constexpr SerParams V2_DISK
Definition: protocol.h:431
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:27
Definition: block.h:74
Undo information for a CBlock.
Definition: undo.h:64
BloomFilter is a probabilistic filter which SPV clients provide so that we can filter the transaction...
Definition: bloom.h:45
const MessageStartChars & MessageStart() const
Definition: chainparams.h:90
Used to marshal pointers into hashes for db storage.
Definition: chain.h:318
Fee rate in satoshis per virtualbyte: CAmount / vB the feerate is represented internally as FeeFrac.
Definition: feerate.h:32
inv message data
Definition: protocol.h:514
Used to relay blocks as header + vector<merkle branch> to filtered nodes.
Definition: merkleblock.h:127
Message header.
Definition: protocol.h:29
bool IsMessageTypeValid() const
Definition: protocol.cpp:26
Network address.
Definition: netaddress.h:113
static constexpr SerParams V1
Definition: netaddress.h:231
static constexpr SerParams V2
Definition: netaddress.h:232
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:29
Data structure that represents a partial merkle tree.
Definition: merkleblock.h:57
An encapsulated public key.
Definition: pubkey.h:32
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:406
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:530
An input of a transaction.
Definition: transaction.h:62
An output of a transaction.
Definition: transaction.h:140
Undo information for a CTransaction.
Definition: undo.h:54
A UTXO entry.
Definition: coins.h:46
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:165
A structure for PSBTs which contain per-input information.
Definition: psbt.h:281
A structure for PSBTs which contains per output information.
Definition: psbt.h:939
A version of CTransaction with the PSBT format.
Definition: psbt.h:1240
Minimal stream for reading from an existing byte array by std::span.
Definition: streams.h:83
Metadata describing a serialized version of a UTXO set from which an assumeutxo Chainstate can be con...
Definition: utxo_snapshot.h:38
160-bit opaque blob.
Definition: uint256.h:184
256-bit opaque blob.
Definition: uint256.h:196
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
Definition: merkle.cpp:66
#define FUZZ_TARGET_DESERIALIZE(name, code)
Definition: deserialize.cpp:46
void initialize_deserialize()
Definition: deserialize.cpp:41
#define FUZZ_TARGET(...)
Definition: fuzz.h:35
std::span< const uint8_t > FuzzBufferType
Definition: fuzz.h:25
#define T(expected, seed, data)
util::LineReader reader
Definition: basic.cpp:8
static constexpr TransactionSerParams TX_WITH_WITNESS
Definition: transaction.h:180
void Serialize(Stream &, V)=delete
constexpr deserialize_type deserialize
Definition: serialize.h:52
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:117
assert(!tx.IsCoinBase())