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-2020 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 
530 template<size_t Limit>
532 {
533  template<typename Stream>
534  void Unser(Stream& s, std::string& v)
535  {
536  size_t size = ReadCompactSize(s);
537  if (size > Limit) {
538  throw std::ios_base::failure("String length limit exceeded");
539  }
540  v.resize(size);
541  if (size != 0) s.read((char*)v.data(), size);
542  }
543 
544  template<typename Stream>
545  void Ser(Stream& s, const std::string& v)
546  {
547  s << v;
548  }
549 };
550 
564 template<class Formatter>
566 {
567  template<typename Stream, typename V>
568  void Ser(Stream& s, const V& v)
569  {
570  Formatter formatter;
571  WriteCompactSize(s, v.size());
572  for (const typename V::value_type& elem : v) {
573  formatter.Ser(s, elem);
574  }
575  }
576 
577  template<typename Stream, typename V>
578  void Unser(Stream& s, V& v)
579  {
580  Formatter formatter;
581  v.clear();
582  size_t size = ReadCompactSize(s);
583  size_t allocated = 0;
584  while (allocated < size) {
585  // For DoS prevention, do not blindly allocate as much as the stream claims to contain.
586  // Instead, allocate in 5MiB batches, so that an attacker actually needs to provide
587  // X MiB of data to make us allocate X+5 Mib.
588  static_assert(sizeof(typename V::value_type) <= MAX_VECTOR_ALLOCATE, "Vector element size too large");
589  allocated = std::min(size, allocated + MAX_VECTOR_ALLOCATE / sizeof(typename V::value_type));
590  v.reserve(allocated);
591  while (v.size() < allocated) {
592  v.emplace_back();
593  formatter.Unser(s, v.back());
594  }
595  }
596  };
597 };
598 
606 template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str);
607 template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str);
608 
613 template<typename Stream, unsigned int N, typename T> void Serialize_impl(Stream& os, const prevector<N, T>& v, const unsigned char&);
614 template<typename Stream, unsigned int N, typename T, typename V> void Serialize_impl(Stream& os, const prevector<N, T>& v, const V&);
615 template<typename Stream, unsigned int N, typename T> inline void Serialize(Stream& os, const prevector<N, T>& v);
616 template<typename Stream, unsigned int N, typename T> void Unserialize_impl(Stream& is, prevector<N, T>& v, const unsigned char&);
617 template<typename Stream, unsigned int N, typename T, typename V> void Unserialize_impl(Stream& is, prevector<N, T>& v, const V&);
618 template<typename Stream, unsigned int N, typename T> inline void Unserialize(Stream& is, prevector<N, T>& v);
619 
624 template<typename Stream, typename T, typename A> void Serialize_impl(Stream& os, const std::vector<T, A>& v, const unsigned char&);
625 template<typename Stream, typename T, typename A> void Serialize_impl(Stream& os, const std::vector<T, A>& v, const bool&);
626 template<typename Stream, typename T, typename A, typename V> void Serialize_impl(Stream& os, const std::vector<T, A>& v, const V&);
627 template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v);
628 template<typename Stream, typename T, typename A> void Unserialize_impl(Stream& is, std::vector<T, A>& v, const unsigned char&);
629 template<typename Stream, typename T, typename A, typename V> void Unserialize_impl(Stream& is, std::vector<T, A>& v, const V&);
630 template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v);
631 
635 template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item);
636 template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item);
637 
641 template<typename Stream, typename K, typename T, typename Pred, typename A> void Serialize(Stream& os, const std::map<K, T, Pred, A>& m);
642 template<typename Stream, typename K, typename T, typename Pred, typename A> void Unserialize(Stream& is, std::map<K, T, Pred, A>& m);
643 
647 template<typename Stream, typename K, typename Pred, typename A> void Serialize(Stream& os, const std::set<K, Pred, A>& m);
648 template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m);
649 
653 template<typename Stream, typename T> void Serialize(Stream& os, const std::shared_ptr<const T>& p);
654 template<typename Stream, typename T> void Unserialize(Stream& os, std::shared_ptr<const T>& p);
655 
659 template<typename Stream, typename T> void Serialize(Stream& os, const std::unique_ptr<const T>& p);
660 template<typename Stream, typename T> void Unserialize(Stream& os, std::unique_ptr<const T>& p);
661 
662 
663 
667 template<typename Stream, typename T>
668 inline void Serialize(Stream& os, const T& a)
669 {
670  a.Serialize(os);
671 }
672 
673 template<typename Stream, typename T>
674 inline void Unserialize(Stream& is, T&& a)
675 {
676  a.Unserialize(is);
677 }
678 
685 {
686  template<typename Stream, typename T>
687  static void Ser(Stream& s, const T& t) { Serialize(s, t); }
688 
689  template<typename Stream, typename T>
690  static void Unser(Stream& s, T& t) { Unserialize(s, t); }
691 };
692 
693 
694 
695 
696 
700 template<typename Stream, typename C>
701 void Serialize(Stream& os, const std::basic_string<C>& str)
702 {
703  WriteCompactSize(os, str.size());
704  if (!str.empty())
705  os.write((char*)str.data(), str.size() * sizeof(C));
706 }
707 
708 template<typename Stream, typename C>
709 void Unserialize(Stream& is, std::basic_string<C>& str)
710 {
711  unsigned int nSize = ReadCompactSize(is);
712  str.resize(nSize);
713  if (nSize != 0)
714  is.read((char*)str.data(), nSize * sizeof(C));
715 }
716 
717 
718 
722 template<typename Stream, unsigned int N, typename T>
723 void Serialize_impl(Stream& os, const prevector<N, T>& v, const unsigned char&)
724 {
725  WriteCompactSize(os, v.size());
726  if (!v.empty())
727  os.write((char*)v.data(), v.size() * sizeof(T));
728 }
729 
730 template<typename Stream, unsigned int N, typename T, typename V>
731 void Serialize_impl(Stream& os, const prevector<N, T>& v, const V&)
732 {
734 }
735 
736 template<typename Stream, unsigned int N, typename T>
737 inline void Serialize(Stream& os, const prevector<N, T>& v)
738 {
739  Serialize_impl(os, v, T());
740 }
741 
742 
743 template<typename Stream, unsigned int N, typename T>
744 void Unserialize_impl(Stream& is, prevector<N, T>& v, const unsigned char&)
745 {
746  // Limit size per read so bogus size value won't cause out of memory
747  v.clear();
748  unsigned int nSize = ReadCompactSize(is);
749  unsigned int i = 0;
750  while (i < nSize)
751  {
752  unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
753  v.resize_uninitialized(i + blk);
754  is.read((char*)&v[i], blk * sizeof(T));
755  i += blk;
756  }
757 }
758 
759 template<typename Stream, unsigned int N, typename T, typename V>
760 void Unserialize_impl(Stream& is, prevector<N, T>& v, const V&)
761 {
763 }
764 
765 template<typename Stream, unsigned int N, typename T>
766 inline void Unserialize(Stream& is, prevector<N, T>& v)
767 {
768  Unserialize_impl(is, v, T());
769 }
770 
771 
772 
776 template<typename Stream, typename T, typename A>
777 void Serialize_impl(Stream& os, const std::vector<T, A>& v, const unsigned char&)
778 {
779  WriteCompactSize(os, v.size());
780  if (!v.empty())
781  os.write((char*)v.data(), v.size() * sizeof(T));
782 }
783 
784 template<typename Stream, typename T, typename A>
785 void Serialize_impl(Stream& os, const std::vector<T, A>& v, const bool&)
786 {
787  // A special case for std::vector<bool>, as dereferencing
788  // std::vector<bool>::const_iterator does not result in a const bool&
789  // due to std::vector's special casing for bool arguments.
790  WriteCompactSize(os, v.size());
791  for (bool elem : v) {
792  ::Serialize(os, elem);
793  }
794 }
795 
796 template<typename Stream, typename T, typename A, typename V>
797 void Serialize_impl(Stream& os, const std::vector<T, A>& v, const V&)
798 {
800 }
801 
802 template<typename Stream, typename T, typename A>
803 inline void Serialize(Stream& os, const std::vector<T, A>& v)
804 {
805  Serialize_impl(os, v, T());
806 }
807 
808 
809 template<typename Stream, typename T, typename A>
810 void Unserialize_impl(Stream& is, std::vector<T, A>& v, const unsigned char&)
811 {
812  // Limit size per read so bogus size value won't cause out of memory
813  v.clear();
814  unsigned int nSize = ReadCompactSize(is);
815  unsigned int i = 0;
816  while (i < nSize)
817  {
818  unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
819  v.resize(i + blk);
820  is.read((char*)&v[i], blk * sizeof(T));
821  i += blk;
822  }
823 }
824 
825 template<typename Stream, typename T, typename A, typename V>
826 void Unserialize_impl(Stream& is, std::vector<T, A>& v, const V&)
827 {
829 }
830 
831 template<typename Stream, typename T, typename A>
832 inline void Unserialize(Stream& is, std::vector<T, A>& v)
833 {
834  Unserialize_impl(is, v, T());
835 }
836 
837 
838 
842 template<typename Stream, typename K, typename T>
843 void Serialize(Stream& os, const std::pair<K, T>& item)
844 {
845  Serialize(os, item.first);
846  Serialize(os, item.second);
847 }
848 
849 template<typename Stream, typename K, typename T>
850 void Unserialize(Stream& is, std::pair<K, T>& item)
851 {
852  Unserialize(is, item.first);
853  Unserialize(is, item.second);
854 }
855 
856 
857 
861 template<typename Stream, typename K, typename T, typename Pred, typename A>
862 void Serialize(Stream& os, const std::map<K, T, Pred, A>& m)
863 {
864  WriteCompactSize(os, m.size());
865  for (const auto& entry : m)
866  Serialize(os, entry);
867 }
868 
869 template<typename Stream, typename K, typename T, typename Pred, typename A>
870 void Unserialize(Stream& is, std::map<K, T, Pred, A>& m)
871 {
872  m.clear();
873  unsigned int nSize = ReadCompactSize(is);
874  typename std::map<K, T, Pred, A>::iterator mi = m.begin();
875  for (unsigned int i = 0; i < nSize; i++)
876  {
877  std::pair<K, T> item;
878  Unserialize(is, item);
879  mi = m.insert(mi, item);
880  }
881 }
882 
883 
884 
888 template<typename Stream, typename K, typename Pred, typename A>
889 void Serialize(Stream& os, const std::set<K, Pred, A>& m)
890 {
891  WriteCompactSize(os, m.size());
892  for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
893  Serialize(os, (*it));
894 }
895 
896 template<typename Stream, typename K, typename Pred, typename A>
897 void Unserialize(Stream& is, std::set<K, Pred, A>& m)
898 {
899  m.clear();
900  unsigned int nSize = ReadCompactSize(is);
901  typename std::set<K, Pred, A>::iterator it = m.begin();
902  for (unsigned int i = 0; i < nSize; i++)
903  {
904  K key;
905  Unserialize(is, key);
906  it = m.insert(it, key);
907  }
908 }
909 
910 
911 
915 template<typename Stream, typename T> void
916 Serialize(Stream& os, const std::unique_ptr<const T>& p)
917 {
918  Serialize(os, *p);
919 }
920 
921 template<typename Stream, typename T>
922 void Unserialize(Stream& is, std::unique_ptr<const T>& p)
923 {
924  p.reset(new T(deserialize, is));
925 }
926 
927 
928 
932 template<typename Stream, typename T> void
933 Serialize(Stream& os, const std::shared_ptr<const T>& p)
934 {
935  Serialize(os, *p);
936 }
937 
938 template<typename Stream, typename T>
939 void Unserialize(Stream& is, std::shared_ptr<const T>& p)
940 {
941  p = std::make_shared<const T>(deserialize, is);
942 }
943 
944 
945 
950 {
951  constexpr bool ForRead() const { return false; }
952 };
954 {
955  constexpr bool ForRead() const { return true; }
956 };
957 
958 
959 
960 
961 
962 
963 
964 
965 /* ::GetSerializeSize implementations
966  *
967  * Computing the serialized size of objects is done through a special stream
968  * object of type CSizeComputer, which only records the number of bytes written
969  * to it.
970  *
971  * If your Serialize or SerializationOp method has non-trivial overhead for
972  * serialization, it may be worthwhile to implement a specialized version for
973  * CSizeComputer, which uses the s.seek() method to record bytes that would
974  * be written instead.
975  */
977 {
978 protected:
979  size_t nSize;
980 
981  const int nVersion;
982 public:
983  explicit CSizeComputer(int nVersionIn) : nSize(0), nVersion(nVersionIn) {}
984 
985  void write(const char *psz, size_t _nSize)
986  {
987  this->nSize += _nSize;
988  }
989 
991  void seek(size_t _nSize)
992  {
993  this->nSize += _nSize;
994  }
995 
996  template<typename T>
998  {
999  ::Serialize(*this, obj);
1000  return (*this);
1001  }
1002 
1003  size_t size() const {
1004  return nSize;
1005  }
1006 
1007  int GetVersion() const { return nVersion; }
1008 };
1009 
1010 template<typename Stream>
1011 void SerializeMany(Stream& s)
1012 {
1013 }
1014 
1015 template<typename Stream, typename Arg, typename... Args>
1016 void SerializeMany(Stream& s, const Arg& arg, const Args&... args)
1017 {
1018  ::Serialize(s, arg);
1019  ::SerializeMany(s, args...);
1020 }
1021 
1022 template<typename Stream>
1023 inline void UnserializeMany(Stream& s)
1024 {
1025 }
1026 
1027 template<typename Stream, typename Arg, typename... Args>
1028 inline void UnserializeMany(Stream& s, Arg&& arg, Args&&... args)
1029 {
1030  ::Unserialize(s, arg);
1031  ::UnserializeMany(s, args...);
1032 }
1033 
1034 template<typename Stream, typename... Args>
1035 inline void SerReadWriteMany(Stream& s, CSerActionSerialize ser_action, const Args&... args)
1036 {
1037  ::SerializeMany(s, args...);
1038 }
1039 
1040 template<typename Stream, typename... Args>
1041 inline void SerReadWriteMany(Stream& s, CSerActionUnserialize ser_action, Args&&... args)
1042 {
1043  ::UnserializeMany(s, args...);
1044 }
1045 
1046 template<typename Stream, typename Type, typename Fn>
1047 inline void SerRead(Stream& s, CSerActionSerialize ser_action, Type&&, Fn&&)
1048 {
1049 }
1050 
1051 template<typename Stream, typename Type, typename Fn>
1052 inline void SerRead(Stream& s, CSerActionUnserialize ser_action, Type&& obj, Fn&& fn)
1053 {
1054  fn(s, std::forward<Type>(obj));
1055 }
1056 
1057 template<typename Stream, typename Type, typename Fn>
1058 inline void SerWrite(Stream& s, CSerActionSerialize ser_action, Type&& obj, Fn&& fn)
1059 {
1060  fn(s, std::forward<Type>(obj));
1061 }
1062 
1063 template<typename Stream, typename Type, typename Fn>
1064 inline void SerWrite(Stream& s, CSerActionUnserialize ser_action, Type&&, Fn&&)
1065 {
1066 }
1067 
1068 template<typename I>
1069 inline void WriteVarInt(CSizeComputer &s, I n)
1070 {
1071  s.seek(GetSizeOfVarInt<I>(n));
1072 }
1073 
1074 inline void WriteCompactSize(CSizeComputer &s, uint64_t nSize)
1075 {
1076  s.seek(GetSizeOfCompactSize(nSize));
1077 }
1078 
1079 template <typename T>
1080 size_t GetSerializeSize(const T& t, int nVersion = 0)
1081 {
1082  return (CSizeComputer(nVersion) << t).size();
1083 }
1084 
1085 template <typename... T>
1086 size_t GetSerializeSizeMany(int nVersion, const T&... t)
1087 {
1088  CSizeComputer sc(nVersion);
1089  SerializeMany(sc, t...);
1090  return sc.size();
1091 }
1092 
1093 #endif // BITCOIN_SERIALIZE_H
DefaultFormatter
Default formatter.
Definition: serialize.h:684
GetSerializeSize
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition: serialize.h:1080
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:1007
DefaultFormatter::Unser
static void Unser(Stream &s, T &t)
Definition: serialize.h:690
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:687
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:565
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:1086
SerWrite
void SerWrite(Stream &s, CSerActionSerialize ser_action, Type &&obj, Fn &&fn)
Definition: serialize.h:1058
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:1003
CSizeComputer::operator<<
CSizeComputer & operator<<(const T &obj)
Definition: serialize.h:997
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:744
CheckVarIntMode
Definition: serialize.h:351
CSerActionSerialize
Support for SERIALIZE_METHODS and READWRITE macro.
Definition: serialize.h:949
be64toh
uint64_t be64toh(uint64_t big_endian_64bits)
Definition: endian.h:226
CSerActionUnserialize
Definition: serialize.h:953
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:1047
CustomUintFormatter::Unser
void Unser(Stream &s, I &v)
Definition: serialize.h:489
CSizeComputer::nVersion
const int nVersion
Definition: serialize.h:981
Span::size
constexpr std::size_t size() const noexcept
Definition: span.h:182
Span
A Span is an object that can refer to a contiguous sequence of objects.
Definition: span.h:92
CSerActionUnserialize::ForRead
constexpr bool ForRead() const
Definition: serialize.h:955
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:531
CSizeComputer
Definition: serialize.h:976
LimitedStringFormatter::Ser
void Ser(Stream &s, const std::string &v)
Definition: serialize.h:545
ser_readdata16
uint16_t ser_readdata16(Stream &s)
Definition: serialize.h:95
WriteCompactSize
void WriteCompactSize(CSizeComputer &os, uint64_t nSize)
Definition: serialize.h:1074
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:723
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:951
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:983
UnserializeMany
void UnserializeMany(Stream &s)
Definition: serialize.h:1023
SerializeMany
void SerializeMany(Stream &s)
Definition: serialize.h:1011
CheckVarIntMode::CheckVarIntMode
constexpr CheckVarIntMode()
Definition: serialize.h:352
SerReadWriteMany
void SerReadWriteMany(Stream &s, CSerActionSerialize ser_action, const Args &... args)
Definition: serialize.h:1035
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:985
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:534
prevector< N, T >
Span::data
constexpr C * data() const noexcept
Definition: span.h:169
le64toh
uint64_t le64toh(uint64_t little_endian_64bits)
Definition: endian.h:233
Wrapper::Serialize
void Serialize(Stream &s) const
Definition: serialize.h:425
WriteVarInt
void WriteVarInt(CSizeComputer &os, I n)
Definition: serialize.h:1069
X
#define X(name)
Definition: net.cpp:555
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
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:578
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:568
CSizeComputer::seek
void seek(size_t _nSize)
Pretend _nSize bytes are written, without specifying them.
Definition: serialize.h:991
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
ser_readdata64
uint64_t ser_readdata64(Stream &s)
Definition: serialize.h:119
CustomUintFormatter::MAX
static constexpr uint64_t MAX
Definition: serialize.h:475
CSizeComputer::nSize
size_t nSize
Definition: serialize.h:979
endian.h