Compile with DEBUG_LOCKORDER to detect inconsistent lock orderings that can cause...
[novacoin.git] / src / util.h
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file license.txt 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 __WXMSW__
11 #include <sys/types.h>
12 #include <sys/time.h>
13 #include <sys/resource.h>
14 #endif
15 #include <map>
16 #include <vector>
17 #include <string>
18
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)    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 mutex
227 class CCriticalSection
228 {
229 protected:
230     boost::interprocess::interprocess_recursive_mutex mutex;
231 public:
232     explicit CCriticalSection() { }
233     ~CCriticalSection() { }
234     void Enter(const char* pszName, const char* pszFile, int nLine);
235     void Leave();
236     bool TryEnter(const char* pszName, const char* pszFile, int nLine);
237 };
238
239 // Automatically leave critical section when leaving block, needed for exception safety
240 class CCriticalBlock
241 {
242 protected:
243     CCriticalSection* pcs;
244
245 public:
246     CCriticalBlock(CCriticalSection& csIn, const char* pszName, const char* pszFile, int nLine)
247     {
248         pcs = &csIn;
249         pcs->Enter(pszName, pszFile, nLine);
250     }
251     ~CCriticalBlock()
252     {
253         pcs->Leave();
254     }
255 };
256
257 // WARNING: This will catch continue and break!
258 // break is caught with an assertion, but there's no way to detect continue.
259 // I'd rather be careful than suffer the other more error prone syntax.
260 // The compiler will optimise away all this loop junk.
261 #define CRITICAL_BLOCK(cs)     \
262     for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by CRITICAL_BLOCK!" && !fcriticalblockonce)), fcriticalblockonce=false) \
263         for (CCriticalBlock criticalblock(cs, #cs, __FILE__, __LINE__); fcriticalblockonce; fcriticalblockonce=false)
264
265 class CTryCriticalBlock
266 {
267 protected:
268     CCriticalSection* pcs;
269
270 public:
271     CTryCriticalBlock(CCriticalSection& csIn, const char* pszName, const char* pszFile, int nLine)
272     {
273         pcs = (csIn.TryEnter(pszName, pszFile, nLine) ? &csIn : NULL);
274     }
275     ~CTryCriticalBlock()
276     {
277         if (pcs)
278         {
279             pcs->Leave();
280         }
281     }
282     bool Entered() { return pcs != NULL; }
283 };
284
285 #define TRY_CRITICAL_BLOCK(cs)     \
286     for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by TRY_CRITICAL_BLOCK!" && !fcriticalblockonce)), fcriticalblockonce=false) \
287         for (CTryCriticalBlock criticalblock(cs, #cs, __FILE__, __LINE__); fcriticalblockonce && (fcriticalblockonce = criticalblock.Entered()); fcriticalblockonce=false)
288
289
290
291
292
293
294
295
296
297
298 inline std::string i64tostr(int64 n)
299 {
300     return strprintf("%"PRI64d, n);
301 }
302
303 inline std::string itostr(int n)
304 {
305     return strprintf("%d", n);
306 }
307
308 inline int64 atoi64(const char* psz)
309 {
310 #ifdef _MSC_VER
311     return _atoi64(psz);
312 #else
313     return strtoll(psz, NULL, 10);
314 #endif
315 }
316
317 inline int64 atoi64(const std::string& str)
318 {
319 #ifdef _MSC_VER
320     return _atoi64(str.c_str());
321 #else
322     return strtoll(str.c_str(), NULL, 10);
323 #endif
324 }
325
326 inline int atoi(const std::string& str)
327 {
328     return atoi(str.c_str());
329 }
330
331 inline int roundint(double d)
332 {
333     return (int)(d > 0 ? d + 0.5 : d - 0.5);
334 }
335
336 inline int64 roundint64(double d)
337 {
338     return (int64)(d > 0 ? d + 0.5 : d - 0.5);
339 }
340
341 inline int64 abs64(int64 n)
342 {
343     return (n >= 0 ? n : -n);
344 }
345
346 template<typename T>
347 std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
348 {
349     if (itbegin == itend)
350         return "";
351     const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
352     const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
353     std::string str;
354     str.reserve((pend-pbegin) * (fSpaces ? 3 : 2));
355     for (const unsigned char* p = pbegin; p != pend; p++)
356         str += strprintf((fSpaces && p != pend-1 ? "%02x " : "%02x"), *p);
357     return str;
358 }
359
360 inline std::string HexStr(const std::vector<unsigned char>& vch, bool fSpaces=false)
361 {
362     return HexStr(vch.begin(), vch.end(), fSpaces);
363 }
364
365 template<typename T>
366 std::string HexNumStr(const T itbegin, const T itend, bool f0x=true)
367 {
368     if (itbegin == itend)
369         return "";
370     const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
371     const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
372     std::string str = (f0x ? "0x" : "");
373     str.reserve(str.size() + (pend-pbegin) * 2);
374     for (const unsigned char* p = pend-1; p >= pbegin; p--)
375         str += strprintf("%02x", *p);
376     return str;
377 }
378
379 inline std::string HexNumStr(const std::vector<unsigned char>& vch, bool f0x=true)
380 {
381     return HexNumStr(vch.begin(), vch.end(), f0x);
382 }
383
384 template<typename T>
385 void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)
386 {
387     printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());
388 }
389
390 inline void PrintHex(const std::vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true)
391 {
392     printf(pszFormat, HexStr(vch, fSpaces).c_str());
393 }
394
395 inline int64 GetPerformanceCounter()
396 {
397     int64 nCounter = 0;
398 #ifdef __WXMSW__
399     QueryPerformanceCounter((LARGE_INTEGER*)&nCounter);
400 #else
401     timeval t;
402     gettimeofday(&t, NULL);
403     nCounter = t.tv_sec * 1000000 + t.tv_usec;
404 #endif
405     return nCounter;
406 }
407
408 inline int64 GetTimeMillis()
409 {
410     return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) -
411             boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
412 }
413
414 inline std::string DateTimeStrFormat(const char* pszFormat, int64 nTime)
415 {
416     time_t n = nTime;
417     struct tm* ptmTime = gmtime(&n);
418     char pszTime[200];
419     strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime);
420     return pszTime;
421 }
422
423 template<typename T>
424 void skipspaces(T& it)
425 {
426     while (isspace(*it))
427         ++it;
428 }
429
430 inline bool IsSwitchChar(char c)
431 {
432 #ifdef __WXMSW__
433     return c == '-' || c == '/';
434 #else
435     return c == '-';
436 #endif
437 }
438
439 inline std::string GetArg(const std::string& strArg, const std::string& strDefault)
440 {
441     if (mapArgs.count(strArg))
442         return mapArgs[strArg];
443     return strDefault;
444 }
445
446 inline int64 GetArg(const std::string& strArg, int64 nDefault)
447 {
448     if (mapArgs.count(strArg))
449         return atoi64(mapArgs[strArg]);
450     return nDefault;
451 }
452
453 inline bool GetBoolArg(const std::string& strArg)
454 {
455     if (mapArgs.count(strArg))
456     {
457         if (mapArgs[strArg].empty())
458             return true;
459         return (atoi(mapArgs[strArg]) != 0);
460     }
461     return false;
462 }
463
464
465
466
467
468
469
470
471
472
473 inline void heapchk()
474 {
475 #ifdef __WXMSW__
476     /// for debugging
477     //if (_heapchk() != _HEAPOK)
478     //    DebugBreak();
479 #endif
480 }
481
482 // Randomize the stack to help protect against buffer overrun exploits
483 #define IMPLEMENT_RANDOMIZE_STACK(ThreadFn)     \
484     {                                           \
485         static char nLoops;                     \
486         if (nLoops <= 0)                        \
487             nLoops = GetRand(20) + 1;           \
488         if (nLoops-- > 1)                       \
489         {                                       \
490             ThreadFn;                           \
491             return;                             \
492         }                                       \
493     }
494
495 #define CATCH_PRINT_EXCEPTION(pszFn)     \
496     catch (std::exception& e) {          \
497         PrintException(&e, (pszFn));     \
498     } catch (...) {                      \
499         PrintException(NULL, (pszFn));   \
500     }
501
502
503
504
505
506
507
508
509
510
511 template<typename T1>
512 inline uint256 Hash(const T1 pbegin, const T1 pend)
513 {
514     static unsigned char pblank[1];
515     uint256 hash1;
516     SHA256((pbegin == pend ? pblank : (unsigned char*)&pbegin[0]), (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);
517     uint256 hash2;
518     SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
519     return hash2;
520 }
521
522 template<typename T1, typename T2>
523 inline uint256 Hash(const T1 p1begin, const T1 p1end,
524                     const T2 p2begin, const T2 p2end)
525 {
526     static unsigned char pblank[1];
527     uint256 hash1;
528     SHA256_CTX ctx;
529     SHA256_Init(&ctx);
530     SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
531     SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
532     SHA256_Final((unsigned char*)&hash1, &ctx);
533     uint256 hash2;
534     SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
535     return hash2;
536 }
537
538 template<typename T1, typename T2, typename T3>
539 inline uint256 Hash(const T1 p1begin, const T1 p1end,
540                     const T2 p2begin, const T2 p2end,
541                     const T3 p3begin, const T3 p3end)
542 {
543     static unsigned char pblank[1];
544     uint256 hash1;
545     SHA256_CTX ctx;
546     SHA256_Init(&ctx);
547     SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
548     SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
549     SHA256_Update(&ctx, (p3begin == p3end ? pblank : (unsigned char*)&p3begin[0]), (p3end - p3begin) * sizeof(p3begin[0]));
550     SHA256_Final((unsigned char*)&hash1, &ctx);
551     uint256 hash2;
552     SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
553     return hash2;
554 }
555
556 template<typename T>
557 uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=VERSION)
558 {
559     // Most of the time is spent allocating and deallocating CDataStream's
560     // buffer.  If this ever needs to be optimized further, make a CStaticStream
561     // class with its buffer on the stack.
562     CDataStream ss(nType, nVersion);
563     ss.reserve(10000);
564     ss << obj;
565     return Hash(ss.begin(), ss.end());
566 }
567
568 inline uint160 Hash160(const std::vector<unsigned char>& vch)
569 {
570     uint256 hash1;
571     SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);
572     uint160 hash2;
573     RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
574     return hash2;
575 }
576
577
578
579
580
581
582
583
584
585
586
587 // Note: It turns out we might have been able to use boost::thread
588 // by using TerminateThread(boost::thread.native_handle(), 0);
589 #ifdef __WXMSW__
590 typedef HANDLE pthread_t;
591
592 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
593 {
594     DWORD nUnused = 0;
595     HANDLE hthread =
596         CreateThread(
597             NULL,                        // default security
598             0,                           // inherit stack size from parent
599             (LPTHREAD_START_ROUTINE)pfn, // function pointer
600             parg,                        // argument
601             0,                           // creation option, start immediately
602             &nUnused);                   // thread identifier
603     if (hthread == NULL)
604     {
605         printf("Error: CreateThread() returned %d\n", GetLastError());
606         return (pthread_t)0;
607     }
608     if (!fWantHandle)
609     {
610         CloseHandle(hthread);
611         return (pthread_t)-1;
612     }
613     return hthread;
614 }
615
616 inline void SetThreadPriority(int nPriority)
617 {
618     SetThreadPriority(GetCurrentThread(), nPriority);
619 }
620 #else
621 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
622 {
623     pthread_t hthread = 0;
624     int ret = pthread_create(&hthread, NULL, (void*(*)(void*))pfn, parg);
625     if (ret != 0)
626     {
627         printf("Error: pthread_create() returned %d\n", ret);
628         return (pthread_t)0;
629     }
630     if (!fWantHandle)
631     {
632         pthread_detach(hthread);
633         return (pthread_t)-1;
634     }
635     return hthread;
636 }
637
638 #define THREAD_PRIORITY_LOWEST          PRIO_MAX
639 #define THREAD_PRIORITY_BELOW_NORMAL    2
640 #define THREAD_PRIORITY_NORMAL          0
641 #define THREAD_PRIORITY_ABOVE_NORMAL    0
642
643 inline void SetThreadPriority(int nPriority)
644 {
645     // It's unclear if it's even possible to change thread priorities on Linux,
646     // but we really and truly need it for the generation threads.
647 #ifdef PRIO_THREAD
648     setpriority(PRIO_THREAD, 0, nPriority);
649 #else
650     setpriority(PRIO_PROCESS, 0, nPriority);
651 #endif
652 }
653
654 inline bool TerminateThread(pthread_t hthread, unsigned int nExitCode)
655 {
656     return (pthread_cancel(hthread) == 0);
657 }
658
659 inline void ExitThread(size_t nExitCode)
660 {
661     pthread_exit((void*)nExitCode);
662 }
663 #endif
664
665
666
667
668
669 inline bool AffinityBugWorkaround(void(*pfn)(void*))
670 {
671 #ifdef __WXMSW__
672     // Sometimes after a few hours affinity gets stuck on one processor
673     DWORD dwProcessAffinityMask = -1;
674     DWORD dwSystemAffinityMask = -1;
675     GetProcessAffinityMask(GetCurrentProcess(), &dwProcessAffinityMask, &dwSystemAffinityMask);
676     DWORD dwPrev1 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
677     DWORD dwPrev2 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
678     if (dwPrev2 != dwProcessAffinityMask)
679     {
680         printf("AffinityBugWorkaround() : SetThreadAffinityMask=%d, ProcessAffinityMask=%d, restarting thread\n", dwPrev2, dwProcessAffinityMask);
681         if (!CreateThread(pfn, NULL))
682             printf("Error: CreateThread() failed\n");
683         return true;
684     }
685 #endif
686     return false;
687 }
688
689 #endif