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