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