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