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