Bitcoin Core 29.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
15#include <algorithm>
16#include <concepts>
17#include <cstdint>
18#include <cstring>
19#include <ios>
20#include <limits>
21#include <map>
22#include <memory>
23#include <set>
24#include <string>
25#include <utility>
26#include <vector>
27
32static constexpr uint64_t MAX_SIZE = 0x02000000;
33
35static const unsigned int MAX_VECTOR_ALLOCATE = 5000000;
36
50
51/*
52 * Lowest-level serialization and conversion.
53 */
54template<typename Stream> inline void ser_writedata8(Stream &s, uint8_t obj)
55{
56 s.write(std::as_bytes(std::span{&obj, 1}));
57}
58template<typename Stream> inline void ser_writedata16(Stream &s, uint16_t obj)
59{
60 obj = htole16_internal(obj);
61 s.write(std::as_bytes(std::span{&obj, 1}));
62}
63template<typename Stream> inline void ser_writedata16be(Stream &s, uint16_t obj)
64{
65 obj = htobe16_internal(obj);
66 s.write(std::as_bytes(std::span{&obj, 1}));
67}
68template<typename Stream> inline void ser_writedata32(Stream &s, uint32_t obj)
69{
70 obj = htole32_internal(obj);
71 s.write(std::as_bytes(std::span{&obj, 1}));
72}
73template<typename Stream> inline void ser_writedata32be(Stream &s, uint32_t obj)
74{
75 obj = htobe32_internal(obj);
76 s.write(std::as_bytes(std::span{&obj, 1}));
77}
78template<typename Stream> inline void ser_writedata64(Stream &s, uint64_t obj)
79{
80 obj = htole64_internal(obj);
81 s.write(std::as_bytes(std::span{&obj, 1}));
82}
83template<typename Stream> inline uint8_t ser_readdata8(Stream &s)
84{
85 uint8_t obj;
86 s.read(std::as_writable_bytes(std::span{&obj, 1}));
87 return obj;
88}
89template<typename Stream> inline uint16_t ser_readdata16(Stream &s)
90{
91 uint16_t obj;
92 s.read(std::as_writable_bytes(std::span{&obj, 1}));
93 return le16toh_internal(obj);
94}
95template<typename Stream> inline uint16_t ser_readdata16be(Stream &s)
96{
97 uint16_t obj;
98 s.read(std::as_writable_bytes(std::span{&obj, 1}));
99 return be16toh_internal(obj);
100}
101template<typename Stream> inline uint32_t ser_readdata32(Stream &s)
102{
103 uint32_t obj;
104 s.read(std::as_writable_bytes(std::span{&obj, 1}));
105 return le32toh_internal(obj);
106}
107template<typename Stream> inline uint32_t ser_readdata32be(Stream &s)
108{
109 uint32_t obj;
110 s.read(std::as_writable_bytes(std::span{&obj, 1}));
111 return be32toh_internal(obj);
112}
113template<typename Stream> inline uint64_t ser_readdata64(Stream &s)
114{
115 uint64_t obj;
116 s.read(std::as_writable_bytes(std::span{&obj, 1}));
117 return le64toh_internal(obj);
118}
119
120
121class SizeComputer;
122
143template <class Out, class In>
145{
146 static_assert(std::is_base_of_v<Out, In>);
147 return x;
148}
149template <class Out, class In>
150const Out& AsBase(const In& x)
151{
152 static_assert(std::is_base_of_v<Out, In>);
153 return x;
154}
155
156#define READWRITE(...) (ser_action.SerReadWriteMany(s, __VA_ARGS__))
157#define SER_READ(obj, code) ser_action.SerRead(s, obj, [&](Stream& s, std::remove_const_t<Type>& obj) { code; })
158#define SER_WRITE(obj, code) ser_action.SerWrite(s, obj, [&](Stream& s, const Type& obj) { code; })
159
176#define FORMATTER_METHODS(cls, obj) \
177 template<typename Stream> \
178 static void Ser(Stream& s, const cls& obj) { SerializationOps(obj, s, ActionSerialize{}); } \
179 template<typename Stream> \
180 static void Unser(Stream& s, cls& obj) { SerializationOps(obj, s, ActionUnserialize{}); } \
181 template<typename Stream, typename Type, typename Operation> \
182 static void SerializationOps(Type& obj, Stream& s, Operation ser_action)
183
217#define SER_PARAMS(type) (s.template GetParams<type>())
218
219#define BASE_SERIALIZE_METHODS(cls) \
220 template <typename Stream> \
221 void Serialize(Stream& s) const \
222 { \
223 static_assert(std::is_same_v<const cls&, decltype(*this)>, "Serialize type mismatch"); \
224 Ser(s, *this); \
225 } \
226 template <typename Stream> \
227 void Unserialize(Stream& s) \
228 { \
229 static_assert(std::is_same_v<cls&, decltype(*this)>, "Unserialize type mismatch"); \
230 Unser(s, *this); \
231 }
232
240#define SERIALIZE_METHODS(cls, obj) \
241 BASE_SERIALIZE_METHODS(cls) \
242 FORMATTER_METHODS(cls, obj)
243
244// Templates for serializing to anything that looks like a stream,
245// i.e. anything that supports .read(std::span<std::byte>) and .write(std::span<const std::byte>)
246//
247
248// Typically int8_t and char are distinct types, but some systems may define int8_t
249// in terms of char. Forbid serialization of char in the typical case, but allow it if
250// it's the only way to describe an int8_t.
251template<class T>
252concept CharNotInt8 = std::same_as<T, char> && !std::same_as<T, int8_t>;
253
254// clang-format off
255template <typename Stream, CharNotInt8 V> void Serialize(Stream&, V) = delete; // char serialization forbidden. Use uint8_t or int8_t
256template <typename Stream> void Serialize(Stream& s, std::byte a) { ser_writedata8(s, uint8_t(a)); }
257template <typename Stream> void Serialize(Stream& s, int8_t a) { ser_writedata8(s, uint8_t(a)); }
258template <typename Stream> void Serialize(Stream& s, uint8_t a) { ser_writedata8(s, a); }
259template <typename Stream> void Serialize(Stream& s, int16_t a) { ser_writedata16(s, uint16_t(a)); }
260template <typename Stream> void Serialize(Stream& s, uint16_t a) { ser_writedata16(s, a); }
261template <typename Stream> void Serialize(Stream& s, int32_t a) { ser_writedata32(s, uint32_t(a)); }
262template <typename Stream> void Serialize(Stream& s, uint32_t a) { ser_writedata32(s, a); }
263template <typename Stream> void Serialize(Stream& s, int64_t a) { ser_writedata64(s, uint64_t(a)); }
264template <typename Stream> void Serialize(Stream& s, uint64_t a) { ser_writedata64(s, a); }
265
266template <typename Stream, BasicByte B, size_t N> void Serialize(Stream& s, const B (&a)[N]) { s.write(MakeByteSpan(a)); }
267template <typename Stream, BasicByte B, size_t N> void Serialize(Stream& s, const std::array<B, N>& a) { s.write(MakeByteSpan(a)); }
268template <typename Stream, BasicByte B, size_t N> void Serialize(Stream& s, std::span<B, N> span) { s.write(std::as_bytes(span)); }
269template <typename Stream, BasicByte B> void Serialize(Stream& s, std::span<B> span) { s.write(std::as_bytes(span)); }
270
271template <typename Stream, CharNotInt8 V> void Unserialize(Stream&, V) = delete; // char serialization forbidden. Use uint8_t or int8_t
272template <typename Stream> void Unserialize(Stream& s, std::byte& a) { a = std::byte(ser_readdata8(s)); }
273template <typename Stream> void Unserialize(Stream& s, int8_t& a) { a = int8_t(ser_readdata8(s)); }
274template <typename Stream> void Unserialize(Stream& s, uint8_t& a) { a = ser_readdata8(s); }
275template <typename Stream> void Unserialize(Stream& s, int16_t& a) { a = int16_t(ser_readdata16(s)); }
276template <typename Stream> void Unserialize(Stream& s, uint16_t& a) { a = ser_readdata16(s); }
277template <typename Stream> void Unserialize(Stream& s, int32_t& a) { a = int32_t(ser_readdata32(s)); }
278template <typename Stream> void Unserialize(Stream& s, uint32_t& a) { a = ser_readdata32(s); }
279template <typename Stream> void Unserialize(Stream& s, int64_t& a) { a = int64_t(ser_readdata64(s)); }
280template <typename Stream> void Unserialize(Stream& s, uint64_t& a) { a = ser_readdata64(s); }
281
282template <typename Stream, BasicByte B, size_t N> void Unserialize(Stream& s, B (&a)[N]) { s.read(MakeWritableByteSpan(a)); }
283template <typename Stream, BasicByte B, size_t N> void Unserialize(Stream& s, std::array<B, N>& a) { s.read(MakeWritableByteSpan(a)); }
284template <typename Stream, BasicByte B, size_t N> void Unserialize(Stream& s, std::span<B, N> span) { s.read(std::as_writable_bytes(span)); }
285template <typename Stream, BasicByte B> void Unserialize(Stream& s, std::span<B> span) { s.read(std::as_writable_bytes(span)); }
286
287template <typename Stream> void Serialize(Stream& s, bool a) { uint8_t f = a; ser_writedata8(s, f); }
288template <typename Stream> void Unserialize(Stream& s, bool& a) { uint8_t f = ser_readdata8(s); a = f; }
289// clang-format on
290
291
299constexpr inline unsigned int GetSizeOfCompactSize(uint64_t nSize)
300{
301 if (nSize < 253) return sizeof(unsigned char);
302 else if (nSize <= std::numeric_limits<uint16_t>::max()) return sizeof(unsigned char) + sizeof(uint16_t);
303 else if (nSize <= std::numeric_limits<unsigned int>::max()) return sizeof(unsigned char) + sizeof(unsigned int);
304 else return sizeof(unsigned char) + sizeof(uint64_t);
305}
306
307inline void WriteCompactSize(SizeComputer& os, uint64_t nSize);
308
309template<typename Stream>
310void WriteCompactSize(Stream& os, uint64_t nSize)
311{
312 if (nSize < 253)
313 {
315 }
316 else if (nSize <= std::numeric_limits<uint16_t>::max())
317 {
318 ser_writedata8(os, 253);
320 }
321 else if (nSize <= std::numeric_limits<unsigned int>::max())
322 {
323 ser_writedata8(os, 254);
325 }
326 else
327 {
328 ser_writedata8(os, 255);
330 }
331 return;
332}
333
340template<typename Stream>
341uint64_t ReadCompactSize(Stream& is, bool range_check = true)
342{
343 uint8_t chSize = ser_readdata8(is);
344 uint64_t nSizeRet = 0;
345 if (chSize < 253)
346 {
347 nSizeRet = chSize;
348 }
349 else if (chSize == 253)
350 {
351 nSizeRet = ser_readdata16(is);
352 if (nSizeRet < 253)
353 throw std::ios_base::failure("non-canonical ReadCompactSize()");
354 }
355 else if (chSize == 254)
356 {
357 nSizeRet = ser_readdata32(is);
358 if (nSizeRet < 0x10000u)
359 throw std::ios_base::failure("non-canonical ReadCompactSize()");
360 }
361 else
362 {
363 nSizeRet = ser_readdata64(is);
364 if (nSizeRet < 0x100000000ULL)
365 throw std::ios_base::failure("non-canonical ReadCompactSize()");
366 }
367 if (range_check && nSizeRet > MAX_SIZE) {
368 throw std::ios_base::failure("ReadCompactSize(): size too large");
369 }
370 return nSizeRet;
371}
372
408
409template <VarIntMode Mode, typename I>
411 constexpr CheckVarIntMode()
412 {
413 static_assert(Mode != VarIntMode::DEFAULT || std::is_unsigned_v<I>, "Unsigned type required with mode DEFAULT.");
414 static_assert(Mode != VarIntMode::NONNEGATIVE_SIGNED || std::is_signed_v<I>, "Signed type required with mode NONNEGATIVE_SIGNED.");
415 }
416};
417
418template<VarIntMode Mode, typename I>
419inline unsigned int GetSizeOfVarInt(I n)
420{
422 int nRet = 0;
423 while(true) {
424 nRet++;
425 if (n <= 0x7F)
426 break;
427 n = (n >> 7) - 1;
428 }
429 return nRet;
430}
431
432template<typename I>
433inline void WriteVarInt(SizeComputer& os, I n);
434
435template<typename Stream, VarIntMode Mode, typename I>
436void WriteVarInt(Stream& os, I n)
437{
439 unsigned char tmp[(sizeof(n)*8+6)/7];
440 int len=0;
441 while(true) {
442 tmp[len] = (n & 0x7F) | (len ? 0x80 : 0x00);
443 if (n <= 0x7F)
444 break;
445 n = (n >> 7) - 1;
446 len++;
447 }
448 do {
449 ser_writedata8(os, tmp[len]);
450 } while(len--);
451}
452
453template<typename Stream, VarIntMode Mode, typename I>
454I ReadVarInt(Stream& is)
455{
457 I n = 0;
458 while(true) {
459 unsigned char chData = ser_readdata8(is);
460 if (n > (std::numeric_limits<I>::max() >> 7)) {
461 throw std::ios_base::failure("ReadVarInt(): size too large");
462 }
463 n = (n << 7) | (chData & 0x7F);
464 if (chData & 0x80) {
465 if (n == std::numeric_limits<I>::max()) {
466 throw std::ios_base::failure("ReadVarInt(): size too large");
467 }
468 n++;
469 } else {
470 return n;
471 }
472 }
473}
474
476template<typename Formatter, typename T>
478{
479 static_assert(std::is_lvalue_reference_v<T>, "Wrapper needs an lvalue reference type T");
480protected:
482public:
483 explicit Wrapper(T obj) : m_object(obj) {}
484 template<typename Stream> void Serialize(Stream &s) const { Formatter().Ser(s, m_object); }
485 template<typename Stream> void Unserialize(Stream &s) { Formatter().Unser(s, m_object); }
486};
487
498template<typename Formatter, typename T>
499static inline Wrapper<Formatter, T&> Using(T&& t) { return Wrapper<Formatter, T&>(t); }
500
501#define VARINT_MODE(obj, mode) Using<VarIntFormatter<mode>>(obj)
502#define VARINT(obj) Using<VarIntFormatter<VarIntMode::DEFAULT>>(obj)
503#define COMPACTSIZE(obj) Using<CompactSizeFormatter<true>>(obj)
504#define LIMITED_STRING(obj,n) Using<LimitedStringFormatter<n>>(obj)
505
507template<VarIntMode Mode>
509{
510 template<typename Stream, typename I> void Ser(Stream &s, I v)
511 {
512 WriteVarInt<Stream,Mode, std::remove_cv_t<I>>(s, v);
513 }
514
515 template<typename Stream, typename I> void Unser(Stream& s, I& v)
516 {
517 v = ReadVarInt<Stream,Mode, std::remove_cv_t<I>>(s);
518 }
519};
520
530template<int Bytes, bool BigEndian = false>
532{
533 static_assert(Bytes > 0 && Bytes <= 8, "CustomUintFormatter Bytes out of range");
534 static constexpr uint64_t MAX = 0xffffffffffffffff >> (8 * (8 - Bytes));
535
536 template <typename Stream, typename I> void Ser(Stream& s, I v)
537 {
538 if (v < 0 || v > MAX) throw std::ios_base::failure("CustomUintFormatter value out of range");
539 if (BigEndian) {
540 uint64_t raw = htobe64_internal(v);
541 s.write(std::as_bytes(std::span{&raw, 1}).last(Bytes));
542 } else {
543 uint64_t raw = htole64_internal(v);
544 s.write(std::as_bytes(std::span{&raw, 1}).first(Bytes));
545 }
546 }
547
548 template <typename Stream, typename I> void Unser(Stream& s, I& v)
549 {
550 using U = typename std::conditional_t<std::is_enum_v<I>, std::underlying_type<I>, std::common_type<I>>::type;
551 static_assert(std::numeric_limits<U>::max() >= MAX && std::numeric_limits<U>::min() <= 0, "Assigned type too small");
552 uint64_t raw = 0;
553 if (BigEndian) {
554 s.read(std::as_writable_bytes(std::span{&raw, 1}).last(Bytes));
555 v = static_cast<I>(be64toh_internal(raw));
556 } else {
557 s.read(std::as_writable_bytes(std::span{&raw, 1}).first(Bytes));
558 v = static_cast<I>(le64toh_internal(raw));
559 }
560 }
561};
562
564
566template<bool RangeCheck>
568{
569 template<typename Stream, typename I>
570 void Unser(Stream& s, I& v)
571 {
572 uint64_t n = ReadCompactSize<Stream>(s, RangeCheck);
573 if (n < std::numeric_limits<I>::min() || n > std::numeric_limits<I>::max()) {
574 throw std::ios_base::failure("CompactSize exceeds limit of type");
575 }
576 v = n;
577 }
578
579 template<typename Stream, typename I>
580 void Ser(Stream& s, I v)
581 {
582 static_assert(std::is_unsigned_v<I>, "CompactSize only supported for unsigned integers");
583 static_assert(std::numeric_limits<I>::max() <= std::numeric_limits<uint64_t>::max(), "CompactSize only supports 64-bit integers and below");
584
585 WriteCompactSize<Stream>(s, v);
586 }
587};
588
589template <typename U, bool LOSSY = false>
591 template <typename Stream, typename Tp>
592 void Unser(Stream& s, Tp& tp)
593 {
594 U u;
595 s >> u;
596 // Lossy deserialization does not make sense, so force Wnarrowing
597 tp = Tp{typename Tp::duration{typename Tp::duration::rep{u}}};
598 }
599 template <typename Stream, typename Tp>
600 void Ser(Stream& s, Tp tp)
601 {
602 if constexpr (LOSSY) {
603 s << U(tp.time_since_epoch().count());
604 } else {
605 s << U{tp.time_since_epoch().count()};
606 }
607 }
608};
609template <typename U>
611
613{
614protected:
615 uint64_t n;
616public:
617 explicit CompactSizeWriter(uint64_t n_in) : n(n_in) { }
618
619 template<typename Stream>
620 void Serialize(Stream &s) const {
621 WriteCompactSize<Stream>(s, n);
622 }
623};
624
625template<size_t Limit>
627{
628 template<typename Stream>
629 void Unser(Stream& s, std::string& v)
630 {
631 size_t size = ReadCompactSize(s);
632 if (size > Limit) {
633 throw std::ios_base::failure("String length limit exceeded");
634 }
635 v.resize(size);
636 if (size != 0) s.read(MakeWritableByteSpan(v));
637 }
638
639 template<typename Stream>
640 void Ser(Stream& s, const std::string& v)
641 {
642 s << v;
643 }
644};
645
659template<class Formatter>
661{
662 template<typename Stream, typename V>
663 void Ser(Stream& s, const V& v)
664 {
665 Formatter formatter;
666 WriteCompactSize(s, v.size());
667 for (const typename V::value_type& elem : v) {
668 formatter.Ser(s, elem);
669 }
670 }
671
672 template<typename Stream, typename V>
673 void Unser(Stream& s, V& v)
674 {
675 Formatter formatter;
676 v.clear();
677 size_t size = ReadCompactSize(s);
678 size_t allocated = 0;
679 while (allocated < size) {
680 // For DoS prevention, do not blindly allocate as much as the stream claims to contain.
681 // Instead, allocate in 5MiB batches, so that an attacker actually needs to provide
682 // X MiB of data to make us allocate X+5 Mib.
683 static_assert(sizeof(typename V::value_type) <= MAX_VECTOR_ALLOCATE, "Vector element size too large");
684 allocated = std::min(size, allocated + MAX_VECTOR_ALLOCATE / sizeof(typename V::value_type));
685 v.reserve(allocated);
686 while (v.size() < allocated) {
687 v.emplace_back();
688 formatter.Unser(s, v.back());
689 }
690 }
691 };
692};
693
701template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str);
702template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str);
703
707template<typename Stream, unsigned int N, typename T> inline void Serialize(Stream& os, const prevector<N, T>& v);
708template<typename Stream, unsigned int N, typename T> inline void Unserialize(Stream& is, prevector<N, T>& v);
709
713template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v);
714template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v);
715
719template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item);
720template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item);
721
725template<typename Stream, typename K, typename T, typename Pred, typename A> void Serialize(Stream& os, const std::map<K, T, Pred, A>& m);
726template<typename Stream, typename K, typename T, typename Pred, typename A> void Unserialize(Stream& is, std::map<K, T, Pred, A>& m);
727
731template<typename Stream, typename K, typename Pred, typename A> void Serialize(Stream& os, const std::set<K, Pred, A>& m);
732template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m);
733
737template<typename Stream, typename T> void Serialize(Stream& os, const std::shared_ptr<const T>& p);
738template<typename Stream, typename T> void Unserialize(Stream& os, std::shared_ptr<const T>& p);
739
743template<typename Stream, typename T> void Serialize(Stream& os, const std::unique_ptr<const T>& p);
744template<typename Stream, typename T> void Unserialize(Stream& os, std::unique_ptr<const T>& p);
745
746
750template <class T, class Stream>
751concept Serializable = requires(T a, Stream s) { a.Serialize(s); };
752template <typename Stream, typename T>
754void Serialize(Stream& os, const T& a)
755{
756 a.Serialize(os);
757}
758
759template <class T, class Stream>
760concept Unserializable = requires(T a, Stream s) { a.Unserialize(s); };
761template <typename Stream, typename T>
763void Unserialize(Stream& is, T&& a)
764{
765 a.Unserialize(is);
766}
767
774{
775 template<typename Stream, typename T>
776 static void Ser(Stream& s, const T& t) { Serialize(s, t); }
777
778 template<typename Stream, typename T>
779 static void Unser(Stream& s, T& t) { Unserialize(s, t); }
780};
781
782
783
784
785
789template<typename Stream, typename C>
790void Serialize(Stream& os, const std::basic_string<C>& str)
791{
792 WriteCompactSize(os, str.size());
793 if (!str.empty())
794 os.write(MakeByteSpan(str));
795}
796
797template<typename Stream, typename C>
798void Unserialize(Stream& is, std::basic_string<C>& str)
799{
800 unsigned int nSize = ReadCompactSize(is);
801 str.resize(nSize);
802 if (nSize != 0)
803 is.read(MakeWritableByteSpan(str));
804}
805
806
807
811template <typename Stream, unsigned int N, typename T>
812void Serialize(Stream& os, const prevector<N, T>& v)
813{
814 if constexpr (BasicByte<T>) { // Use optimized version for unformatted basic bytes
815 WriteCompactSize(os, v.size());
816 if (!v.empty()) os.write(MakeByteSpan(v));
817 } else {
819 }
820}
821
822
823template <typename Stream, unsigned int N, typename T>
824void Unserialize(Stream& is, prevector<N, T>& v)
825{
826 if constexpr (BasicByte<T>) { // Use optimized version for unformatted basic bytes
827 // Limit size per read so bogus size value won't cause out of memory
828 v.clear();
829 unsigned int nSize = ReadCompactSize(is);
830 unsigned int i = 0;
831 while (i < nSize) {
832 unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
833 v.resize_uninitialized(i + blk);
834 is.read(std::as_writable_bytes(std::span{&v[i], blk}));
835 i += blk;
836 }
837 } else {
839 }
840}
841
842
846template <typename Stream, typename T, typename A>
847void Serialize(Stream& os, const std::vector<T, A>& v)
848{
849 if constexpr (BasicByte<T>) { // Use optimized version for unformatted basic bytes
850 WriteCompactSize(os, v.size());
851 if (!v.empty()) os.write(MakeByteSpan(v));
852 } else if constexpr (std::is_same_v<T, bool>) {
853 // A special case for std::vector<bool>, as dereferencing
854 // std::vector<bool>::const_iterator does not result in a const bool&
855 // due to std::vector's special casing for bool arguments.
856 WriteCompactSize(os, v.size());
857 for (bool elem : v) {
858 ::Serialize(os, elem);
859 }
860 } else {
862 }
863}
864
865
866template <typename Stream, typename T, typename A>
867void Unserialize(Stream& is, std::vector<T, A>& v)
868{
869 if constexpr (BasicByte<T>) { // Use optimized version for unformatted basic bytes
870 // Limit size per read so bogus size value won't cause out of memory
871 v.clear();
872 unsigned int nSize = ReadCompactSize(is);
873 unsigned int i = 0;
874 while (i < nSize) {
875 unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
876 v.resize(i + blk);
877 is.read(std::as_writable_bytes(std::span{&v[i], blk}));
878 i += blk;
879 }
880 } else {
882 }
883}
884
885
889template<typename Stream, typename K, typename T>
890void Serialize(Stream& os, const std::pair<K, T>& item)
891{
892 Serialize(os, item.first);
893 Serialize(os, item.second);
894}
895
896template<typename Stream, typename K, typename T>
897void Unserialize(Stream& is, std::pair<K, T>& item)
898{
899 Unserialize(is, item.first);
900 Unserialize(is, item.second);
901}
902
903
904
908template<typename Stream, typename K, typename T, typename Pred, typename A>
909void Serialize(Stream& os, const std::map<K, T, Pred, A>& m)
910{
911 WriteCompactSize(os, m.size());
912 for (const auto& entry : m)
913 Serialize(os, entry);
914}
915
916template<typename Stream, typename K, typename T, typename Pred, typename A>
917void Unserialize(Stream& is, std::map<K, T, Pred, A>& m)
918{
919 m.clear();
920 unsigned int nSize = ReadCompactSize(is);
921 typename std::map<K, T, Pred, A>::iterator mi = m.begin();
922 for (unsigned int i = 0; i < nSize; i++)
923 {
924 std::pair<K, T> item;
925 Unserialize(is, item);
926 mi = m.insert(mi, item);
927 }
928}
929
930
931
935template<typename Stream, typename K, typename Pred, typename A>
936void Serialize(Stream& os, const std::set<K, Pred, A>& m)
937{
938 WriteCompactSize(os, m.size());
939 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
940 Serialize(os, (*it));
941}
942
943template<typename Stream, typename K, typename Pred, typename A>
944void Unserialize(Stream& is, std::set<K, Pred, A>& m)
945{
946 m.clear();
947 unsigned int nSize = ReadCompactSize(is);
948 typename std::set<K, Pred, A>::iterator it = m.begin();
949 for (unsigned int i = 0; i < nSize; i++)
950 {
951 K key;
952 Unserialize(is, key);
953 it = m.insert(it, key);
954 }
955}
956
957
958
962template<typename Stream, typename T> void
963Serialize(Stream& os, const std::unique_ptr<const T>& p)
964{
965 Serialize(os, *p);
966}
967
968template<typename Stream, typename T>
969void Unserialize(Stream& is, std::unique_ptr<const T>& p)
970{
971 p.reset(new T(deserialize, is));
972}
973
974
975
979template<typename Stream, typename T> void
980Serialize(Stream& os, const std::shared_ptr<const T>& p)
981{
982 Serialize(os, *p);
983}
984
985template<typename Stream, typename T>
986void Unserialize(Stream& is, std::shared_ptr<const T>& p)
987{
988 p = std::make_shared<const T>(deserialize, is);
989}
990
995template <typename Stream, typename... Args>
996void SerializeMany(Stream& s, const Args&... args)
997{
998 (::Serialize(s, args), ...);
999}
1000
1001template <typename Stream, typename... Args>
1002inline void UnserializeMany(Stream& s, Args&&... args)
1003{
1004 (::Unserialize(s, args), ...);
1005}
1006
1011 static constexpr bool ForRead() { return false; }
1012
1013 template<typename Stream, typename... Args>
1014 static void SerReadWriteMany(Stream& s, const Args&... args)
1015 {
1016 ::SerializeMany(s, args...);
1017 }
1018
1019 template<typename Stream, typename Type, typename Fn>
1020 static void SerRead(Stream& s, Type&&, Fn&&)
1021 {
1022 }
1023
1024 template<typename Stream, typename Type, typename Fn>
1025 static void SerWrite(Stream& s, Type&& obj, Fn&& fn)
1026 {
1027 fn(s, std::forward<Type>(obj));
1028 }
1029};
1031 static constexpr bool ForRead() { return true; }
1032
1033 template<typename Stream, typename... Args>
1034 static void SerReadWriteMany(Stream& s, Args&&... args)
1035 {
1037 }
1038
1039 template<typename Stream, typename Type, typename Fn>
1040 static void SerRead(Stream& s, Type&& obj, Fn&& fn)
1041 {
1042 fn(s, std::forward<Type>(obj));
1043 }
1044
1045 template<typename Stream, typename Type, typename Fn>
1046 static void SerWrite(Stream& s, Type&&, Fn&&)
1047 {
1048 }
1049};
1050
1051/* ::GetSerializeSize implementations
1052 *
1053 * Computing the serialized size of objects is done through a special stream
1054 * object of type SizeComputer, which only records the number of bytes written
1055 * to it.
1056 *
1057 * If your Serialize or SerializationOp method has non-trivial overhead for
1058 * serialization, it may be worthwhile to implement a specialized version for
1059 * SizeComputer, which uses the s.seek() method to record bytes that would
1060 * be written instead.
1061 */
1063{
1064protected:
1065 size_t nSize{0};
1066
1067public:
1068 SizeComputer() = default;
1069
1070 void write(std::span<const std::byte> src)
1071 {
1072 this->nSize += src.size();
1073 }
1074
1076 void seek(size_t _nSize)
1077 {
1078 this->nSize += _nSize;
1079 }
1080
1081 template<typename T>
1083 {
1084 ::Serialize(*this, obj);
1085 return (*this);
1086 }
1087
1088 size_t size() const {
1089 return nSize;
1090 }
1091};
1092
1093template<typename I>
1094inline void WriteVarInt(SizeComputer &s, I n)
1095{
1096 s.seek(GetSizeOfVarInt<I>(n));
1097}
1098
1099inline void WriteCompactSize(SizeComputer &s, uint64_t nSize)
1100{
1101 s.seek(GetSizeOfCompactSize(nSize));
1102}
1103
1104template <typename T>
1105size_t GetSerializeSize(const T& t)
1106{
1107 return (SizeComputer() << t).size();
1108}
1109
1111template<typename T>
1112concept ContainsStream = requires(T t) { t.GetStream(); };
1113
1115template <typename SubStream, typename Params>
1117{
1119 // If ParamsStream constructor is passed an lvalue argument, Substream will
1120 // be a reference type, and m_substream will reference that argument.
1121 // Otherwise m_substream will be a substream instance and move from the
1122 // argument. Letting ParamsStream contain a substream instance instead of
1123 // just a reference is useful to make the ParamsStream object self contained
1124 // and let it do cleanup when destroyed, for example by closing files if
1125 // SubStream is a file stream.
1126 SubStream m_substream;
1127
1128public:
1129 ParamsStream(SubStream&& substream, const Params& params LIFETIMEBOUND) : m_params{params}, m_substream{std::forward<SubStream>(substream)} {}
1130
1131 template <typename NestedSubstream, typename Params1, typename Params2, typename... NestedParams>
1132 ParamsStream(NestedSubstream&& s, const Params1& params1 LIFETIMEBOUND, const Params2& params2 LIFETIMEBOUND, const NestedParams&... params LIFETIMEBOUND)
1133 : ParamsStream{::ParamsStream{std::forward<NestedSubstream>(s), params2, params...}, params1} {}
1134
1135 template <typename U> ParamsStream& operator<<(const U& obj) { ::Serialize(*this, obj); return *this; }
1136 template <typename U> ParamsStream& operator>>(U&& obj) { ::Unserialize(*this, obj); return *this; }
1137 void write(std::span<const std::byte> src) { GetStream().write(src); }
1138 void read(std::span<std::byte> dst) { GetStream().read(dst); }
1139 void ignore(size_t num) { GetStream().ignore(num); }
1140 bool eof() const { return GetStream().eof(); }
1141 size_t size() const { return GetStream().size(); }
1142
1144 template <typename P>
1145 const auto& GetParams() const
1146 {
1147 if constexpr (std::is_convertible_v<Params, P>) {
1148 return m_params;
1149 } else {
1150 return m_substream.template GetParams<P>();
1151 }
1152 }
1153
1156 {
1157 if constexpr (ContainsStream<SubStream>) {
1158 return m_substream.GetStream();
1159 } else {
1160 return m_substream;
1161 }
1162 }
1163 const auto& GetStream() const
1164 {
1165 if constexpr (ContainsStream<SubStream>) {
1166 return m_substream.GetStream();
1167 } else {
1168 return m_substream;
1169 }
1170 }
1171};
1172
1178template <typename Substream, typename Params>
1180
1185template <typename Substream, typename Params1, typename Params2, typename... Params>
1186ParamsStream(Substream&& s, const Params1& params1, const Params2& params2, const Params&... params) ->
1187 ParamsStream<decltype(ParamsStream{std::forward<Substream>(s), params2, params...}), Params1>;
1188
1190template <typename Params, typename T>
1192{
1195
1196public:
1197 explicit ParamsWrapper(const Params& params, T& obj) : m_params{params}, m_object{obj} {}
1198
1199 template <typename Stream>
1200 void Serialize(Stream& s) const
1201 {
1202 ParamsStream ss{s, m_params};
1203 ::Serialize(ss, m_object);
1204 }
1205 template <typename Stream>
1206 void Unserialize(Stream& s)
1207 {
1208 ParamsStream ss{s, m_params};
1210 }
1211};
1212
1222#define SER_PARAMS_OPFUNC \
1223 \
1228 template <typename T> \
1229 auto operator()(T&& t) const \
1230 { \
1231 return ParamsWrapper{*this, t}; \
1232 }
1233
1234#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:620
CompactSizeWriter(uint64_t n_in)
Definition: serialize.h:617
Wrapper that overrides the GetParams() function of a stream.
Definition: serialize.h:1117
bool eof() const
Definition: serialize.h:1140
ParamsStream & operator<<(const U &obj)
Definition: serialize.h:1135
ParamsStream & operator>>(U &&obj)
Definition: serialize.h:1136
ParamsStream(NestedSubstream &&s, const Params1 &params1 LIFETIMEBOUND, const Params2 &params2 LIFETIMEBOUND, const NestedParams &... params LIFETIMEBOUND)
Definition: serialize.h:1132
auto & GetStream()
Get reference to underlying stream.
Definition: serialize.h:1155
size_t size() const
Definition: serialize.h:1141
void ignore(size_t num)
Definition: serialize.h:1139
const Params & m_params
Definition: serialize.h:1118
const auto & GetParams() const
Get reference to stream parameters.
Definition: serialize.h:1145
void write(std::span< const std::byte > src)
Definition: serialize.h:1137
SubStream m_substream
Definition: serialize.h:1126
void read(std::span< std::byte > dst)
Definition: serialize.h:1138
const auto & GetStream() const
Definition: serialize.h:1163
ParamsStream(SubStream &&substream, const Params &params LIFETIMEBOUND)
Definition: serialize.h:1129
Wrapper that serializes objects with the specified parameters.
Definition: serialize.h:1192
const Params & m_params
Definition: serialize.h:1193
void Unserialize(Stream &s)
Definition: serialize.h:1206
void Serialize(Stream &s) const
Definition: serialize.h:1200
ParamsWrapper(const Params &params, T &obj)
Definition: serialize.h:1197
void write(std::span< const std::byte > src)
Definition: serialize.h:1070
void seek(size_t _nSize)
Pretend _nSize bytes are written, without specifying them.
Definition: serialize.h:1076
size_t nSize
Definition: serialize.h:1065
size_t size() const
Definition: serialize.h:1088
SizeComputer()=default
SizeComputer & operator<<(const T &obj)
Definition: serialize.h:1082
Simple wrapper class to serialize objects using a formatter; used by Using().
Definition: serialize.h:478
Wrapper(T obj)
Definition: serialize.h:483
T m_object
Definition: serialize.h:481
void Serialize(Stream &s) const
Definition: serialize.h:484
void Unserialize(Stream &s)
Definition: serialize.h:485
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:257
void clear()
Definition: prevector.h:309
size_type size() const
Definition: prevector.h:253
void resize_uninitialized(size_type new_size)
Definition: prevector.h:355
Check if type contains a stream by seeing if has a GetStream() method.
Definition: serialize.h:1112
If none of the specialized versions above matched, default to calling member function.
Definition: serialize.h:751
BSWAP_CONSTEXPR uint32_t be32toh_internal(uint32_t big_endian_32bits)
Definition: endian.h:43
BSWAP_CONSTEXPR uint16_t be16toh_internal(uint16_t big_endian_16bits)
Definition: endian.h:23
BSWAP_CONSTEXPR uint64_t htobe64_internal(uint64_t host_64bits)
Definition: endian.h:53
BSWAP_CONSTEXPR uint16_t htobe16_internal(uint16_t host_16bits)
Definition: endian.h:13
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)
size_t GetSerializeSize(const T &t)
Definition: serialize.h:1105
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:299
void SerializeMany(Stream &s, const Args &... args)
Support for (un)serializing many things at once.
Definition: serialize.h:996
static const unsigned int MAX_VECTOR_ALLOCATE
Maximum amount of memory (in bytes) to allocate at once when deserializing vectors.
Definition: serialize.h:35
uint8_t ser_readdata8(Stream &s)
Definition: serialize.h:83
I ReadVarInt(Stream &is)
Definition: serialize.h:454
void ser_writedata32be(Stream &s, uint32_t obj)
Definition: serialize.h:73
VarIntMode
Variable-length integers: bytes are a MSB base-128 encoding of the number.
Definition: serialize.h:407
@ NONNEGATIVE_SIGNED
void ser_writedata32(Stream &s, uint32_t obj)
Definition: serialize.h:68
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:32
constexpr deserialize_type deserialize
Definition: serialize.h:49
void ser_writedata16(Stream &s, uint16_t obj)
Definition: serialize.h:58
void Unserialize(Stream &, V)=delete
void UnserializeMany(Stream &s, Args &&... args)
Definition: serialize.h:1002
Out & AsBase(In &x)
Convert any argument to a reference to X, maintaining constness.
Definition: serialize.h:144
void WriteVarInt(SizeComputer &os, I n)
Definition: serialize.h:1094
void WriteCompactSize(SizeComputer &os, uint64_t nSize)
Definition: serialize.h:1099
void ser_writedata16be(Stream &s, uint16_t obj)
Definition: serialize.h:63
uint16_t ser_readdata16(Stream &s)
Definition: serialize.h:89
uint64_t ser_readdata64(Stream &s)
Definition: serialize.h:113
void ser_writedata8(Stream &s, uint8_t obj)
Definition: serialize.h:54
uint64_t ReadCompactSize(Stream &is, bool range_check=true)
Decode a CompactSize-encoded variable-length integer.
Definition: serialize.h:341
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:499
unsigned int GetSizeOfVarInt(I n)
Definition: serialize.h:419
uint32_t ser_readdata32(Stream &s)
Definition: serialize.h:101
uint16_t ser_readdata16be(Stream &s)
Definition: serialize.h:95
void ser_writedata64(Stream &s, uint64_t obj)
Definition: serialize.h:78
uint32_t ser_readdata32be(Stream &s)
Definition: serialize.h:107
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:1010
static void SerReadWriteMany(Stream &s, const Args &... args)
Definition: serialize.h:1014
static constexpr bool ForRead()
Definition: serialize.h:1011
static void SerWrite(Stream &s, Type &&obj, Fn &&fn)
Definition: serialize.h:1025
static void SerRead(Stream &s, Type &&, Fn &&)
Definition: serialize.h:1020
static constexpr bool ForRead()
Definition: serialize.h:1031
static void SerReadWriteMany(Stream &s, Args &&... args)
Definition: serialize.h:1034
static void SerRead(Stream &s, Type &&obj, Fn &&fn)
Definition: serialize.h:1040
static void SerWrite(Stream &s, Type &&, Fn &&)
Definition: serialize.h:1046
constexpr CheckVarIntMode()
Definition: serialize.h:411
void Unser(Stream &s, Tp &tp)
Definition: serialize.h:592
void Ser(Stream &s, Tp tp)
Definition: serialize.h:600
Formatter for integers in CompactSize format.
Definition: serialize.h:568
void Unser(Stream &s, I &v)
Definition: serialize.h:570
void Ser(Stream &s, I v)
Definition: serialize.h:580
Serialization wrapper class for custom integers and enums.
Definition: serialize.h:532
static constexpr uint64_t MAX
Definition: serialize.h:534
void Ser(Stream &s, I v)
Definition: serialize.h:536
void Unser(Stream &s, I &v)
Definition: serialize.h:548
Default formatter.
Definition: serialize.h:774
static void Ser(Stream &s, const T &t)
Definition: serialize.h:776
static void Unser(Stream &s, T &t)
Definition: serialize.h:779
void Unser(Stream &s, std::string &v)
Definition: serialize.h:629
void Ser(Stream &s, const std::string &v)
Definition: serialize.h:640
Serialization wrapper class for integers in VarInt format.
Definition: serialize.h:509
void Ser(Stream &s, I v)
Definition: serialize.h:510
void Unser(Stream &s, I &v)
Definition: serialize.h:515
Formatter to serialize/deserialize vector elements using another formatter.
Definition: serialize.h:661
void Unser(Stream &s, V &v)
Definition: serialize.h:673
void Ser(Stream &s, const V &v)
Definition: serialize.h:663
Dummy data type to identify deserializing constructors.
Definition: serialize.h:48
#define B
Definition: util_tests.cpp:545