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
27 /**
28 * The maximum size of a serialized object in bytes or number of elements
29 * (for eg vectors) when the size is encoded as CompactSize.
30 */
31 static constexpr uint64_t MAX_SIZE = 0x02000000;
main(void)32
33 /** Maximum amount of memory (in bytes) to allocate at once when deserializing vectors. */
34 static const unsigned int MAX_VECTOR_ALLOCATE = 5000000;
35
36 /**
37 * Dummy data type to identify deserializing constructors.
38 *
39 * By convention, a constructor of a type T with signature
40 *
41 * template <typename Stream> T::T(deserialize_type, Stream& s)
42 *
43 * is a deserializing constructor, which builds the type by
44 * deserializing it from s. If T contains const fields, this
45 * is likely the only way to do so.
46 */
47 struct deserialize_type {};
48 constexpr deserialize_type deserialize {};
49
50 //! Safely convert odd char pointer types to standard ones.
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)
run_tests(secp256k1_context * ctx,unsigned char * key)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
127 /////////////////////////////////////////////////////////////////
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
143 //! Convert the reference base type to X, without changing constness or reference type.
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
152 /**
153 * Implement the Ser and Unser methods needed for implementing a formatter (see Using below).
154 *
155 * Both Ser and Unser are delegated to a single static method SerializationOps, which is polymorphic
156 * in the serialized/deserialized type (allowing it to be const when serializing, and non-const when
157 * deserializing).
158 *
159 * Example use:
160 * struct FooFormatter {
161 * FORMATTER_METHODS(Class, obj) { READWRITE(obj.val1, VARINT(obj.val2)); }
162 * }
163 * would define a class FooFormatter that defines a serialization of Class objects consisting
164 * of serializing its val1 member using the default serialization, and its val2 member using
165 * VARINT serialization. That FooFormatter can then be used in statements like
166 * READWRITE(Using<FooFormatter>(obj.bla)).
167 */
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 /**
177 * Implement the Serialize and Unserialize methods by delegating to a single templated
178 * static method that takes the to-be-(de)serialized object as a parameter. This approach
179 * has the advantage that the constness of the object becomes a template parameter, and
180 * thus allows a single implementation that sees the object as const for serializing
181 * and non-const for deserializing, without casts.
182 */
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
233 /**
234 * Compact Size
235 * size < 253 -- 1 byte
236 * size <= USHRT_MAX -- 3 bytes (253 + 2 bytes)
237 * size <= UINT_MAX -- 5 bytes (254 + 4 bytes)
238 * size > UINT_MAX -- 9 bytes (255 + 8 bytes)
239 */
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
275 /**
276 * Decode a CompactSize-encoded variable-length integer.
277 *
278 * As these are primarily used to encode the size of vector-like serializations, by default a range
279 * check is performed. When used as a generic number encoding, range_check should be set to false.
280 */
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
314 /**
315 * Variable-length integers: bytes are a MSB base-128 encoding of the number.
316 * The high bit in each byte signifies whether another digit follows. To make
317 * sure the encoding is one-to-one, one is subtracted from all but the last digit.
318 * Thus, the byte sequence a[] with length len, where all but the last byte
319 * has bit 128 set, encodes the number:
320 *
321 * (a[len-1] & 0x7F) + sum(i=1..len-1, 128^i*((a[len-i-1] & 0x7F)+1))
322 *
323 * Properties:
324 * * Very small (0-127: 1 byte, 128-16511: 2 bytes, 16512-2113663: 3 bytes)
325 * * Every integer has exactly one encoding
326 * * Encoding does not depend on size of original integer type
327 * * No redundancy: every (infinite) byte sequence corresponds to a list
328 * of encoded integers.
329 *
330 * 0: [0x00] 256: [0x81 0x00]
331 * 1: [0x01] 16383: [0xFE 0x7F]
332 * 127: [0x7F] 16384: [0xFF 0x00]
333 * 128: [0x80 0x00] 16511: [0xFF 0x7F]
334 * 255: [0x80 0x7F] 65535: [0x82 0xFE 0x7F]
335 * 2^32: [0x8E 0xFE 0xFE 0xFF 0x00]
336 */
337
338 /**
339 * Mode for encoding VarInts.
340 *
341 * Currently there is no support for signed encodings. The default mode will not
342 * compile with signed values, and the legacy "nonnegative signed" mode will
343 * accept signed values, but improperly encode and decode them if they are
344 * negative. In the future, the DEFAULT mode could be extended to support
345 * negative numbers in a backwards compatible way, and additional modes could be
346 * added to support different varint formats (e.g. zigzag encoding).
347 */
348 enum class VarIntMode { DEFAULT, NONNEGATIVE_SIGNED };
349
350 template <VarIntMode Mode, typename I>
351 struct CheckVarIntMode {
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 {
362 CheckVarIntMode<Mode, I>();
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 {
379 CheckVarIntMode<Mode, I>();
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 {
397 CheckVarIntMode<Mode, I>();
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
416 /** Simple wrapper class to serialize objects using a formatter; used by Using(). */
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
429 /** Cause serialization/deserialization of an object to be done using a specified formatter class.
430 *
431 * To use this, you need a class Formatter that has public functions Ser(stream, const object&) for
432 * serialization, and Unser(stream, object&) for deserialization. Serialization routines (inside
433 * READWRITE, or directly with << and >> operators), can then use Using<Formatter>(object).
434 *
435 * This works by constructing a Wrapper<Formatter, T>-wrapped version of object, where T is
436 * const during serialization, and non-const during deserialization, which maintains const
437 * correctness.
438 */
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
447 /** Serialization wrapper class for integers in VarInt format. */
448 template<VarIntMode Mode>
449 struct VarIntFormatter
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
462 /** Serialization wrapper class for custom integers and enums.
463 *
464 * It permits specifying the serialized size (1 to 8 bytes) and endianness.
465 *
466 * Use the big endian mode for values that are stored in memory in native
467 * byte order, but serialized in big endian notation. This is only intended
468 * to implement serializers that are compatible with existing formats, and
469 * its use is not recommended for new data structures.
470 */
471 template<int Bytes, bool BigEndian = false>
472 struct CustomUintFormatter
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
504 template<int Bytes> using BigEndianFormatter = CustomUintFormatter<Bytes, true>;
505
506 /** Formatter for integers in CompactSize format. */
507 template<bool RangeCheck>
508 struct CompactSizeFormatter
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>
531 struct LimitedStringFormatter
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
551 /** Formatter to serialize/deserialize vector elements using another formatter
552 *
553 * Example:
554 * struct X {
555 * std::vector<uint64_t> v;
556 * SERIALIZE_METHODS(X, obj) { READWRITE(Using<VectorFormatter<VarInt>>(obj.v)); }
557 * };
558 * will define a struct that contains a vector of uint64_t, which is serialized
559 * as a vector of VarInt-encoded integers.
560 *
561 * V is not required to be an std::vector type. It works for any class that
562 * exposes a value_type, size, reserve, emplace_back, back, and const iterators.
563 */
564 template<class Formatter>
565 struct VectorFormatter
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
599 /**
600 * Forward declarations
601 */
602
603 /**
604 * string
605 */
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
609 /**
610 * prevector
611 * prevectors of unsigned char are a special case and are intended to be serialized as a single opaque blob.
612 */
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
620 /**
621 * vector
622 * vectors of unsigned char are a special case and are intended to be serialized as a single opaque blob.
623 */
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
632 /**
633 * pair
634 */
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
638 /**
639 * map
640 */
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
644 /**
645 * set
646 */
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
650 /**
651 * shared_ptr
652 */
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
656 /**
657 * unique_ptr
658 */
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
664 /**
665 * If none of the specialized versions above matched, default to calling member function.
666 */
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
679 /** Default formatter. Serializes objects as themselves.
680 *
681 * The vector/prevector serialization code passes this to VectorFormatter
682 * to enable reusing that logic. It shouldn't be needed elsewhere.
683 */
684 struct DefaultFormatter
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
697 /**
698 * string
699 */
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
719 /**
720 * prevector
721 */
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 {
733 Serialize(os, Using<VectorFormatter<DefaultFormatter>>(v));
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 {
762 Unserialize(is, Using<VectorFormatter<DefaultFormatter>>(v));
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
773 /**
774 * vector
775 */
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 {
799 Serialize(os, Using<VectorFormatter<DefaultFormatter>>(v));
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 {
828 Unserialize(is, Using<VectorFormatter<DefaultFormatter>>(v));
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
839 /**
840 * pair
841 */
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
858 /**
859 * map
860 */
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
885 /**
886 * set
887 */
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
912 /**
913 * unique_ptr
914 */
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
929 /**
930 * shared_ptr
931 */
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
946 /**
947 * Support for SERIALIZE_METHODS and READWRITE macro.
948 */
949 struct CSerActionSerialize
950 {
951 constexpr bool ForRead() const { return false; }
952 };
953 struct CSerActionUnserialize
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 */
976 class CSizeComputer
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
990 /** Pretend _nSize bytes are written, without specifying them. */
991 void seek(size_t _nSize)
992 {
993 this->nSize += _nSize;
994 }
995
996 template<typename T>
997 CSizeComputer& operator<<(const T& obj)
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
1094