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