Transaction hash caching
[novacoin.git] / src / serialize.h
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 #ifndef BITCOIN_SERIALIZE_H
6 #define BITCOIN_SERIALIZE_H
7
8 #include <string>
9 #include <vector>
10 #include <map>
11 #include <set>
12 #include <cassert>
13 #include <limits>
14 #include <cstring>
15 #include <cstdio>
16
17 #include <boost/type_traits/is_fundamental.hpp>
18 #include <boost/tuple/tuple.hpp>
19 #include <boost/tuple/tuple_comparison.hpp>
20 #include <boost/tuple/tuple_io.hpp>
21
22 #include "allocators.h"
23 #include "version.h"
24
25 typedef long long  int64;
26 typedef unsigned long long  uint64;
27
28 class CScript;
29 class CDataStream;
30 class CAutoFile;
31 static const unsigned int MAX_SIZE = 0x02000000;
32
33 // Used to bypass the rule against non-const reference to temporary
34 // where it makes sense with wrappers such as CFlatData or CTxDB
35 template<typename T>
36 inline T& REF(const T& val)
37 {
38     return const_cast<T&>(val);
39 }
40
41 /////////////////////////////////////////////////////////////////
42 //
43 // Templates for serializing to anything that looks like a stream,
44 // i.e. anything that supports .read(char*, int) and .write(char*, int)
45 //
46
47 enum
48 {
49     // primary actions
50     SER_NETWORK         = (1 << 0),
51     SER_DISK            = (1 << 1),
52     SER_GETHASH         = (1 << 2),
53
54     // modifiers
55     SER_SKIPSIG         = (1 << 16),
56     SER_BLOCKHEADERONLY = (1 << 17),
57 };
58
59 #define IMPLEMENT_SERIALIZE(statements)    \
60     unsigned int GetSerializeSize(int nType, int nVersion) const  \
61     {                                           \
62         CSerActionGetSerializeSize ser_action;  \
63         const bool fGetSize = true;             \
64         const bool fWrite = false;              \
65         const bool fRead = false;               \
66         unsigned int nSerSize = 0;              \
67         ser_streamplaceholder s;                \
68         assert(fGetSize||fWrite||fRead); /* suppress warning */ \
69         s.nType = nType;                        \
70         s.nVersion = nVersion;                  \
71         {statements}                            \
72         return nSerSize;                        \
73     }                                           \
74     template<typename Stream>                   \
75     void Serialize(Stream& s, int nType, int nVersion) const  \
76     {                                           \
77         CSerActionSerialize ser_action;         \
78         const bool fGetSize = false;            \
79         const bool fWrite = true;               \
80         const bool fRead = false;               \
81         unsigned int nSerSize = 0;              \
82         assert(fGetSize||fWrite||fRead); /* suppress warning */ \
83         {statements}                            \
84     }                                           \
85     template<typename Stream>                   \
86     void Unserialize(Stream& s, int nType, int nVersion)  \
87     {                                           \
88         CSerActionUnserialize ser_action;       \
89         const bool fGetSize = false;            \
90         const bool fWrite = false;              \
91         const bool fRead = true;                \
92         unsigned int nSerSize = 0;              \
93         assert(fGetSize||fWrite||fRead); /* suppress warning */ \
94         {statements}                            \
95     }
96
97 #define READWRITE(obj)      (nSerSize += ::SerReadWrite(s, (obj), nType, nVersion, ser_action))
98
99
100
101
102
103
104 //
105 // Basic types
106 //
107 #define WRITEDATA(s, obj)   s.write((char*)&(obj), sizeof(obj))
108 #define READDATA(s, obj)    s.read((char*)&(obj), sizeof(obj))
109
110 inline unsigned int GetSerializeSize(char a,           int, int=0) { return sizeof(a); }
111 inline unsigned int GetSerializeSize(signed char a,    int, int=0) { return sizeof(a); }
112 inline unsigned int GetSerializeSize(unsigned char a,  int, int=0) { return sizeof(a); }
113 inline unsigned int GetSerializeSize(signed short a,   int, int=0) { return sizeof(a); }
114 inline unsigned int GetSerializeSize(unsigned short a, int, int=0) { return sizeof(a); }
115 inline unsigned int GetSerializeSize(signed int a,     int, int=0) { return sizeof(a); }
116 inline unsigned int GetSerializeSize(unsigned int a,   int, int=0) { return sizeof(a); }
117 inline unsigned int GetSerializeSize(signed long a,    int, int=0) { return sizeof(a); }
118 inline unsigned int GetSerializeSize(unsigned long a,  int, int=0) { return sizeof(a); }
119 inline unsigned int GetSerializeSize(int64 a,          int, int=0) { return sizeof(a); }
120 inline unsigned int GetSerializeSize(uint64 a,         int, int=0) { return sizeof(a); }
121 inline unsigned int GetSerializeSize(float a,          int, int=0) { return sizeof(a); }
122 inline unsigned int GetSerializeSize(double a,         int, int=0) { return sizeof(a); }
123
124 template<typename Stream> inline void Serialize(Stream& s, char a,           int, int=0) { WRITEDATA(s, a); }
125 template<typename Stream> inline void Serialize(Stream& s, signed char a,    int, int=0) { WRITEDATA(s, a); }
126 template<typename Stream> inline void Serialize(Stream& s, unsigned char a,  int, int=0) { WRITEDATA(s, a); }
127 template<typename Stream> inline void Serialize(Stream& s, signed short a,   int, int=0) { WRITEDATA(s, a); }
128 template<typename Stream> inline void Serialize(Stream& s, unsigned short a, int, int=0) { WRITEDATA(s, a); }
129 template<typename Stream> inline void Serialize(Stream& s, signed int a,     int, int=0) { WRITEDATA(s, a); }
130 template<typename Stream> inline void Serialize(Stream& s, unsigned int a,   int, int=0) { WRITEDATA(s, a); }
131 template<typename Stream> inline void Serialize(Stream& s, signed long a,    int, int=0) { WRITEDATA(s, a); }
132 template<typename Stream> inline void Serialize(Stream& s, unsigned long a,  int, int=0) { WRITEDATA(s, a); }
133 template<typename Stream> inline void Serialize(Stream& s, int64 a,          int, int=0) { WRITEDATA(s, a); }
134 template<typename Stream> inline void Serialize(Stream& s, uint64 a,         int, int=0) { WRITEDATA(s, a); }
135 template<typename Stream> inline void Serialize(Stream& s, float a,          int, int=0) { WRITEDATA(s, a); }
136 template<typename Stream> inline void Serialize(Stream& s, double a,         int, int=0) { WRITEDATA(s, a); }
137
138 template<typename Stream> inline void Unserialize(Stream& s, char& a,           int, int=0) { READDATA(s, a); }
139 template<typename Stream> inline void Unserialize(Stream& s, signed char& a,    int, int=0) { READDATA(s, a); }
140 template<typename Stream> inline void Unserialize(Stream& s, unsigned char& a,  int, int=0) { READDATA(s, a); }
141 template<typename Stream> inline void Unserialize(Stream& s, signed short& a,   int, int=0) { READDATA(s, a); }
142 template<typename Stream> inline void Unserialize(Stream& s, unsigned short& a, int, int=0) { READDATA(s, a); }
143 template<typename Stream> inline void Unserialize(Stream& s, signed int& a,     int, int=0) { READDATA(s, a); }
144 template<typename Stream> inline void Unserialize(Stream& s, unsigned int& a,   int, int=0) { READDATA(s, a); }
145 template<typename Stream> inline void Unserialize(Stream& s, signed long& a,    int, int=0) { READDATA(s, a); }
146 template<typename Stream> inline void Unserialize(Stream& s, unsigned long& a,  int, int=0) { READDATA(s, a); }
147 template<typename Stream> inline void Unserialize(Stream& s, int64& a,          int, int=0) { READDATA(s, a); }
148 template<typename Stream> inline void Unserialize(Stream& s, uint64& a,         int, int=0) { READDATA(s, a); }
149 template<typename Stream> inline void Unserialize(Stream& s, float& a,          int, int=0) { READDATA(s, a); }
150 template<typename Stream> inline void Unserialize(Stream& s, double& a,         int, int=0) { READDATA(s, a); }
151
152 inline unsigned int GetSerializeSize(bool a, int, int=0)                          { return sizeof(char); }
153 template<typename Stream> inline void Serialize(Stream& s, bool a, int, int=0)    { char f=a; WRITEDATA(s, f); }
154 template<typename Stream> inline void Unserialize(Stream& s, bool& a, int, int=0) { char f; READDATA(s, f); a=f; }
155
156
157 #ifndef THROW_WITH_STACKTRACE
158 #define THROW_WITH_STACKTRACE(exception)  \
159 {                                         \
160     LogStackTrace();                      \
161     throw (exception);                    \
162 }
163 void LogStackTrace();
164 #endif
165
166 //
167 // Compact size
168 //  size <  253        -- 1 byte
169 //  size <= USHRT_MAX  -- 3 bytes  (253 + 2 bytes)
170 //  size <= UINT_MAX   -- 5 bytes  (254 + 4 bytes)
171 //  size >  UINT_MAX   -- 9 bytes  (255 + 8 bytes)
172 //
173 inline unsigned int GetSizeOfCompactSize(uint64 nSize)
174 {
175     if (nSize < 253)             return sizeof(unsigned char);
176     else if (nSize <= std::numeric_limits<unsigned short>::max()) return sizeof(unsigned char) + sizeof(unsigned short);
177     else if (nSize <= std::numeric_limits<unsigned int>::max())  return sizeof(unsigned char) + sizeof(unsigned int);
178     else                         return sizeof(unsigned char) + sizeof(uint64);
179 }
180
181 template<typename Stream>
182 void WriteCompactSize(Stream& os, uint64 nSize)
183 {
184     if (nSize < 253)
185     {
186         unsigned char chSize = nSize;
187         WRITEDATA(os, chSize);
188     }
189     else if (nSize <= std::numeric_limits<unsigned short>::max())
190     {
191         unsigned char chSize = 253;
192         unsigned short xSize = nSize;
193         WRITEDATA(os, chSize);
194         WRITEDATA(os, xSize);
195     }
196     else if (nSize <= std::numeric_limits<unsigned int>::max())
197     {
198         unsigned char chSize = 254;
199         unsigned int xSize = nSize;
200         WRITEDATA(os, chSize);
201         WRITEDATA(os, xSize);
202     }
203     else
204     {
205         unsigned char chSize = 255;
206         uint64 xSize = nSize;
207         WRITEDATA(os, chSize);
208         WRITEDATA(os, xSize);
209     }
210     return;
211 }
212
213 template<typename Stream>
214 uint64 ReadCompactSize(Stream& is)
215 {
216     unsigned char chSize;
217     READDATA(is, chSize);
218     uint64 nSizeRet = 0;
219     if (chSize < 253)
220     {
221         nSizeRet = chSize;
222     }
223     else if (chSize == 253)
224     {
225         unsigned short xSize;
226         READDATA(is, xSize);
227         nSizeRet = xSize;
228     }
229     else if (chSize == 254)
230     {
231         unsigned int xSize;
232         READDATA(is, xSize);
233         nSizeRet = xSize;
234     }
235     else
236     {
237         uint64 xSize;
238         READDATA(is, xSize);
239         nSizeRet = xSize;
240     }
241     if (nSizeRet > (uint64)MAX_SIZE)
242         THROW_WITH_STACKTRACE(std::ios_base::failure("ReadCompactSize() : size too large"));
243     return nSizeRet;
244 }
245
246
247 // Variable-length integers: bytes are a MSB base-128 encoding of the number.
248 // The high bit in each byte signifies whether another digit follows. To make
249 // the encoding is one-to-one, one is subtracted from all but the last digit.
250 // Thus, the byte sequence a[] with length len, where all but the last byte
251 // has bit 128 set, encodes the number:
252 //
253 //   (a[len-1] & 0x7F) + sum(i=1..len-1, 128^i*((a[len-i-1] & 0x7F)+1))
254 //
255 // Properties:
256 // * Very small (0-127: 1 byte, 128-16511: 2 bytes, 16512-2113663: 3 bytes)
257 // * Every integer has exactly one encoding
258 // * Encoding does not depend on size of original integer type
259 // * No redundancy: every (infinite) byte sequence corresponds to a list
260 //   of encoded integers.
261 //
262 // 0:         [0x00]  256:        [0x81 0x00]
263 // 1:         [0x01]  16383:      [0xFE 0x7F]
264 // 127:       [0x7F]  16384:      [0xFF 0x00]
265 // 128:  [0x80 0x00]  16511: [0x80 0xFF 0x7F]
266 // 255:  [0x80 0x7F]  65535: [0x82 0xFD 0x7F]
267 // 2^32:           [0x8E 0xFE 0xFE 0xFF 0x00]
268
269 template<typename I>
270 inline unsigned int GetSizeOfVarInt(I n)
271 {
272     int nRet = 0;
273     while(true) {
274         nRet++;
275         if (n <= 0x7F)
276             break;
277         n = (n >> 7) - 1;
278     }
279     return nRet;
280 }
281
282 template<typename Stream, typename I>
283 void WriteVarInt(Stream& os, I n)
284 {
285     unsigned char tmp[(sizeof(n)*8+6)/7];
286     int len=0;
287     while(true) {
288         tmp[len] = (n & 0x7F) | (len ? 0x80 : 0x00);
289         if (n <= 0x7F)
290             break;
291         n = (n >> 7) - 1;
292         len++;
293     }
294     do {
295         WRITEDATA(os, tmp[len]);
296     } while(len--);
297 }
298
299 template<typename Stream, typename I>
300 I ReadVarInt(Stream& is)
301 {
302     I n = 0;
303     while(true) {
304         unsigned char chData;
305         READDATA(is, chData);
306         n = (n << 7) | (chData & 0x7F);
307         if (chData & 0x80)
308             n++;
309         else
310             return n;
311     }
312 }
313
314
315 #define FLATDATA(obj)   REF(CFlatData((char*)&(obj), (char*)&(obj) + sizeof(obj)))
316 #define VARINT(obj)     REF(WrapVarInt(REF(obj)))
317
318 /** Wrapper for serializing arrays and POD.
319  */
320 class CFlatData
321 {
322 protected:
323     char* pbegin;
324     char* pend;
325 public:
326     CFlatData(void* pbeginIn, void* pendIn) : pbegin((char*)pbeginIn), pend((char*)pendIn) { }
327     char* begin() { return pbegin; }
328     const char* begin() const { return pbegin; }
329     char* end() { return pend; }
330     const char* end() const { return pend; }
331
332     unsigned int GetSerializeSize(int, int=0) const
333     {
334         return pend - pbegin;
335     }
336
337     template<typename Stream>
338     void Serialize(Stream& s, int, int=0) const
339     {
340         s.write(pbegin, pend - pbegin);
341     }
342
343     template<typename Stream>
344     void Unserialize(Stream& s, int, int=0)
345     {
346         s.read(pbegin, pend - pbegin);
347     }
348 };
349
350 template<typename I>
351 class CVarInt
352 {
353 protected:
354     I &n;
355 public:
356     CVarInt(I& nIn) : n(nIn) { }
357
358     unsigned int GetSerializeSize(int, int) const {
359         return GetSizeOfVarInt<I>(n);
360     }
361
362     template<typename Stream>
363     void Serialize(Stream &s, int, int) const {
364         WriteVarInt<Stream,I>(s, n);
365     }
366
367     template<typename Stream>
368     void Unserialize(Stream& s, int, int) {
369         n = ReadVarInt<Stream,I>(s);
370     }
371 };
372
373 template<typename I>
374 CVarInt<I> WrapVarInt(I& n) { return CVarInt<I>(n); }
375
376 //
377 // Forward declarations
378 //
379
380 // string
381 template<typename C> unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int=0);
382 template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str, int, int=0);
383 template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str, int, int=0);
384
385 // vector
386 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);
387 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);
388 template<typename T, typename A> inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion);
389 template<typename Stream, typename T, typename A> void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);
390 template<typename Stream, typename T, typename A> void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);
391 template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion);
392 template<typename Stream, typename T, typename A> void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);
393 template<typename Stream, typename T, typename A> void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);
394 template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion);
395
396 // others derived from vector
397 extern inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion);
398 template<typename Stream> void Serialize(Stream& os, const CScript& v, int nType, int nVersion);
399 template<typename Stream> void Unserialize(Stream& is, CScript& v, int nType, int nVersion);
400
401 // pair
402 template<typename K, typename T> unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion);
403 template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion);
404 template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion);
405
406 // 3 tuple
407 template<typename T0, typename T1, typename T2> unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion);
408 template<typename Stream, typename T0, typename T1, typename T2> void Serialize(Stream& os, const boost::tuple<T0, T1, T2>& item, int nType, int nVersion);
409 template<typename Stream, typename T0, typename T1, typename T2> void Unserialize(Stream& is, boost::tuple<T0, T1, T2>& item, int nType, int nVersion);
410
411 // 4 tuple
412 template<typename T0, typename T1, typename T2, typename T3> unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion);
413 template<typename Stream, typename T0, typename T1, typename T2, typename T3> void Serialize(Stream& os, const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion);
414 template<typename Stream, typename T0, typename T1, typename T2, typename T3> void Unserialize(Stream& is, boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion);
415
416 // map
417 template<typename K, typename T, typename Pred, typename A> unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion);
418 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);
419 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);
420
421 // set
422 template<typename K, typename Pred, typename A> unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion);
423 template<typename Stream, typename K, typename Pred, typename A> void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion);
424 template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion);
425
426
427
428
429
430 //
431 // If none of the specialized versions above matched, default to calling member function.
432 // "int nType" is changed to "long nType" to keep from getting an ambiguous overload error.
433 // The compiler will only cast int to long if none of the other templates matched.
434 // Thanks to Boost serialization for this idea.
435 //
436 template<typename T>
437 inline unsigned int GetSerializeSize(const T& a, long nType, int nVersion)
438 {
439     return a.GetSerializeSize((int)nType, nVersion);
440 }
441
442 template<typename Stream, typename T>
443 inline void Serialize(Stream& os, const T& a, long nType, int nVersion)
444 {
445     a.Serialize(os, (int)nType, nVersion);
446 }
447
448 template<typename Stream, typename T>
449 inline void Unserialize(Stream& is, T& a, long nType, int nVersion)
450 {
451     a.Unserialize(is, (int)nType, nVersion);
452 }
453
454
455
456
457
458 //
459 // string
460 //
461 template<typename C>
462 unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int)
463 {
464     return GetSizeOfCompactSize(str.size()) + str.size() * sizeof(str[0]);
465 }
466
467 template<typename Stream, typename C>
468 void Serialize(Stream& os, const std::basic_string<C>& str, int, int)
469 {
470     WriteCompactSize(os, str.size());
471     if (!str.empty())
472         os.write((char*)&str[0], str.size() * sizeof(str[0]));
473 }
474
475 template<typename Stream, typename C>
476 void Unserialize(Stream& is, std::basic_string<C>& str, int, int)
477 {
478     unsigned int nSize = ReadCompactSize(is);
479     str.resize(nSize);
480     if (nSize != 0)
481         is.read((char*)&str[0], nSize * sizeof(str[0]));
482 }
483
484
485
486 //
487 // vector
488 //
489 template<typename T, typename A>
490 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
491 {
492     return (GetSizeOfCompactSize(v.size()) + v.size() * sizeof(T));
493 }
494
495 template<typename T, typename A>
496 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
497 {
498     unsigned int nSize = GetSizeOfCompactSize(v.size());
499     for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
500         nSize += GetSerializeSize((*vi), nType, nVersion);
501     return nSize;
502 }
503
504 template<typename T, typename A>
505 inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion)
506 {
507     return GetSerializeSize_impl(v, nType, nVersion, boost::is_fundamental<T>());
508 }
509
510
511 template<typename Stream, typename T, typename A>
512 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
513 {
514     WriteCompactSize(os, v.size());
515     if (!v.empty())
516         os.write((char*)&v[0], v.size() * sizeof(T));
517 }
518
519 template<typename Stream, typename T, typename A>
520 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
521 {
522     WriteCompactSize(os, v.size());
523     for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
524         ::Serialize(os, (*vi), nType, nVersion);
525 }
526
527 template<typename Stream, typename T, typename A>
528 inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion)
529 {
530     Serialize_impl(os, v, nType, nVersion, boost::is_fundamental<T>());
531 }
532
533
534 template<typename Stream, typename T, typename A>
535 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
536 {
537     // Limit size per read so bogus size value won't cause out of memory
538     v.clear();
539     unsigned int nSize = ReadCompactSize(is);
540     unsigned int i = 0;
541     while (i < nSize)
542     {
543         unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
544         v.resize(i + blk);
545         is.read((char*)&v[i], blk * sizeof(T));
546         i += blk;
547     }
548 }
549
550 template<typename Stream, typename T, typename A>
551 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
552 {
553     v.clear();
554     unsigned int nSize = ReadCompactSize(is);
555     unsigned int i = 0;
556     unsigned int nMid = 0;
557     while (nMid < nSize)
558     {
559         nMid += 5000000 / sizeof(T);
560         if (nMid > nSize)
561             nMid = nSize;
562         v.resize(nMid);
563         for (; i < nMid; i++)
564             Unserialize(is, v[i], nType, nVersion);
565     }
566 }
567
568 template<typename Stream, typename T, typename A>
569 inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion)
570 {
571     Unserialize_impl(is, v, nType, nVersion, boost::is_fundamental<T>());
572 }
573
574
575
576 //
577 // others derived from vector
578 //
579 inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion)
580 {
581     return GetSerializeSize((const std::vector<unsigned char>&)v, nType, nVersion);
582 }
583
584 template<typename Stream>
585 void Serialize(Stream& os, const CScript& v, int nType, int nVersion)
586 {
587     Serialize(os, (const std::vector<unsigned char>&)v, nType, nVersion);
588 }
589
590 template<typename Stream>
591 void Unserialize(Stream& is, CScript& v, int nType, int nVersion)
592 {
593     Unserialize(is, (std::vector<unsigned char>&)v, nType, nVersion);
594 }
595
596
597
598 //
599 // pair
600 //
601 template<typename K, typename T>
602 unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion)
603 {
604     return GetSerializeSize(item.first, nType, nVersion) + GetSerializeSize(item.second, nType, nVersion);
605 }
606
607 template<typename Stream, typename K, typename T>
608 void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion)
609 {
610     Serialize(os, item.first, nType, nVersion);
611     Serialize(os, item.second, nType, nVersion);
612 }
613
614 template<typename Stream, typename K, typename T>
615 void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion)
616 {
617     Unserialize(is, item.first, nType, nVersion);
618     Unserialize(is, item.second, nType, nVersion);
619 }
620
621
622
623 //
624 // 3 tuple
625 //
626 template<typename T0, typename T1, typename T2>
627 unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
628 {
629     unsigned int nSize = 0;
630     nSize += GetSerializeSize(boost::get<0>(item), nType, nVersion);
631     nSize += GetSerializeSize(boost::get<1>(item), nType, nVersion);
632     nSize += GetSerializeSize(boost::get<2>(item), nType, nVersion);
633     return nSize;
634 }
635
636 template<typename Stream, typename T0, typename T1, typename T2>
637 void Serialize(Stream& os, const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
638 {
639     Serialize(os, boost::get<0>(item), nType, nVersion);
640     Serialize(os, boost::get<1>(item), nType, nVersion);
641     Serialize(os, boost::get<2>(item), nType, nVersion);
642 }
643
644 template<typename Stream, typename T0, typename T1, typename T2>
645 void Unserialize(Stream& is, boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
646 {
647     Unserialize(is, boost::get<0>(item), nType, nVersion);
648     Unserialize(is, boost::get<1>(item), nType, nVersion);
649     Unserialize(is, boost::get<2>(item), nType, nVersion);
650 }
651
652
653
654 //
655 // 4 tuple
656 //
657 template<typename T0, typename T1, typename T2, typename T3>
658 unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
659 {
660     unsigned int nSize = 0;
661     nSize += GetSerializeSize(boost::get<0>(item), nType, nVersion);
662     nSize += GetSerializeSize(boost::get<1>(item), nType, nVersion);
663     nSize += GetSerializeSize(boost::get<2>(item), nType, nVersion);
664     nSize += GetSerializeSize(boost::get<3>(item), nType, nVersion);
665     return nSize;
666 }
667
668 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
669 void Serialize(Stream& os, const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
670 {
671     Serialize(os, boost::get<0>(item), nType, nVersion);
672     Serialize(os, boost::get<1>(item), nType, nVersion);
673     Serialize(os, boost::get<2>(item), nType, nVersion);
674     Serialize(os, boost::get<3>(item), nType, nVersion);
675 }
676
677 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
678 void Unserialize(Stream& is, boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
679 {
680     Unserialize(is, boost::get<0>(item), nType, nVersion);
681     Unserialize(is, boost::get<1>(item), nType, nVersion);
682     Unserialize(is, boost::get<2>(item), nType, nVersion);
683     Unserialize(is, boost::get<3>(item), nType, nVersion);
684 }
685
686
687
688 //
689 // map
690 //
691 template<typename K, typename T, typename Pred, typename A>
692 unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion)
693 {
694     unsigned int nSize = GetSizeOfCompactSize(m.size());
695     for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
696         nSize += GetSerializeSize((*mi), nType, nVersion);
697     return nSize;
698 }
699
700 template<typename Stream, typename K, typename T, typename Pred, typename A>
701 void Serialize(Stream& os, const std::map<K, T, Pred, A>& m, int nType, int nVersion)
702 {
703     WriteCompactSize(os, m.size());
704     for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
705         Serialize(os, (*mi), nType, nVersion);
706 }
707
708 template<typename Stream, typename K, typename T, typename Pred, typename A>
709 void Unserialize(Stream& is, std::map<K, T, Pred, A>& m, int nType, int nVersion)
710 {
711     m.clear();
712     unsigned int nSize = ReadCompactSize(is);
713     typename std::map<K, T, Pred, A>::iterator mi = m.begin();
714     for (unsigned int i = 0; i < nSize; i++)
715     {
716         std::pair<K, T> item;
717         Unserialize(is, item, nType, nVersion);
718         mi = m.insert(mi, item);
719     }
720 }
721
722
723
724 //
725 // set
726 //
727 template<typename K, typename Pred, typename A>
728 unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion)
729 {
730     unsigned int nSize = GetSizeOfCompactSize(m.size());
731     for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
732         nSize += GetSerializeSize((*it), nType, nVersion);
733     return nSize;
734 }
735
736 template<typename Stream, typename K, typename Pred, typename A>
737 void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion)
738 {
739     WriteCompactSize(os, m.size());
740     for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
741         Serialize(os, (*it), nType, nVersion);
742 }
743
744 template<typename Stream, typename K, typename Pred, typename A>
745 void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion)
746 {
747     m.clear();
748     unsigned int nSize = ReadCompactSize(is);
749     typename std::set<K, Pred, A>::iterator it = m.begin();
750     for (unsigned int i = 0; i < nSize; i++)
751     {
752         K key;
753         Unserialize(is, key, nType, nVersion);
754         it = m.insert(it, key);
755     }
756 }
757
758
759
760 //
761 // Support for IMPLEMENT_SERIALIZE and READWRITE macro
762 //
763 class CSerActionGetSerializeSize { };
764 class CSerActionSerialize { };
765 class CSerActionUnserialize { };
766
767 template<typename Stream, typename T>
768 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionGetSerializeSize ser_action)
769 {
770     return ::GetSerializeSize(obj, nType, nVersion);
771 }
772
773 template<typename Stream, typename T>
774 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionSerialize ser_action)
775 {
776     ::Serialize(s, obj, nType, nVersion);
777     return 0;
778 }
779
780 template<typename Stream, typename T>
781 inline unsigned int SerReadWrite(Stream& s, T& obj, int nType, int nVersion, CSerActionUnserialize ser_action)
782 {
783     ::Unserialize(s, obj, nType, nVersion);
784     return 0;
785 }
786
787 struct ser_streamplaceholder
788 {
789     int nType;
790     int nVersion;
791 };
792
793
794
795
796
797
798
799
800
801
802
803
804 /** Double ended buffer combining vector and stream-like interfaces.
805  *
806  * >> and << read and write unformatted data using the above serialization templates.
807  * Fills with data in linear time; some stringstream implementations take N^2 time.
808  */
809 class CDataStream
810 {
811 protected:
812     typedef std::vector<char, zero_after_free_allocator<char> > vector_type;
813     vector_type vch;
814     unsigned int nReadPos;
815     short state;
816     short exceptmask;
817 public:
818     int nType;
819     int nVersion;
820
821     typedef vector_type::allocator_type   allocator_type;
822     typedef vector_type::size_type        size_type;
823     typedef vector_type::difference_type  difference_type;
824     typedef vector_type::reference        reference;
825     typedef vector_type::const_reference  const_reference;
826     typedef vector_type::value_type       value_type;
827     typedef vector_type::iterator         iterator;
828     typedef vector_type::const_iterator   const_iterator;
829     typedef vector_type::reverse_iterator reverse_iterator;
830
831     explicit CDataStream(int nTypeIn, int nVersionIn)
832     {
833         Init(nTypeIn, nVersionIn);
834     }
835
836     CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn, int nVersionIn) : vch(pbegin, pend)
837     {
838         Init(nTypeIn, nVersionIn);
839     }
840
841 #if !defined(_MSC_VER) || _MSC_VER >= 1300
842     CDataStream(const char* pbegin, const char* pend, int nTypeIn, int nVersionIn) : vch(pbegin, pend)
843     {
844         Init(nTypeIn, nVersionIn);
845     }
846 #endif
847
848     CDataStream(const vector_type& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
849     {
850         Init(nTypeIn, nVersionIn);
851     }
852
853     CDataStream(const std::vector<char>& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
854     {
855         Init(nTypeIn, nVersionIn);
856     }
857
858     CDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn, int nVersionIn) : vch((char*)&vchIn.begin()[0], (char*)&vchIn.end()[0])
859     {
860         Init(nTypeIn, nVersionIn);
861     }
862
863     void Init(int nTypeIn, int nVersionIn)
864     {
865         nReadPos = 0;
866         nType = nTypeIn;
867         nVersion = nVersionIn;
868         state = 0;
869         exceptmask = std::ios::badbit | std::ios::failbit;
870     }
871
872     CDataStream& operator+=(const CDataStream& b)
873     {
874         vch.insert(vch.end(), b.begin(), b.end());
875         return *this;
876     }
877
878     friend CDataStream operator+(const CDataStream& a, const CDataStream& b)
879     {
880         CDataStream ret = a;
881         ret += b;
882         return (ret);
883     }
884
885     std::string str() const
886     {
887         return (std::string(begin(), end()));
888     }
889
890
891     //
892     // Vector subset
893     //
894     const_iterator begin() const                     { return vch.begin() + nReadPos; }
895     iterator begin()                                 { return vch.begin() + nReadPos; }
896     const_iterator end() const                       { return vch.end(); }
897     iterator end()                                   { return vch.end(); }
898     size_type size() const                           { return vch.size() - nReadPos; }
899     bool empty() const                               { return vch.size() == nReadPos; }
900     void resize(size_type n, value_type c=0)         { vch.resize(n + nReadPos, c); }
901     void reserve(size_type n)                        { vch.reserve(n + nReadPos); }
902     const_reference operator[](size_type pos) const  { return vch[pos + nReadPos]; }
903     reference operator[](size_type pos)              { return vch[pos + nReadPos]; }
904     void clear()                                     { vch.clear(); nReadPos = 0; }
905     iterator insert(iterator it, const char& x=char()) { return vch.insert(it, x); }
906     void insert(iterator it, size_type n, const char& x) { vch.insert(it, n, x); }
907
908     void insert(iterator it, const_iterator first, const_iterator last)
909     {
910         assert(last - first >= 0);
911         if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
912         {
913             // special case for inserting at the front when there's room
914             nReadPos -= (last - first);
915             memcpy(&vch[nReadPos], &first[0], last - first);
916         }
917         else
918             vch.insert(it, first, last);
919     }
920
921     void insert(iterator it, std::vector<char>::const_iterator first, std::vector<char>::const_iterator last)
922     {
923         assert(last - first >= 0);
924         if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
925         {
926             // special case for inserting at the front when there's room
927             nReadPos -= (last - first);
928             memcpy(&vch[nReadPos], &first[0], last - first);
929         }
930         else
931             vch.insert(it, first, last);
932     }
933
934 #if !defined(_MSC_VER) || _MSC_VER >= 1300
935     void insert(iterator it, const char* first, const char* last)
936     {
937         assert(last - first >= 0);
938         if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
939         {
940             // special case for inserting at the front when there's room
941             nReadPos -= (last - first);
942             memcpy(&vch[nReadPos], &first[0], last - first);
943         }
944         else
945             vch.insert(it, first, last);
946     }
947 #endif
948
949     iterator erase(iterator it)
950     {
951         if (it == vch.begin() + nReadPos)
952         {
953             // special case for erasing from the front
954             if (++nReadPos >= vch.size())
955             {
956                 // whenever we reach the end, we take the opportunity to clear the buffer
957                 nReadPos = 0;
958                 return vch.erase(vch.begin(), vch.end());
959             }
960             return vch.begin() + nReadPos;
961         }
962         else
963             return vch.erase(it);
964     }
965
966     iterator erase(iterator first, iterator last)
967     {
968         if (first == vch.begin() + nReadPos)
969         {
970             // special case for erasing from the front
971             if (last == vch.end())
972             {
973                 nReadPos = 0;
974                 return vch.erase(vch.begin(), vch.end());
975             }
976             else
977             {
978                 nReadPos = (last - vch.begin());
979                 return last;
980             }
981         }
982         else
983             return vch.erase(first, last);
984     }
985
986     inline void Compact()
987     {
988         vch.erase(vch.begin(), vch.begin() + nReadPos);
989         nReadPos = 0;
990     }
991
992     bool Rewind(size_type n)
993     {
994         // Rewind by n characters if the buffer hasn't been compacted yet
995         if (n > nReadPos)
996             return false;
997         nReadPos -= n;
998         return true;
999     }
1000
1001
1002     //
1003     // Stream subset
1004     //
1005     void setstate(short bits, const char* psz)
1006     {
1007         state |= bits;
1008         if (state & exceptmask)
1009             THROW_WITH_STACKTRACE(std::ios_base::failure(psz));
1010     }
1011
1012     bool eof() const             { return size() == 0; }
1013     bool fail() const            { return state & (std::ios::badbit | std::ios::failbit); }
1014     bool good() const            { return !eof() && (state == 0); }
1015     void clear(short n)          { state = n; }  // name conflict with vector clear()
1016     short exceptions()           { return exceptmask; }
1017     short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CDataStream"); return prev; }
1018     CDataStream* rdbuf()         { return this; }
1019     int in_avail()               { return size(); }
1020
1021     void SetType(int n)          { nType = n; }
1022     int GetType()                { return nType; }
1023     void SetVersion(int n)       { nVersion = n; }
1024     int GetVersion()             { return nVersion; }
1025     void ReadVersion()           { *this >> nVersion; }
1026     void WriteVersion()          { *this << nVersion; }
1027
1028     CDataStream& read(char* pch, int nSize)
1029     {
1030         // Read from the beginning of the buffer
1031         assert(nSize >= 0);
1032         unsigned int nReadPosNext = nReadPos + nSize;
1033         if (nReadPosNext >= vch.size())
1034         {
1035             if (nReadPosNext > vch.size())
1036             {
1037                 setstate(std::ios::failbit, "CDataStream::read() : end of data");
1038                 memset(pch, 0, nSize);
1039                 nSize = vch.size() - nReadPos;
1040             }
1041             memcpy(pch, &vch[nReadPos], nSize);
1042             nReadPos = 0;
1043             vch.clear();
1044             return (*this);
1045         }
1046         memcpy(pch, &vch[nReadPos], nSize);
1047         nReadPos = nReadPosNext;
1048         return (*this);
1049     }
1050
1051     CDataStream& ignore(int nSize)
1052     {
1053         // Ignore from the beginning of the buffer
1054         assert(nSize >= 0);
1055         unsigned int nReadPosNext = nReadPos + nSize;
1056         if (nReadPosNext >= vch.size())
1057         {
1058             if (nReadPosNext > vch.size())
1059             {
1060                 setstate(std::ios::failbit, "CDataStream::ignore() : end of data");
1061                 nSize = vch.size() - nReadPos;
1062             }
1063             nReadPos = 0;
1064             vch.clear();
1065             return (*this);
1066         }
1067         nReadPos = nReadPosNext;
1068         return (*this);
1069     }
1070
1071     CDataStream& write(const char* pch, int nSize)
1072     {
1073         // Write to the end of the buffer
1074         assert(nSize >= 0);
1075         vch.insert(vch.end(), pch, pch + nSize);
1076         return (*this);
1077     }
1078
1079     template<typename Stream>
1080     void Serialize(Stream& s, int nType, int nVersion) const
1081     {
1082         // Special case: stream << stream concatenates like stream += stream
1083         if (!vch.empty())
1084             s.write((char*)&vch[0], vch.size() * sizeof(vch[0]));
1085     }
1086
1087     template<typename T>
1088     unsigned int GetSerializeSize(const T& obj)
1089     {
1090         // Tells the size of the object if serialized to this stream
1091         return ::GetSerializeSize(obj, nType, nVersion);
1092     }
1093
1094     template<typename T>
1095     CDataStream& operator<<(const T& obj)
1096     {
1097         // Serialize to this stream
1098         ::Serialize(*this, obj, nType, nVersion);
1099         return (*this);
1100     }
1101
1102     template<typename T>
1103     CDataStream& operator>>(T& obj)
1104     {
1105         // Unserialize from this stream
1106         ::Unserialize(*this, obj, nType, nVersion);
1107         return (*this);
1108     }
1109 };
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120 /** RAII wrapper for FILE*.
1121  *
1122  * Will automatically close the file when it goes out of scope if not null.
1123  * If you're returning the file pointer, return file.release().
1124  * If you need to close the file early, use file.fclose() instead of fclose(file).
1125  */
1126 class CAutoFile
1127 {
1128 protected:
1129     FILE* file;
1130     short state;
1131     short exceptmask;
1132 public:
1133     int nType;
1134     int nVersion;
1135
1136     CAutoFile(FILE* filenew, int nTypeIn, int nVersionIn)
1137     {
1138         file = filenew;
1139         nType = nTypeIn;
1140         nVersion = nVersionIn;
1141         state = 0;
1142         exceptmask = std::ios::badbit | std::ios::failbit;
1143     }
1144
1145     ~CAutoFile()
1146     {
1147         fclose();
1148     }
1149
1150     void fclose()
1151     {
1152         if (file != NULL && file != stdin && file != stdout && file != stderr)
1153             ::fclose(file);
1154         file = NULL;
1155     }
1156
1157     FILE* release()             { FILE* ret = file; file = NULL; return ret; }
1158     operator FILE*()            { return file; }
1159     FILE* operator->()          { return file; }
1160     FILE& operator*()           { return *file; }
1161     FILE** operator&()          { return &file; }
1162     FILE* operator=(FILE* pnew) { return file = pnew; }
1163     bool operator!()            { return (file == NULL); }
1164
1165
1166     //
1167     // Stream subset
1168     //
1169     void setstate(short bits, const char* psz)
1170     {
1171         state |= bits;
1172         if (state & exceptmask)
1173             THROW_WITH_STACKTRACE(std::ios_base::failure(psz));
1174     }
1175
1176     bool fail() const            { return state & (std::ios::badbit | std::ios::failbit); }
1177     bool good() const            { return state == 0; }
1178     void clear(short n = 0)      { state = n; }
1179     short exceptions()           { return exceptmask; }
1180     short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CAutoFile"); return prev; }
1181
1182     void SetType(int n)          { nType = n; }
1183     int GetType()                { return nType; }
1184     void SetVersion(int n)       { nVersion = n; }
1185     int GetVersion()             { return nVersion; }
1186     void ReadVersion()           { *this >> nVersion; }
1187     void WriteVersion()          { *this << nVersion; }
1188
1189     CAutoFile& read(char* pch, size_t nSize)
1190     {
1191         if (!file)
1192             throw std::ios_base::failure("CAutoFile::read : file handle is NULL");
1193         if (fread(pch, 1, nSize, file) != nSize)
1194             setstate(std::ios::failbit, feof(file) ? "CAutoFile::read : end of file" : "CAutoFile::read : fread failed");
1195         return (*this);
1196     }
1197
1198     CAutoFile& write(const char* pch, size_t nSize)
1199     {
1200         if (!file)
1201             throw std::ios_base::failure("CAutoFile::write : file handle is NULL");
1202         if (fwrite(pch, 1, nSize, file) != nSize)
1203             setstate(std::ios::failbit, "CAutoFile::write : write failed");
1204         return (*this);
1205     }
1206
1207     template<typename T>
1208     unsigned int GetSerializeSize(const T& obj)
1209     {
1210         // Tells the size of the object if serialized to this stream
1211         return ::GetSerializeSize(obj, nType, nVersion);
1212     }
1213
1214     template<typename T>
1215     CAutoFile& operator<<(const T& obj)
1216     {
1217         // Serialize to this stream
1218         if (!file)
1219             throw std::ios_base::failure("CAutoFile::operator<< : file handle is NULL");
1220         ::Serialize(*this, obj, nType, nVersion);
1221         return (*this);
1222     }
1223
1224     template<typename T>
1225     CAutoFile& operator>>(T& obj)
1226     {
1227         // Unserialize from this stream
1228         if (!file)
1229             throw std::ios_base::failure("CAutoFile::operator>> : file handle is NULL");
1230         ::Unserialize(*this, obj, nType, nVersion);
1231         return (*this);
1232     }
1233 };
1234
1235 #endif