directory re-organization (keeps the old build system)
[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
5
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
19
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
28
29 #ifdef snprintf
30 #undef snprintf
31 #endif
32 #define snprintf my_snprintf
33
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
45
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>
48
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)
53 {
54     return (T&)val;
55 }
56
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)
60 {
61     union
62     {
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;
69 }
70
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)
102 {
103     boost::thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(n));
104 }
105 #endif
106
107 inline int myclosesocket(SOCKET& hSocket)
108 {
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;
118 }
119 #define closesocket(s)      myclosesocket(s)
120
121 #ifndef GUI
122 inline const char* _(const char* psz)
123 {
124     return psz;
125 }
126 #endif
127
128
129
130
131
132
133
134
135
136
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 fServer;
147 extern bool fCommandLine;
148 extern string strMiscWarning;
149 extern bool fTestNet;
150 extern bool fNoListen;
151 extern bool fLogTimestamps;
152
153 void RandAddSeed();
154 void RandAddSeedPerfmon();
155 int OutputDebugStringF(const char* pszFormat, ...);
156 int my_snprintf(char* buffer, size_t limit, const char* format, ...);
157 string strprintf(const char* format, ...);
158 bool error(const char* format, ...);
159 void LogException(std::exception* pex, const char* pszThread);
160 void PrintException(std::exception* pex, const char* pszThread);
161 void PrintExceptionContinue(std::exception* pex, const char* pszThread);
162 void ParseString(const string& str, char c, vector<string>& v);
163 string FormatMoney(int64 n, bool fPlus=false);
164 bool ParseMoney(const string& str, int64& nRet);
165 bool ParseMoney(const char* pszIn, int64& nRet);
166 vector<unsigned char> ParseHex(const char* psz);
167 vector<unsigned char> ParseHex(const string& str);
168 void ParseParameters(int argc, char* argv[]);
169 const char* wxGetTranslation(const char* psz);
170 bool WildcardMatch(const char* psz, const char* mask);
171 bool WildcardMatch(const string& str, const string& mask);
172 int GetFilesize(FILE* file);
173 void GetDataDir(char* pszDirRet);
174 string GetConfigFile();
175 string GetPidFile();
176 void CreatePidFile(string pidFile, pid_t pid);
177 void ReadConfigFile(map<string, string>& mapSettingsRet, map<string, vector<string> >& mapMultiSettingsRet);
178 #ifdef __WXMSW__
179 string MyGetSpecialFolderPath(int nFolder, bool fCreate);
180 #endif
181 string GetDefaultDataDir();
182 string GetDataDir();
183 void ShrinkDebugFile();
184 int GetRandInt(int nMax);
185 uint64 GetRand(uint64 nMax);
186 int64 GetTime();
187 int64 GetAdjustedTime();
188 void AddTimeData(unsigned int ip, int64 nTime);
189 string FormatFullVersion();
190
191
192
193
194
195
196
197
198
199
200
201
202
203 // Wrapper to automatically initialize critical sections
204 class CCriticalSection
205 {
206 #ifdef __WXMSW__
207 protected:
208     CRITICAL_SECTION cs;
209 public:
210     explicit CCriticalSection() { InitializeCriticalSection(&cs); }
211     ~CCriticalSection() { DeleteCriticalSection(&cs); }
212     void Enter() { EnterCriticalSection(&cs); }
213     void Leave() { LeaveCriticalSection(&cs); }
214     bool TryEnter() { return TryEnterCriticalSection(&cs); }
215 #else
216 protected:
217     boost::interprocess::interprocess_recursive_mutex mutex;
218 public:
219     explicit CCriticalSection() { }
220     ~CCriticalSection() { }
221     void Enter() { mutex.lock(); }
222     void Leave() { mutex.unlock(); }
223     bool TryEnter() { return mutex.try_lock(); }
224 #endif
225 public:
226     const char* pszFile;
227     int nLine;
228 };
229
230 // Automatically leave critical section when leaving block, needed for exception safety
231 class CCriticalBlock
232 {
233 protected:
234     CCriticalSection* pcs;
235 public:
236     CCriticalBlock(CCriticalSection& csIn) { pcs = &csIn; pcs->Enter(); }
237     ~CCriticalBlock() { pcs->Leave(); }
238 };
239
240 // WARNING: This will catch continue and break!
241 // break is caught with an assertion, but there's no way to detect continue.
242 // I'd rather be careful than suffer the other more error prone syntax.
243 // The compiler will optimise away all this loop junk.
244 #define CRITICAL_BLOCK(cs)     \
245     for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by CRITICAL_BLOCK!", !fcriticalblockonce)), fcriticalblockonce=false)  \
246     for (CCriticalBlock criticalblock(cs); fcriticalblockonce && (cs.pszFile=__FILE__, cs.nLine=__LINE__, true); fcriticalblockonce=false, cs.pszFile=NULL, cs.nLine=0)
247
248 class CTryCriticalBlock
249 {
250 protected:
251     CCriticalSection* pcs;
252 public:
253     CTryCriticalBlock(CCriticalSection& csIn) { pcs = (csIn.TryEnter() ? &csIn : NULL); }
254     ~CTryCriticalBlock() { if (pcs) pcs->Leave(); }
255     bool Entered() { return pcs != NULL; }
256 };
257
258 #define TRY_CRITICAL_BLOCK(cs)     \
259     for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by TRY_CRITICAL_BLOCK!", !fcriticalblockonce)), fcriticalblockonce=false)  \
260     for (CTryCriticalBlock criticalblock(cs); fcriticalblockonce && (fcriticalblockonce = criticalblock.Entered()) && (cs.pszFile=__FILE__, cs.nLine=__LINE__, true); fcriticalblockonce=false, cs.pszFile=NULL, cs.nLine=0)
261
262
263
264
265
266
267
268
269
270
271 inline string i64tostr(int64 n)
272 {
273     return strprintf("%"PRI64d, n);
274 }
275
276 inline string itostr(int n)
277 {
278     return strprintf("%d", n);
279 }
280
281 inline int64 atoi64(const char* psz)
282 {
283 #ifdef _MSC_VER
284     return _atoi64(psz);
285 #else
286     return strtoll(psz, NULL, 10);
287 #endif
288 }
289
290 inline int64 atoi64(const string& str)
291 {
292 #ifdef _MSC_VER
293     return _atoi64(str.c_str());
294 #else
295     return strtoll(str.c_str(), NULL, 10);
296 #endif
297 }
298
299 inline int atoi(const string& str)
300 {
301     return atoi(str.c_str());
302 }
303
304 inline int roundint(double d)
305 {
306     return (int)(d > 0 ? d + 0.5 : d - 0.5);
307 }
308
309 inline int64 roundint64(double d)
310 {
311     return (int64)(d > 0 ? d + 0.5 : d - 0.5);
312 }
313
314 inline int64 abs64(int64 n)
315 {
316     return (n >= 0 ? n : -n);
317 }
318
319 template<typename T>
320 string HexStr(const T itbegin, const T itend, bool fSpaces=false)
321 {
322     if (itbegin == itend)
323         return "";
324     const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
325     const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
326     string str;
327     str.reserve((pend-pbegin) * (fSpaces ? 3 : 2));
328     for (const unsigned char* p = pbegin; p != pend; p++)
329         str += strprintf((fSpaces && p != pend-1 ? "%02x " : "%02x"), *p);
330     return str;
331 }
332
333 inline string HexStr(const vector<unsigned char>& vch, bool fSpaces=false)
334 {
335     return HexStr(vch.begin(), vch.end(), fSpaces);
336 }
337
338 template<typename T>
339 string HexNumStr(const T itbegin, const T itend, bool f0x=true)
340 {
341     if (itbegin == itend)
342         return "";
343     const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
344     const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
345     string str = (f0x ? "0x" : "");
346     str.reserve(str.size() + (pend-pbegin) * 2);
347     for (const unsigned char* p = pend-1; p >= pbegin; p--)
348         str += strprintf("%02x", *p);
349     return str;
350 }
351
352 inline string HexNumStr(const vector<unsigned char>& vch, bool f0x=true)
353 {
354     return HexNumStr(vch.begin(), vch.end(), f0x);
355 }
356
357 template<typename T>
358 void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)
359 {
360     printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());
361 }
362
363 inline void PrintHex(const vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true)
364 {
365     printf(pszFormat, HexStr(vch, fSpaces).c_str());
366 }
367
368 inline int64 GetPerformanceCounter()
369 {
370     int64 nCounter = 0;
371 #ifdef __WXMSW__
372     QueryPerformanceCounter((LARGE_INTEGER*)&nCounter);
373 #else
374     timeval t;
375     gettimeofday(&t, NULL);
376     nCounter = t.tv_sec * 1000000 + t.tv_usec;
377 #endif
378     return nCounter;
379 }
380
381 inline int64 GetTimeMillis()
382 {
383     return (posix_time::ptime(posix_time::microsec_clock::universal_time()) -
384             posix_time::ptime(gregorian::date(1970,1,1))).total_milliseconds();
385 }
386
387 inline string DateTimeStrFormat(const char* pszFormat, int64 nTime)
388 {
389     time_t n = nTime;
390     struct tm* ptmTime = gmtime(&n);
391     char pszTime[200];
392     strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime);
393     return pszTime;
394 }
395
396 template<typename T>
397 void skipspaces(T& it)
398 {
399     while (isspace(*it))
400         ++it;
401 }
402
403 inline bool IsSwitchChar(char c)
404 {
405 #ifdef __WXMSW__
406     return c == '-' || c == '/';
407 #else
408     return c == '-';
409 #endif
410 }
411
412 inline string GetArg(const string& strArg, const string& strDefault)
413 {
414     if (mapArgs.count(strArg))
415         return mapArgs[strArg];
416     return strDefault;
417 }
418
419 inline int64 GetArg(const string& strArg, int64 nDefault)
420 {
421     if (mapArgs.count(strArg))
422         return atoi64(mapArgs[strArg]);
423     return nDefault;
424 }
425
426 inline bool GetBoolArg(const string& strArg)
427 {
428     if (mapArgs.count(strArg))
429     {
430         if (mapArgs[strArg].empty())
431             return true;
432         return (atoi(mapArgs[strArg]) != 0);
433     }
434     return false;
435 }
436
437
438
439
440
441
442
443
444
445
446 inline void heapchk()
447 {
448 #ifdef __WXMSW__
449     /// for debugging
450     //if (_heapchk() != _HEAPOK)
451     //    DebugBreak();
452 #endif
453 }
454
455 // Randomize the stack to help protect against buffer overrun exploits
456 #define IMPLEMENT_RANDOMIZE_STACK(ThreadFn)     \
457     {                                           \
458         static char nLoops;                     \
459         if (nLoops <= 0)                        \
460             nLoops = GetRand(20) + 1;           \
461         if (nLoops-- > 1)                       \
462         {                                       \
463             ThreadFn;                           \
464             return;                             \
465         }                                       \
466     }
467
468 #define CATCH_PRINT_EXCEPTION(pszFn)     \
469     catch (std::exception& e) {          \
470         PrintException(&e, (pszFn));     \
471     } catch (...) {                      \
472         PrintException(NULL, (pszFn));   \
473     }
474
475
476
477
478
479
480
481
482
483
484 template<typename T1>
485 inline uint256 Hash(const T1 pbegin, const T1 pend)
486 {
487     static unsigned char pblank[1];
488     uint256 hash1;
489     SHA256((pbegin == pend ? pblank : (unsigned char*)&pbegin[0]), (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);
490     uint256 hash2;
491     SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
492     return hash2;
493 }
494
495 template<typename T1, typename T2>
496 inline uint256 Hash(const T1 p1begin, const T1 p1end,
497                     const T2 p2begin, const T2 p2end)
498 {
499     static unsigned char pblank[1];
500     uint256 hash1;
501     SHA256_CTX ctx;
502     SHA256_Init(&ctx);
503     SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
504     SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
505     SHA256_Final((unsigned char*)&hash1, &ctx);
506     uint256 hash2;
507     SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
508     return hash2;
509 }
510
511 template<typename T1, typename T2, typename T3>
512 inline uint256 Hash(const T1 p1begin, const T1 p1end,
513                     const T2 p2begin, const T2 p2end,
514                     const T3 p3begin, const T3 p3end)
515 {
516     static unsigned char pblank[1];
517     uint256 hash1;
518     SHA256_CTX ctx;
519     SHA256_Init(&ctx);
520     SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
521     SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
522     SHA256_Update(&ctx, (p3begin == p3end ? pblank : (unsigned char*)&p3begin[0]), (p3end - p3begin) * sizeof(p3begin[0]));
523     SHA256_Final((unsigned char*)&hash1, &ctx);
524     uint256 hash2;
525     SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
526     return hash2;
527 }
528
529 template<typename T>
530 uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=VERSION)
531 {
532     // Most of the time is spent allocating and deallocating CDataStream's
533     // buffer.  If this ever needs to be optimized further, make a CStaticStream
534     // class with its buffer on the stack.
535     CDataStream ss(nType, nVersion);
536     ss.reserve(10000);
537     ss << obj;
538     return Hash(ss.begin(), ss.end());
539 }
540
541 inline uint160 Hash160(const vector<unsigned char>& vch)
542 {
543     uint256 hash1;
544     SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);
545     uint160 hash2;
546     RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
547     return hash2;
548 }
549
550
551
552
553
554
555
556
557
558
559
560 // Note: It turns out we might have been able to use boost::thread
561 // by using TerminateThread(boost::thread.native_handle(), 0);
562 #ifdef __WXMSW__
563 typedef HANDLE pthread_t;
564
565 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
566 {
567     DWORD nUnused = 0;
568     HANDLE hthread =
569         CreateThread(
570             NULL,                        // default security
571             0,                           // inherit stack size from parent
572             (LPTHREAD_START_ROUTINE)pfn, // function pointer
573             parg,                        // argument
574             0,                           // creation option, start immediately
575             &nUnused);                   // thread identifier
576     if (hthread == NULL)
577     {
578         printf("Error: CreateThread() returned %d\n", GetLastError());
579         return (pthread_t)0;
580     }
581     if (!fWantHandle)
582     {
583         CloseHandle(hthread);
584         return (pthread_t)-1;
585     }
586     return hthread;
587 }
588
589 inline void SetThreadPriority(int nPriority)
590 {
591     SetThreadPriority(GetCurrentThread(), nPriority);
592 }
593 #else
594 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
595 {
596     pthread_t hthread = 0;
597     int ret = pthread_create(&hthread, NULL, (void*(*)(void*))pfn, parg);
598     if (ret != 0)
599     {
600         printf("Error: pthread_create() returned %d\n", ret);
601         return (pthread_t)0;
602     }
603     if (!fWantHandle)
604         return (pthread_t)-1;
605     return hthread;
606 }
607
608 #define THREAD_PRIORITY_LOWEST          PRIO_MAX
609 #define THREAD_PRIORITY_BELOW_NORMAL    2
610 #define THREAD_PRIORITY_NORMAL          0
611 #define THREAD_PRIORITY_ABOVE_NORMAL    0
612
613 inline void SetThreadPriority(int nPriority)
614 {
615     // It's unclear if it's even possible to change thread priorities on Linux,
616     // but we really and truly need it for the generation threads.
617 #ifdef PRIO_THREAD
618     setpriority(PRIO_THREAD, 0, nPriority);
619 #else
620     setpriority(PRIO_PROCESS, 0, nPriority);
621 #endif
622 }
623
624 inline bool TerminateThread(pthread_t hthread, unsigned int nExitCode)
625 {
626     return (pthread_cancel(hthread) == 0);
627 }
628
629 inline void ExitThread(unsigned int nExitCode)
630 {
631     pthread_exit((void*)nExitCode);
632 }
633 #endif
634
635
636
637
638
639 inline bool AffinityBugWorkaround(void(*pfn)(void*))
640 {
641 #ifdef __WXMSW__
642     // Sometimes after a few hours affinity gets stuck on one processor
643     DWORD dwProcessAffinityMask = -1;
644     DWORD dwSystemAffinityMask = -1;
645     GetProcessAffinityMask(GetCurrentProcess(), &dwProcessAffinityMask, &dwSystemAffinityMask);
646     DWORD dwPrev1 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
647     DWORD dwPrev2 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
648     if (dwPrev2 != dwProcessAffinityMask)
649     {
650         printf("AffinityBugWorkaround() : SetThreadAffinityMask=%d, ProcessAffinityMask=%d, restarting thread\n", dwPrev2, dwProcessAffinityMask);
651         if (!CreateThread(pfn, NULL))
652             printf("Error: CreateThread() failed\n");
653         return true;
654     }
655 #endif
656     return false;
657 }