1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2015 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 <assert.h>
13 #include <ios>
14 #include <limits>
15 #include <map>
16 #include <set>
17 #include <stdint.h>
18 #include <string>
19 #include <string.h>
20 #include <utility>
21 #include <vector>
22 
23 #include "prevector.h"
24 
25 static const unsigned int MAX_SIZE = 0x02000000;
26 
27 /**
28  * Used to bypass the rule against non-const reference to temporary
29  * where it makes sense with wrappers such as CFlatData or CTxDB
30  */
31 template<typename T>
REF(const T & val)32 inline T& REF(const T& val)
33 {
34     return const_cast<T&>(val);
35 }
36 
37 /**
38  * Used to acquire a non-const pointer "this" to generate bodies
39  * of const serialization operations from a template
40  */
41 template<typename T>
NCONST_PTR(const T * val)42 inline T* NCONST_PTR(const T* val)
43 {
44     return const_cast<T*>(val);
45 }
46 
47 /**
48  * Get begin pointer of vector (non-const version).
49  * @note These functions avoid the undefined case of indexing into an empty
50  * vector, as well as that of indexing after the end of the vector.
51  */
52 template <typename V>
begin_ptr(V & v)53 inline typename V::value_type* begin_ptr(V& v)
54 {
55     return v.empty() ? NULL : &v[0];
56 }
57 /** Get begin pointer of vector (const version) */
58 template <typename V>
begin_ptr(const V & v)59 inline const typename V::value_type* begin_ptr(const V& v)
60 {
61     return v.empty() ? NULL : &v[0];
62 }
63 /** Get end pointer of vector (non-const version) */
64 template <typename V>
end_ptr(V & v)65 inline typename V::value_type* end_ptr(V& v)
66 {
67     return v.empty() ? NULL : (&v[0] + v.size());
68 }
69 /** Get end pointer of vector (const version) */
70 template <typename V>
end_ptr(const V & v)71 inline const typename V::value_type* end_ptr(const V& v)
72 {
73     return v.empty() ? NULL : (&v[0] + v.size());
74 }
75 
76 /*
77  * Lowest-level serialization and conversion.
78  * @note Sizes of these types are verified in the tests
79  */
ser_writedata8(Stream & s,uint8_t obj)80 template<typename Stream> inline void ser_writedata8(Stream &s, uint8_t obj)
81 {
82     s.write((char*)&obj, 1);
83 }
ser_writedata16(Stream & s,uint16_t obj)84 template<typename Stream> inline void ser_writedata16(Stream &s, uint16_t obj)
85 {
86     obj = htole16(obj);
87     s.write((char*)&obj, 2);
88 }
ser_writedata32(Stream & s,uint32_t obj)89 template<typename Stream> inline void ser_writedata32(Stream &s, uint32_t obj)
90 {
91     obj = htole32(obj);
92     s.write((char*)&obj, 4);
93 }
ser_writedata64(Stream & s,uint64_t obj)94 template<typename Stream> inline void ser_writedata64(Stream &s, uint64_t obj)
95 {
96     obj = htole64(obj);
97     s.write((char*)&obj, 8);
98 }
ser_readdata8(Stream & s)99 template<typename Stream> inline uint8_t ser_readdata8(Stream &s)
100 {
101     uint8_t obj;
102     s.read((char*)&obj, 1);
103     return obj;
104 }
ser_readdata16(Stream & s)105 template<typename Stream> inline uint16_t ser_readdata16(Stream &s)
106 {
107     uint16_t obj;
108     s.read((char*)&obj, 2);
109     return le16toh(obj);
110 }
ser_readdata32(Stream & s)111 template<typename Stream> inline uint32_t ser_readdata32(Stream &s)
112 {
113     uint32_t obj;
114     s.read((char*)&obj, 4);
115     return le32toh(obj);
116 }
ser_readdata64(Stream & s)117 template<typename Stream> inline uint64_t ser_readdata64(Stream &s)
118 {
119     uint64_t obj;
120     s.read((char*)&obj, 8);
121     return le64toh(obj);
122 }
ser_double_to_uint64(double x)123 inline uint64_t ser_double_to_uint64(double x)
124 {
125     union { double x; uint64_t y; } tmp;
126     tmp.x = x;
127     return tmp.y;
128 }
ser_float_to_uint32(float x)129 inline uint32_t ser_float_to_uint32(float x)
130 {
131     union { float x; uint32_t y; } tmp;
132     tmp.x = x;
133     return tmp.y;
134 }
ser_uint64_to_double(uint64_t y)135 inline double ser_uint64_to_double(uint64_t y)
136 {
137     union { double x; uint64_t y; } tmp;
138     tmp.y = y;
139     return tmp.x;
140 }
ser_uint32_to_float(uint32_t y)141 inline float ser_uint32_to_float(uint32_t y)
142 {
143     union { float x; uint32_t y; } tmp;
144     tmp.y = y;
145     return tmp.x;
146 }
147 
148 
149 /////////////////////////////////////////////////////////////////
150 //
151 // Templates for serializing to anything that looks like a stream,
152 // i.e. anything that supports .read(char*, size_t) and .write(char*, size_t)
153 //
154 
155 enum
156 {
157     // primary actions
158     SER_NETWORK         = (1 << 0),
159     SER_DISK            = (1 << 1),
160     SER_GETHASH         = (1 << 2),
161 };
162 
163 #define READWRITE(obj)      (::SerReadWrite(s, (obj), nType, nVersion, ser_action))
164 
165 /**
166  * Implement three methods for serializable objects. These are actually wrappers over
167  * "SerializationOp" template, which implements the body of each class' serialization
168  * code. Adding "ADD_SERIALIZE_METHODS" in the body of the class causes these wrappers to be
169  * added as members.
170  */
171 #define ADD_SERIALIZE_METHODS                                                          \
172     size_t GetSerializeSize(int nType, int nVersion) const {                         \
173         CSizeComputer s(nType, nVersion);                                            \
174         NCONST_PTR(this)->SerializationOp(s, CSerActionSerialize(), nType, nVersion);\
175         return s.size();                                                             \
176     }                                                                                \
177     template<typename Stream>                                                        \
178     void Serialize(Stream& s, int nType, int nVersion) const {                       \
179         NCONST_PTR(this)->SerializationOp(s, CSerActionSerialize(), nType, nVersion);\
180     }                                                                                \
181     template<typename Stream>                                                        \
182     void Unserialize(Stream& s, int nType, int nVersion) {                           \
183         SerializationOp(s, CSerActionUnserialize(), nType, nVersion);                \
184     }
185 
186 /*
187  * Basic Types
188  */
189 inline unsigned int GetSerializeSize(char a,      int, int=0) { return 1; }
190 inline unsigned int GetSerializeSize(int8_t a,    int, int=0) { return 1; }
191 inline unsigned int GetSerializeSize(uint8_t a,   int, int=0) { return 1; }
192 inline unsigned int GetSerializeSize(int16_t a,   int, int=0) { return 2; }
193 inline unsigned int GetSerializeSize(uint16_t a,  int, int=0) { return 2; }
194 inline unsigned int GetSerializeSize(int32_t a,   int, int=0) { return 4; }
195 inline unsigned int GetSerializeSize(uint32_t a,  int, int=0) { return 4; }
196 inline unsigned int GetSerializeSize(int64_t a,   int, int=0) { return 8; }
197 inline unsigned int GetSerializeSize(uint64_t a,  int, int=0) { return 8; }
198 inline unsigned int GetSerializeSize(float a,     int, int=0) { return 4; }
199 inline unsigned int GetSerializeSize(double a,    int, int=0) { return 8; }
200 
201 template<typename Stream> inline void Serialize(Stream& s, char a,         int, int=0) { ser_writedata8(s, a); } // TODO Get rid of bare char
202 template<typename Stream> inline void Serialize(Stream& s, int8_t a,       int, int=0) { ser_writedata8(s, a); }
203 template<typename Stream> inline void Serialize(Stream& s, uint8_t a,      int, int=0) { ser_writedata8(s, a); }
204 template<typename Stream> inline void Serialize(Stream& s, int16_t a,      int, int=0) { ser_writedata16(s, a); }
205 template<typename Stream> inline void Serialize(Stream& s, uint16_t a,     int, int=0) { ser_writedata16(s, a); }
206 template<typename Stream> inline void Serialize(Stream& s, int32_t a,      int, int=0) { ser_writedata32(s, a); }
207 template<typename Stream> inline void Serialize(Stream& s, uint32_t a,     int, int=0) { ser_writedata32(s, a); }
208 template<typename Stream> inline void Serialize(Stream& s, int64_t a,      int, int=0) { ser_writedata64(s, a); }
209 template<typename Stream> inline void Serialize(Stream& s, uint64_t a,     int, int=0) { ser_writedata64(s, a); }
210 template<typename Stream> inline void Serialize(Stream& s, float a,        int, int=0) { ser_writedata32(s, ser_float_to_uint32(a)); }
211 template<typename Stream> inline void Serialize(Stream& s, double a,       int, int=0) { ser_writedata64(s, ser_double_to_uint64(a)); }
212 
213 template<typename Stream> inline void Unserialize(Stream& s, char& a,      int, int=0) { a = ser_readdata8(s); } // TODO Get rid of bare char
214 template<typename Stream> inline void Unserialize(Stream& s, int8_t& a,    int, int=0) { a = ser_readdata8(s); }
215 template<typename Stream> inline void Unserialize(Stream& s, uint8_t& a,   int, int=0) { a = ser_readdata8(s); }
216 template<typename Stream> inline void Unserialize(Stream& s, int16_t& a,   int, int=0) { a = ser_readdata16(s); }
217 template<typename Stream> inline void Unserialize(Stream& s, uint16_t& a,  int, int=0) { a = ser_readdata16(s); }
218 template<typename Stream> inline void Unserialize(Stream& s, int32_t& a,   int, int=0) { a = ser_readdata32(s); }
219 template<typename Stream> inline void Unserialize(Stream& s, uint32_t& a,  int, int=0) { a = ser_readdata32(s); }
220 template<typename Stream> inline void Unserialize(Stream& s, int64_t& a,   int, int=0) { a = ser_readdata64(s); }
221 template<typename Stream> inline void Unserialize(Stream& s, uint64_t& a,  int, int=0) { a = ser_readdata64(s); }
222 template<typename Stream> inline void Unserialize(Stream& s, float& a,     int, int=0) { a = ser_uint32_to_float(ser_readdata32(s)); }
223 template<typename Stream> inline void Unserialize(Stream& s, double& a,    int, int=0) { a = ser_uint64_to_double(ser_readdata64(s)); }
224 
225 inline unsigned int GetSerializeSize(bool a, int, int=0)                          { return sizeof(char); }
226 template<typename Stream> inline void Serialize(Stream& s, bool a, int, int=0)    { char f=a; ser_writedata8(s, f); }
227 template<typename Stream> inline void Unserialize(Stream& s, bool& a, int, int=0) { char f=ser_readdata8(s); a=f; }
228 
229 
230 
231 
232 
233 
234 /**
235  * Compact Size
236  * size <  253        -- 1 byte
237  * size <= USHRT_MAX  -- 3 bytes  (253 + 2 bytes)
238  * size <= UINT_MAX   -- 5 bytes  (254 + 4 bytes)
239  * size >  UINT_MAX   -- 9 bytes  (255 + 8 bytes)
240  */
GetSizeOfCompactSize(uint64_t nSize)241 inline unsigned int GetSizeOfCompactSize(uint64_t nSize)
242 {
243     if (nSize < 253)             return sizeof(unsigned char);
244     else if (nSize <= std::numeric_limits<unsigned short>::max()) return sizeof(unsigned char) + sizeof(unsigned short);
245     else if (nSize <= std::numeric_limits<unsigned int>::max())  return sizeof(unsigned char) + sizeof(unsigned int);
246     else                         return sizeof(unsigned char) + sizeof(uint64_t);
247 }
248 
249 template<typename Stream>
WriteCompactSize(Stream & os,uint64_t nSize)250 void WriteCompactSize(Stream& os, uint64_t nSize)
251 {
252     if (nSize < 253)
253     {
254         ser_writedata8(os, nSize);
255     }
256     else if (nSize <= std::numeric_limits<unsigned short>::max())
257     {
258         ser_writedata8(os, 253);
259         ser_writedata16(os, nSize);
260     }
261     else if (nSize <= std::numeric_limits<unsigned int>::max())
262     {
263         ser_writedata8(os, 254);
264         ser_writedata32(os, nSize);
265     }
266     else
267     {
268         ser_writedata8(os, 255);
269         ser_writedata64(os, nSize);
270     }
271     return;
272 }
273 
274 template<typename Stream>
ReadCompactSize(Stream & is)275 uint64_t ReadCompactSize(Stream& is)
276 {
277     uint8_t chSize = ser_readdata8(is);
278     uint64_t nSizeRet = 0;
279     if (chSize < 253)
280     {
281         nSizeRet = chSize;
282     }
283     else if (chSize == 253)
284     {
285         nSizeRet = ser_readdata16(is);
286         if (nSizeRet < 253)
287             throw std::ios_base::failure("non-canonical ReadCompactSize()");
288     }
289     else if (chSize == 254)
290     {
291         nSizeRet = ser_readdata32(is);
292         if (nSizeRet < 0x10000u)
293             throw std::ios_base::failure("non-canonical ReadCompactSize()");
294     }
295     else
296     {
297         nSizeRet = ser_readdata64(is);
298         if (nSizeRet < 0x100000000ULL)
299             throw std::ios_base::failure("non-canonical ReadCompactSize()");
300     }
301     if (nSizeRet > (uint64_t)MAX_SIZE)
302         throw std::ios_base::failure("ReadCompactSize(): size too large");
303     return nSizeRet;
304 }
305 
306 /**
307  * Variable-length integers: bytes are a MSB base-128 encoding of the number.
308  * The high bit in each byte signifies whether another digit follows. To make
309  * sure the encoding is one-to-one, one is subtracted from all but the last digit.
310  * Thus, the byte sequence a[] with length len, where all but the last byte
311  * has bit 128 set, encodes the number:
312  *
313  *  (a[len-1] & 0x7F) + sum(i=1..len-1, 128^i*((a[len-i-1] & 0x7F)+1))
314  *
315  * Properties:
316  * * Very small (0-127: 1 byte, 128-16511: 2 bytes, 16512-2113663: 3 bytes)
317  * * Every integer has exactly one encoding
318  * * Encoding does not depend on size of original integer type
319  * * No redundancy: every (infinite) byte sequence corresponds to a list
320  *   of encoded integers.
321  *
322  * 0:         [0x00]  256:        [0x81 0x00]
323  * 1:         [0x01]  16383:      [0xFE 0x7F]
324  * 127:       [0x7F]  16384:      [0xFF 0x00]
325  * 128:  [0x80 0x00]  16511:      [0xFF 0x7F]
326  * 255:  [0x80 0x7F]  65535: [0x82 0xFE 0x7F]
327  * 2^32:           [0x8E 0xFE 0xFE 0xFF 0x00]
328  */
329 
330 template<typename I>
GetSizeOfVarInt(I n)331 inline unsigned int GetSizeOfVarInt(I n)
332 {
333     int nRet = 0;
334     while(true) {
335         nRet++;
336         if (n <= 0x7F)
337             break;
338         n = (n >> 7) - 1;
339     }
340     return nRet;
341 }
342 
343 template<typename Stream, typename I>
WriteVarInt(Stream & os,I n)344 void WriteVarInt(Stream& os, I n)
345 {
346     unsigned char tmp[(sizeof(n)*8+6)/7];
347     int len=0;
348     while(true) {
349         tmp[len] = (n & 0x7F) | (len ? 0x80 : 0x00);
350         if (n <= 0x7F)
351             break;
352         n = (n >> 7) - 1;
353         len++;
354     }
355     do {
356         ser_writedata8(os, tmp[len]);
357     } while(len--);
358 }
359 
360 template<typename Stream, typename I>
ReadVarInt(Stream & is)361 I ReadVarInt(Stream& is)
362 {
363     I n = 0;
364     while(true) {
365         unsigned char chData = ser_readdata8(is);
366         n = (n << 7) | (chData & 0x7F);
367         if (chData & 0x80)
368             n++;
369         else
370             return n;
371     }
372 }
373 
374 #define FLATDATA(obj) REF(CFlatData((char*)&(obj), (char*)&(obj) + sizeof(obj)))
375 #define VARINT(obj) REF(WrapVarInt(REF(obj)))
376 #define COMPACTSIZE(obj) REF(CCompactSize(REF(obj)))
377 #define LIMITED_STRING(obj,n) REF(LimitedString< n >(REF(obj)))
378 
379 /**
380  * Wrapper for serializing arrays and POD.
381  */
382 class CFlatData
383 {
384 protected:
385     char* pbegin;
386     char* pend;
387 public:
CFlatData(void * pbeginIn,void * pendIn)388     CFlatData(void* pbeginIn, void* pendIn) : pbegin((char*)pbeginIn), pend((char*)pendIn) { }
389     template <class T, class TAl>
CFlatData(std::vector<T,TAl> & v)390     explicit CFlatData(std::vector<T,TAl> &v)
391     {
392         pbegin = (char*)begin_ptr(v);
393         pend = (char*)end_ptr(v);
394     }
395     template <unsigned int N, typename T, typename S, typename D>
CFlatData(prevector<N,T,S,D> & v)396     explicit CFlatData(prevector<N, T, S, D> &v)
397     {
398         pbegin = (char*)begin_ptr(v);
399         pend = (char*)end_ptr(v);
400     }
begin()401     char* begin() { return pbegin; }
begin()402     const char* begin() const { return pbegin; }
end()403     char* end() { return pend; }
end()404     const char* end() const { return pend; }
405 
406     unsigned int GetSerializeSize(int, int=0) const
407     {
408         return pend - pbegin;
409     }
410 
411     template<typename Stream>
412     void Serialize(Stream& s, int, int=0) const
413     {
414         s.write(pbegin, pend - pbegin);
415     }
416 
417     template<typename Stream>
418     void Unserialize(Stream& s, int, int=0)
419     {
420         s.read(pbegin, pend - pbegin);
421     }
422 };
423 
424 template<typename I>
425 class CVarInt
426 {
427 protected:
428     I &n;
429 public:
CVarInt(I & nIn)430     CVarInt(I& nIn) : n(nIn) { }
431 
GetSerializeSize(int,int)432     unsigned int GetSerializeSize(int, int) const {
433         return GetSizeOfVarInt<I>(n);
434     }
435 
436     template<typename Stream>
Serialize(Stream & s,int,int)437     void Serialize(Stream &s, int, int) const {
438         WriteVarInt<Stream,I>(s, n);
439     }
440 
441     template<typename Stream>
Unserialize(Stream & s,int,int)442     void Unserialize(Stream& s, int, int) {
443         n = ReadVarInt<Stream,I>(s);
444     }
445 };
446 
447 class CCompactSize
448 {
449 protected:
450     uint64_t &n;
451 public:
CCompactSize(uint64_t & nIn)452     CCompactSize(uint64_t& nIn) : n(nIn) { }
453 
GetSerializeSize(int,int)454     unsigned int GetSerializeSize(int, int) const {
455         return GetSizeOfCompactSize(n);
456     }
457 
458     template<typename Stream>
Serialize(Stream & s,int,int)459     void Serialize(Stream &s, int, int) const {
460         WriteCompactSize<Stream>(s, n);
461     }
462 
463     template<typename Stream>
Unserialize(Stream & s,int,int)464     void Unserialize(Stream& s, int, int) {
465         n = ReadCompactSize<Stream>(s);
466     }
467 };
468 
469 template<size_t Limit>
470 class LimitedString
471 {
472 protected:
473     std::string& string;
474 public:
LimitedString(std::string & string)475     LimitedString(std::string& string) : string(string) {}
476 
477     template<typename Stream>
478     void Unserialize(Stream& s, int, int=0)
479     {
480         size_t size = ReadCompactSize(s);
481         if (size > Limit) {
482             throw std::ios_base::failure("String length limit exceeded");
483         }
484         string.resize(size);
485         if (size != 0)
486             s.read((char*)&string[0], size);
487     }
488 
489     template<typename Stream>
490     void Serialize(Stream& s, int, int=0) const
491     {
492         WriteCompactSize(s, string.size());
493         if (!string.empty())
494             s.write((char*)&string[0], string.size());
495     }
496 
497     unsigned int GetSerializeSize(int, int=0) const
498     {
499         return GetSizeOfCompactSize(string.size()) + string.size();
500     }
501 };
502 
503 template<typename I>
WrapVarInt(I & n)504 CVarInt<I> WrapVarInt(I& n) { return CVarInt<I>(n); }
505 
506 /**
507  * Forward declarations
508  */
509 
510 /**
511  *  string
512  */
513 template<typename C> unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int=0);
514 template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str, int, int=0);
515 template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str, int, int=0);
516 
517 /**
518  * prevector
519  * prevectors of unsigned char are a special case and are intended to be serialized as a single opaque blob.
520  */
521 template<unsigned int N, typename T> unsigned int GetSerializeSize_impl(const prevector<N, T>& v, int nType, int nVersion, const unsigned char&);
522 template<unsigned int N, typename T, typename V> unsigned int GetSerializeSize_impl(const prevector<N, T>& v, int nType, int nVersion, const V&);
523 template<unsigned int N, typename T> inline unsigned int GetSerializeSize(const prevector<N, T>& v, int nType, int nVersion);
524 template<typename Stream, unsigned int N, typename T> void Serialize_impl(Stream& os, const prevector<N, T>& v, int nType, int nVersion, const unsigned char&);
525 template<typename Stream, unsigned int N, typename T, typename V> void Serialize_impl(Stream& os, const prevector<N, T>& v, int nType, int nVersion, const V&);
526 template<typename Stream, unsigned int N, typename T> inline void Serialize(Stream& os, const prevector<N, T>& v, int nType, int nVersion);
527 template<typename Stream, unsigned int N, typename T> void Unserialize_impl(Stream& is, prevector<N, T>& v, int nType, int nVersion, const unsigned char&);
528 template<typename Stream, unsigned int N, typename T, typename V> void Unserialize_impl(Stream& is, prevector<N, T>& v, int nType, int nVersion, const V&);
529 template<typename Stream, unsigned int N, typename T> inline void Unserialize(Stream& is, prevector<N, T>& v, int nType, int nVersion);
530 
531 /**
532  * vector
533  * vectors of unsigned char are a special case and are intended to be serialized as a single opaque blob.
534  */
535 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const unsigned char&);
536 template<typename T, typename A, typename V> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const V&);
537 template<typename T, typename A> inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion);
538 template<typename Stream, typename T, typename A> void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const unsigned char&);
539 template<typename Stream, typename T, typename A, typename V> void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const V&);
540 template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion);
541 template<typename Stream, typename T, typename A> void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const unsigned char&);
542 template<typename Stream, typename T, typename A, typename V> void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const V&);
543 template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion);
544 
545 /**
546  * pair
547  */
548 template<typename K, typename T> unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion);
549 template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion);
550 template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion);
551 
552 /**
553  * map
554  */
555 template<typename K, typename T, typename Pred, typename A> unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion);
556 template<typename Stream, typename K, typename T, typename Pred, typename A> void Serialize(Stream& os, const std::map<K, T, Pred, A>& m, int nType, int nVersion);
557 template<typename Stream, typename K, typename T, typename Pred, typename A> void Unserialize(Stream& is, std::map<K, T, Pred, A>& m, int nType, int nVersion);
558 
559 /**
560  * set
561  */
562 template<typename K, typename Pred, typename A> unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion);
563 template<typename Stream, typename K, typename Pred, typename A> void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion);
564 template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion);
565 
566 
567 
568 
569 
570 /**
571  * If none of the specialized versions above matched, default to calling member function.
572  * "int nType" is changed to "long nType" to keep from getting an ambiguous overload error.
573  * The compiler will only cast int to long if none of the other templates matched.
574  * Thanks to Boost serialization for this idea.
575  */
576 template<typename T>
GetSerializeSize(const T & a,long nType,int nVersion)577 inline unsigned int GetSerializeSize(const T& a, long nType, int nVersion)
578 {
579     return a.GetSerializeSize((int)nType, nVersion);
580 }
581 
582 template<typename Stream, typename T>
Serialize(Stream & os,const T & a,long nType,int nVersion)583 inline void Serialize(Stream& os, const T& a, long nType, int nVersion)
584 {
585     a.Serialize(os, (int)nType, nVersion);
586 }
587 
588 template<typename Stream, typename T>
Unserialize(Stream & is,T & a,long nType,int nVersion)589 inline void Unserialize(Stream& is, T& a, long nType, int nVersion)
590 {
591     a.Unserialize(is, (int)nType, nVersion);
592 }
593 
594 
595 
596 
597 
598 /**
599  * string
600  */
601 template<typename C>
GetSerializeSize(const std::basic_string<C> & str,int,int)602 unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int)
603 {
604     return GetSizeOfCompactSize(str.size()) + str.size() * sizeof(str[0]);
605 }
606 
607 template<typename Stream, typename C>
Serialize(Stream & os,const std::basic_string<C> & str,int,int)608 void Serialize(Stream& os, const std::basic_string<C>& str, int, int)
609 {
610     WriteCompactSize(os, str.size());
611     if (!str.empty())
612         os.write((char*)&str[0], str.size() * sizeof(str[0]));
613 }
614 
615 template<typename Stream, typename C>
Unserialize(Stream & is,std::basic_string<C> & str,int,int)616 void Unserialize(Stream& is, std::basic_string<C>& str, int, int)
617 {
618     unsigned int nSize = ReadCompactSize(is);
619     str.resize(nSize);
620     if (nSize != 0)
621         is.read((char*)&str[0], nSize * sizeof(str[0]));
622 }
623 
624 
625 
626 /**
627  * prevector
628  */
629 template<unsigned int N, typename T>
GetSerializeSize_impl(const prevector<N,T> & v,int nType,int nVersion,const unsigned char &)630 unsigned int GetSerializeSize_impl(const prevector<N, T>& v, int nType, int nVersion, const unsigned char&)
631 {
632     return (GetSizeOfCompactSize(v.size()) + v.size() * sizeof(T));
633 }
634 
635 template<unsigned int N, typename T, typename V>
GetSerializeSize_impl(const prevector<N,T> & v,int nType,int nVersion,const V &)636 unsigned int GetSerializeSize_impl(const prevector<N, T>& v, int nType, int nVersion, const V&)
637 {
638     unsigned int nSize = GetSizeOfCompactSize(v.size());
639     for (typename prevector<N, T>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
640         nSize += GetSerializeSize((*vi), nType, nVersion);
641     return nSize;
642 }
643 
644 template<unsigned int N, typename T>
GetSerializeSize(const prevector<N,T> & v,int nType,int nVersion)645 inline unsigned int GetSerializeSize(const prevector<N, T>& v, int nType, int nVersion)
646 {
647     return GetSerializeSize_impl(v, nType, nVersion, T());
648 }
649 
650 
651 template<typename Stream, unsigned int N, typename T>
Serialize_impl(Stream & os,const prevector<N,T> & v,int nType,int nVersion,const unsigned char &)652 void Serialize_impl(Stream& os, const prevector<N, T>& v, int nType, int nVersion, const unsigned char&)
653 {
654     WriteCompactSize(os, v.size());
655     if (!v.empty())
656         os.write((char*)&v[0], v.size() * sizeof(T));
657 }
658 
659 template<typename Stream, unsigned int N, typename T, typename V>
Serialize_impl(Stream & os,const prevector<N,T> & v,int nType,int nVersion,const V &)660 void Serialize_impl(Stream& os, const prevector<N, T>& v, int nType, int nVersion, const V&)
661 {
662     WriteCompactSize(os, v.size());
663     for (typename prevector<N, T>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
664         ::Serialize(os, (*vi), nType, nVersion);
665 }
666 
667 template<typename Stream, unsigned int N, typename T>
Serialize(Stream & os,const prevector<N,T> & v,int nType,int nVersion)668 inline void Serialize(Stream& os, const prevector<N, T>& v, int nType, int nVersion)
669 {
670     Serialize_impl(os, v, nType, nVersion, T());
671 }
672 
673 
674 template<typename Stream, unsigned int N, typename T>
Unserialize_impl(Stream & is,prevector<N,T> & v,int nType,int nVersion,const unsigned char &)675 void Unserialize_impl(Stream& is, prevector<N, T>& v, int nType, int nVersion, const unsigned char&)
676 {
677     // Limit size per read so bogus size value won't cause out of memory
678     v.clear();
679     unsigned int nSize = ReadCompactSize(is);
680     unsigned int i = 0;
681     while (i < nSize)
682     {
683         unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
684         v.resize(i + blk);
685         is.read((char*)&v[i], blk * sizeof(T));
686         i += blk;
687     }
688 }
689 
690 template<typename Stream, unsigned int N, typename T, typename V>
Unserialize_impl(Stream & is,prevector<N,T> & v,int nType,int nVersion,const V &)691 void Unserialize_impl(Stream& is, prevector<N, T>& v, int nType, int nVersion, const V&)
692 {
693     v.clear();
694     unsigned int nSize = ReadCompactSize(is);
695     unsigned int i = 0;
696     unsigned int nMid = 0;
697     while (nMid < nSize)
698     {
699         nMid += 5000000 / sizeof(T);
700         if (nMid > nSize)
701             nMid = nSize;
702         v.resize(nMid);
703         for (; i < nMid; i++)
704             Unserialize(is, v[i], nType, nVersion);
705     }
706 }
707 
708 template<typename Stream, unsigned int N, typename T>
Unserialize(Stream & is,prevector<N,T> & v,int nType,int nVersion)709 inline void Unserialize(Stream& is, prevector<N, T>& v, int nType, int nVersion)
710 {
711     Unserialize_impl(is, v, nType, nVersion, T());
712 }
713 
714 
715 
716 /**
717  * vector
718  */
719 template<typename T, typename A>
GetSerializeSize_impl(const std::vector<T,A> & v,int nType,int nVersion,const unsigned char &)720 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const unsigned char&)
721 {
722     return (GetSizeOfCompactSize(v.size()) + v.size() * sizeof(T));
723 }
724 
725 template<typename T, typename A, typename V>
GetSerializeSize_impl(const std::vector<T,A> & v,int nType,int nVersion,const V &)726 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const V&)
727 {
728     unsigned int nSize = GetSizeOfCompactSize(v.size());
729     for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
730         nSize += GetSerializeSize((*vi), nType, nVersion);
731     return nSize;
732 }
733 
734 template<typename T, typename A>
GetSerializeSize(const std::vector<T,A> & v,int nType,int nVersion)735 inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion)
736 {
737     return GetSerializeSize_impl(v, nType, nVersion, T());
738 }
739 
740 
741 template<typename Stream, typename T, typename A>
Serialize_impl(Stream & os,const std::vector<T,A> & v,int nType,int nVersion,const unsigned char &)742 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const unsigned char&)
743 {
744     WriteCompactSize(os, v.size());
745     if (!v.empty())
746         os.write((char*)&v[0], v.size() * sizeof(T));
747 }
748 
749 template<typename Stream, typename T, typename A, typename V>
Serialize_impl(Stream & os,const std::vector<T,A> & v,int nType,int nVersion,const V &)750 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const V&)
751 {
752     WriteCompactSize(os, v.size());
753     for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
754         ::Serialize(os, (*vi), nType, nVersion);
755 }
756 
757 template<typename Stream, typename T, typename A>
Serialize(Stream & os,const std::vector<T,A> & v,int nType,int nVersion)758 inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion)
759 {
760     Serialize_impl(os, v, nType, nVersion, T());
761 }
762 
763 
764 template<typename Stream, typename T, typename A>
Unserialize_impl(Stream & is,std::vector<T,A> & v,int nType,int nVersion,const unsigned char &)765 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const unsigned char&)
766 {
767     // Limit size per read so bogus size value won't cause out of memory
768     v.clear();
769     unsigned int nSize = ReadCompactSize(is);
770     unsigned int i = 0;
771     while (i < nSize)
772     {
773         unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
774         v.resize(i + blk);
775         is.read((char*)&v[i], blk * sizeof(T));
776         i += blk;
777     }
778 }
779 
780 template<typename Stream, typename T, typename A, typename V>
Unserialize_impl(Stream & is,std::vector<T,A> & v,int nType,int nVersion,const V &)781 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const V&)
782 {
783     v.clear();
784     unsigned int nSize = ReadCompactSize(is);
785     unsigned int i = 0;
786     unsigned int nMid = 0;
787     while (nMid < nSize)
788     {
789         nMid += 5000000 / sizeof(T);
790         if (nMid > nSize)
791             nMid = nSize;
792         v.resize(nMid);
793         for (; i < nMid; i++)
794             Unserialize(is, v[i], nType, nVersion);
795     }
796 }
797 
798 template<typename Stream, typename T, typename A>
Unserialize(Stream & is,std::vector<T,A> & v,int nType,int nVersion)799 inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion)
800 {
801     Unserialize_impl(is, v, nType, nVersion, T());
802 }
803 
804 
805 
806 /**
807  * pair
808  */
809 template<typename K, typename T>
GetSerializeSize(const std::pair<K,T> & item,int nType,int nVersion)810 unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion)
811 {
812     return GetSerializeSize(item.first, nType, nVersion) + GetSerializeSize(item.second, nType, nVersion);
813 }
814 
815 template<typename Stream, typename K, typename T>
Serialize(Stream & os,const std::pair<K,T> & item,int nType,int nVersion)816 void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion)
817 {
818     Serialize(os, item.first, nType, nVersion);
819     Serialize(os, item.second, nType, nVersion);
820 }
821 
822 template<typename Stream, typename K, typename T>
Unserialize(Stream & is,std::pair<K,T> & item,int nType,int nVersion)823 void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion)
824 {
825     Unserialize(is, item.first, nType, nVersion);
826     Unserialize(is, item.second, nType, nVersion);
827 }
828 
829 
830 
831 /**
832  * map
833  */
834 template<typename K, typename T, typename Pred, typename A>
GetSerializeSize(const std::map<K,T,Pred,A> & m,int nType,int nVersion)835 unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion)
836 {
837     unsigned int nSize = GetSizeOfCompactSize(m.size());
838     for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
839         nSize += GetSerializeSize((*mi), nType, nVersion);
840     return nSize;
841 }
842 
843 template<typename Stream, typename K, typename T, typename Pred, typename A>
Serialize(Stream & os,const std::map<K,T,Pred,A> & m,int nType,int nVersion)844 void Serialize(Stream& os, const std::map<K, T, Pred, A>& m, int nType, int nVersion)
845 {
846     WriteCompactSize(os, m.size());
847     for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
848         Serialize(os, (*mi), nType, nVersion);
849 }
850 
851 template<typename Stream, typename K, typename T, typename Pred, typename A>
Unserialize(Stream & is,std::map<K,T,Pred,A> & m,int nType,int nVersion)852 void Unserialize(Stream& is, std::map<K, T, Pred, A>& m, int nType, int nVersion)
853 {
854     m.clear();
855     unsigned int nSize = ReadCompactSize(is);
856     typename std::map<K, T, Pred, A>::iterator mi = m.begin();
857     for (unsigned int i = 0; i < nSize; i++)
858     {
859         std::pair<K, T> item;
860         Unserialize(is, item, nType, nVersion);
861         mi = m.insert(mi, item);
862     }
863 }
864 
865 
866 
867 /**
868  * set
869  */
870 template<typename K, typename Pred, typename A>
GetSerializeSize(const std::set<K,Pred,A> & m,int nType,int nVersion)871 unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion)
872 {
873     unsigned int nSize = GetSizeOfCompactSize(m.size());
874     for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
875         nSize += GetSerializeSize((*it), nType, nVersion);
876     return nSize;
877 }
878 
879 template<typename Stream, typename K, typename Pred, typename A>
Serialize(Stream & os,const std::set<K,Pred,A> & m,int nType,int nVersion)880 void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion)
881 {
882     WriteCompactSize(os, m.size());
883     for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
884         Serialize(os, (*it), nType, nVersion);
885 }
886 
887 template<typename Stream, typename K, typename Pred, typename A>
Unserialize(Stream & is,std::set<K,Pred,A> & m,int nType,int nVersion)888 void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion)
889 {
890     m.clear();
891     unsigned int nSize = ReadCompactSize(is);
892     typename std::set<K, Pred, A>::iterator it = m.begin();
893     for (unsigned int i = 0; i < nSize; i++)
894     {
895         K key;
896         Unserialize(is, key, nType, nVersion);
897         it = m.insert(it, key);
898     }
899 }
900 
901 
902 
903 /**
904  * Support for ADD_SERIALIZE_METHODS and READWRITE macro
905  */
906 struct CSerActionSerialize
907 {
ForReadCSerActionSerialize908     bool ForRead() const { return false; }
909 };
910 struct CSerActionUnserialize
911 {
ForReadCSerActionUnserialize912     bool ForRead() const { return true; }
913 };
914 
915 template<typename Stream, typename T>
SerReadWrite(Stream & s,const T & obj,int nType,int nVersion,CSerActionSerialize ser_action)916 inline void SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionSerialize ser_action)
917 {
918     ::Serialize(s, obj, nType, nVersion);
919 }
920 
921 template<typename Stream, typename T>
SerReadWrite(Stream & s,T & obj,int nType,int nVersion,CSerActionUnserialize ser_action)922 inline void SerReadWrite(Stream& s, T& obj, int nType, int nVersion, CSerActionUnserialize ser_action)
923 {
924     ::Unserialize(s, obj, nType, nVersion);
925 }
926 
927 
928 
929 
930 
931 
932 
933 
934 
935 class CSizeComputer
936 {
937 protected:
938     size_t nSize;
939 
940 public:
941     int nType;
942     int nVersion;
943 
CSizeComputer(int nTypeIn,int nVersionIn)944     CSizeComputer(int nTypeIn, int nVersionIn) : nSize(0), nType(nTypeIn), nVersion(nVersionIn) {}
945 
write(const char * psz,size_t nSize)946     CSizeComputer& write(const char *psz, size_t nSize)
947     {
948         this->nSize += nSize;
949         return *this;
950     }
951 
952     template<typename T>
953     CSizeComputer& operator<<(const T& obj)
954     {
955         ::Serialize(*this, obj, nType, nVersion);
956         return (*this);
957     }
958 
size()959     size_t size() const {
960         return nSize;
961     }
962 };
963 
964 #endif // BITCOIN_SERIALIZE_H
965