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