temp patch for qtui
[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 #ifndef BITCOIN_UTIL_H
5 #define BITCOIN_UTIL_H
6
7 #include "uint256.h"
8
9 #ifndef __WXMSW__
10 #include <sys/types.h>
11 #include <sys/time.h>
12 #include <sys/resource.h>
13 #endif
14 #include <map>
15 #include <vector>
16 #include <string>
17
18 #include <boost/thread.hpp>
19 #include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>
20 #include <boost/date_time/gregorian/gregorian_types.hpp>
21 #include <boost/date_time/posix_time/posix_time_types.hpp>
22
23 #include <openssl/sha.h>
24 #include <openssl/ripemd.h>
25
26
27 #if defined(_MSC_VER) || defined(__BORLANDC__)
28 typedef __int64  int64;
29 typedef unsigned __int64  uint64;
30 #else
31 typedef long long  int64;
32 typedef unsigned long long  uint64;
33 #endif
34 #if defined(_MSC_VER) && _MSC_VER < 1300
35 #define for  if (false) ; else for
36 #endif
37 #ifndef _MSC_VER
38 #define __forceinline  inline
39 #endif
40
41 #define loop                for (;;)
42 #define BEGIN(a)            ((char*)&(a))
43 #define END(a)              ((char*)&((&(a))[1]))
44 #define UBEGIN(a)           ((unsigned char*)&(a))
45 #define UEND(a)             ((unsigned char*)&((&(a))[1]))
46 #define ARRAYLEN(array)     (sizeof(array)/sizeof((array)[0]))
47 #define printf              OutputDebugStringF
48
49 #ifdef snprintf
50 #undef snprintf
51 #endif
52 #define snprintf my_snprintf
53
54 #ifndef PRI64d
55 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MSVCRT__)
56 #define PRI64d  "I64d"
57 #define PRI64u  "I64u"
58 #define PRI64x  "I64x"
59 #else
60 #define PRI64d  "lld"
61 #define PRI64u  "llu"
62 #define PRI64x  "llx"
63 #endif
64 #endif
65
66 // This is needed because the foreach macro can't get over the comma in pair<t1, t2>
67 #define PAIRTYPE(t1, t2)    std::pair<t1, t2>
68
69 // Used to bypass the rule against non-const reference to temporary
70 // where it makes sense with wrappers such as CFlatData or CTxDB
71 template<typename T>
72 inline T& REF(const T& val)
73 {
74     return (T&)val;
75 }
76
77 // Align by increasing pointer, must have extra space at end of buffer
78 template <size_t nBytes, typename T>
79 T* alignup(T* p)
80 {
81     union
82     {
83         T* ptr;
84         size_t n;
85     } u;
86     u.ptr = p;
87     u.n = (u.n + (nBytes-1)) & ~(nBytes-1);
88     return u.ptr;
89 }
90
91 #ifdef __WXMSW__
92 #define MSG_NOSIGNAL        0
93 #define MSG_DONTWAIT        0
94 #ifndef UINT64_MAX
95 #define UINT64_MAX          _UI64_MAX
96 #define INT64_MAX           _I64_MAX
97 #define INT64_MIN           _I64_MIN
98 #endif
99 #ifndef S_IRUSR
100 #define S_IRUSR             0400
101 #define S_IWUSR             0200
102 #endif
103 #define unlink              _unlink
104 typedef int socklen_t;
105 #else
106 #define WSAGetLastError()   errno
107 #define WSAEINVAL           EINVAL
108 #define WSAEALREADY         EALREADY
109 #define WSAEWOULDBLOCK      EWOULDBLOCK
110 #define WSAEMSGSIZE         EMSGSIZE
111 #define WSAEINTR            EINTR
112 #define WSAEINPROGRESS      EINPROGRESS
113 #define WSAEADDRINUSE       EADDRINUSE
114 #define WSAENOTSOCK         EBADF
115 #define INVALID_SOCKET      (SOCKET)(~0)
116 #define SOCKET_ERROR        -1
117 typedef u_int SOCKET;
118 #define _vsnprintf(a,b,c,d) vsnprintf(a,b,c,d)
119 #define strlwr(psz)         to_lower(psz)
120 #define _strlwr(psz)        to_lower(psz)
121 #define MAX_PATH            1024
122 #define Beep(n1,n2)         (0)
123 inline void Sleep(int64 n)
124 {
125     boost::thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(n));
126 }
127 #endif
128
129 inline int myclosesocket(SOCKET& hSocket)
130 {
131     if (hSocket == INVALID_SOCKET)
132         return WSAENOTSOCK;
133 #ifdef __WXMSW__
134     int ret = closesocket(hSocket);
135 #else
136     int ret = close(hSocket);
137 #endif
138     hSocket = INVALID_SOCKET;
139     return ret;
140 }
141 #define closesocket(s)      myclosesocket(s)
142 #if !defined(QT_GUI) && !defined(GUI)
143 inline const char* _(const char* psz)
144 {
145     return psz;
146 }
147 #endif
148
149
150
151
152
153
154
155
156
157 extern std::map<std::string, std::string> mapArgs;
158 extern std::map<std::string, std::vector<std::string> > mapMultiArgs;
159 extern bool fDebug;
160 extern bool fPrintToConsole;
161 extern bool fPrintToDebugger;
162 extern char pszSetDataDir[MAX_PATH];
163 extern bool fRequestShutdown;
164 extern bool fShutdown;
165 extern bool fDaemon;
166 extern bool fServer;
167 extern bool fCommandLine;
168 extern std::string strMiscWarning;
169 extern bool fTestNet;
170 extern bool fNoListen;
171 extern bool fLogTimestamps;
172
173 void RandAddSeed();
174 void RandAddSeedPerfmon();
175 int OutputDebugStringF(const char* pszFormat, ...);
176 int my_snprintf(char* buffer, size_t limit, const char* format, ...);
177 std::string strprintf(const std::string &format, ...);
178 bool error(const std::string &format, ...);
179 void LogException(std::exception* pex, const char* pszThread);
180 void PrintException(std::exception* pex, const char* pszThread);
181 void PrintExceptionContinue(std::exception* pex, const char* pszThread);
182 void ParseString(const std::string& str, char c, std::vector<std::string>& v);
183 std::string FormatMoney(int64 n, bool fPlus=false);
184 bool ParseMoney(const std::string& str, int64& nRet);
185 bool ParseMoney(const char* pszIn, int64& nRet);
186 std::vector<unsigned char> ParseHex(const char* psz);
187 std::vector<unsigned char> ParseHex(const std::string& str);
188 void ParseParameters(int argc, char* argv[]);
189 const char* wxGetTranslation(const char* psz);
190 bool WildcardMatch(const char* psz, const char* mask);
191 bool WildcardMatch(const std::string& str, const std::string& mask);
192 int GetFilesize(FILE* file);
193 void GetDataDir(char* pszDirRet);
194 std::string GetConfigFile();
195 std::string GetPidFile();
196 void CreatePidFile(std::string pidFile, pid_t pid);
197 void ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet, std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet);
198 #ifdef __WXMSW__
199 std::string MyGetSpecialFolderPath(int nFolder, bool fCreate);
200 #endif
201 std::string GetDefaultDataDir();
202 std::string GetDataDir();
203 void ShrinkDebugFile();
204 int GetRandInt(int nMax);
205 uint64 GetRand(uint64 nMax);
206 int64 GetTime();
207 int64 GetAdjustedTime();
208 void AddTimeData(unsigned int ip, int64 nTime);
209 std::string FormatFullVersion();
210
211
212
213
214
215
216
217
218
219
220
221
222
223 // Wrapper to automatically initialize critical sections
224 class CCriticalSection
225 {
226 #ifdef __WXMSW__
227 protected:
228     CRITICAL_SECTION cs;
229 public:
230     explicit CCriticalSection() { InitializeCriticalSection(&cs); }
231     ~CCriticalSection() { DeleteCriticalSection(&cs); }
232     void Enter() { EnterCriticalSection(&cs); }
233     void Leave() { LeaveCriticalSection(&cs); }
234     bool TryEnter() { return TryEnterCriticalSection(&cs); }
235 #else
236 protected:
237     boost::interprocess::interprocess_recursive_mutex mutex;
238 public:
239     explicit CCriticalSection() { }
240     ~CCriticalSection() { }
241     void Enter() { mutex.lock(); }
242     void Leave() { mutex.unlock(); }
243     bool TryEnter() { return mutex.try_lock(); }
244 #endif
245 public:
246     const char* pszFile;
247     int nLine;
248 };
249
250 // Automatically leave critical section when leaving block, needed for exception safety
251 class CCriticalBlock
252 {
253 protected:
254     CCriticalSection* pcs;
255 public:
256     CCriticalBlock(CCriticalSection& csIn) { pcs = &csIn; pcs->Enter(); }
257     ~CCriticalBlock() { pcs->Leave(); }
258 };
259
260 // WARNING: This will catch continue and break!
261 // break is caught with an assertion, but there's no way to detect continue.
262 // I'd rather be careful than suffer the other more error prone syntax.
263 // The compiler will optimise away all this loop junk.
264 #define CRITICAL_BLOCK(cs)     \
265     for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by CRITICAL_BLOCK!", !fcriticalblockonce)), fcriticalblockonce=false)  \
266     for (CCriticalBlock criticalblock(cs); fcriticalblockonce && (cs.pszFile=__FILE__, cs.nLine=__LINE__, true); fcriticalblockonce=false, cs.pszFile=NULL, cs.nLine=0)
267
268 class CTryCriticalBlock
269 {
270 protected:
271     CCriticalSection* pcs;
272 public:
273     CTryCriticalBlock(CCriticalSection& csIn) { pcs = (csIn.TryEnter() ? &csIn : NULL); }
274     ~CTryCriticalBlock() { if (pcs) pcs->Leave(); }
275     bool Entered() { return pcs != NULL; }
276 };
277
278 #define TRY_CRITICAL_BLOCK(cs)     \
279     for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by TRY_CRITICAL_BLOCK!", !fcriticalblockonce)), fcriticalblockonce=false)  \
280     for (CTryCriticalBlock criticalblock(cs); fcriticalblockonce && (fcriticalblockonce = criticalblock.Entered()) && (cs.pszFile=__FILE__, cs.nLine=__LINE__, true); fcriticalblockonce=false, cs.pszFile=NULL, cs.nLine=0)
281
282
283
284
285
286
287
288
289
290
291 inline std::string i64tostr(int64 n)
292 {
293     return strprintf("%"PRI64d, n);
294 }
295
296 inline std::string itostr(int n)
297 {
298     return strprintf("%d", n);
299 }
300
301 inline int64 atoi64(const char* psz)
302 {
303 #ifdef _MSC_VER
304     return _atoi64(psz);
305 #else
306     return strtoll(psz, NULL, 10);
307 #endif
308 }
309
310 inline int64 atoi64(const std::string& str)
311 {
312 #ifdef _MSC_VER
313     return _atoi64(str.c_str());
314 #else
315     return strtoll(str.c_str(), NULL, 10);
316 #endif
317 }
318
319 inline int atoi(const std::string& str)
320 {
321     return atoi(str.c_str());
322 }
323
324 inline int roundint(double d)
325 {
326     return (int)(d > 0 ? d + 0.5 : d - 0.5);
327 }
328
329 inline int64 roundint64(double d)
330 {
331     return (int64)(d > 0 ? d + 0.5 : d - 0.5);
332 }
333
334 inline int64 abs64(int64 n)
335 {
336     return (n >= 0 ? n : -n);
337 }
338
339 template<typename T>
340 std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
341 {
342     if (itbegin == itend)
343         return "";
344     const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
345     const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
346     std::string str;
347     str.reserve((pend-pbegin) * (fSpaces ? 3 : 2));
348     for (const unsigned char* p = pbegin; p != pend; p++)
349         str += strprintf((fSpaces && p != pend-1 ? "%02x " : "%02x"), *p);
350     return str;
351 }
352
353 inline std::string HexStr(const std::vector<unsigned char>& vch, bool fSpaces=false)
354 {
355     return HexStr(vch.begin(), vch.end(), fSpaces);
356 }
357
358 template<typename T>
359 std::string HexNumStr(const T itbegin, const T itend, bool f0x=true)
360 {
361     if (itbegin == itend)
362         return "";
363     const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
364     const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
365     std::string str = (f0x ? "0x" : "");
366     str.reserve(str.size() + (pend-pbegin) * 2);
367     for (const unsigned char* p = pend-1; p >= pbegin; p--)
368         str += strprintf("%02x", *p);
369     return str;
370 }
371
372 inline std::string HexNumStr(const std::vector<unsigned char>& vch, bool f0x=true)
373 {
374     return HexNumStr(vch.begin(), vch.end(), f0x);
375 }
376
377 template<typename T>
378 void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)
379 {
380     printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());
381 }
382
383 inline void PrintHex(const std::vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true)
384 {
385     printf(pszFormat, HexStr(vch, fSpaces).c_str());
386 }
387
388 inline int64 GetPerformanceCounter()
389 {
390     int64 nCounter = 0;
391 #ifdef __WXMSW__
392     QueryPerformanceCounter((LARGE_INTEGER*)&nCounter);
393 #else
394     timeval t;
395     gettimeofday(&t, NULL);
396     nCounter = t.tv_sec * 1000000 + t.tv_usec;
397 #endif
398     return nCounter;
399 }
400
401 inline int64 GetTimeMillis()
402 {
403     return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) -
404             boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
405 }
406
407 inline std::string DateTimeStrFormat(const char* pszFormat, int64 nTime)
408 {
409     time_t n = nTime;
410     struct tm* ptmTime = gmtime(&n);
411     char pszTime[200];
412     strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime);
413     return pszTime;
414 }
415
416 template<typename T>
417 void skipspaces(T& it)
418 {
419     while (isspace(*it))
420         ++it;
421 }
422
423 inline bool IsSwitchChar(char c)
424 {
425 #ifdef __WXMSW__
426     return c == '-' || c == '/';
427 #else
428     return c == '-';
429 #endif
430 }
431
432 inline std::string GetArg(const std::string& strArg, const std::string& strDefault)
433 {
434     if (mapArgs.count(strArg))
435         return mapArgs[strArg];
436     return strDefault;
437 }
438
439 inline int64 GetArg(const std::string& strArg, int64 nDefault)
440 {
441     if (mapArgs.count(strArg))
442         return atoi64(mapArgs[strArg]);
443     return nDefault;
444 }
445
446 inline bool GetBoolArg(const std::string& strArg)
447 {
448     if (mapArgs.count(strArg))
449     {
450         if (mapArgs[strArg].empty())
451             return true;
452         return (atoi(mapArgs[strArg]) != 0);
453     }
454     return false;
455 }
456
457
458
459
460
461
462
463
464
465
466 inline void heapchk()
467 {
468 #ifdef __WXMSW__
469     /// for debugging
470     //if (_heapchk() != _HEAPOK)
471     //    DebugBreak();
472 #endif
473 }
474
475 // Randomize the stack to help protect against buffer overrun exploits
476 #define IMPLEMENT_RANDOMIZE_STACK(ThreadFn)     \
477     {                                           \
478         static char nLoops;                     \
479         if (nLoops <= 0)                        \
480             nLoops = GetRand(20) + 1;           \
481         if (nLoops-- > 1)                       \
482         {                                       \
483             ThreadFn;                           \
484             return;                             \
485         }                                       \
486     }
487
488 #define CATCH_PRINT_EXCEPTION(pszFn)     \
489     catch (std::exception& e) {          \
490         PrintException(&e, (pszFn));     \
491     } catch (...) {                      \
492         PrintException(NULL, (pszFn));   \
493     }
494
495
496
497
498
499
500
501
502
503
504 template<typename T1>
505 inline uint256 Hash(const T1 pbegin, const T1 pend)
506 {
507     static unsigned char pblank[1];
508     uint256 hash1;
509     SHA256((pbegin == pend ? pblank : (unsigned char*)&pbegin[0]), (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);
510     uint256 hash2;
511     SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
512     return hash2;
513 }
514
515 template<typename T1, typename T2>
516 inline uint256 Hash(const T1 p1begin, const T1 p1end,
517                     const T2 p2begin, const T2 p2end)
518 {
519     static unsigned char pblank[1];
520     uint256 hash1;
521     SHA256_CTX ctx;
522     SHA256_Init(&ctx);
523     SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
524     SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
525     SHA256_Final((unsigned char*)&hash1, &ctx);
526     uint256 hash2;
527     SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
528     return hash2;
529 }
530
531 template<typename T1, typename T2, typename T3>
532 inline uint256 Hash(const T1 p1begin, const T1 p1end,
533                     const T2 p2begin, const T2 p2end,
534                     const T3 p3begin, const T3 p3end)
535 {
536     static unsigned char pblank[1];
537     uint256 hash1;
538     SHA256_CTX ctx;
539     SHA256_Init(&ctx);
540     SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
541     SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
542     SHA256_Update(&ctx, (p3begin == p3end ? pblank : (unsigned char*)&p3begin[0]), (p3end - p3begin) * sizeof(p3begin[0]));
543     SHA256_Final((unsigned char*)&hash1, &ctx);
544     uint256 hash2;
545     SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
546     return hash2;
547 }
548
549 template<typename T>
550 uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=VERSION)
551 {
552     // Most of the time is spent allocating and deallocating CDataStream's
553     // buffer.  If this ever needs to be optimized further, make a CStaticStream
554     // class with its buffer on the stack.
555     CDataStream ss(nType, nVersion);
556     ss.reserve(10000);
557     ss << obj;
558     return Hash(ss.begin(), ss.end());
559 }
560
561 inline uint160 Hash160(const std::vector<unsigned char>& vch)
562 {
563     uint256 hash1;
564     SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);
565     uint160 hash2;
566     RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
567     return hash2;
568 }
569
570
571
572
573
574
575
576
577
578
579
580 // Note: It turns out we might have been able to use boost::thread
581 // by using TerminateThread(boost::thread.native_handle(), 0);
582 #ifdef __WXMSW__
583 typedef HANDLE pthread_t;
584
585 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
586 {
587     DWORD nUnused = 0;
588     HANDLE hthread =
589         CreateThread(
590             NULL,                        // default security
591             0,                           // inherit stack size from parent
592             (LPTHREAD_START_ROUTINE)pfn, // function pointer
593             parg,                        // argument
594             0,                           // creation option, start immediately
595             &nUnused);                   // thread identifier
596     if (hthread == NULL)
597     {
598         printf("Error: CreateThread() returned %d\n", GetLastError());
599         return (pthread_t)0;
600     }
601     if (!fWantHandle)
602     {
603         CloseHandle(hthread);
604         return (pthread_t)-1;
605     }
606     return hthread;
607 }
608
609 inline void SetThreadPriority(int nPriority)
610 {
611     SetThreadPriority(GetCurrentThread(), nPriority);
612 }
613 #else
614 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
615 {
616     pthread_t hthread = 0;
617     int ret = pthread_create(&hthread, NULL, (void*(*)(void*))pfn, parg);
618     if (ret != 0)
619     {
620         printf("Error: pthread_create() returned %d\n", ret);
621         return (pthread_t)0;
622     }
623     if (!fWantHandle)
624         return (pthread_t)-1;
625     return hthread;
626 }
627
628 #define THREAD_PRIORITY_LOWEST          PRIO_MAX
629 #define THREAD_PRIORITY_BELOW_NORMAL    2
630 #define THREAD_PRIORITY_NORMAL          0
631 #define THREAD_PRIORITY_ABOVE_NORMAL    0
632
633 inline void SetThreadPriority(int nPriority)
634 {
635     // It's unclear if it's even possible to change thread priorities on Linux,
636     // but we really and truly need it for the generation threads.
637 #ifdef PRIO_THREAD
638     setpriority(PRIO_THREAD, 0, nPriority);
639 #else
640     setpriority(PRIO_PROCESS, 0, nPriority);
641 #endif
642 }
643
644 inline bool TerminateThread(pthread_t hthread, unsigned int nExitCode)
645 {
646     return (pthread_cancel(hthread) == 0);
647 }
648
649 inline void ExitThread(unsigned int nExitCode)
650 {
651     pthread_exit((void*)nExitCode);
652 }
653 #endif
654
655
656
657
658
659 inline bool AffinityBugWorkaround(void(*pfn)(void*))
660 {
661 #ifdef __WXMSW__
662     // Sometimes after a few hours affinity gets stuck on one processor
663     DWORD dwProcessAffinityMask = -1;
664     DWORD dwSystemAffinityMask = -1;
665     GetProcessAffinityMask(GetCurrentProcess(), &dwProcessAffinityMask, &dwSystemAffinityMask);
666     DWORD dwPrev1 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
667     DWORD dwPrev2 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
668     if (dwPrev2 != dwProcessAffinityMask)
669     {
670         printf("AffinityBugWorkaround() : SetThreadAffinityMask=%d, ProcessAffinityMask=%d, restarting thread\n", dwPrev2, dwProcessAffinityMask);
671         if (!CreateThread(pfn, NULL))
672             printf("Error: CreateThread() failed\n");
673         return true;
674     }
675 #endif
676     return false;
677 }
678
679 #endif