Bitcoin Core 32.99.0
P2P Digital Currency
Loading...
Searching...
No Matches
serialize_tests.cpp
Go to the documentation of this file.
1// Copyright (c) 2012-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 <hash.h>
6#include <serialize.h>
7#include <streams.h>
8#include <test/util/common.h>
10#include <util/strencodings.h>
11
12#include <algorithm>
13#include <cstdint>
14#include <string>
15
16#include <boost/test/unit_test.hpp>
17
19
20// For testing move-semantics, declare a version of datastream that can be moved
21// but is not copyable.
31
33{
34protected:
35 int intval;
36 bool boolval;
37 std::string stringval;
38 char charstrval[16];
40public:
42 CSerializeMethodsTestSingle(int intvalin, bool boolvalin, std::string stringvalin, const uint8_t* charstrvalin, const CTransactionRef& txvalin) : intval(intvalin), boolval(boolvalin), stringval(std::move(stringvalin)), txval(txvalin)
43 {
44 memcpy(charstrval, charstrvalin, sizeof(charstrval));
45 }
46
48 {
49 READWRITE(obj.intval);
50 READWRITE(obj.boolval);
51 READWRITE(obj.stringval);
52 READWRITE(obj.charstrval);
54 }
55
57 {
58 return intval == rhs.intval &&
59 boolval == rhs.boolval &&
60 stringval == rhs.stringval &&
61 strcmp(charstrval, rhs.charstrval) == 0 &&
62 txval->Equals(*rhs.txval);
63 }
64};
65
76
78{
79 BOOST_CHECK_EQUAL(sizeof(unsigned char), GetSerializeSize((unsigned char)0));
88 // Bool is serialized as uint8_t
90
91 // Sanity-check GetSerializeSize and c++ type matching
92 BOOST_CHECK_EQUAL(GetSerializeSize((unsigned char)0), 1U);
102 BOOST_CHECK_EQUAL(GetSerializeSize(std::array<uint8_t, 1>{0}), 1U);
103 BOOST_CHECK_EQUAL(GetSerializeSize(std::array<uint8_t, 2>{0, 0}), 2U);
104}
105
107{
108 // encode
109
110 DataStream ss{};
111 DataStream::size_type size = 0;
112 for (int i = 0; i < 100000; i++) {
115 BOOST_CHECK(size == ss.size());
116 }
117
118 for (uint64_t i = 0; i < 100000000000ULL; i += 999999937) {
119 ss << VARINT(i);
120 size += ::GetSerializeSize(VARINT(i));
121 BOOST_CHECK(size == ss.size());
122 }
123
124 // decode
125 for (int i = 0; i < 100000; i++) {
126 int j = -1;
128 BOOST_CHECK_MESSAGE(i == j, "decoded:" << j << " expected:" << i);
129 }
130
131 for (uint64_t i = 0; i < 100000000000ULL; i += 999999937) {
132 uint64_t j = std::numeric_limits<uint64_t>::max();
133 ss >> VARINT(j);
134 BOOST_CHECK_MESSAGE(i == j, "decoded:" << j << " expected:" << i);
135 }
136}
137
139{
140 DataStream ss{};
145 ss << VARINT(uint8_t{0x80}); BOOST_CHECK_EQUAL(HexStr(ss), "8000"); ss.clear();
149 ss << VARINT(uint16_t{0xffff}); BOOST_CHECK_EQUAL(HexStr(ss), "82fe7f"); ss.clear();
152 ss << VARINT(0x80123456U); BOOST_CHECK_EQUAL(HexStr(ss), "86ffc7e756"); ss.clear();
153 ss << VARINT(uint32_t{0x80123456U}); BOOST_CHECK_EQUAL(HexStr(ss), "86ffc7e756"); ss.clear();
154 ss << VARINT(0xffffffff); BOOST_CHECK_EQUAL(HexStr(ss), "8efefefe7f"); ss.clear();
155 ss << VARINT_MODE(0x7fffffffffffffffLL, VarIntMode::NONNEGATIVE_SIGNED); BOOST_CHECK_EQUAL(HexStr(ss), "fefefefefefefefe7f"); ss.clear();
156 ss << VARINT(0xffffffffffffffffULL); BOOST_CHECK_EQUAL(HexStr(ss), "80fefefefefefefefe7f"); ss.clear();
157}
158
160{
161 DataStream ss{};
162 std::vector<char>::size_type i, j;
163
164 for (i = 1; i <= MAX_SIZE; i *= 2)
165 {
166 WriteCompactSize(ss, i-1);
168 }
169 for (i = 1; i <= MAX_SIZE; i *= 2)
170 {
172 BOOST_CHECK_MESSAGE((i-1) == j, "decoded:" << j << " expected:" << (i-1));
174 BOOST_CHECK_MESSAGE(i == j, "decoded:" << j << " expected:" << i);
175 }
176}
177
178static bool isCanonicalException(const std::ios_base::failure& ex)
179{
180 std::ios_base::failure expectedException("non-canonical ReadCompactSize()");
181
182 // The string returned by what() can be different for different platforms.
183 // Instead of directly comparing the ex.what() with an expected string,
184 // create an instance of exception to see if ex.what() matches
185 // the expected explanatory string returned by the exception instance.
186 return strcmp(expectedException.what(), ex.what()) == 0;
187}
188
190{
191 std::vector<uint8_t> vec1{1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1};
192 std::vector<bool> vec2{1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1};
193
194 BOOST_CHECK(vec1 == std::vector<uint8_t>(vec2.begin(), vec2.end()));
195 BOOST_CHECK((HashWriter{} << vec1).GetHash() == (HashWriter{} << vec2).GetHash());
196}
197
199{
200 std::array<uint8_t, 32> array1{1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1};
202 ds << array1;
203 std::array<uint8_t, 32> array2;
204 ds >> array2;
206}
207
209{
210 // Write some non-canonical CompactSize encodings, and
211 // make sure an exception is thrown when read back.
212 DataStream ss{};
213 std::vector<char>::size_type n;
214
215 // zero encoded with three bytes:
216 ss << std::span{"\xfd\x00\x00"}.first(3);
218
219 // 0xfc encoded with three bytes:
220 ss << std::span{"\xfd\xfc\x00"}.first(3);
222
223 // 0xfd encoded with three bytes is OK:
224 ss << std::span{"\xfd\xfd\x00"}.first(3);
225 n = ReadCompactSize(ss);
226 BOOST_CHECK(n == 0xfd);
227
228 // zero encoded with five bytes:
229 ss << std::span{"\xfe\x00\x00\x00\x00"}.first(5);
231
232 // 0xffff encoded with five bytes:
233 ss << std::span{"\xfe\xff\xff\x00\x00"}.first(5);
235
236 // zero encoded with nine bytes:
237 ss << std::span{"\xff\x00\x00\x00\x00\x00\x00\x00\x00"}.first(9);
239
240 // 0x01ffffff encoded with nine bytes:
241 ss << std::span{"\xff\xff\xff\xff\x01\x00\x00\x00\x00"}.first(9);
243}
244
246{
247 // A CompactSize prefix followed by fewer bytes than it announces fails to read.
248 for (const char* hex : {"fd", "fd01", "fe010000", "ff01000000000000"}) {
249 DataStream ss{ParseHex(hex)};
250 BOOST_CHECK_EXCEPTION(ReadCompactSize(ss), std::ios_base::failure, HasReason{"end of data"});
251 }
252}
253
255{
256 const std::string_view sv{"hello, world"};
258 ss << sv;
259 std::string s;
260 ss >> s;
262}
263
265{
266 const std::vector<int> v = {1,2,3,4,-5,-6,-7,-8,-9,-10,10000,20000,-30000};
267
268 auto check = [&]<size_t N>() {
270 ss << v;
271 try {
272 std::vector<int> r;
273 ss >> LIMITED_VECTOR(r, N);
274 BOOST_CHECK_LE(r.size(), N);
275 BOOST_CHECK(std::ranges::equal(r, v));
276 } catch (const std::ios_base::failure&) {
277 BOOST_CHECK_GT(v.size(), N);
278 }
279 };
280 check.operator()<0>();
281 check.operator()<10>();
282 check.operator()<12>();
283 check.operator()<13>();
284 check.operator()<14>();
285 check.operator()<100>();
286}
287
289{
290 int intval(100);
291 bool boolval(true);
292 std::string stringval("testing");
293 const uint8_t charstrval[16]{"testing charstr"};
296 CSerializeMethodsTestSingle methodtest1(intval, boolval, stringval, charstrval, tx_ref);
297 CSerializeMethodsTestMany methodtest2(intval, boolval, stringval, charstrval, tx_ref);
302 ss << methodtest1;
303 ss >> methodtest4;
304 ss << methodtest2;
305 ss >> methodtest3;
309
311 ss2 << intval << boolval << stringval << charstrval << TX_WITH_WITNESS(txval);
312 ss2 >> methodtest3;
314 {
316 const std::string in{"ab"};
317 ds << std::span{in} << std::byte{'c'};
318 std::array<std::byte, 2> out;
319 std::byte out_3;
320 ds >> std::span{out} >> out_3;
321 BOOST_CHECK_EQUAL(out.at(0), std::byte{'a'});
322 BOOST_CHECK_EQUAL(out.at(1), std::byte{'b'});
323 BOOST_CHECK_EQUAL(out_3, std::byte{'c'});
324 }
325}
326
328 const enum {
333};
336
338class Base
339{
340public:
342
343 Base() : m_base_data(17) {}
345
346 template <typename Stream>
347 void Serialize(Stream& s) const
348 {
349 if (s.template GetParams<BaseFormat>().m_base_format == BaseFormat::RAW) {
350 s << m_base_data;
351 } else {
353 }
354 }
355
356 template <typename Stream>
357 void Unserialize(Stream& s)
358 {
359 if (s.template GetParams<BaseFormat>().m_base_format == BaseFormat::RAW) {
360 s >> m_base_data;
361 } else {
362 std::string hex{"aa"};
363 s >> std::span{hex}.first(hex.size());
364 m_base_data = TryParseHex<uint8_t>(hex).value().at(0);
365 }
366 }
367};
368
381
382class Derived : public Base
383{
384public:
385 std::string m_derived_data;
386
388 {
389 auto& fmt = SER_PARAMS(DerivedAndBaseFormat);
390 READWRITE(fmt.m_base_format(AsBase<Base>(obj)));
391
392 if (ser_action.ForRead()) {
393 std::string str;
394 s >> str;
395 SER_READ(obj, obj.m_derived_data = str);
396 } else {
397 s << (fmt.m_derived_format == DerivedAndBaseFormat::DerivedFormat::LOWER ?
398 ToLower(obj.m_derived_data) :
399 ToUpper(obj.m_derived_data));
400 }
401 }
402};
403
408
413{
414public:
415 template <typename Stream>
416 void Serialize(Stream& s) const
417 {
418 const uint8_t param = s.template GetParams<OtherParam>().param;
419 s << param;
420 }
421
422 template <typename Stream>
423 void Unserialize(Stream& s) const
424 {
425 const uint8_t param = s.template GetParams<OtherParam>().param;
426 uint8_t value;
427 s >> value;
428 BOOST_CHECK_EQUAL(value, param);
429 }
430};
431
440{
441 const OtherParam other_param_used{.param = 0x10};
442 const OtherParam other_param_ignored{.param = 0x11};
444 const OtherParamChecker check;
447
448 Base base1{0x20};
449 pstream << base1 << check << other_param_override(check);
450 BOOST_CHECK_EQUAL(stream.str(), "\x20\x10\x12");
451
452 Base base2;
453 pstream >> base2 >> check >> other_param_override(check);
454 BOOST_CHECK_EQUAL(base2.m_base_data, 0x20);
455}
456
459{
460 UncopyableStream stream{MakeByteSpan(std::string_view{"abc"})};
461 ParamsStream pstream{std::move(stream), RAW, HEX, RAW};
462 BOOST_CHECK_EQUAL(pstream.GetStream().str(), "abc");
463 pstream.GetStream().clear();
464
465 Base base1{0x20};
466 pstream << base1;
467 BOOST_CHECK_EQUAL(pstream.GetStream().str(), "\x20");
468
469 Base base2;
470 pstream >> base2;
471 BOOST_CHECK_EQUAL(base2.m_base_data, 0x20);
472}
473
475{
476 Base b{0x0F};
477
479
480 stream << RAW(b);
481 BOOST_CHECK_EQUAL(stream.str(), "\x0F");
482
483 b.m_base_data = 0;
484 stream >> RAW(b);
485 BOOST_CHECK_EQUAL(b.m_base_data, 0x0F);
486
487 stream.clear();
488
489 stream << HEX(b);
490 BOOST_CHECK_EQUAL(stream.str(), "0f");
491
492 b.m_base_data = 0;
493 stream >> HEX(b);
494 BOOST_CHECK_EQUAL(b.m_base_data, 0x0F);
495}
496
498{
499 std::vector<Base> v{Base{0x0F}, Base{0xFF}};
500
502
503 stream << RAW(v);
504 BOOST_CHECK_EQUAL(stream.str(), "\x02\x0F\xFF");
505
506 v[0].m_base_data = 0;
507 v[1].m_base_data = 0;
508 stream >> RAW(v);
509 BOOST_CHECK_EQUAL(v[0].m_base_data, 0x0F);
510 BOOST_CHECK_EQUAL(v[1].m_base_data, 0xFF);
511
512 stream.clear();
513
514 stream << HEX(v);
515 BOOST_CHECK_EQUAL(stream.str(), "\x02"
516 "0fff");
517
518 v[0].m_base_data = 0;
519 v[1].m_base_data = 0;
520 stream >> HEX(v);
521 BOOST_CHECK_EQUAL(v[0].m_base_data, 0x0F);
522 BOOST_CHECK_EQUAL(v[1].m_base_data, 0xFF);
523}
524
527
529{
530 Derived d;
531 d.m_base_data = 0x0F;
532 d.m_derived_data = "xY";
533
535
536 stream << RAW_LOWER(d);
537
538 stream << HEX_UPPER(d);
539
540 BOOST_CHECK_EQUAL(stream.str(), "\x0F\x02xy"
541 "0f\x02XY");
542}
543
(Un)serialize a number as raw byte or 2 hexadecimal chars.
uint8_t m_base_data
void Unserialize(Stream &s)
void Serialize(Stream &s) const
Base(uint8_t data)
SERIALIZE_METHODS(CSerializeMethodsTestMany, obj)
CSerializeMethodsTestSingle(int intvalin, bool boolvalin, std::string stringvalin, const uint8_t *charstrvalin, const CTransactionRef &txvalin)
SERIALIZE_METHODS(CSerializeMethodsTestSingle, obj)
bool operator==(const CSerializeMethodsTestSingle &rhs) const
Double ended buffer combining vector and stream-like interfaces.
Definition streams.h:165
size_type size() const
Definition streams.h:198
vector_type::size_type size_type
Definition streams.h:173
void clear()
Definition streams.h:204
DataStream()=default
enum DerivedAndBaseFormat::DerivedFormat m_derived_format
std::string m_derived_data
SERIALIZE_METHODS(Derived, obj)
BOOST_CHECK_EXCEPTION predicates to check the specific validation error.
Definition common.h:19
A writer stream (for serialization) that computes a 256-bit hash.
Definition hash.h:109
Checker for value of OtherParam.
void Unserialize(Stream &s) const
void Serialize(Stream &s) const
Wrapper that overrides the GetParams() function of a stream.
Definition serialize.h:1169
UncopyableStream & operator=(const UncopyableStream &)=delete
UncopyableStream(const UncopyableStream &)=delete
UncopyableStream(UncopyableStream &&) noexcept=default
static const PrecomputedData data
Precomputed COutPoint and CCoins values.
BOOST_FIXTURE_TEST_SUITE(cuckoocache_tests, BasicTestingSetup)
Test Suite for CuckooCache.
BOOST_AUTO_TEST_SUITE_END()
std::string HexStr(const std::span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition hex_base.cpp:30
BOOST_CHECK_GT(excessive_headers.size(), MAX_HEADERS_SIZE)
BOOST_CHECK_EXCEPTION(HTTPHeaders{}.Read(reader), std::runtime_error, HasReason{"Empty HTTP header name"})
#define BOOST_CHECK_EQUAL(v1, v2)
Definition object.cpp:17
#define BOOST_CHECK(expr)
Definition object.cpp:16
constexpr TransactionSerParams TX_WITH_WITNESS
static CTransactionRef MakeTransactionRef(Tx &&txIn)
std::shared_ptr< const CTransaction > CTransactionRef
#define VARINT(obj)
Definition serialize.h:494
#define VARINT_MODE(obj, mode)
Definition serialize.h:493
#define SER_PARAMS(type)
Formatter methods can retrieve parameters attached to a stream using the SER_PARAMS(type) macro as lo...
Definition serialize.h:209
@ NONNEGATIVE_SIGNED
constexpr uint64_t MAX_SIZE
The maximum size of a serialized object in bytes or number of elements (for eg vectors) when the size...
Definition serialize.h:35
#define LIMITED_VECTOR(obj, n)
Definition serialize.h:497
void WriteCompactSize(SizeComputer &os, uint64_t nSize)
Definition serialize.h:1151
#define SER_READ(obj, code)
Definition serialize.h:149
#define SER_PARAMS_OPFUNC
Helper macro for SerParams structs.
Definition serialize.h:1274
uint64_t ReadCompactSize(Stream &is, bool range_check=true)
Decode a CompactSize-encoded variable-length integer.
Definition serialize.h:333
uint64_t GetSerializeSize(const T &t)
Definition serialize.h:1157
#define READWRITE(...)
Definition serialize.h:148
constexpr DerivedAndBaseFormat HEX_UPPER
constexpr BaseFormat RAW
constexpr DerivedAndBaseFormat RAW_LOWER
constexpr BaseFormat HEX
static bool isCanonicalException(const std::ios_base::failure &ex)
BOOST_AUTO_TEST_CASE(sizes)
auto MakeByteSpan(const V &v) noexcept
Definition span.h:84
std::vector< Byte > ParseHex(std::string_view hex_str)
Like TryParseHex, but returns an empty vector on invalid input.
enum BaseFormat::@15 m_base_format
Basic testing setup.
A mutable version of CTransaction.
DataStream ss
std::string ToUpper(std::string_view str)
Returns the uppercase equivalent of the given string.
std::string ToLower(std::string_view str)
Returns the lowercase equivalent of the given string.
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.
Definition time.h:82