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