Merge remote branch 'refs/remotes/svn/trunk' into svn
[bitcoinplatinum.git] / util.h
blob31ba4f5224b8a6f30765125267dc0410ae04f9e9
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.
6 #if defined(_MSC_VER) || defined(__BORLANDC__)
7 typedef __int64 int64;
8 typedef unsigned __int64 uint64;
9 #else
10 typedef long long int64;
11 typedef unsigned long long uint64;
12 #endif
13 #if defined(_MSC_VER) && _MSC_VER < 1300
14 #define for if (false) ; else for
15 #endif
16 #ifndef _MSC_VER
17 #define __forceinline inline
18 #endif
20 #define foreach BOOST_FOREACH
21 #define loop for (;;)
22 #define BEGIN(a) ((char*)&(a))
23 #define END(a) ((char*)&((&(a))[1]))
24 #define UBEGIN(a) ((unsigned char*)&(a))
25 #define UEND(a) ((unsigned char*)&((&(a))[1]))
26 #define ARRAYLEN(array) (sizeof(array)/sizeof((array)[0]))
27 #define printf OutputDebugStringF
29 #ifdef snprintf
30 #undef snprintf
31 #endif
32 #define snprintf my_snprintf
34 #ifndef PRI64d
35 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MSVCRT__)
36 #define PRI64d "I64d"
37 #define PRI64u "I64u"
38 #define PRI64x "I64x"
39 #else
40 #define PRI64d "lld"
41 #define PRI64u "llu"
42 #define PRI64x "llx"
43 #endif
44 #endif
46 // This is needed because the foreach macro can't get over the comma in pair<t1, t2>
47 #define PAIRTYPE(t1, t2) pair<t1, t2>
49 // Used to bypass the rule against non-const reference to temporary
50 // where it makes sense with wrappers such as CFlatData or CTxDB
51 template<typename T>
52 inline T& REF(const T& val)
54 return (T&)val;
57 // Align by increasing pointer, must have extra space at end of buffer
58 template <size_t nBytes, typename T>
59 T* alignup(T* p)
61 union
63 T* ptr;
64 size_t n;
65 } u;
66 u.ptr = p;
67 u.n = (u.n + (nBytes-1)) & ~(nBytes-1);
68 return u.ptr;
71 #ifdef __WXMSW__
72 #define MSG_NOSIGNAL 0
73 #define MSG_DONTWAIT 0
74 #ifndef UINT64_MAX
75 #define UINT64_MAX _UI64_MAX
76 #define INT64_MAX _I64_MAX
77 #define INT64_MIN _I64_MIN
78 #endif
79 #ifndef S_IRUSR
80 #define S_IRUSR 0400
81 #define S_IWUSR 0200
82 #endif
83 #define unlink _unlink
84 typedef int socklen_t;
85 #else
86 #define WSAGetLastError() errno
87 #define WSAEWOULDBLOCK EWOULDBLOCK
88 #define WSAEMSGSIZE EMSGSIZE
89 #define WSAEINTR EINTR
90 #define WSAEINPROGRESS EINPROGRESS
91 #define WSAEADDRINUSE EADDRINUSE
92 #define WSAENOTSOCK EBADF
93 #define INVALID_SOCKET (SOCKET)(~0)
94 #define SOCKET_ERROR -1
95 typedef u_int SOCKET;
96 #define _vsnprintf(a,b,c,d) vsnprintf(a,b,c,d)
97 #define strlwr(psz) to_lower(psz)
98 #define _strlwr(psz) to_lower(psz)
99 #define MAX_PATH 1024
100 #define Beep(n1,n2) (0)
101 inline void Sleep(int64 n)
103 boost::thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(n));
105 #endif
107 inline int myclosesocket(SOCKET& hSocket)
109 if (hSocket == INVALID_SOCKET)
110 return WSAENOTSOCK;
111 #ifdef __WXMSW__
112 int ret = closesocket(hSocket);
113 #else
114 int ret = close(hSocket);
115 #endif
116 hSocket = INVALID_SOCKET;
117 return ret;
119 #define closesocket(s) myclosesocket(s)
121 #ifndef GUI
122 inline const char* _(const char* psz)
124 return psz;
126 #endif
137 extern map<string, string> mapArgs;
138 extern map<string, vector<string> > mapMultiArgs;
139 extern bool fDebug;
140 extern bool fPrintToConsole;
141 extern bool fPrintToDebugger;
142 extern char pszSetDataDir[MAX_PATH];
143 extern bool fRequestShutdown;
144 extern bool fShutdown;
145 extern bool fDaemon;
146 extern bool fCommandLine;
147 extern string strMiscWarning;
148 extern bool fTestNet;
150 void RandAddSeed();
151 void RandAddSeedPerfmon();
152 int OutputDebugStringF(const char* pszFormat, ...);
153 int my_snprintf(char* buffer, size_t limit, const char* format, ...);
154 string strprintf(const char* format, ...);
155 bool error(const char* format, ...);
156 void LogException(std::exception* pex, const char* pszThread);
157 void PrintException(std::exception* pex, const char* pszThread);
158 void PrintExceptionContinue(std::exception* pex, const char* pszThread);
159 void ParseString(const string& str, char c, vector<string>& v);
160 string FormatMoney(int64 n, bool fPlus=false);
161 bool ParseMoney(const string& str, int64& nRet);
162 bool ParseMoney(const char* pszIn, int64& nRet);
163 vector<unsigned char> ParseHex(const char* psz);
164 vector<unsigned char> ParseHex(const string& str);
165 void ParseParameters(int argc, char* argv[]);
166 const char* wxGetTranslation(const char* psz);
167 bool WildcardMatch(const char* psz, const char* mask);
168 bool WildcardMatch(const string& str, const string& mask);
169 int GetFilesize(FILE* file);
170 void GetDataDir(char* pszDirRet);
171 string GetConfigFile();
172 void ReadConfigFile(map<string, string>& mapSettingsRet, map<string, vector<string> >& mapMultiSettingsRet);
173 #ifdef __WXMSW__
174 string MyGetSpecialFolderPath(int nFolder, bool fCreate);
175 #endif
176 string GetDefaultDataDir();
177 string GetDataDir();
178 void ShrinkDebugFile();
179 int GetRandInt(int nMax);
180 uint64 GetRand(uint64 nMax);
181 int64 GetTime();
182 int64 GetAdjustedTime();
183 void AddTimeData(unsigned int ip, int64 nTime);
197 // Wrapper to automatically initialize critical sections
198 class CCriticalSection
200 #ifdef __WXMSW__
201 protected:
202 CRITICAL_SECTION cs;
203 public:
204 explicit CCriticalSection() { InitializeCriticalSection(&cs); }
205 ~CCriticalSection() { DeleteCriticalSection(&cs); }
206 void Enter() { EnterCriticalSection(&cs); }
207 void Leave() { LeaveCriticalSection(&cs); }
208 bool TryEnter() { return TryEnterCriticalSection(&cs); }
209 #else
210 protected:
211 boost::interprocess::interprocess_recursive_mutex mutex;
212 public:
213 explicit CCriticalSection() { }
214 ~CCriticalSection() { }
215 void Enter() { mutex.lock(); }
216 void Leave() { mutex.unlock(); }
217 bool TryEnter() { return mutex.try_lock(); }
218 #endif
219 public:
220 const char* pszFile;
221 int nLine;
224 // Automatically leave critical section when leaving block, needed for exception safety
225 class CCriticalBlock
227 protected:
228 CCriticalSection* pcs;
229 public:
230 CCriticalBlock(CCriticalSection& csIn) { pcs = &csIn; pcs->Enter(); }
231 ~CCriticalBlock() { pcs->Leave(); }
234 // WARNING: This will catch continue and break!
235 // break is caught with an assertion, but there's no way to detect continue.
236 // I'd rather be careful than suffer the other more error prone syntax.
237 // The compiler will optimise away all this loop junk.
238 #define CRITICAL_BLOCK(cs) \
239 for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by CRITICAL_BLOCK!", !fcriticalblockonce)), fcriticalblockonce=false) \
240 for (CCriticalBlock criticalblock(cs); fcriticalblockonce && (cs.pszFile=__FILE__, cs.nLine=__LINE__, true); fcriticalblockonce=false, cs.pszFile=NULL, cs.nLine=0)
242 class CTryCriticalBlock
244 protected:
245 CCriticalSection* pcs;
246 public:
247 CTryCriticalBlock(CCriticalSection& csIn) { pcs = (csIn.TryEnter() ? &csIn : NULL); }
248 ~CTryCriticalBlock() { if (pcs) pcs->Leave(); }
249 bool Entered() { return pcs != NULL; }
252 #define TRY_CRITICAL_BLOCK(cs) \
253 for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by TRY_CRITICAL_BLOCK!", !fcriticalblockonce)), fcriticalblockonce=false) \
254 for (CTryCriticalBlock criticalblock(cs); fcriticalblockonce && (fcriticalblockonce = criticalblock.Entered()) && (cs.pszFile=__FILE__, cs.nLine=__LINE__, true); fcriticalblockonce=false, cs.pszFile=NULL, cs.nLine=0)
265 inline string i64tostr(int64 n)
267 return strprintf("%"PRI64d, n);
270 inline string itostr(int n)
272 return strprintf("%d", n);
275 inline int64 atoi64(const char* psz)
277 #ifdef _MSC_VER
278 return _atoi64(psz);
279 #else
280 return strtoll(psz, NULL, 10);
281 #endif
284 inline int64 atoi64(const string& str)
286 #ifdef _MSC_VER
287 return _atoi64(str.c_str());
288 #else
289 return strtoll(str.c_str(), NULL, 10);
290 #endif
293 inline int atoi(const string& str)
295 return atoi(str.c_str());
298 inline int roundint(double d)
300 return (int)(d > 0 ? d + 0.5 : d - 0.5);
303 inline int64 roundint64(double d)
305 return (int64)(d > 0 ? d + 0.5 : d - 0.5);
308 inline int64 abs64(int64 n)
310 return (n >= 0 ? n : -n);
313 template<typename T>
314 string HexStr(const T itbegin, const T itend, bool fSpaces=false)
316 if (itbegin == itend)
317 return "";
318 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
319 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
320 string str;
321 str.reserve((pend-pbegin) * (fSpaces ? 3 : 2));
322 for (const unsigned char* p = pbegin; p != pend; p++)
323 str += strprintf((fSpaces && p != pend-1 ? "%02x " : "%02x"), *p);
324 return str;
327 inline string HexStr(const vector<unsigned char>& vch, bool fSpaces=false)
329 return HexStr(vch.begin(), vch.end(), fSpaces);
332 template<typename T>
333 string HexNumStr(const T itbegin, const T itend, bool f0x=true)
335 if (itbegin == itend)
336 return "";
337 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
338 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
339 string str = (f0x ? "0x" : "");
340 str.reserve(str.size() + (pend-pbegin) * 2);
341 for (const unsigned char* p = pend-1; p >= pbegin; p--)
342 str += strprintf("%02x", *p);
343 return str;
346 inline string HexNumStr(const vector<unsigned char>& vch, bool f0x=true)
348 return HexNumStr(vch.begin(), vch.end(), f0x);
351 template<typename T>
352 void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)
354 printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());
357 inline void PrintHex(const vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true)
359 printf(pszFormat, HexStr(vch, fSpaces).c_str());
362 inline int64 GetPerformanceCounter()
364 int64 nCounter = 0;
365 #ifdef __WXMSW__
366 QueryPerformanceCounter((LARGE_INTEGER*)&nCounter);
367 #else
368 timeval t;
369 gettimeofday(&t, NULL);
370 nCounter = t.tv_sec * 1000000 + t.tv_usec;
371 #endif
372 return nCounter;
375 inline int64 GetTimeMillis()
377 return (posix_time::ptime(posix_time::microsec_clock::universal_time()) -
378 posix_time::ptime(gregorian::date(1970,1,1))).total_milliseconds();
381 inline string DateTimeStrFormat(const char* pszFormat, int64 nTime)
383 time_t n = nTime;
384 struct tm* ptmTime = gmtime(&n);
385 char pszTime[200];
386 strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime);
387 return pszTime;
390 template<typename T>
391 void skipspaces(T& it)
393 while (isspace(*it))
394 ++it;
397 inline bool IsSwitchChar(char c)
399 #ifdef __WXMSW__
400 return c == '-' || c == '/';
401 #else
402 return c == '-';
403 #endif
406 inline string GetArg(const string& strArg, const string& strDefault)
408 if (mapArgs.count(strArg))
409 return mapArgs[strArg];
410 return strDefault;
413 inline int64 GetArg(const string& strArg, int64 nDefault)
415 if (mapArgs.count(strArg))
416 return atoi64(mapArgs[strArg]);
417 return nDefault;
420 inline string FormatVersion(int nVersion)
422 if (nVersion%100 == 0)
423 return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
424 else
425 return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
437 inline void heapchk()
439 #ifdef __WXMSW__
440 /// for debugging
441 //if (_heapchk() != _HEAPOK)
442 // DebugBreak();
443 #endif
446 // Randomize the stack to help protect against buffer overrun exploits
447 #define IMPLEMENT_RANDOMIZE_STACK(ThreadFn) \
449 static char nLoops; \
450 if (nLoops <= 0) \
451 nLoops = GetRand(20) + 1; \
452 if (nLoops-- > 1) \
454 ThreadFn; \
455 return; \
459 #define CATCH_PRINT_EXCEPTION(pszFn) \
460 catch (std::exception& e) { \
461 PrintException(&e, (pszFn)); \
462 } catch (...) { \
463 PrintException(NULL, (pszFn)); \
475 template<typename T1>
476 inline uint256 Hash(const T1 pbegin, const T1 pend)
478 static unsigned char pblank[1];
479 uint256 hash1;
480 SHA256((pbegin == pend ? pblank : (unsigned char*)&pbegin[0]), (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);
481 uint256 hash2;
482 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
483 return hash2;
486 template<typename T1, typename T2>
487 inline uint256 Hash(const T1 p1begin, const T1 p1end,
488 const T2 p2begin, const T2 p2end)
490 static unsigned char pblank[1];
491 uint256 hash1;
492 SHA256_CTX ctx;
493 SHA256_Init(&ctx);
494 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
495 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
496 SHA256_Final((unsigned char*)&hash1, &ctx);
497 uint256 hash2;
498 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
499 return hash2;
502 template<typename T1, typename T2, typename T3>
503 inline uint256 Hash(const T1 p1begin, const T1 p1end,
504 const T2 p2begin, const T2 p2end,
505 const T3 p3begin, const T3 p3end)
507 static unsigned char pblank[1];
508 uint256 hash1;
509 SHA256_CTX ctx;
510 SHA256_Init(&ctx);
511 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
512 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
513 SHA256_Update(&ctx, (p3begin == p3end ? pblank : (unsigned char*)&p3begin[0]), (p3end - p3begin) * sizeof(p3begin[0]));
514 SHA256_Final((unsigned char*)&hash1, &ctx);
515 uint256 hash2;
516 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
517 return hash2;
520 template<typename T>
521 uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=VERSION)
523 // Most of the time is spent allocating and deallocating CDataStream's
524 // buffer. If this ever needs to be optimized further, make a CStaticStream
525 // class with its buffer on the stack.
526 CDataStream ss(nType, nVersion);
527 ss.reserve(10000);
528 ss << obj;
529 return Hash(ss.begin(), ss.end());
532 inline uint160 Hash160(const vector<unsigned char>& vch)
534 uint256 hash1;
535 SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);
536 uint160 hash2;
537 RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
538 return hash2;
551 // Note: It turns out we might have been able to use boost::thread
552 // by using TerminateThread(boost::thread.native_handle(), 0);
553 #ifdef __WXMSW__
554 typedef HANDLE pthread_t;
556 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
558 DWORD nUnused = 0;
559 HANDLE hthread =
560 CreateThread(
561 NULL, // default security
562 0, // inherit stack size from parent
563 (LPTHREAD_START_ROUTINE)pfn, // function pointer
564 parg, // argument
565 0, // creation option, start immediately
566 &nUnused); // thread identifier
567 if (hthread == NULL)
569 printf("Error: CreateThread() returned %d\n", GetLastError());
570 return (pthread_t)0;
572 if (!fWantHandle)
574 CloseHandle(hthread);
575 return (pthread_t)-1;
577 return hthread;
580 inline void SetThreadPriority(int nPriority)
582 SetThreadPriority(GetCurrentThread(), nPriority);
584 #else
585 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
587 pthread_t hthread = 0;
588 int ret = pthread_create(&hthread, NULL, (void*(*)(void*))pfn, parg);
589 if (ret != 0)
591 printf("Error: pthread_create() returned %d\n", ret);
592 return (pthread_t)0;
594 if (!fWantHandle)
595 return (pthread_t)-1;
596 return hthread;
599 #define THREAD_PRIORITY_LOWEST PRIO_MAX
600 #define THREAD_PRIORITY_BELOW_NORMAL 2
601 #define THREAD_PRIORITY_NORMAL 0
602 #define THREAD_PRIORITY_ABOVE_NORMAL 0
604 inline void SetThreadPriority(int nPriority)
606 // It's unclear if it's even possible to change thread priorities on Linux,
607 // but we really and truly need it for the generation threads.
608 #ifdef PRIO_THREAD
609 setpriority(PRIO_THREAD, 0, nPriority);
610 #else
611 setpriority(PRIO_PROCESS, 0, nPriority);
612 #endif
615 inline bool TerminateThread(pthread_t hthread, unsigned int nExitCode)
617 return (pthread_cancel(hthread) == 0);
620 inline void ExitThread(unsigned int nExitCode)
622 pthread_exit((void*)nExitCode);
624 #endif
630 inline bool AffinityBugWorkaround(void(*pfn)(void*))
632 #ifdef __WXMSW__
633 // Sometimes after a few hours affinity gets stuck on one processor
634 DWORD dwProcessAffinityMask = -1;
635 DWORD dwSystemAffinityMask = -1;
636 GetProcessAffinityMask(GetCurrentProcess(), &dwProcessAffinityMask, &dwSystemAffinityMask);
637 DWORD dwPrev1 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
638 DWORD dwPrev2 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
639 if (dwPrev2 != dwProcessAffinityMask)
641 printf("AffinityBugWorkaround() : SetThreadAffinityMask=%d, ProcessAffinityMask=%d, restarting thread\n", dwPrev2, dwProcessAffinityMask);
642 if (!CreateThread(pfn, NULL))
643 printf("Error: CreateThread() failed\n");
644 return true;
646 #endif
647 return false;