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