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