Bitcoin Core 31.99.0
P2P Digital Currency
serialize.h
Go to the documentation of this file.
1// Copyright (c) 2009-2010 Satoshi Nakamoto
2// Copyright (c) 2009-present The Bitcoin Core developers
3// Distributed under the MIT software license, see the accompanying
4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6#ifndef BITCOIN_SERIALIZE_H
7#define BITCOIN_SERIALIZE_H
8
9#include <attributes.h>
10#include <compat/assumptions.h> // IWYU pragma: keep
11#include <compat/endian.h>
12#include <prevector.h>
13#include <span.h>
14#include <util/overflow.h>
15
16#include <algorithm>
17#include <concepts>
18#include <cstdint>
19#include <cstring>
20#include <ios>
21#include <limits>
22#include <map>
23#include <memory>
24#include <set>
25#include <span>
26#include <string>
27#include <utility>
28#include <vector>
29
34static constexpr uint64_t MAX_SIZE = 0x02000000;
35
37static const unsigned int MAX_VECTOR_ALLOCATE = 5000000;
38
52
53/*
54 * Lowest-level serialization and conversion.
55 */
56template<typename Stream> inline void ser_writedata8(Stream &s, uint8_t obj)
57{
58 s.write(std::as_bytes(std::span{&obj, 1}));
59}
60template<typename Stream> inline void ser_writedata16(Stream &s, uint16_t obj)
61{
62 obj = htole16_internal(obj);
63 s.write(std::as_bytes(std::span{&obj, 1}));
64}
65template<typename Stream> inline void ser_writedata32(Stream &s, uint32_t obj)
66{
67 obj = htole32_internal(obj);
68 s.write(std::as_bytes(std::span{&obj, 1}));
69}
70template<typename Stream> inline void ser_writedata32be(Stream &s, uint32_t obj)
71{
72 obj = htobe32_internal(obj);
73 s.write(std::as_bytes(std::span{&obj, 1}));
74}
75template<typename Stream> inline void ser_writedata64(Stream &s, uint64_t obj)
76{
77 obj = htole64_internal(obj);
78 s.write(std::as_bytes(std::span{&obj, 1}));
79}
80template<typename Stream> inline uint8_t ser_readdata8(Stream &s)
81{
82 uint8_t obj;
83 s.read(std::as_writable_bytes(std::span{&obj, 1}));
84 return obj;
85}
86template<typename Stream> inline uint16_t ser_readdata16(Stream &s)
87{
88 uint16_t obj;
89 s.read(std::as_writable_bytes(std::span{&obj, 1}));
90 return le16toh_internal(obj);
91}
92template<typename Stream> inline uint32_t ser_readdata32(Stream &s)
93{
94 uint32_t obj;
95 s.read(std::as_writable_bytes(std::span{&obj, 1}));
96 return le32toh_internal(obj);
97}
98template<typename Stream> inline uint32_t ser_readdata32be(Stream &s)
99{
100 uint32_t obj;
101 s.read(std::as_writable_bytes(std::span{&obj, 1}));
102 return be32toh_internal(obj);
103}
104template<typename Stream> inline uint64_t ser_readdata64(Stream &s)
105{
106 uint64_t obj;
107 s.read(std::as_writable_bytes(std::span{&obj, 1}));
108 return le64toh_internal(obj);
109}
110
111
112class SizeComputer;
113
134template <class Out, class In>
136{
137 static_assert(std::is_base_of_v<Out, In>);
138 return x;
139}
140template <class Out, class In>
141const Out& AsBase(const In& x)
142{
143 static_assert(std::is_base_of_v<Out, In>);
144 return x;
145}
146
147#define READWRITE(...) (ser_action.SerReadWriteMany(s, __VA_ARGS__))
148#define SER_READ(obj, code) ser_action.SerRead(s, obj, [&](Stream& s, std::remove_const_t<Type>& obj) { code; })
149#define SER_WRITE(obj, code) ser_action.SerWrite(s, obj, [&](Stream& s, const Type& obj) { code; })
150
167#define FORMATTER_METHODS(cls, obj) \
168 template<typename Stream> \
169 static void Ser(Stream& s, const cls& obj) { SerializationOps(obj, s, ActionSerialize{}); } \
170 template<typename Stream> \
171 static void Unser(Stream& s, cls& obj) { SerializationOps(obj, s, ActionUnserialize{}); } \
172 template<typename Stream, typename Type, typename Operation> \
173 static void SerializationOps(Type& obj, Stream& s, Operation ser_action)
174
208#define SER_PARAMS(type) (s.template GetParams<type>())
209
210#define BASE_SERIALIZE_METHODS(cls) \
211 template <typename Stream> \
212 void Serialize(Stream& s) const \
213 { \
214 static_assert(std::is_same_v<const cls&, decltype(*this)>, "Serialize type mismatch"); \
215 Ser(s, *this); \
216 } \
217 template <typename Stream> \
218 void Unserialize(Stream& s) \
219 { \
220 static_assert(std::is_same_v<cls&, decltype(*this)>, "Unserialize type mismatch"); \
221 Unser(s, *this); \
222 }
223
231#define SERIALIZE_METHODS(cls, obj) \
232 BASE_SERIALIZE_METHODS(cls) \
233 FORMATTER_METHODS(cls, obj)
234
235// Templates for serializing to anything that looks like a stream,
236// i.e. anything that supports .read(std::span<std::byte>) and .write(std::span<const std::byte>)
237//
238
239// Typically int8_t and char are distinct types, but some systems may define int8_t
240// in terms of char. Forbid serialization of char in the typical case, but allow it if
241// it's the only way to describe an int8_t.
242template<class T>
243concept CharNotInt8 = std::same_as<T, char> && !std::same_as<T, int8_t>;
244
245// clang-format off
246template <typename Stream, CharNotInt8 V> void Serialize(Stream&, V) = delete; // char serialization forbidden. Use uint8_t or int8_t
247template <typename Stream> void Serialize(Stream& s, std::byte a) { ser_writedata8(s, uint8_t(a)); }
248template <typename Stream> void Serialize(Stream& s, int8_t a) { ser_writedata8(s, uint8_t(a)); }
249template <typename Stream> void Serialize(Stream& s, uint8_t a) { ser_writedata8(s, a); }
250template <typename Stream> void Serialize(Stream& s, int16_t a) { ser_writedata16(s, uint16_t(a)); }
251template <typename Stream> void Serialize(Stream& s, uint16_t a) { ser_writedata16(s, a); }
252template <typename Stream> void Serialize(Stream& s, int32_t a) { ser_writedata32(s, uint32_t(a)); }
253template <typename Stream> void Serialize(Stream& s, uint32_t a) { ser_writedata32(s, a); }
254template <typename Stream> void Serialize(Stream& s, int64_t a) { ser_writedata64(s, uint64_t(a)); }
255template <typename Stream> void Serialize(Stream& s, uint64_t a) { ser_writedata64(s, a); }
256
257template <typename Stream, BasicByte B, size_t N> void Serialize(Stream& s, const B (&a)[N]) { s.write(MakeByteSpan(a)); }
258template <typename Stream, BasicByte B, size_t N> void Serialize(Stream& s, const std::array<B, N>& a) { s.write(MakeByteSpan(a)); }
259template <typename Stream, BasicByte B, size_t N> void Serialize(Stream& s, std::span<B, N> span) { s.write(std::as_bytes(span)); }
260template <typename Stream, BasicByte B> void Serialize(Stream& s, std::span<B> span) { s.write(std::as_bytes(span)); }
261
262template <typename Stream, CharNotInt8 V> void Unserialize(Stream&, V) = delete; // char serialization forbidden. Use uint8_t or int8_t
263template <typename Stream> void Unserialize(Stream& s, std::byte& a) { a = std::byte(ser_readdata8(s)); }
264template <typename Stream> void Unserialize(Stream& s, int8_t& a) { a = int8_t(ser_readdata8(s)); }
265template <typename Stream> void Unserialize(Stream& s, uint8_t& a) { a = ser_readdata8(s); }
266template <typename Stream> void Unserialize(Stream& s, int16_t& a) { a = int16_t(ser_readdata16(s)); }
267template <typename Stream> void Unserialize(Stream& s, uint16_t& a) { a = ser_readdata16(s); }
268template <typename Stream> void Unserialize(Stream& s, int32_t& a) { a = int32_t(ser_readdata32(s)); }
269template <typename Stream> void Unserialize(Stream& s, uint32_t& a) { a = ser_readdata32(s); }
270template <typename Stream> void Unserialize(Stream& s, int64_t& a) { a = int64_t(ser_readdata64(s)); }
271template <typename Stream> void Unserialize(Stream& s, uint64_t& a) { a = ser_readdata64(s); }
272
273template <typename Stream, BasicByte B, size_t N> void Unserialize(Stream& s, B (&a)[N]) { s.read(MakeWritableByteSpan(a)); }
274template <typename Stream, BasicByte B, size_t N> void Unserialize(Stream& s, std::array<B, N>& a) { s.read(MakeWritableByteSpan(a)); }
275template <typename Stream, BasicByte B, size_t N> void Unserialize(Stream& s, std::span<B, N> span) { s.read(std::as_writable_bytes(span)); }
276template <typename Stream, BasicByte B> void Unserialize(Stream& s, std::span<B> span) { s.read(std::as_writable_bytes(span)); }
277
278template <typename Stream> void Serialize(Stream& s, bool a) { uint8_t f = a; ser_writedata8(s, f); }
279template <typename Stream> void Unserialize(Stream& s, bool& a) { uint8_t f = ser_readdata8(s); a = f; }
280// clang-format on
281
282
290constexpr inline unsigned int GetSizeOfCompactSize(uint64_t nSize)
291{
292 if (nSize < 253) return sizeof(unsigned char);
293 else if (nSize <= std::numeric_limits<uint16_t>::max()) return sizeof(unsigned char) + sizeof(uint16_t);
294 else if (nSize <= std::numeric_limits<unsigned int>::max()) return sizeof(unsigned char) + sizeof(unsigned int);
295 else return sizeof(unsigned char) + sizeof(uint64_t);
296}
297
298inline void WriteCompactSize(SizeComputer& os, uint64_t nSize);
299
300template<typename Stream>
301void WriteCompactSize(Stream& os, uint64_t nSize)
302{
303 if (nSize < 253)
304 {
305 ser_writedata8(os, nSize);
306 }
307 else if (nSize <= std::numeric_limits<uint16_t>::max())
308 {
309 ser_writedata8(os, 253);
310 ser_writedata16(os, nSize);
311 }
312 else if (nSize <= std::numeric_limits<unsigned int>::max())
313 {
314 ser_writedata8(os, 254);
315 ser_writedata32(os, nSize);
316 }
317 else
318 {
319 ser_writedata8(os, 255);
320 ser_writedata64(os, nSize);
321 }
322 return;
323}
324
331template<typename Stream>
332uint64_t ReadCompactSize(Stream& is, bool range_check = true)
333{
334 uint8_t chSize = ser_readdata8(is);
335 uint64_t nSizeRet = 0;
336 if (chSize < 253)
337 {
338 nSizeRet = chSize;
339 }
340 else if (chSize == 253)
341 {
342 nSizeRet = ser_readdata16(is);
343 if (nSizeRet < 253)
344 throw std::ios_base::failure("non-canonical ReadCompactSize()");
345 }
346 else if (chSize == 254)
347 {
348 nSizeRet = ser_readdata32(is);
349 if (nSizeRet < 0x10000u)
350 throw std::ios_base::failure("non-canonical ReadCompactSize()");
351 }
352 else
353 {
354 nSizeRet = ser_readdata64(is);
355 if (nSizeRet < 0x100000000ULL)
356 throw std::ios_base::failure("non-canonical ReadCompactSize()");
357 }
358 if (range_check && nSizeRet > MAX_SIZE) {
359 throw std::ios_base::failure("ReadCompactSize(): size too large");
360 }
361 return nSizeRet;
362}
363
399
400template <VarIntMode Mode, typename I>
402 constexpr CheckVarIntMode()
403 {
404 static_assert(Mode != VarIntMode::DEFAULT || std::is_unsigned_v<I>, "Unsigned type required with mode DEFAULT.");
405 static_assert(Mode != VarIntMode::NONNEGATIVE_SIGNED || std::is_signed_v<I>, "Signed type required with mode NONNEGATIVE_SIGNED.");
406 }
407};
408
409template<VarIntMode Mode, typename I>
410inline unsigned int GetSizeOfVarInt(I n)
411{
413 int nRet = 0;
414 while(true) {
415 nRet++;
416 if (n <= 0x7F)
417 break;
418 n = (n >> 7) - 1;
419 }
420 return nRet;
421}
422
423template<typename I>
424inline void WriteVarInt(SizeComputer& os, I n);
425
426template<typename Stream, VarIntMode Mode, typename I>
427void WriteVarInt(Stream& os, I n)
428{
430 unsigned char tmp[CeilDiv(sizeof(n) * 8, 7u)];
431 int len=0;
432 while(true) {
433 tmp[len] = (n & 0x7F) | (len ? 0x80 : 0x00);
434 if (n <= 0x7F)
435 break;
436 n = (n >> 7) - 1;
437 len++;
438 }
439 do {
440 ser_writedata8(os, tmp[len]);
441 } while(len--);
442}
443
444template<typename Stream, VarIntMode Mode, typename I>
445I ReadVarInt(Stream& is)
446{
448 I n = 0;
449 while(true) {
450 unsigned char chData = ser_readdata8(is);
451 if (n > (std::numeric_limits<I>::max() >> 7)) {
452 throw std::ios_base::failure("ReadVarInt(): size too large");
453 }
454 n = (n << 7) | (chData & 0x7F);
455 if (chData & 0x80) {
456 if (n == std::numeric_limits<I>::max()) {
457 throw std::ios_base::failure("ReadVarInt(): size too large");
458 }
459 n++;
460 } else {
461 return n;
462 }
463 }
464}
465
467template<typename Formatter, typename T>
469{
470 static_assert(std::is_lvalue_reference_v<T>, "Wrapper needs an lvalue reference type T");
471protected:
473public:
474 explicit Wrapper(T obj) : m_object(obj) {}
475 template<typename Stream> void Serialize(Stream &s) const { Formatter().Ser(s, m_object); }
476 template<typename Stream> void Unserialize(Stream &s) { Formatter().Unser(s, m_object); }
477};
478
489template<typename Formatter, typename T>
490static inline Wrapper<Formatter, T&> Using(T&& t) { return Wrapper<Formatter, T&>(t); }
491
492#define VARINT_MODE(obj, mode) Using<VarIntFormatter<mode>>(obj)
493#define VARINT(obj) Using<VarIntFormatter<VarIntMode::DEFAULT>>(obj)
494#define COMPACTSIZE(obj) Using<CompactSizeFormatter<true>>(obj)
495#define LIMITED_STRING(obj,n) Using<LimitedStringFormatter<n>>(obj)
496
498template<VarIntMode Mode>
500{
501 template<typename Stream, typename I> void Ser(Stream &s, I v)
502 {
503 WriteVarInt<Stream,Mode, std::remove_cv_t<I>>(s, v);
504 }
505
506 template<typename Stream, typename I> void Unser(Stream& s, I& v)
507 {
508 v = ReadVarInt<Stream,Mode, std::remove_cv_t<I>>(s);
509 }
510};
511
521template<int Bytes, bool BigEndian = false>
523{
524 static_assert(Bytes > 0 && Bytes <= 8, "CustomUintFormatter Bytes out of range");
525 static constexpr uint64_t MAX = 0xffffffffffffffff >> (8 * (8 - Bytes));
526
527 template <typename Stream, typename I> void Ser(Stream& s, I v)
528 {
529 if (v < 0 || v > MAX) throw std::ios_base::failure("CustomUintFormatter value out of range");
530 if (BigEndian) {
531 uint64_t raw = htobe64_internal(v);
532 s.write(std::as_bytes(std::span{&raw, 1}).last(Bytes));
533 } else {
534 uint64_t raw = htole64_internal(v);
535 s.write(std::as_bytes(std::span{&raw, 1}).first(Bytes));
536 }
537 }
538
539 template <typename Stream, typename I> void Unser(Stream& s, I& v)
540 {
541 using U = typename std::conditional_t<std::is_enum_v<I>, std::underlying_type<I>, std::common_type<I>>::type;
542 static_assert(std::numeric_limits<U>::max() >= MAX && std::numeric_limits<U>::min() <= 0, "Assigned type too small");
543 uint64_t raw = 0;
544 if (BigEndian) {
545 s.read(std::as_writable_bytes(std::span{&raw, 1}).last(Bytes));
546 v = static_cast<I>(be64toh_internal(raw));
547 } else {
548 s.read(std::as_writable_bytes(std::span{&raw, 1}).first(Bytes));
549 v = static_cast<I>(le64toh_internal(raw));
550 }
551 }
552};
553
555
557template<bool RangeCheck>
559{
560 template<typename Stream, typename I>
561 void Unser(Stream& s, I& v)
562 {
563 uint64_t n = ReadCompactSize<Stream>(s, RangeCheck);
564 if (n < std::numeric_limits<I>::min() || n > std::numeric_limits<I>::max()) {
565 throw std::ios_base::failure("CompactSize exceeds limit of type");
566 }
567 v = n;
568 }
569
570 template<typename Stream, typename I>
571 void Ser(Stream& s, I v)
572 {
573 static_assert(std::is_unsigned_v<I>, "CompactSize only supported for unsigned integers");
574 static_assert(std::numeric_limits<I>::max() <= std::numeric_limits<uint64_t>::max(), "CompactSize only supports 64-bit integers and below");
575
576 WriteCompactSize<Stream>(s, v);
577 }
578};
579
580template <typename U, bool LOSSY = false>
582 template <typename Stream, typename Tp>
583 void Unser(Stream& s, Tp& tp)
584 {
585 U u;
586 s >> u;
587 // Lossy deserialization does not make sense, so force Wnarrowing
588 tp = Tp{typename Tp::duration{typename Tp::duration::rep{u}}};
589 }
590 template <typename Stream, typename Tp>
591 void Ser(Stream& s, Tp tp)
592 {
593 if constexpr (LOSSY) {
594 s << U(tp.time_since_epoch().count());
595 } else {
596 s << U{tp.time_since_epoch().count()};
597 }
598 }
599};
600template <typename U>
602
604{
605protected:
606 uint64_t n;
607public:
608 explicit CompactSizeWriter(uint64_t n_in) : n(n_in) { }
609
610 template<typename Stream>
611 void Serialize(Stream &s) const {
612 WriteCompactSize<Stream>(s, n);
613 }
614};
615
616template<size_t Limit>
618{
619 template<typename Stream>
620 void Unser(Stream& s, std::string& v)
621 {
622 size_t size = ReadCompactSize(s);
623 if (size > Limit) {
624 throw std::ios_base::failure("String length limit exceeded");
625 }
626 v.resize(size);
627 if (size != 0) s.read(MakeWritableByteSpan(v));
628 }
629
630 template<typename Stream>
631 void Ser(Stream& s, const std::string& v)
632 {
633 s << v;
634 }
635};
636
650template<class Formatter>
652{
653 template<typename Stream, typename V>
654 void Ser(Stream& s, const V& v)
655 {
656 Formatter formatter;
657 WriteCompactSize(s, v.size());
658 for (const typename V::value_type& elem : v) {
659 formatter.Ser(s, elem);
660 }
661 }
662
663 template<typename Stream, typename V>
664 void Unser(Stream& s, V& v)
665 {
666 Formatter formatter;
667 v.clear();
668 size_t size = ReadCompactSize(s);
669 size_t allocated = 0;
670 while (allocated < size) {
671 // For DoS prevention, do not blindly allocate as much as the stream claims to contain.
672 // Instead, allocate in 5MiB batches, so that an attacker actually needs to provide
673 // X MiB of data to make us allocate X+5 Mib.
674 static_assert(sizeof(typename V::value_type) <= MAX_VECTOR_ALLOCATE, "Vector element size too large");
675 allocated = std::min(size, allocated + MAX_VECTOR_ALLOCATE / sizeof(typename V::value_type));
676 v.reserve(allocated);
677 while (v.size() < allocated) {
678 v.emplace_back();
679 formatter.Unser(s, v.back());
680 }
681 }
682 };
683};
684
692template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str);
693template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str);
694
698template<typename Stream, unsigned int N, typename T> inline void Serialize(Stream& os, const prevector<N, T>& v);
699template<typename Stream, unsigned int N, typename T> inline void Unserialize(Stream& is, prevector<N, T>& v);
700
704template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v);
705template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v);
706
710template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item);
711template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item);
712
716template<typename Stream, typename K, typename T, typename Pred, typename A> void Serialize(Stream& os, const std::map<K, T, Pred, A>& m);
717template<typename Stream, typename K, typename T, typename Pred, typename A> void Unserialize(Stream& is, std::map<K, T, Pred, A>& m);
718
722template<typename Stream, typename K, typename Pred, typename A> void Serialize(Stream& os, const std::set<K, Pred, A>& m);
723template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m);
724
728template<typename Stream, typename T> void Serialize(Stream& os, const std::shared_ptr<const T>& p);
729template<typename Stream, typename T> void Unserialize(Stream& os, std::shared_ptr<const T>& p);
730
734template<typename Stream, typename T> void Serialize(Stream& os, const std::unique_ptr<const T>& p);
735template<typename Stream, typename T> void Unserialize(Stream& os, std::unique_ptr<const T>& p);
736
737
741template <class T, class Stream>
742concept Serializable = requires(T a, Stream s) { a.Serialize(s); };
743template <typename Stream, typename T>
745void Serialize(Stream& os, const T& a)
746{
747 a.Serialize(os);
748}
749
750template <class T, class Stream>
751concept Unserializable = requires(T a, Stream s) { a.Unserialize(s); };
752template <typename Stream, typename T>
754void Unserialize(Stream& is, T&& a)
755{
756 a.Unserialize(is);
757}
758
765{
766 template<typename Stream, typename T>
767 static void Ser(Stream& s, const T& t) { Serialize(s, t); }
768
769 template<typename Stream, typename T>
770 static void Unser(Stream& s, T& t) { Unserialize(s, t); }
771};
772
773
774
775
776
780template<typename Stream, typename C>
781void Serialize(Stream& os, const std::basic_string<C>& str)
782{
783 WriteCompactSize(os, str.size());
784 if (!str.empty())
785 os.write(MakeByteSpan(str));
786}
787
788template<typename Stream, typename C>
789void Unserialize(Stream& is, std::basic_string<C>& str)
790{
791 unsigned int nSize = ReadCompactSize(is);
792 str.resize(nSize);
793 if (nSize != 0)
794 is.read(MakeWritableByteSpan(str));
795}
796
797
798
802template <typename Stream, unsigned int N, typename T>
803void Serialize(Stream& os, const prevector<N, T>& v)
804{
805 if constexpr (BasicByte<T>) { // Use optimized version for unformatted basic bytes
806 WriteCompactSize(os, v.size());
807 if (!v.empty()) os.write(MakeByteSpan(v));
808 } else {
810 }
811}
812
813
814template <typename Stream, unsigned int N, typename T>
815void Unserialize(Stream& is, prevector<N, T>& v)
816{
817 if constexpr (BasicByte<T>) { // Use optimized version for unformatted basic bytes
818 // Limit size per read so bogus size value won't cause out of memory
819 v.clear();
820 unsigned int nSize = ReadCompactSize(is);
821 unsigned int i = 0;
822 while (i < nSize) {
823 unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
824 v.resize_uninitialized(i + blk);
825 is.read(std::as_writable_bytes(std::span{&v[i], blk}));
826 i += blk;
827 }
828 } else {
830 }
831}
832
833
837template <typename Stream, typename T, typename A>
838void Serialize(Stream& os, const std::vector<T, A>& v)
839{
840 if constexpr (BasicByte<T>) { // Use optimized version for unformatted basic bytes
841 WriteCompactSize(os, v.size());
842 if (!v.empty()) os.write(MakeByteSpan(v));
843 } else if constexpr (std::is_same_v<T, bool>) {
844 // A special case for std::vector<bool>, as dereferencing
845 // std::vector<bool>::const_iterator does not result in a const bool&
846 // due to std::vector's special casing for bool arguments.
847 WriteCompactSize(os, v.size());
848 for (bool elem : v) {
849 ::Serialize(os, elem);
850 }
851 } else {
853 }
854}
855
856
857template <typename Stream, typename T, typename A>
858void Unserialize(Stream& is, std::vector<T, A>& v)
859{
860 if constexpr (BasicByte<T>) { // Use optimized version for unformatted basic bytes
861 // Limit size per read so bogus size value won't cause out of memory
862 v.clear();
863 unsigned int nSize = ReadCompactSize(is);
864 unsigned int i = 0;
865 while (i < nSize) {
866 unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
867 v.resize(i + blk);
868 is.read(std::as_writable_bytes(std::span{&v[i], blk}));
869 i += blk;
870 }
871 } else {
873 }
874}
875
876
880template<typename Stream, typename K, typename T>
881void Serialize(Stream& os, const std::pair<K, T>& item)
882{
883 Serialize(os, item.first);
884 Serialize(os, item.second);
885}
886
887template<typename Stream, typename K, typename T>
888void Unserialize(Stream& is, std::pair<K, T>& item)
889{
890 Unserialize(is, item.first);
891 Unserialize(is, item.second);
892}
893
894
895
899template<typename Stream, typename K, typename T, typename Pred, typename A>
900void Serialize(Stream& os, const std::map<K, T, Pred, A>& m)
901{
902 WriteCompactSize(os, m.size());
903 for (const auto& entry : m)
904 Serialize(os, entry);
905}
906
907template<typename Stream, typename K, typename T, typename Pred, typename A>
908void Unserialize(Stream& is, std::map<K, T, Pred, A>& m)
909{
910 m.clear();
911 unsigned int nSize = ReadCompactSize(is);
912 typename std::map<K, T, Pred, A>::iterator mi = m.begin();
913 for (unsigned int i = 0; i < nSize; i++)
914 {
915 std::pair<K, T> item;
916 Unserialize(is, item);
917 mi = m.insert(mi, item);
918 }
919}
920
921
922
926template<typename Stream, typename K, typename Pred, typename A>
927void Serialize(Stream& os, const std::set<K, Pred, A>& m)
928{
929 WriteCompactSize(os, m.size());
930 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
931 Serialize(os, (*it));
932}
933
934template<typename Stream, typename K, typename Pred, typename A>
935void Unserialize(Stream& is, std::set<K, Pred, A>& m)
936{
937 m.clear();
938 unsigned int nSize = ReadCompactSize(is);
939 typename std::set<K, Pred, A>::iterator it = m.begin();
940 for (unsigned int i = 0; i < nSize; i++)
941 {
942 K key;
943 Unserialize(is, key);
944 it = m.insert(it, key);
945 }
946}
947
948
949
953template<typename Stream, typename T> void
954Serialize(Stream& os, const std::unique_ptr<const T>& p)
955{
956 Serialize(os, *p);
957}
958
959template<typename Stream, typename T>
960void Unserialize(Stream& is, std::unique_ptr<const T>& p)
961{
962 p.reset(new T(deserialize, is));
963}
964
965
966
970template<typename Stream, typename T> void
971Serialize(Stream& os, const std::shared_ptr<const T>& p)
972{
973 Serialize(os, *p);
974}
975
976template<typename Stream, typename T>
977void Unserialize(Stream& is, std::shared_ptr<const T>& p)
978{
979 p = std::make_shared<const T>(deserialize, is);
980}
981
986template <typename Stream, typename... Args>
987void SerializeMany(Stream& s, const Args&... args)
988{
989 (::Serialize(s, args), ...);
990}
991
992template <typename Stream, typename... Args>
993inline void UnserializeMany(Stream& s, Args&&... args)
994{
995 (::Unserialize(s, args), ...);
996}
997
1002 static constexpr bool ForRead() { return false; }
1003
1004 template<typename Stream, typename... Args>
1005 static void SerReadWriteMany(Stream& s, const Args&... args)
1006 {
1007 ::SerializeMany(s, args...);
1008 }
1009
1010 template<typename Stream, typename Type, typename Fn>
1011 static void SerRead(Stream& s, Type&&, Fn&&)
1012 {
1013 }
1014
1015 template<typename Stream, typename Type, typename Fn>
1016 static void SerWrite(Stream& s, Type&& obj, Fn&& fn)
1017 {
1018 fn(s, std::forward<Type>(obj));
1019 }
1020};
1022 static constexpr bool ForRead() { return true; }
1023
1024 template<typename Stream, typename... Args>
1025 static void SerReadWriteMany(Stream& s, Args&&... args)
1026 {
1028 }
1029
1030 template<typename Stream, typename Type, typename Fn>
1031 static void SerRead(Stream& s, Type&& obj, Fn&& fn)
1032 {
1033 fn(s, std::forward<Type>(obj));
1034 }
1035
1036 template<typename Stream, typename Type, typename Fn>
1037 static void SerWrite(Stream& s, Type&&, Fn&&)
1038 {
1039 }
1040};
1041
1042/* ::GetSerializeSize implementations
1043 *
1044 * Computing the serialized size of objects is done through a special stream
1045 * object of type SizeComputer, which only records the number of bytes written
1046 * to it.
1047 *
1048 * If your Serialize or SerializationOp method has non-trivial overhead for
1049 * serialization, it may be worthwhile to implement a specialized version for
1050 * SizeComputer, which uses the s.seek() method to record bytes that would
1051 * be written instead.
1052 */
1054{
1055protected:
1056 uint64_t m_size{0};
1057
1058public:
1059 SizeComputer() = default;
1060
1061 void write(std::span<const std::byte> src)
1062 {
1063 m_size += src.size();
1064 }
1065
1067 void seek(uint64_t num)
1068 {
1069 m_size += num;
1070 }
1071
1072 template <typename T>
1074 {
1075 ::Serialize(*this, obj);
1076 return *this;
1077 }
1078
1079 uint64_t size() const
1080 {
1081 return m_size;
1082 }
1083};
1084
1085template<typename I>
1086inline void WriteVarInt(SizeComputer &s, I n)
1087{
1088 s.seek(GetSizeOfVarInt<I>(n));
1089}
1090
1091inline void WriteCompactSize(SizeComputer &s, uint64_t nSize)
1092{
1093 s.seek(GetSizeOfCompactSize(nSize));
1094}
1095
1096template <typename T>
1097uint64_t GetSerializeSize(const T& t)
1098{
1099 return (SizeComputer() << t).size();
1100}
1101
1103template<typename T>
1104concept ContainsStream = requires(T t) { t.GetStream(); };
1105
1107template <typename SubStream, typename Params>
1109{
1111 // If ParamsStream constructor is passed an lvalue argument, Substream will
1112 // be a reference type, and m_substream will reference that argument.
1113 // Otherwise m_substream will be a substream instance and move from the
1114 // argument. Letting ParamsStream contain a substream instance instead of
1115 // just a reference is useful to make the ParamsStream object self contained
1116 // and let it do cleanup when destroyed, for example by closing files if
1117 // SubStream is a file stream.
1118 SubStream m_substream;
1119
1120public:
1121 ParamsStream(SubStream&& substream, const Params& params LIFETIMEBOUND) : m_params{params}, m_substream{std::forward<SubStream>(substream)} {}
1122
1123 template <typename NestedSubstream, typename Params1, typename Params2, typename... NestedParams>
1124 ParamsStream(NestedSubstream&& s, const Params1& params1 LIFETIMEBOUND, const Params2& params2 LIFETIMEBOUND, const NestedParams&... params LIFETIMEBOUND)
1125 : ParamsStream{::ParamsStream{std::forward<NestedSubstream>(s), params2, params...}, params1} {}
1126
1127 template <typename U> ParamsStream& operator<<(const U& obj) { ::Serialize(*this, obj); return *this; }
1128 template <typename U> ParamsStream& operator>>(U&& obj) { ::Unserialize(*this, obj); return *this; }
1129 void write(std::span<const std::byte> src) { GetStream().write(src); }
1130 void read(std::span<std::byte> dst) { GetStream().read(dst); }
1131 void ignore(size_t num) { GetStream().ignore(num); }
1132 bool empty() const { return GetStream().empty(); }
1133 size_t size() const { return GetStream().size(); }
1134
1136 template <typename P>
1137 const auto& GetParams() const
1138 {
1139 if constexpr (std::is_convertible_v<Params, P>) {
1140 return m_params;
1141 } else {
1142 return m_substream.template GetParams<P>();
1143 }
1144 }
1145
1148 {
1149 if constexpr (ContainsStream<SubStream>) {
1150 return m_substream.GetStream();
1151 } else {
1152 return m_substream;
1153 }
1154 }
1155 const auto& GetStream() const
1156 {
1157 if constexpr (ContainsStream<SubStream>) {
1158 return m_substream.GetStream();
1159 } else {
1160 return m_substream;
1161 }
1162 }
1163};
1164
1170template <typename Substream, typename Params>
1172
1177template <typename Substream, typename Params1, typename Params2, typename... Params>
1178ParamsStream(Substream&& s, const Params1& params1, const Params2& params2, const Params&... params) ->
1179 ParamsStream<decltype(ParamsStream{std::forward<Substream>(s), params2, params...}), Params1>;
1180
1182template <typename Params, typename T>
1184{
1187
1188public:
1189 explicit ParamsWrapper(const Params& params, T& obj) : m_params{params}, m_object{obj} {}
1190
1191 template <typename Stream>
1192 void Serialize(Stream& s) const
1193 {
1194 ParamsStream ss{s, m_params};
1195 ::Serialize(ss, m_object);
1196 }
1197 template <typename Stream>
1198 void Unserialize(Stream& s)
1199 {
1200 ParamsStream ss{s, m_params};
1202 }
1203};
1204
1214#define SER_PARAMS_OPFUNC \
1215 \
1220 template <typename T> \
1221 auto operator()(T&& t) const \
1222 { \
1223 return ParamsWrapper{*this, t}; \
1224 }
1225
1226#endif // BITCOIN_SERIALIZE_H
#define LIFETIMEBOUND
Definition: attributes.h:16
ArgsManager & args
Definition: bitcoind.cpp:277
const CChainParams & Params()
Return the currently selected parameters.
void Serialize(Stream &s) const
Definition: serialize.h:611
CompactSizeWriter(uint64_t n_in)
Definition: serialize.h:608
Wrapper that overrides the GetParams() function of a stream.
Definition: serialize.h:1109
ParamsStream & operator<<(const U &obj)
Definition: serialize.h:1127
ParamsStream & operator>>(U &&obj)
Definition: serialize.h:1128
ParamsStream(NestedSubstream &&s, const Params1 &params1 LIFETIMEBOUND, const Params2 &params2 LIFETIMEBOUND, const NestedParams &... params LIFETIMEBOUND)
Definition: serialize.h:1124
auto & GetStream()
Get reference to underlying stream.
Definition: serialize.h:1147
bool empty() const
Definition: serialize.h:1132
size_t size() const
Definition: serialize.h:1133
void ignore(size_t num)
Definition: serialize.h:1131
const Params & m_params
Definition: serialize.h:1110
const auto & GetParams() const
Get reference to stream parameters.
Definition: serialize.h:1137
void write(std::span< const std::byte > src)
Definition: serialize.h:1129
SubStream m_substream
Definition: serialize.h:1118
void read(std::span< std::byte > dst)
Definition: serialize.h:1130
const auto & GetStream() const
Definition: serialize.h:1155
ParamsStream(SubStream &&substream, const Params &params LIFETIMEBOUND)
Definition: serialize.h:1121
Wrapper that serializes objects with the specified parameters.
Definition: serialize.h:1184
const Params & m_params
Definition: serialize.h:1185
void Unserialize(Stream &s)
Definition: serialize.h:1198
void Serialize(Stream &s) const
Definition: serialize.h:1192
ParamsWrapper(const Params &params, T &obj)
Definition: serialize.h:1189
void seek(uint64_t num)
Pretend this many bytes are written, without specifying them.
Definition: serialize.h:1067
void write(std::span< const std::byte > src)
Definition: serialize.h:1061
uint64_t m_size
Definition: serialize.h:1056
SizeComputer()=default
uint64_t size() const
Definition: serialize.h:1079
SizeComputer & operator<<(const T &obj)
Definition: serialize.h:1073
Simple wrapper class to serialize objects using a formatter; used by Using().
Definition: serialize.h:469
Wrapper(T obj)
Definition: serialize.h:474
T m_object
Definition: serialize.h:472
void Serialize(Stream &s) const
Definition: serialize.h:475
void Unserialize(Stream &s)
Definition: serialize.h:476
Implements a drop-in replacement for std::vector<T> which stores up to N elements directly (without h...
Definition: prevector.h:37
bool empty() const
Definition: prevector.h:251
void clear()
Definition: prevector.h:303
size_type size() const
Definition: prevector.h:247
void resize_uninitialized(size_type new_size)
Definition: prevector.h:349
Check if type contains a stream by seeing if has a GetStream() method.
Definition: serialize.h:1104
If none of the specialized versions above matched, default to calling member function.
Definition: serialize.h:742
BSWAP_CONSTEXPR uint32_t be32toh_internal(uint32_t big_endian_32bits)
Definition: endian.h:43
BSWAP_CONSTEXPR uint64_t htobe64_internal(uint64_t host_64bits)
Definition: endian.h:53
BSWAP_CONSTEXPR uint32_t htole32_internal(uint32_t host_32bits)
Definition: endian.h:38
BSWAP_CONSTEXPR uint16_t htole16_internal(uint16_t host_16bits)
Definition: endian.h:18
BSWAP_CONSTEXPR uint64_t be64toh_internal(uint64_t big_endian_64bits)
Definition: endian.h:63
BSWAP_CONSTEXPR uint16_t le16toh_internal(uint16_t little_endian_16bits)
Definition: endian.h:28
BSWAP_CONSTEXPR uint64_t htole64_internal(uint64_t host_64bits)
Definition: endian.h:58
BSWAP_CONSTEXPR uint64_t le64toh_internal(uint64_t little_endian_64bits)
Definition: endian.h:68
BSWAP_CONSTEXPR uint32_t le32toh_internal(uint32_t little_endian_32bits)
Definition: endian.h:48
BSWAP_CONSTEXPR uint32_t htobe32_internal(uint32_t host_32bits)
Definition: endian.h:33
#define T(expected, seed, data)
Definition: common.h:29
constexpr auto CeilDiv(const Dividend dividend, const Divisor divisor)
Integer ceiling division (for unsigned values).
Definition: overflow.h:70
void Serialize(Stream &, V)=delete
constexpr unsigned int GetSizeOfCompactSize(uint64_t nSize)
Compact Size size < 253 – 1 byte size <= USHRT_MAX – 3 bytes (253 + 2 bytes) size <= UINT_MAX – 5 byt...
Definition: serialize.h:290
void SerializeMany(Stream &s, const Args &... args)
Support for (un)serializing many things at once.
Definition: serialize.h:987
static const unsigned int MAX_VECTOR_ALLOCATE
Maximum amount of memory (in bytes) to allocate at once when deserializing vectors.
Definition: serialize.h:37
uint8_t ser_readdata8(Stream &s)
Definition: serialize.h:80
I ReadVarInt(Stream &is)
Definition: serialize.h:445
void ser_writedata32be(Stream &s, uint32_t obj)
Definition: serialize.h:70
VarIntMode
Variable-length integers: bytes are a MSB base-128 encoding of the number.
Definition: serialize.h:398
@ NONNEGATIVE_SIGNED
void ser_writedata32(Stream &s, uint32_t obj)
Definition: serialize.h:65
static 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:34
constexpr deserialize_type deserialize
Definition: serialize.h:51
void ser_writedata16(Stream &s, uint16_t obj)
Definition: serialize.h:60
void Unserialize(Stream &, V)=delete
void UnserializeMany(Stream &s, Args &&... args)
Definition: serialize.h:993
Out & AsBase(In &x)
Convert any argument to a reference to X, maintaining constness.
Definition: serialize.h:135
void WriteVarInt(SizeComputer &os, I n)
Definition: serialize.h:1086
void WriteCompactSize(SizeComputer &os, uint64_t nSize)
Definition: serialize.h:1091
uint16_t ser_readdata16(Stream &s)
Definition: serialize.h:86
uint64_t ser_readdata64(Stream &s)
Definition: serialize.h:104
void ser_writedata8(Stream &s, uint8_t obj)
Definition: serialize.h:56
uint64_t ReadCompactSize(Stream &is, bool range_check=true)
Decode a CompactSize-encoded variable-length integer.
Definition: serialize.h:332
ParamsStream(Substream &&, const Params &) -> ParamsStream< Substream, Params >
Explicit template deduction guide is required for single-parameter constructor so Substream&& is trea...
static Wrapper< Formatter, T & > Using(T &&t)
Cause serialization/deserialization of an object to be done using a specified formatter class.
Definition: serialize.h:490
unsigned int GetSizeOfVarInt(I n)
Definition: serialize.h:410
uint64_t GetSerializeSize(const T &t)
Definition: serialize.h:1097
uint32_t ser_readdata32(Stream &s)
Definition: serialize.h:92
void ser_writedata64(Stream &s, uint64_t obj)
Definition: serialize.h:75
uint32_t ser_readdata32be(Stream &s)
Definition: serialize.h:98
auto MakeByteSpan(const V &v) noexcept
Definition: span.h:84
auto MakeWritableByteSpan(V &&v) noexcept
Definition: span.h:89
Support for all macros providing or using the ser_action parameter of the SerializationOps method.
Definition: serialize.h:1001
static void SerReadWriteMany(Stream &s, const Args &... args)
Definition: serialize.h:1005
static constexpr bool ForRead()
Definition: serialize.h:1002
static void SerWrite(Stream &s, Type &&obj, Fn &&fn)
Definition: serialize.h:1016
static void SerRead(Stream &s, Type &&, Fn &&)
Definition: serialize.h:1011
static constexpr bool ForRead()
Definition: serialize.h:1022
static void SerReadWriteMany(Stream &s, Args &&... args)
Definition: serialize.h:1025
static void SerRead(Stream &s, Type &&obj, Fn &&fn)
Definition: serialize.h:1031
static void SerWrite(Stream &s, Type &&, Fn &&)
Definition: serialize.h:1037
constexpr CheckVarIntMode()
Definition: serialize.h:402
void Unser(Stream &s, Tp &tp)
Definition: serialize.h:583
void Ser(Stream &s, Tp tp)
Definition: serialize.h:591
Formatter for integers in CompactSize format.
Definition: serialize.h:559
void Unser(Stream &s, I &v)
Definition: serialize.h:561
void Ser(Stream &s, I v)
Definition: serialize.h:571
Serialization wrapper class for custom integers and enums.
Definition: serialize.h:523
static constexpr uint64_t MAX
Definition: serialize.h:525
void Ser(Stream &s, I v)
Definition: serialize.h:527
void Unser(Stream &s, I &v)
Definition: serialize.h:539
Default formatter.
Definition: serialize.h:765
static void Ser(Stream &s, const T &t)
Definition: serialize.h:767
static void Unser(Stream &s, T &t)
Definition: serialize.h:770
void Unser(Stream &s, std::string &v)
Definition: serialize.h:620
void Ser(Stream &s, const std::string &v)
Definition: serialize.h:631
Serialization wrapper class for integers in VarInt format.
Definition: serialize.h:500
void Ser(Stream &s, I v)
Definition: serialize.h:501
void Unser(Stream &s, I &v)
Definition: serialize.h:506
Formatter to serialize/deserialize vector elements using another formatter.
Definition: serialize.h:652
void Unser(Stream &s, V &v)
Definition: serialize.h:664
void Ser(Stream &s, const V &v)
Definition: serialize.h:654
Dummy data type to identify deserializing constructors.
Definition: serialize.h:50
#define B
Definition: util_tests.cpp:561