Bitcoin Core  22.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-2021 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 <compat/endian.h>
10 
11 #include <algorithm>
12 #include <cstdint>
13 #include <cstring>
14 #include <ios>
15 #include <limits>
16 #include <map>
17 #include <memory>
18 #include <set>
19 #include <string>
20 #include <string.h>
21 #include <utility>
22 #include <vector>
23 
24 #include <prevector.h>
25 #include <span.h>
26 
31 static constexpr uint64_t MAX_SIZE = 0x02000000;
32 
34 static const unsigned int MAX_VECTOR_ALLOCATE = 5000000;
35 
47 struct deserialize_type {};
49 
51 inline char* CharCast(char* c) { return c; }
52 inline char* CharCast(unsigned char* c) { return (char*)c; }
53 inline const char* CharCast(const char* c) { return c; }
54 inline const char* CharCast(const unsigned char* c) { return (const char*)c; }
55 
56 /*
57  * Lowest-level serialization and conversion.
58  * @note Sizes of these types are verified in the tests
59  */
60 template<typename Stream> inline void ser_writedata8(Stream &s, uint8_t obj)
61 {
62  s.write((char*)&obj, 1);
63 }
64 template<typename Stream> inline void ser_writedata16(Stream &s, uint16_t obj)
65 {
66  obj = htole16(obj);
67  s.write((char*)&obj, 2);
68 }
69 template<typename Stream> inline void ser_writedata16be(Stream &s, uint16_t obj)
70 {
71  obj = htobe16(obj);
72  s.write((char*)&obj, 2);
73 }
74 template<typename Stream> inline void ser_writedata32(Stream &s, uint32_t obj)
75 {
76  obj = htole32(obj);
77  s.write((char*)&obj, 4);
78 }
79 template<typename Stream> inline void ser_writedata32be(Stream &s, uint32_t obj)
80 {
81  obj = htobe32(obj);
82  s.write((char*)&obj, 4);
83 }
84 template<typename Stream> inline void ser_writedata64(Stream &s, uint64_t obj)
85 {
86  obj = htole64(obj);
87  s.write((char*)&obj, 8);
88 }
89 template<typename Stream> inline uint8_t ser_readdata8(Stream &s)
90 {
91  uint8_t obj;
92  s.read((char*)&obj, 1);
93  return obj;
94 }
95 template<typename Stream> inline uint16_t ser_readdata16(Stream &s)
96 {
97  uint16_t obj;
98  s.read((char*)&obj, 2);
99  return le16toh(obj);
100 }
101 template<typename Stream> inline uint16_t ser_readdata16be(Stream &s)
102 {
103  uint16_t obj;
104  s.read((char*)&obj, 2);
105  return be16toh(obj);
106 }
107 template<typename Stream> inline uint32_t ser_readdata32(Stream &s)
108 {
109  uint32_t obj;
110  s.read((char*)&obj, 4);
111  return le32toh(obj);
112 }
113 template<typename Stream> inline uint32_t ser_readdata32be(Stream &s)
114 {
115  uint32_t obj;
116  s.read((char*)&obj, 4);
117  return be32toh(obj);
118 }
119 template<typename Stream> inline uint64_t ser_readdata64(Stream &s)
120 {
121  uint64_t obj;
122  s.read((char*)&obj, 8);
123  return le64toh(obj);
124 }
125 
126 
128 //
129 // Templates for serializing to anything that looks like a stream,
130 // i.e. anything that supports .read(char*, size_t) and .write(char*, size_t)
131 //
132 
133 class CSizeComputer;
134 
135 enum
136 {
137  // primary actions
138  SER_NETWORK = (1 << 0),
139  SER_DISK = (1 << 1),
140  SER_GETHASH = (1 << 2),
141 };
142 
144 template<typename X> X& ReadWriteAsHelper(X& x) { return x; }
145 template<typename X> const X& ReadWriteAsHelper(const X& x) { return x; }
146 
147 #define READWRITE(...) (::SerReadWriteMany(s, ser_action, __VA_ARGS__))
148 #define READWRITEAS(type, obj) (::SerReadWriteMany(s, ser_action, ReadWriteAsHelper<type>(obj)))
149 #define SER_READ(obj, code) ::SerRead(s, ser_action, obj, [&](Stream& s, typename std::remove_const<Type>::type& obj) { code; })
150 #define SER_WRITE(obj, code) ::SerWrite(s, ser_action, 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, CSerActionSerialize()); } \
171  template<typename Stream> \
172  static void Unser(Stream& s, cls& obj) { SerializationOps(obj, s, CSerActionUnserialize()); } \
173  template<typename Stream, typename Type, typename Operation> \
174  static inline void SerializationOps(Type& obj, Stream& s, Operation ser_action) \
175 
176 
183 #define SERIALIZE_METHODS(cls, obj) \
184  template<typename Stream> \
185  void Serialize(Stream& s) const \
186  { \
187  static_assert(std::is_same<const cls&, decltype(*this)>::value, "Serialize type mismatch"); \
188  Ser(s, *this); \
189  } \
190  template<typename Stream> \
191  void Unserialize(Stream& s) \
192  { \
193  static_assert(std::is_same<cls&, decltype(*this)>::value, "Unserialize type mismatch"); \
194  Unser(s, *this); \
195  } \
196  FORMATTER_METHODS(cls, obj)
197 
198 #ifndef CHAR_EQUALS_INT8
199 template<typename Stream> inline void Serialize(Stream& s, char a ) { ser_writedata8(s, a); } // TODO Get rid of bare char
200 #endif
201 template<typename Stream> inline void Serialize(Stream& s, int8_t a ) { ser_writedata8(s, a); }
202 template<typename Stream> inline void Serialize(Stream& s, uint8_t a ) { ser_writedata8(s, a); }
203 template<typename Stream> inline void Serialize(Stream& s, int16_t a ) { ser_writedata16(s, a); }
204 template<typename Stream> inline void Serialize(Stream& s, uint16_t a) { ser_writedata16(s, a); }
205 template<typename Stream> inline void Serialize(Stream& s, int32_t a ) { ser_writedata32(s, a); }
206 template<typename Stream> inline void Serialize(Stream& s, uint32_t a) { ser_writedata32(s, a); }
207 template<typename Stream> inline void Serialize(Stream& s, int64_t a ) { ser_writedata64(s, a); }
208 template<typename Stream> inline void Serialize(Stream& s, uint64_t a) { ser_writedata64(s, a); }
209 template<typename Stream, int N> inline void Serialize(Stream& s, const char (&a)[N]) { s.write(a, N); }
210 template<typename Stream, int N> inline void Serialize(Stream& s, const unsigned char (&a)[N]) { s.write(CharCast(a), N); }
211 template<typename Stream> inline void Serialize(Stream& s, const Span<const unsigned char>& span) { s.write(CharCast(span.data()), span.size()); }
212 template<typename Stream> inline void Serialize(Stream& s, const Span<unsigned char>& span) { s.write(CharCast(span.data()), span.size()); }
213 
214 #ifndef CHAR_EQUALS_INT8
215 template<typename Stream> inline void Unserialize(Stream& s, char& a ) { a = ser_readdata8(s); } // TODO Get rid of bare char
216 #endif
217 template<typename Stream> inline void Unserialize(Stream& s, int8_t& a ) { a = ser_readdata8(s); }
218 template<typename Stream> inline void Unserialize(Stream& s, uint8_t& a ) { a = ser_readdata8(s); }
219 template<typename Stream> inline void Unserialize(Stream& s, int16_t& a ) { a = ser_readdata16(s); }
220 template<typename Stream> inline void Unserialize(Stream& s, uint16_t& a) { a = ser_readdata16(s); }
221 template<typename Stream> inline void Unserialize(Stream& s, int32_t& a ) { a = ser_readdata32(s); }
222 template<typename Stream> inline void Unserialize(Stream& s, uint32_t& a) { a = ser_readdata32(s); }
223 template<typename Stream> inline void Unserialize(Stream& s, int64_t& a ) { a = ser_readdata64(s); }
224 template<typename Stream> inline void Unserialize(Stream& s, uint64_t& a) { a = ser_readdata64(s); }
225 template<typename Stream, int N> inline void Unserialize(Stream& s, char (&a)[N]) { s.read(a, N); }
226 template<typename Stream, int N> inline void Unserialize(Stream& s, unsigned char (&a)[N]) { s.read(CharCast(a), N); }
227 template<typename Stream> inline void Unserialize(Stream& s, Span<unsigned char>& span) { s.read(CharCast(span.data()), span.size()); }
228 
229 template <typename Stream> inline void Serialize(Stream& s, bool a) { uint8_t f = a; ser_writedata8(s, f); }
230 template <typename Stream> inline void Unserialize(Stream& s, bool& a) { uint8_t f = ser_readdata8(s); a = f; }
231 
232 
240 inline unsigned int GetSizeOfCompactSize(uint64_t nSize)
241 {
242  if (nSize < 253) return sizeof(unsigned char);
243  else if (nSize <= std::numeric_limits<uint16_t>::max()) return sizeof(unsigned char) + sizeof(uint16_t);
244  else if (nSize <= std::numeric_limits<unsigned int>::max()) return sizeof(unsigned char) + sizeof(unsigned int);
245  else return sizeof(unsigned char) + sizeof(uint64_t);
246 }
247 
248 inline void WriteCompactSize(CSizeComputer& os, uint64_t nSize);
249 
250 template<typename Stream>
251 void WriteCompactSize(Stream& os, uint64_t nSize)
252 {
253  if (nSize < 253)
254  {
255  ser_writedata8(os, nSize);
256  }
257  else if (nSize <= std::numeric_limits<uint16_t>::max())
258  {
259  ser_writedata8(os, 253);
260  ser_writedata16(os, nSize);
261  }
262  else if (nSize <= std::numeric_limits<unsigned int>::max())
263  {
264  ser_writedata8(os, 254);
265  ser_writedata32(os, nSize);
266  }
267  else
268  {
269  ser_writedata8(os, 255);
270  ser_writedata64(os, nSize);
271  }
272  return;
273 }
274 
281 template<typename Stream>
282 uint64_t ReadCompactSize(Stream& is, bool range_check = true)
283 {
284  uint8_t chSize = ser_readdata8(is);
285  uint64_t nSizeRet = 0;
286  if (chSize < 253)
287  {
288  nSizeRet = chSize;
289  }
290  else if (chSize == 253)
291  {
292  nSizeRet = ser_readdata16(is);
293  if (nSizeRet < 253)
294  throw std::ios_base::failure("non-canonical ReadCompactSize()");
295  }
296  else if (chSize == 254)
297  {
298  nSizeRet = ser_readdata32(is);
299  if (nSizeRet < 0x10000u)
300  throw std::ios_base::failure("non-canonical ReadCompactSize()");
301  }
302  else
303  {
304  nSizeRet = ser_readdata64(is);
305  if (nSizeRet < 0x100000000ULL)
306  throw std::ios_base::failure("non-canonical ReadCompactSize()");
307  }
308  if (range_check && nSizeRet > MAX_SIZE) {
309  throw std::ios_base::failure("ReadCompactSize(): size too large");
310  }
311  return nSizeRet;
312 }
313 
349 
350 template <VarIntMode Mode, typename I>
352  constexpr CheckVarIntMode()
353  {
354  static_assert(Mode != VarIntMode::DEFAULT || std::is_unsigned<I>::value, "Unsigned type required with mode DEFAULT.");
355  static_assert(Mode != VarIntMode::NONNEGATIVE_SIGNED || std::is_signed<I>::value, "Signed type required with mode NONNEGATIVE_SIGNED.");
356  }
357 };
358 
359 template<VarIntMode Mode, typename I>
360 inline unsigned int GetSizeOfVarInt(I n)
361 {
363  int nRet = 0;
364  while(true) {
365  nRet++;
366  if (n <= 0x7F)
367  break;
368  n = (n >> 7) - 1;
369  }
370  return nRet;
371 }
372 
373 template<typename I>
374 inline void WriteVarInt(CSizeComputer& os, I n);
375 
376 template<typename Stream, VarIntMode Mode, typename I>
377 void WriteVarInt(Stream& os, I n)
378 {
380  unsigned char tmp[(sizeof(n)*8+6)/7];
381  int len=0;
382  while(true) {
383  tmp[len] = (n & 0x7F) | (len ? 0x80 : 0x00);
384  if (n <= 0x7F)
385  break;
386  n = (n >> 7) - 1;
387  len++;
388  }
389  do {
390  ser_writedata8(os, tmp[len]);
391  } while(len--);
392 }
393 
394 template<typename Stream, VarIntMode Mode, typename I>
395 I ReadVarInt(Stream& is)
396 {
398  I n = 0;
399  while(true) {
400  unsigned char chData = ser_readdata8(is);
401  if (n > (std::numeric_limits<I>::max() >> 7)) {
402  throw std::ios_base::failure("ReadVarInt(): size too large");
403  }
404  n = (n << 7) | (chData & 0x7F);
405  if (chData & 0x80) {
406  if (n == std::numeric_limits<I>::max()) {
407  throw std::ios_base::failure("ReadVarInt(): size too large");
408  }
409  n++;
410  } else {
411  return n;
412  }
413  }
414 }
415 
417 template<typename Formatter, typename T>
418 class Wrapper
419 {
420  static_assert(std::is_lvalue_reference<T>::value, "Wrapper needs an lvalue reference type T");
421 protected:
422  T m_object;
423 public:
424  explicit Wrapper(T obj) : m_object(obj) {}
425  template<typename Stream> void Serialize(Stream &s) const { Formatter().Ser(s, m_object); }
426  template<typename Stream> void Unserialize(Stream &s) { Formatter().Unser(s, m_object); }
427 };
428 
439 template<typename Formatter, typename T>
440 static inline Wrapper<Formatter, T&> Using(T&& t) { return Wrapper<Formatter, T&>(t); }
441 
442 #define VARINT_MODE(obj, mode) Using<VarIntFormatter<mode>>(obj)
443 #define VARINT(obj) Using<VarIntFormatter<VarIntMode::DEFAULT>>(obj)
444 #define COMPACTSIZE(obj) Using<CompactSizeFormatter<true>>(obj)
445 #define LIMITED_STRING(obj,n) Using<LimitedStringFormatter<n>>(obj)
446 
448 template<VarIntMode Mode>
450 {
451  template<typename Stream, typename I> void Ser(Stream &s, I v)
452  {
453  WriteVarInt<Stream,Mode,typename std::remove_cv<I>::type>(s, v);
454  }
455 
456  template<typename Stream, typename I> void Unser(Stream& s, I& v)
457  {
458  v = ReadVarInt<Stream,Mode,typename std::remove_cv<I>::type>(s);
459  }
460 };
461 
471 template<int Bytes, bool BigEndian = false>
473 {
474  static_assert(Bytes > 0 && Bytes <= 8, "CustomUintFormatter Bytes out of range");
475  static constexpr uint64_t MAX = 0xffffffffffffffff >> (8 * (8 - Bytes));
476 
477  template <typename Stream, typename I> void Ser(Stream& s, I v)
478  {
479  if (v < 0 || v > MAX) throw std::ios_base::failure("CustomUintFormatter value out of range");
480  if (BigEndian) {
481  uint64_t raw = htobe64(v);
482  s.write(((const char*)&raw) + 8 - Bytes, Bytes);
483  } else {
484  uint64_t raw = htole64(v);
485  s.write((const char*)&raw, Bytes);
486  }
487  }
488 
489  template <typename Stream, typename I> void Unser(Stream& s, I& v)
490  {
491  using U = typename std::conditional<std::is_enum<I>::value, std::underlying_type<I>, std::common_type<I>>::type::type;
492  static_assert(std::numeric_limits<U>::max() >= MAX && std::numeric_limits<U>::min() <= 0, "Assigned type too small");
493  uint64_t raw = 0;
494  if (BigEndian) {
495  s.read(((char*)&raw) + 8 - Bytes, Bytes);
496  v = static_cast<I>(be64toh(raw));
497  } else {
498  s.read((char*)&raw, Bytes);
499  v = static_cast<I>(le64toh(raw));
500  }
501  }
502 };
503 
505 
507 template<bool RangeCheck>
509 {
510  template<typename Stream, typename I>
511  void Unser(Stream& s, I& v)
512  {
513  uint64_t n = ReadCompactSize<Stream>(s, RangeCheck);
514  if (n < std::numeric_limits<I>::min() || n > std::numeric_limits<I>::max()) {
515  throw std::ios_base::failure("CompactSize exceeds limit of type");
516  }
517  v = n;
518  }
519 
520  template<typename Stream, typename I>
521  void Ser(Stream& s, I v)
522  {
523  static_assert(std::is_unsigned<I>::value, "CompactSize only supported for unsigned integers");
524  static_assert(std::numeric_limits<I>::max() <= std::numeric_limits<uint64_t>::max(), "CompactSize only supports 64-bit integers and below");
525 
526  WriteCompactSize<Stream>(s, v);
527  }
528 };
529 
531 {
532 protected:
533  uint64_t n;
534 public:
535  explicit CompactSizeWriter(uint64_t n_in) : n(n_in) { }
536 
537  template<typename Stream>
538  void Serialize(Stream &s) const {
539  WriteCompactSize<Stream>(s, n);
540  }
541 };
542 
543 template<size_t Limit>
545 {
546  template<typename Stream>
547  void Unser(Stream& s, std::string& v)
548  {
549  size_t size = ReadCompactSize(s);
550  if (size > Limit) {
551  throw std::ios_base::failure("String length limit exceeded");
552  }
553  v.resize(size);
554  if (size != 0) s.read((char*)v.data(), size);
555  }
556 
557  template<typename Stream>
558  void Ser(Stream& s, const std::string& v)
559  {
560  s << v;
561  }
562 };
563 
577 template<class Formatter>
579 {
580  template<typename Stream, typename V>
581  void Ser(Stream& s, const V& v)
582  {
583  Formatter formatter;
584  WriteCompactSize(s, v.size());
585  for (const typename V::value_type& elem : v) {
586  formatter.Ser(s, elem);
587  }
588  }
589 
590  template<typename Stream, typename V>
591  void Unser(Stream& s, V& v)
592  {
593  Formatter formatter;
594  v.clear();
595  size_t size = ReadCompactSize(s);
596  size_t allocated = 0;
597  while (allocated < size) {
598  // For DoS prevention, do not blindly allocate as much as the stream claims to contain.
599  // Instead, allocate in 5MiB batches, so that an attacker actually needs to provide
600  // X MiB of data to make us allocate X+5 Mib.
601  static_assert(sizeof(typename V::value_type) <= MAX_VECTOR_ALLOCATE, "Vector element size too large");
602  allocated = std::min(size, allocated + MAX_VECTOR_ALLOCATE / sizeof(typename V::value_type));
603  v.reserve(allocated);
604  while (v.size() < allocated) {
605  v.emplace_back();
606  formatter.Unser(s, v.back());
607  }
608  }
609  };
610 };
611 
619 template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str);
620 template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str);
621 
626 template<typename Stream, unsigned int N, typename T> void Serialize_impl(Stream& os, const prevector<N, T>& v, const unsigned char&);
627 template<typename Stream, unsigned int N, typename T, typename V> void Serialize_impl(Stream& os, const prevector<N, T>& v, const V&);
628 template<typename Stream, unsigned int N, typename T> inline void Serialize(Stream& os, const prevector<N, T>& v);
629 template<typename Stream, unsigned int N, typename T> void Unserialize_impl(Stream& is, prevector<N, T>& v, const unsigned char&);
630 template<typename Stream, unsigned int N, typename T, typename V> void Unserialize_impl(Stream& is, prevector<N, T>& v, const V&);
631 template<typename Stream, unsigned int N, typename T> inline void Unserialize(Stream& is, prevector<N, T>& v);
632 
637 template<typename Stream, typename T, typename A> void Serialize_impl(Stream& os, const std::vector<T, A>& v, const unsigned char&);
638 template<typename Stream, typename T, typename A> void Serialize_impl(Stream& os, const std::vector<T, A>& v, const bool&);
639 template<typename Stream, typename T, typename A, typename V> void Serialize_impl(Stream& os, const std::vector<T, A>& v, const V&);
640 template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v);
641 template<typename Stream, typename T, typename A> void Unserialize_impl(Stream& is, std::vector<T, A>& v, const unsigned char&);
642 template<typename Stream, typename T, typename A, typename V> void Unserialize_impl(Stream& is, std::vector<T, A>& v, const V&);
643 template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v);
644 
648 template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item);
649 template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item);
650 
654 template<typename Stream, typename K, typename T, typename Pred, typename A> void Serialize(Stream& os, const std::map<K, T, Pred, A>& m);
655 template<typename Stream, typename K, typename T, typename Pred, typename A> void Unserialize(Stream& is, std::map<K, T, Pred, A>& m);
656 
660 template<typename Stream, typename K, typename Pred, typename A> void Serialize(Stream& os, const std::set<K, Pred, A>& m);
661 template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m);
662 
666 template<typename Stream, typename T> void Serialize(Stream& os, const std::shared_ptr<const T>& p);
667 template<typename Stream, typename T> void Unserialize(Stream& os, std::shared_ptr<const T>& p);
668 
672 template<typename Stream, typename T> void Serialize(Stream& os, const std::unique_ptr<const T>& p);
673 template<typename Stream, typename T> void Unserialize(Stream& os, std::unique_ptr<const T>& p);
674 
675 
676 
680 template<typename Stream, typename T>
681 inline void Serialize(Stream& os, const T& a)
682 {
683  a.Serialize(os);
684 }
685 
686 template<typename Stream, typename T>
687 inline void Unserialize(Stream& is, T&& a)
688 {
689  a.Unserialize(is);
690 }
691 
698 {
699  template<typename Stream, typename T>
700  static void Ser(Stream& s, const T& t) { Serialize(s, t); }
701 
702  template<typename Stream, typename T>
703  static void Unser(Stream& s, T& t) { Unserialize(s, t); }
704 };
705 
706 
707 
708 
709 
713 template<typename Stream, typename C>
714 void Serialize(Stream& os, const std::basic_string<C>& str)
715 {
716  WriteCompactSize(os, str.size());
717  if (!str.empty())
718  os.write((char*)str.data(), str.size() * sizeof(C));
719 }
720 
721 template<typename Stream, typename C>
722 void Unserialize(Stream& is, std::basic_string<C>& str)
723 {
724  unsigned int nSize = ReadCompactSize(is);
725  str.resize(nSize);
726  if (nSize != 0)
727  is.read((char*)str.data(), nSize * sizeof(C));
728 }
729 
730 
731 
735 template<typename Stream, unsigned int N, typename T>
736 void Serialize_impl(Stream& os, const prevector<N, T>& v, const unsigned char&)
737 {
738  WriteCompactSize(os, v.size());
739  if (!v.empty())
740  os.write((char*)v.data(), v.size() * sizeof(T));
741 }
742 
743 template<typename Stream, unsigned int N, typename T, typename V>
744 void Serialize_impl(Stream& os, const prevector<N, T>& v, const V&)
745 {
747 }
748 
749 template<typename Stream, unsigned int N, typename T>
750 inline void Serialize(Stream& os, const prevector<N, T>& v)
751 {
752  Serialize_impl(os, v, T());
753 }
754 
755 
756 template<typename Stream, unsigned int N, typename T>
757 void Unserialize_impl(Stream& is, prevector<N, T>& v, const unsigned char&)
758 {
759  // Limit size per read so bogus size value won't cause out of memory
760  v.clear();
761  unsigned int nSize = ReadCompactSize(is);
762  unsigned int i = 0;
763  while (i < nSize)
764  {
765  unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
766  v.resize_uninitialized(i + blk);
767  is.read((char*)&v[i], blk * sizeof(T));
768  i += blk;
769  }
770 }
771 
772 template<typename Stream, unsigned int N, typename T, typename V>
773 void Unserialize_impl(Stream& is, prevector<N, T>& v, const V&)
774 {
776 }
777 
778 template<typename Stream, unsigned int N, typename T>
779 inline void Unserialize(Stream& is, prevector<N, T>& v)
780 {
781  Unserialize_impl(is, v, T());
782 }
783 
784 
785 
789 template<typename Stream, typename T, typename A>
790 void Serialize_impl(Stream& os, const std::vector<T, A>& v, const unsigned char&)
791 {
792  WriteCompactSize(os, v.size());
793  if (!v.empty())
794  os.write((char*)v.data(), v.size() * sizeof(T));
795 }
796 
797 template<typename Stream, typename T, typename A>
798 void Serialize_impl(Stream& os, const std::vector<T, A>& v, const bool&)
799 {
800  // A special case for std::vector<bool>, as dereferencing
801  // std::vector<bool>::const_iterator does not result in a const bool&
802  // due to std::vector's special casing for bool arguments.
803  WriteCompactSize(os, v.size());
804  for (bool elem : v) {
805  ::Serialize(os, elem);
806  }
807 }
808 
809 template<typename Stream, typename T, typename A, typename V>
810 void Serialize_impl(Stream& os, const std::vector<T, A>& v, const V&)
811 {
813 }
814 
815 template<typename Stream, typename T, typename A>
816 inline void Serialize(Stream& os, const std::vector<T, A>& v)
817 {
818  Serialize_impl(os, v, T());
819 }
820 
821 
822 template<typename Stream, typename T, typename A>
823 void Unserialize_impl(Stream& is, std::vector<T, A>& v, const unsigned char&)
824 {
825  // Limit size per read so bogus size value won't cause out of memory
826  v.clear();
827  unsigned int nSize = ReadCompactSize(is);
828  unsigned int i = 0;
829  while (i < nSize)
830  {
831  unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
832  v.resize(i + blk);
833  is.read((char*)&v[i], blk * sizeof(T));
834  i += blk;
835  }
836 }
837 
838 template<typename Stream, typename T, typename A, typename V>
839 void Unserialize_impl(Stream& is, std::vector<T, A>& v, const V&)
840 {
842 }
843 
844 template<typename Stream, typename T, typename A>
845 inline void Unserialize(Stream& is, std::vector<T, A>& v)
846 {
847  Unserialize_impl(is, v, T());
848 }
849 
850 
851 
855 template<typename Stream, typename K, typename T>
856 void Serialize(Stream& os, const std::pair<K, T>& item)
857 {
858  Serialize(os, item.first);
859  Serialize(os, item.second);
860 }
861 
862 template<typename Stream, typename K, typename T>
863 void Unserialize(Stream& is, std::pair<K, T>& item)
864 {
865  Unserialize(is, item.first);
866  Unserialize(is, item.second);
867 }
868 
869 
870 
874 template<typename Stream, typename K, typename T, typename Pred, typename A>
875 void Serialize(Stream& os, const std::map<K, T, Pred, A>& m)
876 {
877  WriteCompactSize(os, m.size());
878  for (const auto& entry : m)
879  Serialize(os, entry);
880 }
881 
882 template<typename Stream, typename K, typename T, typename Pred, typename A>
883 void Unserialize(Stream& is, std::map<K, T, Pred, A>& m)
884 {
885  m.clear();
886  unsigned int nSize = ReadCompactSize(is);
887  typename std::map<K, T, Pred, A>::iterator mi = m.begin();
888  for (unsigned int i = 0; i < nSize; i++)
889  {
890  std::pair<K, T> item;
891  Unserialize(is, item);
892  mi = m.insert(mi, item);
893  }
894 }
895 
896 
897 
901 template<typename Stream, typename K, typename Pred, typename A>
902 void Serialize(Stream& os, const std::set<K, Pred, A>& m)
903 {
904  WriteCompactSize(os, m.size());
905  for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
906  Serialize(os, (*it));
907 }
908 
909 template<typename Stream, typename K, typename Pred, typename A>
910 void Unserialize(Stream& is, std::set<K, Pred, A>& m)
911 {
912  m.clear();
913  unsigned int nSize = ReadCompactSize(is);
914  typename std::set<K, Pred, A>::iterator it = m.begin();
915  for (unsigned int i = 0; i < nSize; i++)
916  {
917  K key;
918  Unserialize(is, key);
919  it = m.insert(it, key);
920  }
921 }
922 
923 
924 
928 template<typename Stream, typename T> void
929 Serialize(Stream& os, const std::unique_ptr<const T>& p)
930 {
931  Serialize(os, *p);
932 }
933 
934 template<typename Stream, typename T>
935 void Unserialize(Stream& is, std::unique_ptr<const T>& p)
936 {
937  p.reset(new T(deserialize, is));
938 }
939 
940 
941 
945 template<typename Stream, typename T> void
946 Serialize(Stream& os, const std::shared_ptr<const T>& p)
947 {
948  Serialize(os, *p);
949 }
950 
951 template<typename Stream, typename T>
952 void Unserialize(Stream& is, std::shared_ptr<const T>& p)
953 {
954  p = std::make_shared<const T>(deserialize, is);
955 }
956 
957 
958 
963 {
964  constexpr bool ForRead() const { return false; }
965 };
967 {
968  constexpr bool ForRead() const { return true; }
969 };
970 
971 
972 
973 
974 
975 
976 
977 
978 /* ::GetSerializeSize implementations
979  *
980  * Computing the serialized size of objects is done through a special stream
981  * object of type CSizeComputer, which only records the number of bytes written
982  * to it.
983  *
984  * If your Serialize or SerializationOp method has non-trivial overhead for
985  * serialization, it may be worthwhile to implement a specialized version for
986  * CSizeComputer, which uses the s.seek() method to record bytes that would
987  * be written instead.
988  */
990 {
991 protected:
992  size_t nSize;
993 
994  const int nVersion;
995 public:
996  explicit CSizeComputer(int nVersionIn) : nSize(0), nVersion(nVersionIn) {}
997 
998  void write(const char *psz, size_t _nSize)
999  {
1000  this->nSize += _nSize;
1001  }
1002 
1004  void seek(size_t _nSize)
1005  {
1006  this->nSize += _nSize;
1007  }
1008 
1009  template<typename T>
1011  {
1012  ::Serialize(*this, obj);
1013  return (*this);
1014  }
1015 
1016  size_t size() const {
1017  return nSize;
1018  }
1019 
1020  int GetVersion() const { return nVersion; }
1021 };
1022 
1023 template<typename Stream>
1024 void SerializeMany(Stream& s)
1025 {
1026 }
1027 
1028 template<typename Stream, typename Arg, typename... Args>
1029 void SerializeMany(Stream& s, const Arg& arg, const Args&... args)
1030 {
1031  ::Serialize(s, arg);
1032  ::SerializeMany(s, args...);
1033 }
1034 
1035 template<typename Stream>
1036 inline void UnserializeMany(Stream& s)
1037 {
1038 }
1039 
1040 template<typename Stream, typename Arg, typename... Args>
1041 inline void UnserializeMany(Stream& s, Arg&& arg, Args&&... args)
1042 {
1043  ::Unserialize(s, arg);
1044  ::UnserializeMany(s, args...);
1045 }
1046 
1047 template<typename Stream, typename... Args>
1048 inline void SerReadWriteMany(Stream& s, CSerActionSerialize ser_action, const Args&... args)
1049 {
1050  ::SerializeMany(s, args...);
1051 }
1052 
1053 template<typename Stream, typename... Args>
1054 inline void SerReadWriteMany(Stream& s, CSerActionUnserialize ser_action, Args&&... args)
1055 {
1056  ::UnserializeMany(s, args...);
1057 }
1058 
1059 template<typename Stream, typename Type, typename Fn>
1060 inline void SerRead(Stream& s, CSerActionSerialize ser_action, Type&&, Fn&&)
1061 {
1062 }
1063 
1064 template<typename Stream, typename Type, typename Fn>
1065 inline void SerRead(Stream& s, CSerActionUnserialize ser_action, Type&& obj, Fn&& fn)
1066 {
1067  fn(s, std::forward<Type>(obj));
1068 }
1069 
1070 template<typename Stream, typename Type, typename Fn>
1071 inline void SerWrite(Stream& s, CSerActionSerialize ser_action, Type&& obj, Fn&& fn)
1072 {
1073  fn(s, std::forward<Type>(obj));
1074 }
1075 
1076 template<typename Stream, typename Type, typename Fn>
1077 inline void SerWrite(Stream& s, CSerActionUnserialize ser_action, Type&&, Fn&&)
1078 {
1079 }
1080 
1081 template<typename I>
1082 inline void WriteVarInt(CSizeComputer &s, I n)
1083 {
1084  s.seek(GetSizeOfVarInt<I>(n));
1085 }
1086 
1087 inline void WriteCompactSize(CSizeComputer &s, uint64_t nSize)
1088 {
1089  s.seek(GetSizeOfCompactSize(nSize));
1090 }
1091 
1092 template <typename T>
1093 size_t GetSerializeSize(const T& t, int nVersion = 0)
1094 {
1095  return (CSizeComputer(nVersion) << t).size();
1096 }
1097 
1098 template <typename... T>
1099 size_t GetSerializeSizeMany(int nVersion, const T&... t)
1100 {
1101  CSizeComputer sc(nVersion);
1102  SerializeMany(sc, t...);
1103  return sc.size();
1104 }
1105 
1106 #endif // BITCOIN_SERIALIZE_H
DefaultFormatter
Default formatter.
Definition: serialize.h:697
GetSerializeSize
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition: serialize.h:1093
htole16
uint16_t htole16(uint16_t host_16bits)
Definition: endian.h:163
deserialize_type
Dummy data type to identify deserializing constructors.
Definition: serialize.h:47
GetSizeOfVarInt
unsigned int GetSizeOfVarInt(I n)
Definition: serialize.h:360
ser_readdata32
uint32_t ser_readdata32(Stream &s)
Definition: serialize.h:107
ser_writedata16be
void ser_writedata16be(Stream &s, uint16_t obj)
Definition: serialize.h:69
SER_DISK
@ SER_DISK
Definition: serialize.h:139
CSizeComputer::GetVersion
int GetVersion() const
Definition: serialize.h:1020
DefaultFormatter::Unser
static void Unser(Stream &s, T &t)
Definition: serialize.h:703
VarIntFormatter
Serialization wrapper class for integers in VarInt format.
Definition: serialize.h:449
htole64
uint64_t htole64(uint64_t host_64bits)
Definition: endian.h:219
DefaultFormatter::Ser
static void Ser(Stream &s, const T &t)
Definition: serialize.h:700
ser_writedata64
void ser_writedata64(Stream &s, uint64_t obj)
Definition: serialize.h:84
string.h
prevector::clear
void clear()
Definition: prevector.h:343
ReadVarInt
I ReadVarInt(Stream &is)
Definition: serialize.h:395
VectorFormatter
Formatter to serialize/deserialize vector elements using another formatter.
Definition: serialize.h:578
le32toh
uint32_t le32toh(uint32_t little_endian_32bits)
Definition: endian.h:205
GetSerializeSizeMany
size_t GetSerializeSizeMany(int nVersion, const T &... t)
Definition: serialize.h:1099
SerWrite
void SerWrite(Stream &s, CSerActionSerialize ser_action, Type &&obj, Fn &&fn)
Definition: serialize.h:1071
VarIntMode::NONNEGATIVE_SIGNED
@ NONNEGATIVE_SIGNED
ReadWriteAsHelper
X & ReadWriteAsHelper(X &x)
Convert the reference base type to X, without changing constness or reference type.
Definition: serialize.h:144
CSizeComputer::size
size_t size() const
Definition: serialize.h:1016
CSizeComputer::operator<<
CSizeComputer & operator<<(const T &obj)
Definition: serialize.h:1010
CompactSizeWriter::n
uint64_t n
Definition: serialize.h:533
ReadCompactSize
uint64_t ReadCompactSize(Stream &is, bool range_check=true)
Decode a CompactSize-encoded variable-length integer.
Definition: serialize.h:282
CustomUintFormatter
Serialization wrapper class for custom integers and enums.
Definition: serialize.h:472
Unserialize_impl
void Unserialize_impl(Stream &is, prevector< N, T > &v, const unsigned char &)
Definition: serialize.h:757
CheckVarIntMode
Definition: serialize.h:351
CSerActionSerialize
Support for SERIALIZE_METHODS and READWRITE macro.
Definition: serialize.h:962
be64toh
uint64_t be64toh(uint64_t big_endian_64bits)
Definition: endian.h:226
CSerActionUnserialize
Definition: serialize.h:966
CompactSizeWriter::Serialize
void Serialize(Stream &s) const
Definition: serialize.h:538
be32toh
uint32_t be32toh(uint32_t big_endian_32bits)
Definition: endian.h:198
SerRead
void SerRead(Stream &s, CSerActionSerialize ser_action, Type &&, Fn &&)
Definition: serialize.h:1060
CustomUintFormatter::Unser
void Unser(Stream &s, I &v)
Definition: serialize.h:489
CSizeComputer::nVersion
const int nVersion
Definition: serialize.h:994
Span::size
constexpr std::size_t size() const noexcept
Definition: span.h:186
Span< const unsigned char >
CSerActionUnserialize::ForRead
constexpr bool ForRead() const
Definition: serialize.h:968
ser_readdata32be
uint32_t ser_readdata32be(Stream &s)
Definition: serialize.h:113
MAX_SIZE
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:31
MAX_VECTOR_ALLOCATE
static const unsigned int MAX_VECTOR_ALLOCATE
Maximum amount of memory (in bytes) to allocate at once when deserializing vectors.
Definition: serialize.h:34
Unserialize
void Unserialize(Stream &s, char &a)
Definition: serialize.h:215
LimitedStringFormatter
Definition: serialize.h:544
CSizeComputer
Definition: serialize.h:989
CompactSizeWriter::CompactSizeWriter
CompactSizeWriter(uint64_t n_in)
Definition: serialize.h:535
LimitedStringFormatter::Ser
void Ser(Stream &s, const std::string &v)
Definition: serialize.h:558
ser_readdata16
uint16_t ser_readdata16(Stream &s)
Definition: serialize.h:95
WriteCompactSize
void WriteCompactSize(CSizeComputer &os, uint64_t nSize)
Definition: serialize.h:1087
span.h
le16toh
uint16_t le16toh(uint16_t little_endian_16bits)
Definition: endian.h:177
Serialize_impl
void Serialize_impl(Stream &os, const prevector< N, T > &v, const unsigned char &)
prevector prevectors of unsigned char are a special case and are intended to be serialized as a singl...
Definition: serialize.h:736
htobe32
uint32_t htobe32(uint32_t host_32bits)
Definition: endian.h:184
ser_readdata16be
uint16_t ser_readdata16be(Stream &s)
Definition: serialize.h:101
be16toh
uint16_t be16toh(uint16_t big_endian_16bits)
Definition: endian.h:170
CSerActionSerialize::ForRead
constexpr bool ForRead() const
Definition: serialize.h:964
ser_readdata8
uint8_t ser_readdata8(Stream &s)
Definition: serialize.h:89
CompactSizeFormatter
Formatter for integers in CompactSize format.
Definition: serialize.h:508
GetSizeOfCompactSize
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:240
htobe16
uint16_t htobe16(uint16_t host_16bits)
Definition: endian.h:156
VarIntMode
VarIntMode
Variable-length integers: bytes are a MSB base-128 encoding of the number.
Definition: serialize.h:348
CSizeComputer::CSizeComputer
CSizeComputer(int nVersionIn)
Definition: serialize.h:996
UnserializeMany
void UnserializeMany(Stream &s)
Definition: serialize.h:1036
SerializeMany
void SerializeMany(Stream &s)
Definition: serialize.h:1024
CheckVarIntMode::CheckVarIntMode
constexpr CheckVarIntMode()
Definition: serialize.h:352
SerReadWriteMany
void SerReadWriteMany(Stream &s, CSerActionSerialize ser_action, const Args &... args)
Definition: serialize.h:1048
ser_writedata8
void ser_writedata8(Stream &s, uint8_t obj)
Definition: serialize.h:60
CustomUintFormatter::Ser
void Ser(Stream &s, I v)
Definition: serialize.h:477
Wrapper::Unserialize
void Unserialize(Stream &s)
Definition: serialize.h:426
htole32
uint32_t htole32(uint32_t host_32bits)
Definition: endian.h:191
ser_writedata32
void ser_writedata32(Stream &s, uint32_t obj)
Definition: serialize.h:74
CSizeComputer::write
void write(const char *psz, size_t _nSize)
Definition: serialize.h:998
VarIntFormatter::Unser
void Unser(Stream &s, I &v)
Definition: serialize.h:456
CompactSizeFormatter::Ser
void Ser(Stream &s, I v)
Definition: serialize.h:521
LimitedStringFormatter::Unser
void Unser(Stream &s, std::string &v)
Definition: serialize.h:547
prevector< N, T >
Span::data
constexpr C * data() const noexcept
Definition: span.h:173
le64toh
uint64_t le64toh(uint64_t little_endian_64bits)
Definition: endian.h:233
ByteUnit::K
@ K
Wrapper::Serialize
void Serialize(Stream &s) const
Definition: serialize.h:425
WriteVarInt
void WriteVarInt(CSizeComputer &os, I n)
Definition: serialize.h:1082
X
#define X(name)
Definition: net.cpp:577
prevector::data
value_type * data()
Definition: prevector.h:528
ser_writedata32be
void ser_writedata32be(Stream &s, uint32_t obj)
Definition: serialize.h:79
ser_writedata16
void ser_writedata16(Stream &s, uint16_t obj)
Definition: serialize.h:64
ByteUnit::T
@ T
Wrapper::Wrapper
Wrapper(T obj)
Definition: serialize.h:424
prevector::size
size_type size() const
Definition: prevector.h:282
prevector::resize_uninitialized
void resize_uninitialized(size_type new_size)
Definition: prevector.h:386
VectorFormatter::Unser
void Unser(Stream &s, V &v)
Definition: serialize.h:591
prevector::empty
bool empty() const
Definition: prevector.h:286
SER_NETWORK
@ SER_NETWORK
Definition: serialize.h:138
prevector.h
Wrapper::m_object
T m_object
Definition: serialize.h:420
Wrapper
Simple wrapper class to serialize objects using a formatter; used by Using().
Definition: serialize.h:418
VarIntMode::DEFAULT
@ DEFAULT
htobe64
uint64_t htobe64(uint64_t host_64bits)
Definition: endian.h:212
T
#define T(expected, seed, data)
Using
static Wrapper< Formatter, T & > Using(T &&t)
Cause serialization/deserialization of an object to be done using a specified formatter class.
Definition: serialize.h:440
VectorFormatter::Ser
void Ser(Stream &s, const V &v)
Definition: serialize.h:581
ByteUnit::m
@ m
CSizeComputer::seek
void seek(size_t _nSize)
Pretend _nSize bytes are written, without specifying them.
Definition: serialize.h:1004
Serialize
void Serialize(Stream &s, char a)
Definition: serialize.h:199
VarIntFormatter::Ser
void Ser(Stream &s, I v)
Definition: serialize.h:451
CharCast
char * CharCast(char *c)
Safely convert odd char pointer types to standard ones.
Definition: serialize.h:51
SER_GETHASH
@ SER_GETHASH
Definition: serialize.h:140
CompactSizeFormatter::Unser
void Unser(Stream &s, I &v)
Definition: serialize.h:511
deserialize
constexpr deserialize_type deserialize
Definition: serialize.h:48
CompactSizeWriter
Definition: serialize.h:530
ser_readdata64
uint64_t ser_readdata64(Stream &s)
Definition: serialize.h:119
ByteUnit::t
@ t
args
ArgsManager args
Definition: notifications.cpp:36
CustomUintFormatter::MAX
static constexpr uint64_t MAX
Definition: serialize.h:475
CSizeComputer::nSize
size_t nSize
Definition: serialize.h:992
endian.h