Remove legacy code, bump version number
[novacoin.git] / src / util.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_UTIL_H
6 #define BITCOIN_UTIL_H
7
8 #include "uint256.h"
9
10 #ifndef WIN32
11 #include <sys/types.h>
12 #include <sys/time.h>
13 #include <sys/resource.h>
14 #else
15 typedef int pid_t; /* define for Windows compatibility */
16 #endif
17 #include <map>
18 #include <vector>
19 #include <string>
20
21 #include <boost/thread.hpp>
22 #include <boost/filesystem.hpp>
23 #include <boost/filesystem/path.hpp>
24 #include <boost/date_time/gregorian/gregorian_types.hpp>
25 #include <boost/date_time/posix_time/posix_time_types.hpp>
26
27 #include <openssl/sha.h>
28 #include <openssl/ripemd.h>
29
30 #include "netbase.h" // for AddTimeData
31
32 typedef long long  int64;
33 typedef unsigned long long  uint64;
34
35 static const int64 COIN = 1000000;
36 static const int64 CENT = 10000;
37
38 #define BEGIN(a)            ((char*)&(a))
39 #define END(a)              ((char*)&((&(a))[1]))
40 #define UBEGIN(a)           ((unsigned char*)&(a))
41 #define UEND(a)             ((unsigned char*)&((&(a))[1]))
42 #define ARRAYLEN(array)     (sizeof(array)/sizeof((array)[0]))
43
44 #define UVOIDBEGIN(a)        ((void*)&(a))
45 #define CVOIDBEGIN(a)        ((const void*)&(a))
46 #define UINTBEGIN(a)        ((uint32_t*)&(a))
47 #define CUINTBEGIN(a)        ((const uint32_t*)&(a))
48
49 #ifndef PRI64d
50 #if defined(_MSC_VER) || defined(__MSVCRT__)
51 #define PRI64d  "I64d"
52 #define PRI64u  "I64u"
53 #define PRI64x  "I64x"
54 #else
55 #define PRI64d  "lld"
56 #define PRI64u  "llu"
57 #define PRI64x  "llx"
58 #endif
59 #endif
60
61 #ifndef THROW_WITH_STACKTRACE
62 #define THROW_WITH_STACKTRACE(exception)  \
63 {                                         \
64     LogStackTrace();                      \
65     throw (exception);                    \
66 }
67 void LogStackTrace();
68 #endif
69
70
71 /* Format characters for (s)size_t and ptrdiff_t */
72 #if defined(_MSC_VER) || defined(__MSVCRT__)
73   /* (s)size_t and ptrdiff_t have the same size specifier in MSVC:
74      http://msdn.microsoft.com/en-us/library/tcxf1dw6%28v=vs.100%29.aspx
75    */
76   #define PRIszx    "Ix"
77   #define PRIszu    "Iu"
78   #define PRIszd    "Id"
79   #define PRIpdx    "Ix"
80   #define PRIpdu    "Iu"
81   #define PRIpdd    "Id"
82 #else /* C99 standard */
83   #define PRIszx    "zx"
84   #define PRIszu    "zu"
85   #define PRIszd    "zd"
86   #define PRIpdx    "tx"
87   #define PRIpdu    "tu"
88   #define PRIpdd    "td"
89 #endif
90
91 // This is needed because the foreach macro can't get over the comma in pair<t1, t2>
92 #define PAIRTYPE(t1, t2)    std::pair<t1, t2>
93
94 // Align by increasing pointer, must have extra space at end of buffer
95 template <size_t nBytes, typename T>
96 T* alignup(T* p)
97 {
98     union
99     {
100         T* ptr;
101         size_t n;
102     } u;
103     u.ptr = p;
104     u.n = (u.n + (nBytes-1)) & ~(nBytes-1);
105     return u.ptr;
106 }
107
108 #ifdef WIN32
109 #define MSG_NOSIGNAL        0
110 #define MSG_DONTWAIT        0
111
112 #ifndef S_IRUSR
113 #define S_IRUSR             0400
114 #define S_IWUSR             0200
115 #endif
116 #else
117 #define MAX_PATH            1024
118 inline void Sleep(int64 n)
119 {
120     /*Boost has a year 2038 problem— if the request sleep time is past epoch+2^31 seconds the sleep returns instantly.
121       So we clamp our sleeps here to 10 years and hope that boost is fixed by 2028.*/
122     boost::thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(n>315576000000LL?315576000000LL:n));
123 }
124 #endif
125
126 /* This GNU C extension enables the compiler to check the format string against the parameters provided.
127  * X is the number of the "format string" parameter, and Y is the number of the first variadic parameter.
128  * Parameters count from 1.
129  */
130 #ifdef __GNUC__
131 #define ATTR_WARN_PRINTF(X,Y) __attribute__((format(printf,X,Y)))
132 #else
133 #define ATTR_WARN_PRINTF(X,Y)
134 #endif
135
136
137
138
139
140
141
142
143 extern std::map<std::string, std::string> mapArgs;
144 extern std::map<std::string, std::vector<std::string> > mapMultiArgs;
145 extern bool fDebug;
146 extern bool fDebugNet;
147 extern bool fPrintToConsole;
148 extern bool fPrintToDebugger;
149 extern bool fRequestShutdown;
150 extern bool fShutdown;
151 extern bool fDaemon;
152 extern bool fServer;
153 extern bool fCommandLine;
154 extern std::string strMiscWarning;
155 extern bool fTestNet;
156 extern bool fNoListen;
157 extern bool fLogTimestamps;
158 extern bool fReopenDebugLog;
159
160 void RandAddSeed();
161 void RandAddSeedPerfmon();
162 int ATTR_WARN_PRINTF(1,2) OutputDebugStringF(const char* pszFormat, ...);
163
164 /*
165   Rationale for the real_strprintf / strprintf construction:
166     It is not allowed to use va_start with a pass-by-reference argument.
167     (C++ standard, 18.7, paragraph 3). Use a dummy argument to work around this, and use a
168     macro to keep similar semantics.
169 */
170
171 /** Overload strprintf for char*, so that GCC format type warnings can be given */
172 std::string ATTR_WARN_PRINTF(1,3) real_strprintf(const char *format, int dummy, ...);
173 /** Overload strprintf for std::string, to be able to use it with _ (translation).
174  * This will not support GCC format type warnings (-Wformat) so be careful.
175  */
176 std::string real_strprintf(const std::string &format, int dummy, ...);
177 #define strprintf(format, ...) real_strprintf(format, 0, __VA_ARGS__)
178 std::string vstrprintf(const char *format, va_list ap);
179
180 bool ATTR_WARN_PRINTF(1,2) error(const char *format, ...);
181
182 /* Redefine printf so that it directs output to debug.log
183  *
184  * Do this *after* defining the other printf-like functions, because otherwise the
185  * __attribute__((format(printf,X,Y))) gets expanded to __attribute__((format(OutputDebugStringF,X,Y)))
186  * which confuses gcc.
187  */
188 #define printf OutputDebugStringF
189
190 void LogException(std::exception* pex, const char* pszThread);
191 void PrintException(std::exception* pex, const char* pszThread);
192 void PrintExceptionContinue(std::exception* pex, const char* pszThread);
193 void ParseString(const std::string& str, char c, std::vector<std::string>& v);
194 std::string FormatMoney(int64 n, bool fPlus=false);
195 bool ParseMoney(const std::string& str, int64& nRet);
196 bool ParseMoney(const char* pszIn, int64& nRet);
197 std::vector<unsigned char> ParseHex(const char* psz);
198 std::vector<unsigned char> ParseHex(const std::string& str);
199 bool IsHex(const std::string& str);
200 std::vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid = NULL);
201 std::string DecodeBase64(const std::string& str);
202 std::string EncodeBase64(const unsigned char* pch, size_t len);
203 std::string EncodeBase64(const std::string& str);
204 std::vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid = NULL);
205 std::string DecodeBase32(const std::string& str);
206 std::string EncodeBase32(const unsigned char* pch, size_t len);
207 std::string EncodeBase32(const std::string& str);
208 void ParseParameters(int argc, const char*const argv[]);
209 bool WildcardMatch(const char* psz, const char* mask);
210 bool WildcardMatch(const std::string& str, const std::string& mask);
211 void FileCommit(FILE *fileout);
212 int GetFilesize(FILE* file);
213 bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest);
214 boost::filesystem::path GetDefaultDataDir();
215 const boost::filesystem::path &GetDataDir(bool fNetSpecific = true);
216 boost::filesystem::path GetConfigFile();
217 boost::filesystem::path GetPidFile();
218 #ifndef WIN32
219 void CreatePidFile(const boost::filesystem::path &path, pid_t pid);
220 #endif
221 void ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet, std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet);
222 #ifdef WIN32
223 boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate = true);
224 #endif
225 void ShrinkDebugFile();
226 int GetRandInt(int nMax);
227 uint64 GetRand(uint64 nMax);
228 uint256 GetRandHash();
229 int64 GetTime();
230 void SetMockTime(int64 nMockTimeIn);
231 int64 GetAdjustedTime();
232 int64 GetTimeOffset();
233 std::string FormatFullVersion();
234 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments);
235 void AddTimeData(const CNetAddr& ip, int64 nTime);
236 void runCommand(std::string strCommand);
237
238
239
240
241
242
243
244
245
246 inline std::string i64tostr(int64 n)
247 {
248     return strprintf("%"PRI64d, n);
249 }
250
251 inline std::string itostr(int n)
252 {
253     return strprintf("%d", n);
254 }
255
256 inline int64 atoi64(const char* psz)
257 {
258 #ifdef _MSC_VER
259     return _atoi64(psz);
260 #else
261     return strtoll(psz, NULL, 10);
262 #endif
263 }
264
265 inline int64 atoi64(const std::string& str)
266 {
267 #ifdef _MSC_VER
268     return _atoi64(str.c_str());
269 #else
270     return strtoll(str.c_str(), NULL, 10);
271 #endif
272 }
273
274 inline int atoi(const std::string& str)
275 {
276     return atoi(str.c_str());
277 }
278
279 inline int roundint(double d)
280 {
281     return (int)(d > 0 ? d + 0.5 : d - 0.5);
282 }
283
284 inline int64 roundint64(double d)
285 {
286     return (int64)(d > 0 ? d + 0.5 : d - 0.5);
287 }
288
289 inline int64 abs64(int64 n)
290 {
291     return (n >= 0 ? n : -n);
292 }
293
294 inline std::string leftTrim(std::string src, char chr)
295 {
296     std::string::size_type pos = src.find_first_not_of(chr, 0);
297
298     if(pos > 0)
299         src.erase(0, pos);
300
301     return src;
302 }
303
304 template<typename T>
305 std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
306 {
307     std::string rv;
308     static const char hexmap[16] = { '0', '1', '2', '3', '4', '5', '6', '7',
309                                      '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
310     rv.reserve((itend-itbegin)*3);
311     for(T it = itbegin; it < itend; ++it)
312     {
313         unsigned char val = (unsigned char)(*it);
314         if(fSpaces && it != itbegin)
315             rv.push_back(' ');
316         rv.push_back(hexmap[val>>4]);
317         rv.push_back(hexmap[val&15]);
318     }
319
320     return rv;
321 }
322
323 inline std::string HexStr(const std::vector<unsigned char>& vch, bool fSpaces=false)
324 {
325     return HexStr(vch.begin(), vch.end(), fSpaces);
326 }
327
328 template<typename T>
329 void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)
330 {
331     printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());
332 }
333
334 inline void PrintHex(const std::vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true)
335 {
336     printf(pszFormat, HexStr(vch, fSpaces).c_str());
337 }
338
339 inline int64 GetPerformanceCounter()
340 {
341     int64 nCounter = 0;
342 #ifdef WIN32
343     QueryPerformanceCounter((LARGE_INTEGER*)&nCounter);
344 #else
345     timeval t;
346     gettimeofday(&t, NULL);
347     nCounter = (int64) t.tv_sec * 1000000 + t.tv_usec;
348 #endif
349     return nCounter;
350 }
351
352 inline int64 GetTimeMillis()
353 {
354     return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) -
355             boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
356 }
357
358 inline std::string DateTimeStrFormat(const char* pszFormat, int64 nTime)
359 {
360     time_t n = nTime;
361     struct tm* ptmTime = gmtime(&n);
362     char pszTime[200];
363     strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime);
364     return pszTime;
365 }
366
367 static const std::string strTimestampFormat = "%Y-%m-%d %H:%M:%S UTC";
368 inline std::string DateTimeStrFormat(int64 nTime)
369 {
370     return DateTimeStrFormat(strTimestampFormat.c_str(), nTime);
371 }
372
373
374 template<typename T>
375 void skipspaces(T& it)
376 {
377     while (isspace(*it))
378         ++it;
379 }
380
381 inline bool IsSwitchChar(char c)
382 {
383 #ifdef WIN32
384     return c == '-' || c == '/';
385 #else
386     return c == '-';
387 #endif
388 }
389
390 /**
391  * Return string argument or default value
392  *
393  * @param strArg Argument to get (e.g. "-foo")
394  * @param default (e.g. "1")
395  * @return command-line argument or default value
396  */
397 std::string GetArg(const std::string& strArg, const std::string& strDefault);
398
399 /**
400  * Return integer argument or default value
401  *
402  * @param strArg Argument to get (e.g. "-foo")
403  * @param default (e.g. 1)
404  * @return command-line argument (0 if invalid number) or default value
405  */
406 int64 GetArg(const std::string& strArg, int64 nDefault);
407
408 /**
409  * Return boolean argument or default value
410  *
411  * @param strArg Argument to get (e.g. "-foo")
412  * @param default (true or false)
413  * @return command-line argument or default value
414  */
415 bool GetBoolArg(const std::string& strArg, bool fDefault=false);
416
417 /**
418  * Set an argument if it doesn't already have a value
419  *
420  * @param strArg Argument to set (e.g. "-foo")
421  * @param strValue Value (e.g. "1")
422  * @return true if argument gets set, false if it already had a value
423  */
424 bool SoftSetArg(const std::string& strArg, const std::string& strValue);
425
426 /**
427  * Set a boolean argument if it doesn't already have a value
428  *
429  * @param strArg Argument to set (e.g. "-foo")
430  * @param fValue Value (e.g. false)
431  * @return true if argument gets set, false if it already had a value
432  */
433 bool SoftSetBoolArg(const std::string& strArg, bool fValue);
434
435
436
437
438
439
440
441
442
443 template<typename T1>
444 inline uint256 Hash(const T1 pbegin, const T1 pend)
445 {
446     static unsigned char pblank[1];
447     uint256 hash1;
448     SHA256((pbegin == pend ? pblank : (unsigned char*)&pbegin[0]), (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);
449     uint256 hash2;
450     SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
451     return hash2;
452 }
453
454 class CHashWriter
455 {
456 private:
457     SHA256_CTX ctx;
458
459 public:
460     int nType;
461     int nVersion;
462
463     void Init() {
464         SHA256_Init(&ctx);
465     }
466
467     CHashWriter(int nTypeIn, int nVersionIn) : nType(nTypeIn), nVersion(nVersionIn) {
468         Init();
469     }
470
471     CHashWriter& write(const char *pch, size_t size) {
472         SHA256_Update(&ctx, pch, size);
473         return (*this);
474     }
475
476     // invalidates the object
477     uint256 GetHash() {
478         uint256 hash1;
479         SHA256_Final((unsigned char*)&hash1, &ctx);
480         uint256 hash2;
481         SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
482         return hash2;
483     }
484
485     template<typename T>
486     CHashWriter& operator<<(const T& obj) {
487         // Serialize to this stream
488         ::Serialize(*this, obj, nType, nVersion);
489         return (*this);
490     }
491 };
492
493
494 template<typename T1, typename T2>
495 inline uint256 Hash(const T1 p1begin, const T1 p1end,
496                     const T2 p2begin, const T2 p2end)
497 {
498     static unsigned char pblank[1];
499     uint256 hash1;
500     SHA256_CTX ctx;
501     SHA256_Init(&ctx);
502     SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
503     SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
504     SHA256_Final((unsigned char*)&hash1, &ctx);
505     uint256 hash2;
506     SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
507     return hash2;
508 }
509
510 template<typename T1, typename T2, typename T3>
511 inline uint256 Hash(const T1 p1begin, const T1 p1end,
512                     const T2 p2begin, const T2 p2end,
513                     const T3 p3begin, const T3 p3end)
514 {
515     static unsigned char pblank[1];
516     uint256 hash1;
517     SHA256_CTX ctx;
518     SHA256_Init(&ctx);
519     SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
520     SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
521     SHA256_Update(&ctx, (p3begin == p3end ? pblank : (unsigned char*)&p3begin[0]), (p3end - p3begin) * sizeof(p3begin[0]));
522     SHA256_Final((unsigned char*)&hash1, &ctx);
523     uint256 hash2;
524     SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
525     return hash2;
526 }
527
528 template<typename T>
529 uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=PROTOCOL_VERSION)
530 {
531     CHashWriter ss(nType, nVersion);
532     ss << obj;
533     return ss.GetHash();
534 }
535
536 inline uint160 Hash160(const std::vector<unsigned char>& vch)
537 {
538     uint256 hash1;
539     SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);
540     uint160 hash2;
541     RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
542     return hash2;
543 }
544
545 /**
546  * Timing-attack-resistant comparison.
547  * Takes time proportional to length
548  * of first argument.
549  */
550 template <typename T>
551 bool TimingResistantEqual(const T& a, const T& b)
552 {
553     if (b.size() == 0) return a.size() == 0;
554     size_t accumulator = a.size() ^ b.size();
555     for (size_t i = 0; i < a.size(); i++)
556         accumulator |= a[i] ^ b[i%b.size()];
557     return accumulator == 0;
558 }
559
560 /** Median filter over a stream of values.
561  * Returns the median of the last N numbers
562  */
563 template <typename T> class CMedianFilter
564 {
565 private:
566     std::vector<T> vValues;
567     std::vector<T> vSorted;
568     unsigned int nSize;
569 public:
570     CMedianFilter(unsigned int size, T initial_value):
571         nSize(size)
572     {
573         vValues.reserve(size);
574         vValues.push_back(initial_value);
575         vSorted = vValues;
576     }
577
578     void input(T value)
579     {
580         if(vValues.size() == nSize)
581         {
582             vValues.erase(vValues.begin());
583         }
584         vValues.push_back(value);
585
586         vSorted.resize(vValues.size());
587         std::copy(vValues.begin(), vValues.end(), vSorted.begin());
588         std::sort(vSorted.begin(), vSorted.end());
589     }
590
591     T median() const
592     {
593         int size = vSorted.size();
594         assert(size>0);
595         if(size & 1) // Odd number of elements
596         {
597             return vSorted[size/2];
598         }
599         else // Even number of elements
600         {
601             return (vSorted[size/2-1] + vSorted[size/2]) / 2;
602         }
603     }
604
605     int size() const
606     {
607         return vValues.size();
608     }
609
610     std::vector<T> sorted () const
611     {
612         return vSorted;
613     }
614 };
615
616 bool NewThread(void(*pfn)(void*), void* parg);
617
618 #ifdef WIN32
619 inline void SetThreadPriority(int nPriority)
620 {
621     SetThreadPriority(GetCurrentThread(), nPriority);
622 }
623 #else
624
625 #define THREAD_PRIORITY_LOWEST          PRIO_MAX
626 #define THREAD_PRIORITY_BELOW_NORMAL    2
627 #define THREAD_PRIORITY_NORMAL          0
628 #define THREAD_PRIORITY_ABOVE_NORMAL    0
629
630 inline void SetThreadPriority(int nPriority)
631 {
632     // It's unclear if it's even possible to change thread priorities on Linux,
633     // but we really and truly need it for the generation threads.
634 #ifdef PRIO_THREAD
635     setpriority(PRIO_THREAD, 0, nPriority);
636 #else
637     setpriority(PRIO_PROCESS, 0, nPriority);
638 #endif
639 }
640
641 inline void ExitThread(size_t nExitCode)
642 {
643     pthread_exit((void*)nExitCode);
644 }
645 #endif
646
647 void RenameThread(const char* name);
648
649 inline uint32_t ByteReverse(uint32_t value)
650 {
651     value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8);
652     return (value<<16) | (value>>16);
653 }
654
655 #endif
656