Cleanup: removed dead code, and use C99 typedefs for int64 (supported by all modern...
[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 WIN32
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 typedef long long  int64;
29 typedef unsigned long long  uint64;
30
31 #define loop                for (;;)
32 #define BEGIN(a)            ((char*)&(a))
33 #define END(a)              ((char*)&((&(a))[1]))
34 #define UBEGIN(a)           ((unsigned char*)&(a))
35 #define UEND(a)             ((unsigned char*)&((&(a))[1]))
36 #define ARRAYLEN(array)     (sizeof(array)/sizeof((array)[0]))
37 #define printf              OutputDebugStringF
38
39 #ifdef snprintf
40 #undef snprintf
41 #endif
42 #define snprintf my_snprintf
43
44 #ifndef PRI64d
45 #if defined(_MSC_VER) || defined(__MSVCRT__)
46 #define PRI64d  "I64d"
47 #define PRI64u  "I64u"
48 #define PRI64x  "I64x"
49 #else
50 #define PRI64d  "lld"
51 #define PRI64u  "llu"
52 #define PRI64x  "llx"
53 #endif
54 #endif
55
56 // This is needed because the foreach macro can't get over the comma in pair<t1, t2>
57 #define PAIRTYPE(t1, t2)    std::pair<t1, t2>
58
59 // Align by increasing pointer, must have extra space at end of buffer
60 template <size_t nBytes, typename T>
61 T* alignup(T* p)
62 {
63     union
64     {
65         T* ptr;
66         size_t n;
67     } u;
68     u.ptr = p;
69     u.n = (u.n + (nBytes-1)) & ~(nBytes-1);
70     return u.ptr;
71 }
72
73 #ifdef WIN32
74 #define MSG_NOSIGNAL        0
75 #define MSG_DONTWAIT        0
76 #ifndef UINT64_MAX
77 #define UINT64_MAX          _UI64_MAX
78 #define INT64_MAX           _I64_MAX
79 #define INT64_MIN           _I64_MIN
80 #endif
81 #ifndef S_IRUSR
82 #define S_IRUSR             0400
83 #define S_IWUSR             0200
84 #endif
85 #define unlink              _unlink
86 typedef int socklen_t;
87 #else
88 #define WSAGetLastError()   errno
89 #define WSAEINVAL           EINVAL
90 #define WSAEALREADY         EALREADY
91 #define WSAEWOULDBLOCK      EWOULDBLOCK
92 #define WSAEMSGSIZE         EMSGSIZE
93 #define WSAEINTR            EINTR
94 #define WSAEINPROGRESS      EINPROGRESS
95 #define WSAEADDRINUSE       EADDRINUSE
96 #define WSAENOTSOCK         EBADF
97 #define INVALID_SOCKET      (SOCKET)(~0)
98 #define SOCKET_ERROR        -1
99 typedef u_int SOCKET;
100 #define _vsnprintf(a,b,c,d) vsnprintf(a,b,c,d)
101 #define strlwr(psz)         to_lower(psz)
102 #define _strlwr(psz)        to_lower(psz)
103 #define MAX_PATH            1024
104 #define Beep(n1,n2)         (0)
105 inline void Sleep(int64 n)
106 {
107     boost::thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(n));
108 }
109 #endif
110
111 inline int myclosesocket(SOCKET& hSocket)
112 {
113     if (hSocket == INVALID_SOCKET)
114         return WSAENOTSOCK;
115 #ifdef WIN32
116     int ret = closesocket(hSocket);
117 #else
118     int ret = close(hSocket);
119 #endif
120     hSocket = INVALID_SOCKET;
121     return ret;
122 }
123 #define closesocket(s)      myclosesocket(s)
124 #if !defined(QT_GUI)
125 inline const char* _(const char* psz)
126 {
127     return psz;
128 }
129 #endif
130
131
132
133
134
135
136
137
138
139 extern std::map<std::string, std::string> mapArgs;
140 extern std::map<std::string, std::vector<std::string> > mapMultiArgs;
141 extern bool fDebug;
142 extern bool fPrintToConsole;
143 extern bool fPrintToDebugger;
144 extern char pszSetDataDir[MAX_PATH];
145 extern bool fRequestShutdown;
146 extern bool fShutdown;
147 extern bool fDaemon;
148 extern bool fServer;
149 extern bool fCommandLine;
150 extern std::string strMiscWarning;
151 extern bool fTestNet;
152 extern bool fNoListen;
153 extern bool fLogTimestamps;
154
155 void RandAddSeed();
156 void RandAddSeedPerfmon();
157 int OutputDebugStringF(const char* pszFormat, ...);
158 int my_snprintf(char* buffer, size_t limit, const char* format, ...);
159 std::string strprintf(const std::string &format, ...);
160 bool error(const std::string &format, ...);
161 void LogException(std::exception* pex, const char* pszThread);
162 void PrintException(std::exception* pex, const char* pszThread);
163 void PrintExceptionContinue(std::exception* pex, const char* pszThread);
164 void ParseString(const std::string& str, char c, std::vector<std::string>& v);
165 std::string FormatMoney(int64 n, bool fPlus=false);
166 bool ParseMoney(const std::string& str, int64& nRet);
167 bool ParseMoney(const char* pszIn, int64& nRet);
168 std::vector<unsigned char> ParseHex(const char* psz);
169 std::vector<unsigned char> ParseHex(const std::string& str);
170 std::vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid = NULL);
171 std::string DecodeBase64(const std::string& str);
172 std::string EncodeBase64(const unsigned char* pch, size_t len);
173 std::string EncodeBase64(const std::string& str);
174 void ParseParameters(int argc, char* argv[]);
175 bool WildcardMatch(const char* psz, const char* mask);
176 bool WildcardMatch(const std::string& str, const std::string& mask);
177 int GetFilesize(FILE* file);
178 void GetDataDir(char* pszDirRet);
179 std::string GetConfigFile();
180 std::string GetPidFile();
181 void CreatePidFile(std::string pidFile, pid_t pid);
182 void ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet, std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet);
183 #ifdef WIN32
184 std::string MyGetSpecialFolderPath(int nFolder, bool fCreate);
185 #endif
186 std::string GetDefaultDataDir();
187 std::string GetDataDir();
188 void ShrinkDebugFile();
189 int GetRandInt(int nMax);
190 uint64 GetRand(uint64 nMax);
191 int64 GetTime();
192 void SetMockTime(int64 nMockTimeIn);
193 int64 GetAdjustedTime();
194 void AddTimeData(unsigned int ip, int64 nTime);
195 std::string FormatFullVersion();
196 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments);
197
198
199
200
201
202
203
204
205
206
207
208
209 // Wrapper to automatically initialize mutex
210 class CCriticalSection
211 {
212 protected:
213     boost::interprocess::interprocess_recursive_mutex mutex;
214 public:
215     explicit CCriticalSection() { }
216     ~CCriticalSection() { }
217     void Enter(const char* pszName, const char* pszFile, int nLine);
218     void Leave();
219     bool TryEnter(const char* pszName, const char* pszFile, int nLine);
220 };
221
222 // Automatically leave critical section when leaving block, needed for exception safety
223 class CCriticalBlock
224 {
225 protected:
226     CCriticalSection* pcs;
227
228 public:
229     CCriticalBlock(CCriticalSection& csIn, const char* pszName, const char* pszFile, int nLine)
230     {
231         pcs = &csIn;
232         pcs->Enter(pszName, pszFile, nLine);
233     }
234
235     operator bool() const
236     {
237         return true;
238     }
239
240     ~CCriticalBlock()
241     {
242         pcs->Leave();
243     }
244 };
245
246 #define CRITICAL_BLOCK(cs)     \
247     if (CCriticalBlock criticalblock = CCriticalBlock(cs, #cs, __FILE__, __LINE__))
248
249 class CTryCriticalBlock
250 {
251 protected:
252     CCriticalSection* pcs;
253
254 public:
255     CTryCriticalBlock(CCriticalSection& csIn, const char* pszName, const char* pszFile, int nLine)
256     {
257         pcs = (csIn.TryEnter(pszName, pszFile, nLine) ? &csIn : NULL);
258     }
259
260     operator bool() const
261     {
262         return Entered();
263     }
264
265     ~CTryCriticalBlock()
266     {
267         if (pcs)
268         {
269             pcs->Leave();
270         }
271     }
272     bool Entered() const { return pcs != NULL; }
273 };
274
275 #define TRY_CRITICAL_BLOCK(cs)     \
276     if (CTryCriticalBlock criticalblock = CTryCriticalBlock(cs, #cs, __FILE__, __LINE__))
277
278
279
280
281
282
283 // This is exactly like std::string, but with a custom allocator.
284 // (secure_allocator<> is defined in serialize.h)
285 typedef std::basic_string<char, std::char_traits<char>, secure_allocator<char> > SecureString;
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 WIN32
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 WIN32
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 // Randomize the stack to help protect against buffer overrun exploits
467 #define IMPLEMENT_RANDOMIZE_STACK(ThreadFn)     \
468     {                                           \
469         static char nLoops;                     \
470         if (nLoops <= 0)                        \
471             nLoops = GetRand(20) + 1;           \
472         if (nLoops-- > 1)                       \
473         {                                       \
474             ThreadFn;                           \
475             return;                             \
476         }                                       \
477     }
478
479 #define CATCH_PRINT_EXCEPTION(pszFn)     \
480     catch (std::exception& e) {          \
481         PrintException(&e, (pszFn));     \
482     } catch (...) {                      \
483         PrintException(NULL, (pszFn));   \
484     }
485
486
487
488
489
490
491
492
493
494
495 template<typename T1>
496 inline uint256 Hash(const T1 pbegin, const T1 pend)
497 {
498     static unsigned char pblank[1];
499     uint256 hash1;
500     SHA256((pbegin == pend ? pblank : (unsigned char*)&pbegin[0]), (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);
501     uint256 hash2;
502     SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
503     return hash2;
504 }
505
506 template<typename T1, typename T2>
507 inline uint256 Hash(const T1 p1begin, const T1 p1end,
508                     const T2 p2begin, const T2 p2end)
509 {
510     static unsigned char pblank[1];
511     uint256 hash1;
512     SHA256_CTX ctx;
513     SHA256_Init(&ctx);
514     SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
515     SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
516     SHA256_Final((unsigned char*)&hash1, &ctx);
517     uint256 hash2;
518     SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
519     return hash2;
520 }
521
522 template<typename T1, typename T2, typename T3>
523 inline uint256 Hash(const T1 p1begin, const T1 p1end,
524                     const T2 p2begin, const T2 p2end,
525                     const T3 p3begin, const T3 p3end)
526 {
527     static unsigned char pblank[1];
528     uint256 hash1;
529     SHA256_CTX ctx;
530     SHA256_Init(&ctx);
531     SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
532     SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
533     SHA256_Update(&ctx, (p3begin == p3end ? pblank : (unsigned char*)&p3begin[0]), (p3end - p3begin) * sizeof(p3begin[0]));
534     SHA256_Final((unsigned char*)&hash1, &ctx);
535     uint256 hash2;
536     SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
537     return hash2;
538 }
539
540 template<typename T>
541 uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=PROTOCOL_VERSION)
542 {
543     // Most of the time is spent allocating and deallocating CDataStream's
544     // buffer.  If this ever needs to be optimized further, make a CStaticStream
545     // class with its buffer on the stack.
546     CDataStream ss(nType, nVersion);
547     ss.reserve(10000);
548     ss << obj;
549     return Hash(ss.begin(), ss.end());
550 }
551
552 inline uint160 Hash160(const std::vector<unsigned char>& vch)
553 {
554     uint256 hash1;
555     SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);
556     uint160 hash2;
557     RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
558     return hash2;
559 }
560
561
562 // Median filter over a stream of values
563 // Returns the median of the last N numbers
564 template <typename T> class CMedianFilter
565 {
566 private:
567     std::vector<T> vValues;
568     std::vector<T> vSorted;
569     int nSize;
570 public:
571     CMedianFilter(int size, T initial_value):
572         nSize(size)
573     {
574         vValues.reserve(size);
575         vValues.push_back(initial_value);
576         vSorted = vValues;
577     }
578     
579     void input(T value)
580     {
581         if(vValues.size() == nSize)
582         {
583             vValues.erase(vValues.begin());
584         }
585         vValues.push_back(value);
586
587         vSorted.resize(vValues.size());
588         std::copy(vValues.begin(), vValues.end(), vSorted.begin());
589         std::sort(vSorted.begin(), vSorted.end());
590     }
591
592     T median() const
593     {
594         int size = vSorted.size();
595         assert(size>0);
596         if(size & 1) // Odd number of elements
597         {
598             return vSorted[size/2];
599         }
600         else // Even number of elements
601         {
602             return (vSorted[size/2-1] + vSorted[size/2]) / 2;
603         }
604     }
605 };
606
607
608
609
610
611
612
613
614
615
616 // Note: It turns out we might have been able to use boost::thread
617 // by using TerminateThread(boost::thread.native_handle(), 0);
618 #ifdef WIN32
619 typedef HANDLE pthread_t;
620
621 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
622 {
623     DWORD nUnused = 0;
624     HANDLE hthread =
625         CreateThread(
626             NULL,                        // default security
627             0,                           // inherit stack size from parent
628             (LPTHREAD_START_ROUTINE)pfn, // function pointer
629             parg,                        // argument
630             0,                           // creation option, start immediately
631             &nUnused);                   // thread identifier
632     if (hthread == NULL)
633     {
634         printf("Error: CreateThread() returned %d\n", GetLastError());
635         return (pthread_t)0;
636     }
637     if (!fWantHandle)
638     {
639         CloseHandle(hthread);
640         return (pthread_t)-1;
641     }
642     return hthread;
643 }
644
645 inline void SetThreadPriority(int nPriority)
646 {
647     SetThreadPriority(GetCurrentThread(), nPriority);
648 }
649 #else
650 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
651 {
652     pthread_t hthread = 0;
653     int ret = pthread_create(&hthread, NULL, (void*(*)(void*))pfn, parg);
654     if (ret != 0)
655     {
656         printf("Error: pthread_create() returned %d\n", ret);
657         return (pthread_t)0;
658     }
659     if (!fWantHandle)
660     {
661         pthread_detach(hthread);
662         return (pthread_t)-1;
663     }
664     return hthread;
665 }
666
667 #define THREAD_PRIORITY_LOWEST          PRIO_MAX
668 #define THREAD_PRIORITY_BELOW_NORMAL    2
669 #define THREAD_PRIORITY_NORMAL          0
670 #define THREAD_PRIORITY_ABOVE_NORMAL    0
671
672 inline void SetThreadPriority(int nPriority)
673 {
674     // It's unclear if it's even possible to change thread priorities on Linux,
675     // but we really and truly need it for the generation threads.
676 #ifdef PRIO_THREAD
677     setpriority(PRIO_THREAD, 0, nPriority);
678 #else
679     setpriority(PRIO_PROCESS, 0, nPriority);
680 #endif
681 }
682
683 inline bool TerminateThread(pthread_t hthread, unsigned int nExitCode)
684 {
685     return (pthread_cancel(hthread) == 0);
686 }
687
688 inline void ExitThread(size_t nExitCode)
689 {
690     pthread_exit((void*)nExitCode);
691 }
692 #endif
693
694
695
696
697
698 inline bool AffinityBugWorkaround(void(*pfn)(void*))
699 {
700 #ifdef WIN32
701     // Sometimes after a few hours affinity gets stuck on one processor
702     DWORD_PTR dwProcessAffinityMask = -1;
703     DWORD_PTR dwSystemAffinityMask = -1;
704     GetProcessAffinityMask(GetCurrentProcess(), &dwProcessAffinityMask, &dwSystemAffinityMask);
705     DWORD dwPrev1 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
706     DWORD dwPrev2 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
707     if (dwPrev2 != dwProcessAffinityMask)
708     {
709         printf("AffinityBugWorkaround() : SetThreadAffinityMask=%d, ProcessAffinityMask=%d, restarting thread\n", dwPrev2, dwProcessAffinityMask);
710         if (!CreateThread(pfn, NULL))
711             printf("Error: CreateThread() failed\n");
712         return true;
713     }
714 #endif
715     return false;
716 }
717
718 inline uint32_t ByteReverse(uint32_t value)
719 {
720         value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8);
721         return (value<<16) | (value>>16);
722 }
723
724 #endif