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