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