dd5c41135eaa3152013ac472e7c1dabd713d098a
[novacoin.git] / src / util.h
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
5 #ifndef BITCOIN_UTIL_H
6 #define BITCOIN_UTIL_H
7
8 #include "uint256.h"
9
10 #ifndef __WXMSW__
11 #include <sys/types.h>
12 #include <sys/time.h>
13 #include <sys/resource.h>
14 #endif
15 #include <map>
16 #include <vector>
17 #include <string>
18
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 // Align by increasing pointer, must have extra space at end of buffer
71 template <size_t nBytes, typename T>
72 T* alignup(T* p)
73 {
74     union
75     {
76         T* ptr;
77         size_t n;
78     } u;
79     u.ptr = p;
80     u.n = (u.n + (nBytes-1)) & ~(nBytes-1);
81     return u.ptr;
82 }
83
84 #ifdef __WXMSW__
85 #define MSG_NOSIGNAL        0
86 #define MSG_DONTWAIT        0
87 #ifndef UINT64_MAX
88 #define UINT64_MAX          _UI64_MAX
89 #define INT64_MAX           _I64_MAX
90 #define INT64_MIN           _I64_MIN
91 #endif
92 #ifndef S_IRUSR
93 #define S_IRUSR             0400
94 #define S_IWUSR             0200
95 #endif
96 #define unlink              _unlink
97 typedef int socklen_t;
98 #else
99 #define WSAGetLastError()   errno
100 #define WSAEINVAL           EINVAL
101 #define WSAEALREADY         EALREADY
102 #define WSAEWOULDBLOCK      EWOULDBLOCK
103 #define WSAEMSGSIZE         EMSGSIZE
104 #define WSAEINTR            EINTR
105 #define WSAEINPROGRESS      EINPROGRESS
106 #define WSAEADDRINUSE       EADDRINUSE
107 #define WSAENOTSOCK         EBADF
108 #define INVALID_SOCKET      (SOCKET)(~0)
109 #define SOCKET_ERROR        -1
110 typedef u_int SOCKET;
111 #define _vsnprintf(a,b,c,d) vsnprintf(a,b,c,d)
112 #define strlwr(psz)         to_lower(psz)
113 #define _strlwr(psz)        to_lower(psz)
114 #define MAX_PATH            1024
115 #define Beep(n1,n2)         (0)
116 inline void Sleep(int64 n)
117 {
118     boost::thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(n));
119 }
120 #endif
121
122 inline int myclosesocket(SOCKET& hSocket)
123 {
124     if (hSocket == INVALID_SOCKET)
125         return WSAENOTSOCK;
126 #ifdef __WXMSW__
127     int ret = closesocket(hSocket);
128 #else
129     int ret = close(hSocket);
130 #endif
131     hSocket = INVALID_SOCKET;
132     return ret;
133 }
134 #define closesocket(s)      myclosesocket(s)
135 #if !defined(QT_GUI) && !defined(GUI)
136 inline const char* _(const char* psz)
137 {
138     return psz;
139 }
140 #endif
141
142
143
144
145
146
147
148
149
150 extern std::map<std::string, std::string> mapArgs;
151 extern std::map<std::string, std::vector<std::string> > mapMultiArgs;
152 extern bool fDebug;
153 extern bool fPrintToConsole;
154 extern bool fPrintToDebugger;
155 extern char pszSetDataDir[MAX_PATH];
156 extern bool fRequestShutdown;
157 extern bool fShutdown;
158 extern bool fDaemon;
159 extern bool fServer;
160 extern bool fCommandLine;
161 extern std::string strMiscWarning;
162 extern bool fTestNet;
163 extern bool fNoListen;
164 extern bool fLogTimestamps;
165
166 void RandAddSeed();
167 void RandAddSeedPerfmon();
168 int OutputDebugStringF(const char* pszFormat, ...);
169 int my_snprintf(char* buffer, size_t limit, const char* format, ...);
170 std::string strprintf(const std::string &format, ...);
171 bool error(const std::string &format, ...);
172 void LogException(std::exception* pex, const char* pszThread);
173 void PrintException(std::exception* pex, const char* pszThread);
174 void PrintExceptionContinue(std::exception* pex, const char* pszThread);
175 void ParseString(const std::string& str, char c, std::vector<std::string>& v);
176 std::string FormatMoney(int64 n, bool fPlus=false);
177 bool ParseMoney(const std::string& str, int64& nRet);
178 bool ParseMoney(const char* pszIn, int64& nRet);
179 std::vector<unsigned char> ParseHex(const char* psz);
180 std::vector<unsigned char> ParseHex(const std::string& str);
181 void ParseParameters(int argc, char* argv[]);
182 const char* wxGetTranslation(const char* psz);
183 bool WildcardMatch(const char* psz, const char* mask);
184 bool WildcardMatch(const std::string& str, const std::string& mask);
185 int GetFilesize(FILE* file);
186 void GetDataDir(char* pszDirRet);
187 std::string GetConfigFile();
188 std::string GetPidFile();
189 void CreatePidFile(std::string pidFile, pid_t pid);
190 void ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet, std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet);
191 #ifdef __WXMSW__
192 std::string MyGetSpecialFolderPath(int nFolder, bool fCreate);
193 #endif
194 std::string GetDefaultDataDir();
195 std::string GetDataDir();
196 void ShrinkDebugFile();
197 int GetRandInt(int nMax);
198 uint64 GetRand(uint64 nMax);
199 int64 GetTime();
200 void SetMockTime(int64 nMockTimeIn);
201 int64 GetAdjustedTime();
202 void AddTimeData(unsigned int ip, int64 nTime);
203 std::string FormatFullVersion();
204
205
206
207
208
209
210
211
212
213
214
215
216
217 // Wrapper to automatically initialize mutex
218 class CCriticalSection
219 {
220 protected:
221     boost::interprocess::interprocess_recursive_mutex mutex;
222 public:
223     explicit CCriticalSection() { }
224     ~CCriticalSection() { }
225     void Enter(const char* pszName, const char* pszFile, int nLine);
226     void Leave();
227     bool TryEnter(const char* pszName, const char* pszFile, 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
236 public:
237     CCriticalBlock(CCriticalSection& csIn, const char* pszName, const char* pszFile, int nLine)
238     {
239         pcs = &csIn;
240         pcs->Enter(pszName, pszFile, nLine);
241     }
242     ~CCriticalBlock()
243     {
244         pcs->Leave();
245     }
246 };
247
248 // WARNING: This will catch continue and break!
249 // break is caught with an assertion, but there's no way to detect continue.
250 // I'd rather be careful than suffer the other more error prone syntax.
251 // The compiler will optimise away all this loop junk.
252 #define CRITICAL_BLOCK(cs)     \
253     for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by CRITICAL_BLOCK!" && !fcriticalblockonce)), fcriticalblockonce=false) \
254         for (CCriticalBlock criticalblock(cs, #cs, __FILE__, __LINE__); fcriticalblockonce; fcriticalblockonce=false)
255
256 class CTryCriticalBlock
257 {
258 protected:
259     CCriticalSection* pcs;
260
261 public:
262     CTryCriticalBlock(CCriticalSection& csIn, const char* pszName, const char* pszFile, int nLine)
263     {
264         pcs = (csIn.TryEnter(pszName, pszFile, nLine) ? &csIn : NULL);
265     }
266     ~CTryCriticalBlock()
267     {
268         if (pcs)
269         {
270             pcs->Leave();
271         }
272     }
273     bool Entered() { return pcs != NULL; }
274 };
275
276 #define TRY_CRITICAL_BLOCK(cs)     \
277     for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by TRY_CRITICAL_BLOCK!" && !fcriticalblockonce)), fcriticalblockonce=false) \
278         for (CTryCriticalBlock criticalblock(cs, #cs, __FILE__, __LINE__); fcriticalblockonce && (fcriticalblockonce = criticalblock.Entered()); fcriticalblockonce=false)
279
280
281
282
283
284
285
286
287
288
289 inline std::string i64tostr(int64 n)
290 {
291     return strprintf("%"PRI64d, n);
292 }
293
294 inline std::string itostr(int n)
295 {
296     return strprintf("%d", n);
297 }
298
299 inline int64 atoi64(const char* psz)
300 {
301 #ifdef _MSC_VER
302     return _atoi64(psz);
303 #else
304     return strtoll(psz, NULL, 10);
305 #endif
306 }
307
308 inline int64 atoi64(const std::string& str)
309 {
310 #ifdef _MSC_VER
311     return _atoi64(str.c_str());
312 #else
313     return strtoll(str.c_str(), NULL, 10);
314 #endif
315 }
316
317 inline int atoi(const std::string& str)
318 {
319     return atoi(str.c_str());
320 }
321
322 inline int roundint(double d)
323 {
324     return (int)(d > 0 ? d + 0.5 : d - 0.5);
325 }
326
327 inline int64 roundint64(double d)
328 {
329     return (int64)(d > 0 ? d + 0.5 : d - 0.5);
330 }
331
332 inline int64 abs64(int64 n)
333 {
334     return (n >= 0 ? n : -n);
335 }
336
337 template<typename T>
338 std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
339 {
340     if (itbegin == itend)
341         return "";
342     const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
343     const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
344     std::string str;
345     str.reserve((pend-pbegin) * (fSpaces ? 3 : 2));
346     for (const unsigned char* p = pbegin; p != pend; p++)
347         str += strprintf((fSpaces && p != pend-1 ? "%02x " : "%02x"), *p);
348     return str;
349 }
350
351 inline std::string HexStr(const std::vector<unsigned char>& vch, bool fSpaces=false)
352 {
353     return HexStr(vch.begin(), vch.end(), fSpaces);
354 }
355
356 template<typename T>
357 std::string HexNumStr(const T itbegin, const T itend, bool f0x=true)
358 {
359     if (itbegin == itend)
360         return "";
361     const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
362     const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
363     std::string str = (f0x ? "0x" : "");
364     str.reserve(str.size() + (pend-pbegin) * 2);
365     for (const unsigned char* p = pend-1; p >= pbegin; p--)
366         str += strprintf("%02x", *p);
367     return str;
368 }
369
370 inline std::string HexNumStr(const std::vector<unsigned char>& vch, bool f0x=true)
371 {
372     return HexNumStr(vch.begin(), vch.end(), f0x);
373 }
374
375 template<typename T>
376 void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)
377 {
378     printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());
379 }
380
381 inline void PrintHex(const std::vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true)
382 {
383     printf(pszFormat, HexStr(vch, fSpaces).c_str());
384 }
385
386 inline int64 GetPerformanceCounter()
387 {
388     int64 nCounter = 0;
389 #ifdef __WXMSW__
390     QueryPerformanceCounter((LARGE_INTEGER*)&nCounter);
391 #else
392     timeval t;
393     gettimeofday(&t, NULL);
394     nCounter = t.tv_sec * 1000000 + t.tv_usec;
395 #endif
396     return nCounter;
397 }
398
399 inline int64 GetTimeMillis()
400 {
401     return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) -
402             boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
403 }
404
405 inline std::string DateTimeStrFormat(const char* pszFormat, int64 nTime)
406 {
407     time_t n = nTime;
408     struct tm* ptmTime = gmtime(&n);
409     char pszTime[200];
410     strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime);
411     return pszTime;
412 }
413
414 template<typename T>
415 void skipspaces(T& it)
416 {
417     while (isspace(*it))
418         ++it;
419 }
420
421 inline bool IsSwitchChar(char c)
422 {
423 #ifdef __WXMSW__
424     return c == '-' || c == '/';
425 #else
426     return c == '-';
427 #endif
428 }
429
430 inline std::string GetArg(const std::string& strArg, const std::string& strDefault)
431 {
432     if (mapArgs.count(strArg))
433         return mapArgs[strArg];
434     return strDefault;
435 }
436
437 inline int64 GetArg(const std::string& strArg, int64 nDefault)
438 {
439     if (mapArgs.count(strArg))
440         return atoi64(mapArgs[strArg]);
441     return nDefault;
442 }
443
444 inline bool GetBoolArg(const std::string& strArg)
445 {
446     if (mapArgs.count(strArg))
447     {
448         if (mapArgs[strArg].empty())
449             return true;
450         return (atoi(mapArgs[strArg]) != 0);
451     }
452     return false;
453 }
454
455
456
457
458
459
460
461
462
463
464 inline void heapchk()
465 {
466 #ifdef __WXMSW__
467     /// for debugging
468     //if (_heapchk() != _HEAPOK)
469     //    DebugBreak();
470 #endif
471 }
472
473 // Randomize the stack to help protect against buffer overrun exploits
474 #define IMPLEMENT_RANDOMIZE_STACK(ThreadFn)     \
475     {                                           \
476         static char nLoops;                     \
477         if (nLoops <= 0)                        \
478             nLoops = GetRand(20) + 1;           \
479         if (nLoops-- > 1)                       \
480         {                                       \
481             ThreadFn;                           \
482             return;                             \
483         }                                       \
484     }
485
486 #define CATCH_PRINT_EXCEPTION(pszFn)     \
487     catch (std::exception& e) {          \
488         PrintException(&e, (pszFn));     \
489     } catch (...) {                      \
490         PrintException(NULL, (pszFn));   \
491     }
492
493
494
495
496
497
498
499
500
501
502 template<typename T1>
503 inline uint256 Hash(const T1 pbegin, const T1 pend)
504 {
505     static unsigned char pblank[1];
506     uint256 hash1;
507     SHA256((pbegin == pend ? pblank : (unsigned char*)&pbegin[0]), (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);
508     uint256 hash2;
509     SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
510     return hash2;
511 }
512
513 template<typename T1, typename T2>
514 inline uint256 Hash(const T1 p1begin, const T1 p1end,
515                     const T2 p2begin, const T2 p2end)
516 {
517     static unsigned char pblank[1];
518     uint256 hash1;
519     SHA256_CTX ctx;
520     SHA256_Init(&ctx);
521     SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
522     SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[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 T1, typename T2, typename T3>
530 inline uint256 Hash(const T1 p1begin, const T1 p1end,
531                     const T2 p2begin, const T2 p2end,
532                     const T3 p3begin, const T3 p3end)
533 {
534     static unsigned char pblank[1];
535     uint256 hash1;
536     SHA256_CTX ctx;
537     SHA256_Init(&ctx);
538     SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
539     SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
540     SHA256_Update(&ctx, (p3begin == p3end ? pblank : (unsigned char*)&p3begin[0]), (p3end - p3begin) * sizeof(p3begin[0]));
541     SHA256_Final((unsigned char*)&hash1, &ctx);
542     uint256 hash2;
543     SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
544     return hash2;
545 }
546
547 template<typename T>
548 uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=VERSION)
549 {
550     // Most of the time is spent allocating and deallocating CDataStream's
551     // buffer.  If this ever needs to be optimized further, make a CStaticStream
552     // class with its buffer on the stack.
553     CDataStream ss(nType, nVersion);
554     ss.reserve(10000);
555     ss << obj;
556     return Hash(ss.begin(), ss.end());
557 }
558
559 inline uint160 Hash160(const std::vector<unsigned char>& vch)
560 {
561     uint256 hash1;
562     SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);
563     uint160 hash2;
564     RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
565     return hash2;
566 }
567
568
569
570
571
572
573
574
575
576
577
578 // Note: It turns out we might have been able to use boost::thread
579 // by using TerminateThread(boost::thread.native_handle(), 0);
580 #ifdef __WXMSW__
581 typedef HANDLE pthread_t;
582
583 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
584 {
585     DWORD nUnused = 0;
586     HANDLE hthread =
587         CreateThread(
588             NULL,                        // default security
589             0,                           // inherit stack size from parent
590             (LPTHREAD_START_ROUTINE)pfn, // function pointer
591             parg,                        // argument
592             0,                           // creation option, start immediately
593             &nUnused);                   // thread identifier
594     if (hthread == NULL)
595     {
596         printf("Error: CreateThread() returned %d\n", GetLastError());
597         return (pthread_t)0;
598     }
599     if (!fWantHandle)
600     {
601         CloseHandle(hthread);
602         return (pthread_t)-1;
603     }
604     return hthread;
605 }
606
607 inline void SetThreadPriority(int nPriority)
608 {
609     SetThreadPriority(GetCurrentThread(), nPriority);
610 }
611 #else
612 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
613 {
614     pthread_t hthread = 0;
615     int ret = pthread_create(&hthread, NULL, (void*(*)(void*))pfn, parg);
616     if (ret != 0)
617     {
618         printf("Error: pthread_create() returned %d\n", ret);
619         return (pthread_t)0;
620     }
621     if (!fWantHandle)
622     {
623         pthread_detach(hthread);
624         return (pthread_t)-1;
625     }
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(size_t 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