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