Merge remote branch 'remotes/svn/trunk' into svn
[bitcoinplatinum.git] / util.h
blob09af956d714ca8fd854f8e352a45f9ad95903f85
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;
149 void RandAddSeed();
150 void RandAddSeedPerfmon();
151 int OutputDebugStringF(const char* pszFormat, ...);
152 int my_snprintf(char* buffer, size_t limit, const char* format, ...);
153 string strprintf(const char* format, ...);
154 bool error(const char* format, ...);
155 void LogException(std::exception* pex, const char* pszThread);
156 void PrintException(std::exception* pex, const char* pszThread);
157 void PrintExceptionContinue(std::exception* pex, const char* pszThread);
158 void ParseString(const string& str, char c, vector<string>& v);
159 string FormatMoney(int64 n, bool fPlus=false);
160 bool ParseMoney(const string& str, int64& nRet);
161 bool ParseMoney(const char* pszIn, int64& nRet);
162 vector<unsigned char> ParseHex(const char* psz);
163 vector<unsigned char> ParseHex(const string& str);
164 void ParseParameters(int argc, char* argv[]);
165 const char* wxGetTranslation(const char* psz);
166 bool WildcardMatch(const char* psz, const char* mask);
167 bool WildcardMatch(const string& str, const string& mask);
168 int GetFilesize(FILE* file);
169 void GetDataDir(char* pszDirRet);
170 string GetConfigFile();
171 void ReadConfigFile(map<string, string>& mapSettingsRet, map<string, vector<string> >& mapMultiSettingsRet);
172 #ifdef __WXMSW__
173 string MyGetSpecialFolderPath(int nFolder, bool fCreate);
174 #endif
175 string GetDefaultDataDir();
176 string GetDataDir();
177 void ShrinkDebugFile();
178 int GetRandInt(int nMax);
179 uint64 GetRand(uint64 nMax);
180 int64 GetTime();
181 int64 GetAdjustedTime();
182 void AddTimeData(unsigned int ip, int64 nTime);
196 // Wrapper to automatically initialize critical sections
197 class CCriticalSection
199 #ifdef __WXMSW__
200 protected:
201 CRITICAL_SECTION cs;
202 public:
203 explicit CCriticalSection() { InitializeCriticalSection(&cs); }
204 ~CCriticalSection() { DeleteCriticalSection(&cs); }
205 void Enter() { EnterCriticalSection(&cs); }
206 void Leave() { LeaveCriticalSection(&cs); }
207 bool TryEnter() { return TryEnterCriticalSection(&cs); }
208 #else
209 protected:
210 boost::interprocess::interprocess_recursive_mutex mutex;
211 public:
212 explicit CCriticalSection() { }
213 ~CCriticalSection() { }
214 void Enter() { mutex.lock(); }
215 void Leave() { mutex.unlock(); }
216 bool TryEnter() { return mutex.try_lock(); }
217 #endif
218 public:
219 const char* pszFile;
220 int nLine;
223 // Automatically leave critical section when leaving block, needed for exception safety
224 class CCriticalBlock
226 protected:
227 CCriticalSection* pcs;
228 public:
229 CCriticalBlock(CCriticalSection& csIn) { pcs = &csIn; pcs->Enter(); }
230 ~CCriticalBlock() { pcs->Leave(); }
233 // WARNING: This will catch continue and break!
234 // break is caught with an assertion, but there's no way to detect continue.
235 // I'd rather be careful than suffer the other more error prone syntax.
236 // The compiler will optimise away all this loop junk.
237 #define CRITICAL_BLOCK(cs) \
238 for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by CRITICAL_BLOCK!", !fcriticalblockonce)), fcriticalblockonce=false) \
239 for (CCriticalBlock criticalblock(cs); fcriticalblockonce && (cs.pszFile=__FILE__, cs.nLine=__LINE__, true); fcriticalblockonce=false, cs.pszFile=NULL, cs.nLine=0)
241 class CTryCriticalBlock
243 protected:
244 CCriticalSection* pcs;
245 public:
246 CTryCriticalBlock(CCriticalSection& csIn) { pcs = (csIn.TryEnter() ? &csIn : NULL); }
247 ~CTryCriticalBlock() { if (pcs) pcs->Leave(); }
248 bool Entered() { return pcs != NULL; }
251 #define TRY_CRITICAL_BLOCK(cs) \
252 for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by TRY_CRITICAL_BLOCK!", !fcriticalblockonce)), fcriticalblockonce=false) \
253 for (CTryCriticalBlock criticalblock(cs); fcriticalblockonce && (fcriticalblockonce = criticalblock.Entered()) && (cs.pszFile=__FILE__, cs.nLine=__LINE__, true); fcriticalblockonce=false, cs.pszFile=NULL, cs.nLine=0)
264 inline string i64tostr(int64 n)
266 return strprintf("%"PRI64d, n);
269 inline string itostr(int n)
271 return strprintf("%d", n);
274 inline int64 atoi64(const char* psz)
276 #ifdef _MSC_VER
277 return _atoi64(psz);
278 #else
279 return strtoll(psz, NULL, 10);
280 #endif
283 inline int64 atoi64(const string& str)
285 #ifdef _MSC_VER
286 return _atoi64(str.c_str());
287 #else
288 return strtoll(str.c_str(), NULL, 10);
289 #endif
292 inline int atoi(const string& str)
294 return atoi(str.c_str());
297 inline int roundint(double d)
299 return (int)(d > 0 ? d + 0.5 : d - 0.5);
302 inline int64 roundint64(double d)
304 return (int64)(d > 0 ? d + 0.5 : d - 0.5);
307 inline int64 abs64(int64 n)
309 return (n >= 0 ? n : -n);
312 template<typename T>
313 string HexStr(const T itbegin, const T itend, bool fSpaces=false)
315 if (itbegin == itend)
316 return "";
317 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
318 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
319 string str;
320 str.reserve((pend-pbegin) * (fSpaces ? 3 : 2));
321 for (const unsigned char* p = pbegin; p != pend; p++)
322 str += strprintf((fSpaces && p != pend-1 ? "%02x " : "%02x"), *p);
323 return str;
326 inline string HexStr(const vector<unsigned char>& vch, bool fSpaces=false)
328 return HexStr(vch.begin(), vch.end(), fSpaces);
331 template<typename T>
332 string HexNumStr(const T itbegin, const T itend, bool f0x=true)
334 if (itbegin == itend)
335 return "";
336 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
337 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
338 string str = (f0x ? "0x" : "");
339 str.reserve(str.size() + (pend-pbegin) * 2);
340 for (const unsigned char* p = pend-1; p >= pbegin; p--)
341 str += strprintf("%02x", *p);
342 return str;
345 inline string HexNumStr(const vector<unsigned char>& vch, bool f0x=true)
347 return HexNumStr(vch.begin(), vch.end(), f0x);
350 template<typename T>
351 void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)
353 printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());
356 inline void PrintHex(const vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true)
358 printf(pszFormat, HexStr(vch, fSpaces).c_str());
361 inline int64 GetPerformanceCounter()
363 int64 nCounter = 0;
364 #ifdef __WXMSW__
365 QueryPerformanceCounter((LARGE_INTEGER*)&nCounter);
366 #else
367 timeval t;
368 gettimeofday(&t, NULL);
369 nCounter = t.tv_sec * 1000000 + t.tv_usec;
370 #endif
371 return nCounter;
374 inline int64 GetTimeMillis()
376 return (posix_time::ptime(posix_time::microsec_clock::universal_time()) -
377 posix_time::ptime(gregorian::date(1970,1,1))).total_milliseconds();
380 inline string DateTimeStrFormat(const char* pszFormat, int64 nTime)
382 time_t n = nTime;
383 struct tm* ptmTime = gmtime(&n);
384 char pszTime[200];
385 strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime);
386 return pszTime;
389 template<typename T>
390 void skipspaces(T& it)
392 while (isspace(*it))
393 ++it;
396 inline bool IsSwitchChar(char c)
398 #ifdef __WXMSW__
399 return c == '-' || c == '/';
400 #else
401 return c == '-';
402 #endif
405 inline string GetArg(const string& strArg, const string& strDefault)
407 if (mapArgs.count(strArg))
408 return mapArgs[strArg];
409 return strDefault;
412 inline int64 GetArg(const string& strArg, int64 nDefault)
414 if (mapArgs.count(strArg))
415 return atoi64(mapArgs[strArg]);
416 return nDefault;
419 inline string FormatVersion(int nVersion)
421 if (nVersion%100 == 0)
422 return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
423 else
424 return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
436 inline void heapchk()
438 #ifdef __WXMSW__
439 /// for debugging
440 //if (_heapchk() != _HEAPOK)
441 // DebugBreak();
442 #endif
445 // Randomize the stack to help protect against buffer overrun exploits
446 #define IMPLEMENT_RANDOMIZE_STACK(ThreadFn) \
448 static char nLoops; \
449 if (nLoops <= 0) \
450 nLoops = GetRand(20) + 1; \
451 if (nLoops-- > 1) \
453 ThreadFn; \
454 return; \
458 #define CATCH_PRINT_EXCEPTION(pszFn) \
459 catch (std::exception& e) { \
460 PrintException(&e, (pszFn)); \
461 } catch (...) { \
462 PrintException(NULL, (pszFn)); \
474 template<typename T1>
475 inline uint256 Hash(const T1 pbegin, const T1 pend)
477 static unsigned char pblank[1];
478 uint256 hash1;
479 SHA256((pbegin == pend ? pblank : (unsigned char*)&pbegin[0]), (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);
480 uint256 hash2;
481 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
482 return hash2;
485 template<typename T1, typename T2>
486 inline uint256 Hash(const T1 p1begin, const T1 p1end,
487 const T2 p2begin, const T2 p2end)
489 static unsigned char pblank[1];
490 uint256 hash1;
491 SHA256_CTX ctx;
492 SHA256_Init(&ctx);
493 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
494 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
495 SHA256_Final((unsigned char*)&hash1, &ctx);
496 uint256 hash2;
497 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
498 return hash2;
501 template<typename T1, typename T2, typename T3>
502 inline uint256 Hash(const T1 p1begin, const T1 p1end,
503 const T2 p2begin, const T2 p2end,
504 const T3 p3begin, const T3 p3end)
506 static unsigned char pblank[1];
507 uint256 hash1;
508 SHA256_CTX ctx;
509 SHA256_Init(&ctx);
510 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
511 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
512 SHA256_Update(&ctx, (p3begin == p3end ? pblank : (unsigned char*)&p3begin[0]), (p3end - p3begin) * sizeof(p3begin[0]));
513 SHA256_Final((unsigned char*)&hash1, &ctx);
514 uint256 hash2;
515 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
516 return hash2;
519 template<typename T>
520 uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=VERSION)
522 // Most of the time is spent allocating and deallocating CDataStream's
523 // buffer. If this ever needs to be optimized further, make a CStaticStream
524 // class with its buffer on the stack.
525 CDataStream ss(nType, nVersion);
526 ss.reserve(10000);
527 ss << obj;
528 return Hash(ss.begin(), ss.end());
531 inline uint160 Hash160(const vector<unsigned char>& vch)
533 uint256 hash1;
534 SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);
535 uint160 hash2;
536 RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
537 return hash2;
550 // Note: It turns out we might have been able to use boost::thread
551 // by using TerminateThread(boost::thread.native_handle(), 0);
552 #ifdef __WXMSW__
553 typedef HANDLE pthread_t;
555 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
557 DWORD nUnused = 0;
558 HANDLE hthread =
559 CreateThread(
560 NULL, // default security
561 0, // inherit stack size from parent
562 (LPTHREAD_START_ROUTINE)pfn, // function pointer
563 parg, // argument
564 0, // creation option, start immediately
565 &nUnused); // thread identifier
566 if (hthread == NULL)
568 printf("Error: CreateThread() returned %d\n", GetLastError());
569 return (pthread_t)0;
571 if (!fWantHandle)
573 CloseHandle(hthread);
574 return (pthread_t)-1;
576 return hthread;
579 inline void SetThreadPriority(int nPriority)
581 SetThreadPriority(GetCurrentThread(), nPriority);
583 #else
584 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
586 pthread_t hthread = 0;
587 int ret = pthread_create(&hthread, NULL, (void*(*)(void*))pfn, parg);
588 if (ret != 0)
590 printf("Error: pthread_create() returned %d\n", ret);
591 return (pthread_t)0;
593 if (!fWantHandle)
594 return (pthread_t)-1;
595 return hthread;
598 #define THREAD_PRIORITY_LOWEST PRIO_MAX
599 #define THREAD_PRIORITY_BELOW_NORMAL 2
600 #define THREAD_PRIORITY_NORMAL 0
601 #define THREAD_PRIORITY_ABOVE_NORMAL 0
603 inline void SetThreadPriority(int nPriority)
605 // It's unclear if it's even possible to change thread priorities on Linux,
606 // but we really and truly need it for the generation threads.
607 #ifdef PRIO_THREAD
608 setpriority(PRIO_THREAD, 0, nPriority);
609 #else
610 setpriority(PRIO_PROCESS, 0, nPriority);
611 #endif
614 inline bool TerminateThread(pthread_t hthread, unsigned int nExitCode)
616 return (pthread_cancel(hthread) == 0);
619 inline void ExitThread(unsigned int nExitCode)
621 pthread_exit((void*)nExitCode);
623 #endif