update bitcoin core to git ce148944c776ae8e91cc058f44ddce356c7cebc9
[novacoin.git] / src / util.h
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
4 #ifndef BITCOIN_UTIL_H
5 #define BITCOIN_UTIL_H
6
7 #include "uint256.h"
8
9 #ifndef __WXMSW__
10 #include <sys/types.h>
11 #include <sys/time.h>
12 #include <sys/resource.h>
13 #endif
14 #include <map>
15 #include <vector>
16 #include <string>
17
18 #include <boost/foreach.hpp>
19 #include <boost/thread.hpp>
20 #include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>
21 #include <boost/date_time/gregorian/gregorian_types.hpp>
22 #include <boost/date_time/posix_time/posix_time_types.hpp>
23
24 #include <openssl/sha.h>
25 #include <openssl/ripemd.h>
26
27
28 #if defined(_MSC_VER) || defined(__BORLANDC__)
29 typedef __int64  int64;
30 typedef unsigned __int64  uint64;
31 #else
32 typedef long long  int64;
33 typedef unsigned long long  uint64;
34 #endif
35 #if defined(_MSC_VER) && _MSC_VER < 1300
36 #define for  if (false) ; else for
37 #endif
38 #ifndef _MSC_VER
39 #define __forceinline  inline
40 #endif
41
42 #define loop                for (;;)
43 #define BEGIN(a)            ((char*)&(a))
44 #define END(a)              ((char*)&((&(a))[1]))
45 #define UBEGIN(a)           ((unsigned char*)&(a))
46 #define UEND(a)             ((unsigned char*)&((&(a))[1]))
47 #define ARRAYLEN(array)     (sizeof(array)/sizeof((array)[0]))
48 #define printf              OutputDebugStringF
49
50 #ifdef snprintf
51 #undef snprintf
52 #endif
53 #define snprintf my_snprintf
54
55 #ifndef PRI64d
56 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MSVCRT__)
57 #define PRI64d  "I64d"
58 #define PRI64u  "I64u"
59 #define PRI64x  "I64x"
60 #else
61 #define PRI64d  "lld"
62 #define PRI64u  "llu"
63 #define PRI64x  "llx"
64 #endif
65 #endif
66
67 // This is needed because the foreach macro can't get over the comma in pair<t1, t2>
68 #define PAIRTYPE(t1, t2)    std::pair<t1, t2>
69
70 // Used to bypass the rule against non-const reference to temporary
71 // where it makes sense with wrappers such as CFlatData or CTxDB
72 template<typename T>
73 inline T& REF(const T& val)
74 {
75     return (T&)val;
76 }
77
78 // Align by increasing pointer, must have extra space at end of buffer
79 template <size_t nBytes, typename T>
80 T* alignup(T* p)
81 {
82     union
83     {
84         T* ptr;
85         size_t n;
86     } u;
87     u.ptr = p;
88     u.n = (u.n + (nBytes-1)) & ~(nBytes-1);
89     return u.ptr;
90 }
91
92 #ifdef __WXMSW__
93 #define MSG_NOSIGNAL        0
94 #define MSG_DONTWAIT        0
95 #ifndef UINT64_MAX
96 #define UINT64_MAX          _UI64_MAX
97 #define INT64_MAX           _I64_MAX
98 #define INT64_MIN           _I64_MIN
99 #endif
100 #ifndef S_IRUSR
101 #define S_IRUSR             0400
102 #define S_IWUSR             0200
103 #endif
104 #define unlink              _unlink
105 typedef int socklen_t;
106 #else
107 #define WSAGetLastError()   errno
108 #define WSAEINVAL           EINVAL
109 #define WSAEALREADY         EALREADY
110 #define WSAEWOULDBLOCK      EWOULDBLOCK
111 #define WSAEMSGSIZE         EMSGSIZE
112 #define WSAEINTR            EINTR
113 #define WSAEINPROGRESS      EINPROGRESS
114 #define WSAEADDRINUSE       EADDRINUSE
115 #define WSAENOTSOCK         EBADF
116 #define INVALID_SOCKET      (SOCKET)(~0)
117 #define SOCKET_ERROR        -1
118 typedef u_int SOCKET;
119 #define _vsnprintf(a,b,c,d) vsnprintf(a,b,c,d)
120 #define strlwr(psz)         to_lower(psz)
121 #define _strlwr(psz)        to_lower(psz)
122 #define MAX_PATH            1024
123 #define Beep(n1,n2)         (0)
124 inline void Sleep(int64 n)
125 {
126     boost::thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(n));
127 }
128 #endif
129
130 inline int myclosesocket(SOCKET& hSocket)
131 {
132     if (hSocket == INVALID_SOCKET)
133         return WSAENOTSOCK;
134 #ifdef __WXMSW__
135     int ret = closesocket(hSocket);
136 #else
137     int ret = close(hSocket);
138 #endif
139     hSocket = INVALID_SOCKET;
140     return ret;
141 }
142 #define closesocket(s)      myclosesocket(s)
143
144 #ifndef GUI
145 inline const char* _(const char* psz)
146 {
147     return psz;
148 }
149 #endif
150
151
152
153
154
155
156
157
158
159
160 extern std::map<std::string, std::string> mapArgs;
161 extern std::map<std::string, std::vector<std::string> > mapMultiArgs;
162 extern bool fDebug;
163 extern bool fPrintToConsole;
164 extern bool fPrintToDebugger;
165 extern char pszSetDataDir[MAX_PATH];
166 extern bool fRequestShutdown;
167 extern bool fShutdown;
168 extern bool fDaemon;
169 extern bool fServer;
170 extern bool fCommandLine;
171 extern std::string strMiscWarning;
172 extern bool fTestNet;
173 extern bool fNoListen;
174 extern bool fLogTimestamps;
175
176 void RandAddSeed();
177 void RandAddSeedPerfmon();
178 int OutputDebugStringF(const char* pszFormat, ...);
179 int my_snprintf(char* buffer, size_t limit, const char* format, ...);
180 std::string strprintf(const char* format, ...);
181 bool error(const char* format, ...);
182 void LogException(std::exception* pex, const char* pszThread);
183 void PrintException(std::exception* pex, const char* pszThread);
184 void PrintExceptionContinue(std::exception* pex, const char* pszThread);
185 void ParseString(const std::string& str, char c, std::vector<std::string>& v);
186 std::string FormatMoney(int64 n, bool fPlus=false);
187 bool ParseMoney(const std::string& str, int64& nRet);
188 bool ParseMoney(const char* pszIn, int64& nRet);
189 std::vector<unsigned char> ParseHex(const char* psz);
190 std::vector<unsigned char> ParseHex(const std::string& str);
191 void ParseParameters(int argc, char* argv[]);
192 const char* wxGetTranslation(const char* psz);
193 bool WildcardMatch(const char* psz, const char* mask);
194 bool WildcardMatch(const std::string& str, const std::string& mask);
195 int GetFilesize(FILE* file);
196 void GetDataDir(char* pszDirRet);
197 std::string GetConfigFile();
198 std::string GetPidFile();
199 void CreatePidFile(std::string pidFile, pid_t pid);
200 void ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet, std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet);
201 #ifdef __WXMSW__
202 std::string MyGetSpecialFolderPath(int nFolder, bool fCreate);
203 #endif
204 std::string GetDefaultDataDir();
205 std::string GetDataDir();
206 void ShrinkDebugFile();
207 int GetRandInt(int nMax);
208 uint64 GetRand(uint64 nMax);
209 int64 GetTime();
210 int64 GetAdjustedTime();
211 void AddTimeData(unsigned int ip, int64 nTime);
212 std::string FormatFullVersion();
213
214
215
216
217
218
219
220
221
222
223
224
225
226 // Wrapper to automatically initialize critical sections
227 class CCriticalSection
228 {
229 #ifdef __WXMSW__
230 protected:
231     CRITICAL_SECTION cs;
232 public:
233     explicit CCriticalSection() { InitializeCriticalSection(&cs); }
234     ~CCriticalSection() { DeleteCriticalSection(&cs); }
235     void Enter() { EnterCriticalSection(&cs); }
236     void Leave() { LeaveCriticalSection(&cs); }
237     bool TryEnter() { return TryEnterCriticalSection(&cs); }
238 #else
239 protected:
240     boost::interprocess::interprocess_recursive_mutex mutex;
241 public:
242     explicit CCriticalSection() { }
243     ~CCriticalSection() { }
244     void Enter() { mutex.lock(); }
245     void Leave() { mutex.unlock(); }
246     bool TryEnter() { return mutex.try_lock(); }
247 #endif
248 public:
249     const char* pszFile;
250     int nLine;
251 };
252
253 // Automatically leave critical section when leaving block, needed for exception safety
254 class CCriticalBlock
255 {
256 protected:
257     CCriticalSection* pcs;
258 public:
259     CCriticalBlock(CCriticalSection& csIn) { pcs = &csIn; pcs->Enter(); }
260     ~CCriticalBlock() { pcs->Leave(); }
261 };
262
263 // WARNING: This will catch continue and break!
264 // break is caught with an assertion, but there's no way to detect continue.
265 // I'd rather be careful than suffer the other more error prone syntax.
266 // The compiler will optimise away all this loop junk.
267 #define CRITICAL_BLOCK(cs)     \
268     for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by CRITICAL_BLOCK!", !fcriticalblockonce)), fcriticalblockonce=false)  \
269     for (CCriticalBlock criticalblock(cs); fcriticalblockonce && (cs.pszFile=__FILE__, cs.nLine=__LINE__, true); fcriticalblockonce=false, cs.pszFile=NULL, cs.nLine=0)
270
271 class CTryCriticalBlock
272 {
273 protected:
274     CCriticalSection* pcs;
275 public:
276     CTryCriticalBlock(CCriticalSection& csIn) { pcs = (csIn.TryEnter() ? &csIn : NULL); }
277     ~CTryCriticalBlock() { if (pcs) pcs->Leave(); }
278     bool Entered() { return pcs != NULL; }
279 };
280
281 #define TRY_CRITICAL_BLOCK(cs)     \
282     for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by TRY_CRITICAL_BLOCK!", !fcriticalblockonce)), fcriticalblockonce=false)  \
283     for (CTryCriticalBlock criticalblock(cs); fcriticalblockonce && (fcriticalblockonce = criticalblock.Entered()) && (cs.pszFile=__FILE__, cs.nLine=__LINE__, true); fcriticalblockonce=false, cs.pszFile=NULL, cs.nLine=0)
284
285
286
287
288
289
290
291
292
293
294 inline std::string i64tostr(int64 n)
295 {
296     return strprintf("%"PRI64d, n);
297 }
298
299 inline std::string itostr(int n)
300 {
301     return strprintf("%d", n);
302 }
303
304 inline int64 atoi64(const char* psz)
305 {
306 #ifdef _MSC_VER
307     return _atoi64(psz);
308 #else
309     return strtoll(psz, NULL, 10);
310 #endif
311 }
312
313 inline int64 atoi64(const std::string& str)
314 {
315 #ifdef _MSC_VER
316     return _atoi64(str.c_str());
317 #else
318     return strtoll(str.c_str(), NULL, 10);
319 #endif
320 }
321
322 inline int atoi(const std::string& str)
323 {
324     return atoi(str.c_str());
325 }
326
327 inline int roundint(double d)
328 {
329     return (int)(d > 0 ? d + 0.5 : d - 0.5);
330 }
331
332 inline int64 roundint64(double d)
333 {
334     return (int64)(d > 0 ? d + 0.5 : d - 0.5);
335 }
336
337 inline int64 abs64(int64 n)
338 {
339     return (n >= 0 ? n : -n);
340 }
341
342 template<typename T>
343 std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
344 {
345     if (itbegin == itend)
346         return "";
347     const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
348     const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
349     std::string str;
350     str.reserve((pend-pbegin) * (fSpaces ? 3 : 2));
351     for (const unsigned char* p = pbegin; p != pend; p++)
352         str += strprintf((fSpaces && p != pend-1 ? "%02x " : "%02x"), *p);
353     return str;
354 }
355
356 inline std::string HexStr(const std::vector<unsigned char>& vch, bool fSpaces=false)
357 {
358     return HexStr(vch.begin(), vch.end(), fSpaces);
359 }
360
361 template<typename T>
362 std::string HexNumStr(const T itbegin, const T itend, bool f0x=true)
363 {
364     if (itbegin == itend)
365         return "";
366     const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
367     const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
368     std::string str = (f0x ? "0x" : "");
369     str.reserve(str.size() + (pend-pbegin) * 2);
370     for (const unsigned char* p = pend-1; p >= pbegin; p--)
371         str += strprintf("%02x", *p);
372     return str;
373 }
374
375 inline std::string HexNumStr(const std::vector<unsigned char>& vch, bool f0x=true)
376 {
377     return HexNumStr(vch.begin(), vch.end(), f0x);
378 }
379
380 template<typename T>
381 void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)
382 {
383     printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());
384 }
385
386 inline void PrintHex(const std::vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true)
387 {
388     printf(pszFormat, HexStr(vch, fSpaces).c_str());
389 }
390
391 inline int64 GetPerformanceCounter()
392 {
393     int64 nCounter = 0;
394 #ifdef __WXMSW__
395     QueryPerformanceCounter((LARGE_INTEGER*)&nCounter);
396 #else
397     timeval t;
398     gettimeofday(&t, NULL);
399     nCounter = t.tv_sec * 1000000 + t.tv_usec;
400 #endif
401     return nCounter;
402 }
403
404 inline int64 GetTimeMillis()
405 {
406     return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) -
407             boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
408 }
409
410 inline std::string DateTimeStrFormat(const char* pszFormat, int64 nTime)
411 {
412     time_t n = nTime;
413     struct tm* ptmTime = gmtime(&n);
414     char pszTime[200];
415     strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime);
416     return pszTime;
417 }
418
419 template<typename T>
420 void skipspaces(T& it)
421 {
422     while (isspace(*it))
423         ++it;
424 }
425
426 inline bool IsSwitchChar(char c)
427 {
428 #ifdef __WXMSW__
429     return c == '-' || c == '/';
430 #else
431     return c == '-';
432 #endif
433 }
434
435 inline std::string GetArg(const std::string& strArg, const std::string& strDefault)
436 {
437     if (mapArgs.count(strArg))
438         return mapArgs[strArg];
439     return strDefault;
440 }
441
442 inline int64 GetArg(const std::string& strArg, int64 nDefault)
443 {
444     if (mapArgs.count(strArg))
445         return atoi64(mapArgs[strArg]);
446     return nDefault;
447 }
448
449 inline bool GetBoolArg(const std::string& strArg)
450 {
451     if (mapArgs.count(strArg))
452     {
453         if (mapArgs[strArg].empty())
454             return true;
455         return (atoi(mapArgs[strArg]) != 0);
456     }
457     return false;
458 }
459
460
461
462
463
464
465
466
467
468
469 inline void heapchk()
470 {
471 #ifdef __WXMSW__
472     /// for debugging
473     //if (_heapchk() != _HEAPOK)
474     //    DebugBreak();
475 #endif
476 }
477
478 // Randomize the stack to help protect against buffer overrun exploits
479 #define IMPLEMENT_RANDOMIZE_STACK(ThreadFn)     \
480     {                                           \
481         static char nLoops;                     \
482         if (nLoops <= 0)                        \
483             nLoops = GetRand(20) + 1;           \
484         if (nLoops-- > 1)                       \
485         {                                       \
486             ThreadFn;                           \
487             return;                             \
488         }                                       \
489     }
490
491 #define CATCH_PRINT_EXCEPTION(pszFn)     \
492     catch (std::exception& e) {          \
493         PrintException(&e, (pszFn));     \
494     } catch (...) {                      \
495         PrintException(NULL, (pszFn));   \
496     }
497
498
499
500
501
502
503
504
505
506
507 template<typename T1>
508 inline uint256 Hash(const T1 pbegin, const T1 pend)
509 {
510     static unsigned char pblank[1];
511     uint256 hash1;
512     SHA256((pbegin == pend ? pblank : (unsigned char*)&pbegin[0]), (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);
513     uint256 hash2;
514     SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
515     return hash2;
516 }
517
518 template<typename T1, typename T2>
519 inline uint256 Hash(const T1 p1begin, const T1 p1end,
520                     const T2 p2begin, const T2 p2end)
521 {
522     static unsigned char pblank[1];
523     uint256 hash1;
524     SHA256_CTX ctx;
525     SHA256_Init(&ctx);
526     SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
527     SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
528     SHA256_Final((unsigned char*)&hash1, &ctx);
529     uint256 hash2;
530     SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
531     return hash2;
532 }
533
534 template<typename T1, typename T2, typename T3>
535 inline uint256 Hash(const T1 p1begin, const T1 p1end,
536                     const T2 p2begin, const T2 p2end,
537                     const T3 p3begin, const T3 p3end)
538 {
539     static unsigned char pblank[1];
540     uint256 hash1;
541     SHA256_CTX ctx;
542     SHA256_Init(&ctx);
543     SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
544     SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
545     SHA256_Update(&ctx, (p3begin == p3end ? pblank : (unsigned char*)&p3begin[0]), (p3end - p3begin) * sizeof(p3begin[0]));
546     SHA256_Final((unsigned char*)&hash1, &ctx);
547     uint256 hash2;
548     SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
549     return hash2;
550 }
551
552 template<typename T>
553 uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=VERSION)
554 {
555     // Most of the time is spent allocating and deallocating CDataStream's
556     // buffer.  If this ever needs to be optimized further, make a CStaticStream
557     // class with its buffer on the stack.
558     CDataStream ss(nType, nVersion);
559     ss.reserve(10000);
560     ss << obj;
561     return Hash(ss.begin(), ss.end());
562 }
563
564 inline uint160 Hash160(const std::vector<unsigned char>& vch)
565 {
566     uint256 hash1;
567     SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);
568     uint160 hash2;
569     RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
570     return hash2;
571 }
572
573
574
575
576
577
578
579
580
581
582
583 // Note: It turns out we might have been able to use boost::thread
584 // by using TerminateThread(boost::thread.native_handle(), 0);
585 #ifdef __WXMSW__
586 typedef HANDLE pthread_t;
587
588 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
589 {
590     DWORD nUnused = 0;
591     HANDLE hthread =
592         CreateThread(
593             NULL,                        // default security
594             0,                           // inherit stack size from parent
595             (LPTHREAD_START_ROUTINE)pfn, // function pointer
596             parg,                        // argument
597             0,                           // creation option, start immediately
598             &nUnused);                   // thread identifier
599     if (hthread == NULL)
600     {
601         printf("Error: CreateThread() returned %d\n", GetLastError());
602         return (pthread_t)0;
603     }
604     if (!fWantHandle)
605     {
606         CloseHandle(hthread);
607         return (pthread_t)-1;
608     }
609     return hthread;
610 }
611
612 inline void SetThreadPriority(int nPriority)
613 {
614     SetThreadPriority(GetCurrentThread(), nPriority);
615 }
616 #else
617 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
618 {
619     pthread_t hthread = 0;
620     int ret = pthread_create(&hthread, NULL, (void*(*)(void*))pfn, parg);
621     if (ret != 0)
622     {
623         printf("Error: pthread_create() returned %d\n", ret);
624         return (pthread_t)0;
625     }
626     if (!fWantHandle)
627         return (pthread_t)-1;
628     return hthread;
629 }
630
631 #define THREAD_PRIORITY_LOWEST          PRIO_MAX
632 #define THREAD_PRIORITY_BELOW_NORMAL    2
633 #define THREAD_PRIORITY_NORMAL          0
634 #define THREAD_PRIORITY_ABOVE_NORMAL    0
635
636 inline void SetThreadPriority(int nPriority)
637 {
638     // It's unclear if it's even possible to change thread priorities on Linux,
639     // but we really and truly need it for the generation threads.
640 #ifdef PRIO_THREAD
641     setpriority(PRIO_THREAD, 0, nPriority);
642 #else
643     setpriority(PRIO_PROCESS, 0, nPriority);
644 #endif
645 }
646
647 inline bool TerminateThread(pthread_t hthread, unsigned int nExitCode)
648 {
649     return (pthread_cancel(hthread) == 0);
650 }
651
652 inline void ExitThread(unsigned int nExitCode)
653 {
654     pthread_exit((void*)nExitCode);
655 }
656 #endif
657
658
659
660
661
662 inline bool AffinityBugWorkaround(void(*pfn)(void*))
663 {
664 #ifdef __WXMSW__
665     // Sometimes after a few hours affinity gets stuck on one processor
666     DWORD dwProcessAffinityMask = -1;
667     DWORD dwSystemAffinityMask = -1;
668     GetProcessAffinityMask(GetCurrentProcess(), &dwProcessAffinityMask, &dwSystemAffinityMask);
669     DWORD dwPrev1 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
670     DWORD dwPrev2 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
671     if (dwPrev2 != dwProcessAffinityMask)
672     {
673         printf("AffinityBugWorkaround() : SetThreadAffinityMask=%d, ProcessAffinityMask=%d, restarting thread\n", dwPrev2, dwProcessAffinityMask);
674         if (!CreateThread(pfn, NULL))
675             printf("Error: CreateThread() failed\n");
676         return true;
677     }
678 #endif
679     return false;
680 }
681
682 #endif