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