Make sure rate-limiting code is thread-safe
[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 fCommandLine;
147 extern string strMiscWarning;
148 extern bool fTestNet;
149 extern bool fNoListen;
150
151 void RandAddSeed();
152 void RandAddSeedPerfmon();
153 int OutputDebugStringF(const char* pszFormat, ...);
154 int my_snprintf(char* buffer, size_t limit, const char* format, ...);
155 string strprintf(const char* format, ...);
156 bool error(const char* format, ...);
157 void LogException(std::exception* pex, const char* pszThread);
158 void PrintException(std::exception* pex, const char* pszThread);
159 void PrintExceptionContinue(std::exception* pex, const char* pszThread);
160 void ParseString(const string& str, char c, vector<string>& v);
161 string FormatMoney(int64 n, bool fPlus=false);
162 bool ParseMoney(const string& str, int64& nRet);
163 bool ParseMoney(const char* pszIn, int64& nRet);
164 vector<unsigned char> ParseHex(const char* psz);
165 vector<unsigned char> ParseHex(const string& str);
166 void ParseParameters(int argc, char* argv[]);
167 const char* wxGetTranslation(const char* psz);
168 bool WildcardMatch(const char* psz, const char* mask);
169 bool WildcardMatch(const string& str, const string& mask);
170 int GetFilesize(FILE* file);
171 void GetDataDir(char* pszDirRet);
172 string GetConfigFile();
173 void ReadConfigFile(map<string, string>& mapSettingsRet, map<string, vector<string> >& mapMultiSettingsRet);
174 #ifdef __WXMSW__
175 string MyGetSpecialFolderPath(int nFolder, bool fCreate);
176 #endif
177 string GetDefaultDataDir();
178 string GetDataDir();
179 void ShrinkDebugFile();
180 int GetRandInt(int nMax);
181 uint64 GetRand(uint64 nMax);
182 int64 GetTime();
183 int64 GetAdjustedTime();
184 void AddTimeData(unsigned int ip, int64 nTime);
185
186
187
188
189
190
191
192
193
194
195
196
197
198 // Wrapper to automatically initialize critical sections
199 class CCriticalSection
200 {
201 #ifdef __WXMSW__
202 protected:
203     CRITICAL_SECTION cs;
204 public:
205     explicit CCriticalSection() { InitializeCriticalSection(&cs); }
206     ~CCriticalSection() { DeleteCriticalSection(&cs); }
207     void Enter() { EnterCriticalSection(&cs); }
208     void Leave() { LeaveCriticalSection(&cs); }
209     bool TryEnter() { return TryEnterCriticalSection(&cs); }
210 #else
211 protected:
212     boost::interprocess::interprocess_recursive_mutex mutex;
213 public:
214     explicit CCriticalSection() { }
215     ~CCriticalSection() { }
216     void Enter() { mutex.lock(); }
217     void Leave() { mutex.unlock(); }
218     bool TryEnter() { return mutex.try_lock(); }
219 #endif
220 public:
221     const char* pszFile;
222     int nLine;
223 };
224
225 // Automatically leave critical section when leaving block, needed for exception safety
226 class CCriticalBlock
227 {
228 protected:
229     CCriticalSection* pcs;
230 public:
231     CCriticalBlock(CCriticalSection& csIn) { pcs = &csIn; pcs->Enter(); }
232     ~CCriticalBlock() { pcs->Leave(); }
233 };
234
235 // WARNING: This will catch continue and break!
236 // break is caught with an assertion, but there's no way to detect continue.
237 // I'd rather be careful than suffer the other more error prone syntax.
238 // The compiler will optimise away all this loop junk.
239 #define CRITICAL_BLOCK(cs)     \
240     for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by CRITICAL_BLOCK!", !fcriticalblockonce)), fcriticalblockonce=false)  \
241     for (CCriticalBlock criticalblock(cs); fcriticalblockonce && (cs.pszFile=__FILE__, cs.nLine=__LINE__, true); fcriticalblockonce=false, cs.pszFile=NULL, cs.nLine=0)
242
243 class CTryCriticalBlock
244 {
245 protected:
246     CCriticalSection* pcs;
247 public:
248     CTryCriticalBlock(CCriticalSection& csIn) { pcs = (csIn.TryEnter() ? &csIn : NULL); }
249     ~CTryCriticalBlock() { if (pcs) pcs->Leave(); }
250     bool Entered() { return pcs != NULL; }
251 };
252
253 #define TRY_CRITICAL_BLOCK(cs)     \
254     for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by TRY_CRITICAL_BLOCK!", !fcriticalblockonce)), fcriticalblockonce=false)  \
255     for (CTryCriticalBlock criticalblock(cs); fcriticalblockonce && (fcriticalblockonce = criticalblock.Entered()) && (cs.pszFile=__FILE__, cs.nLine=__LINE__, true); fcriticalblockonce=false, cs.pszFile=NULL, cs.nLine=0)
256
257
258
259
260
261
262
263
264
265
266 inline string i64tostr(int64 n)
267 {
268     return strprintf("%"PRI64d, n);
269 }
270
271 inline string itostr(int n)
272 {
273     return strprintf("%d", n);
274 }
275
276 inline int64 atoi64(const char* psz)
277 {
278 #ifdef _MSC_VER
279     return _atoi64(psz);
280 #else
281     return strtoll(psz, NULL, 10);
282 #endif
283 }
284
285 inline int64 atoi64(const string& str)
286 {
287 #ifdef _MSC_VER
288     return _atoi64(str.c_str());
289 #else
290     return strtoll(str.c_str(), NULL, 10);
291 #endif
292 }
293
294 inline int atoi(const string& str)
295 {
296     return atoi(str.c_str());
297 }
298
299 inline int roundint(double d)
300 {
301     return (int)(d > 0 ? d + 0.5 : d - 0.5);
302 }
303
304 inline int64 roundint64(double d)
305 {
306     return (int64)(d > 0 ? d + 0.5 : d - 0.5);
307 }
308
309 inline int64 abs64(int64 n)
310 {
311     return (n >= 0 ? n : -n);
312 }
313
314 template<typename T>
315 string HexStr(const T itbegin, const T itend, bool fSpaces=false)
316 {
317     if (itbegin == itend)
318         return "";
319     const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
320     const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
321     string str;
322     str.reserve((pend-pbegin) * (fSpaces ? 3 : 2));
323     for (const unsigned char* p = pbegin; p != pend; p++)
324         str += strprintf((fSpaces && p != pend-1 ? "%02x " : "%02x"), *p);
325     return str;
326 }
327
328 inline string HexStr(const vector<unsigned char>& vch, bool fSpaces=false)
329 {
330     return HexStr(vch.begin(), vch.end(), fSpaces);
331 }
332
333 template<typename T>
334 string HexNumStr(const T itbegin, const T itend, bool f0x=true)
335 {
336     if (itbegin == itend)
337         return "";
338     const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
339     const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
340     string str = (f0x ? "0x" : "");
341     str.reserve(str.size() + (pend-pbegin) * 2);
342     for (const unsigned char* p = pend-1; p >= pbegin; p--)
343         str += strprintf("%02x", *p);
344     return str;
345 }
346
347 inline string HexNumStr(const vector<unsigned char>& vch, bool f0x=true)
348 {
349     return HexNumStr(vch.begin(), vch.end(), f0x);
350 }
351
352 template<typename T>
353 void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)
354 {
355     printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());
356 }
357
358 inline void PrintHex(const vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true)
359 {
360     printf(pszFormat, HexStr(vch, fSpaces).c_str());
361 }
362
363 inline int64 GetPerformanceCounter()
364 {
365     int64 nCounter = 0;
366 #ifdef __WXMSW__
367     QueryPerformanceCounter((LARGE_INTEGER*)&nCounter);
368 #else
369     timeval t;
370     gettimeofday(&t, NULL);
371     nCounter = t.tv_sec * 1000000 + t.tv_usec;
372 #endif
373     return nCounter;
374 }
375
376 inline int64 GetTimeMillis()
377 {
378     return (posix_time::ptime(posix_time::microsec_clock::universal_time()) -
379             posix_time::ptime(gregorian::date(1970,1,1))).total_milliseconds();
380 }
381
382 inline string DateTimeStrFormat(const char* pszFormat, int64 nTime)
383 {
384     time_t n = nTime;
385     struct tm* ptmTime = gmtime(&n);
386     char pszTime[200];
387     strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime);
388     return pszTime;
389 }
390
391 template<typename T>
392 void skipspaces(T& it)
393 {
394     while (isspace(*it))
395         ++it;
396 }
397
398 inline bool IsSwitchChar(char c)
399 {
400 #ifdef __WXMSW__
401     return c == '-' || c == '/';
402 #else
403     return c == '-';
404 #endif
405 }
406
407 inline string GetArg(const string& strArg, const string& strDefault)
408 {
409     if (mapArgs.count(strArg))
410         return mapArgs[strArg];
411     return strDefault;
412 }
413
414 inline int64 GetArg(const string& strArg, int64 nDefault)
415 {
416     if (mapArgs.count(strArg))
417         return atoi64(mapArgs[strArg]);
418     return nDefault;
419 }
420
421 inline bool GetBoolArg(const string& strArg)
422 {
423     if (mapArgs.count(strArg))
424     {
425         if (mapArgs[strArg].empty())
426             return true;
427         return (atoi(mapArgs[strArg]) != 0);
428     }
429     return false;
430 }
431
432 inline string FormatVersion(int nVersion)
433 {
434     if (nVersion%100 == 0)
435         return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
436     else
437         return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
438 }
439
440
441
442
443
444
445
446
447
448
449 inline void heapchk()
450 {
451 #ifdef __WXMSW__
452     /// for debugging
453     //if (_heapchk() != _HEAPOK)
454     //    DebugBreak();
455 #endif
456 }
457
458 // Randomize the stack to help protect against buffer overrun exploits
459 #define IMPLEMENT_RANDOMIZE_STACK(ThreadFn)     \
460     {                                           \
461         static char nLoops;                     \
462         if (nLoops <= 0)                        \
463             nLoops = GetRand(20) + 1;           \
464         if (nLoops-- > 1)                       \
465         {                                       \
466             ThreadFn;                           \
467             return;                             \
468         }                                       \
469     }
470
471 #define CATCH_PRINT_EXCEPTION(pszFn)     \
472     catch (std::exception& e) {          \
473         PrintException(&e, (pszFn));     \
474     } catch (...) {                      \
475         PrintException(NULL, (pszFn));   \
476     }
477
478
479
480
481
482
483
484
485
486
487 template<typename T1>
488 inline uint256 Hash(const T1 pbegin, const T1 pend)
489 {
490     static unsigned char pblank[1];
491     uint256 hash1;
492     SHA256((pbegin == pend ? pblank : (unsigned char*)&pbegin[0]), (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);
493     uint256 hash2;
494     SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
495     return hash2;
496 }
497
498 template<typename T1, typename T2>
499 inline uint256 Hash(const T1 p1begin, const T1 p1end,
500                     const T2 p2begin, const T2 p2end)
501 {
502     static unsigned char pblank[1];
503     uint256 hash1;
504     SHA256_CTX ctx;
505     SHA256_Init(&ctx);
506     SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
507     SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[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 T1, typename T2, typename T3>
515 inline uint256 Hash(const T1 p1begin, const T1 p1end,
516                     const T2 p2begin, const T2 p2end,
517                     const T3 p3begin, const T3 p3end)
518 {
519     static unsigned char pblank[1];
520     uint256 hash1;
521     SHA256_CTX ctx;
522     SHA256_Init(&ctx);
523     SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
524     SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
525     SHA256_Update(&ctx, (p3begin == p3end ? pblank : (unsigned char*)&p3begin[0]), (p3end - p3begin) * sizeof(p3begin[0]));
526     SHA256_Final((unsigned char*)&hash1, &ctx);
527     uint256 hash2;
528     SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
529     return hash2;
530 }
531
532 template<typename T>
533 uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=VERSION)
534 {
535     // Most of the time is spent allocating and deallocating CDataStream's
536     // buffer.  If this ever needs to be optimized further, make a CStaticStream
537     // class with its buffer on the stack.
538     CDataStream ss(nType, nVersion);
539     ss.reserve(10000);
540     ss << obj;
541     return Hash(ss.begin(), ss.end());
542 }
543
544 inline uint160 Hash160(const vector<unsigned char>& vch)
545 {
546     uint256 hash1;
547     SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);
548     uint160 hash2;
549     RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
550     return hash2;
551 }
552
553
554
555
556
557
558
559
560
561
562
563 // Note: It turns out we might have been able to use boost::thread
564 // by using TerminateThread(boost::thread.native_handle(), 0);
565 #ifdef __WXMSW__
566 typedef HANDLE pthread_t;
567
568 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
569 {
570     DWORD nUnused = 0;
571     HANDLE hthread =
572         CreateThread(
573             NULL,                        // default security
574             0,                           // inherit stack size from parent
575             (LPTHREAD_START_ROUTINE)pfn, // function pointer
576             parg,                        // argument
577             0,                           // creation option, start immediately
578             &nUnused);                   // thread identifier
579     if (hthread == NULL)
580     {
581         printf("Error: CreateThread() returned %d\n", GetLastError());
582         return (pthread_t)0;
583     }
584     if (!fWantHandle)
585     {
586         CloseHandle(hthread);
587         return (pthread_t)-1;
588     }
589     return hthread;
590 }
591
592 inline void SetThreadPriority(int nPriority)
593 {
594     SetThreadPriority(GetCurrentThread(), nPriority);
595 }
596 #else
597 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
598 {
599     pthread_t hthread = 0;
600     int ret = pthread_create(&hthread, NULL, (void*(*)(void*))pfn, parg);
601     if (ret != 0)
602     {
603         printf("Error: pthread_create() returned %d\n", ret);
604         return (pthread_t)0;
605     }
606     if (!fWantHandle)
607         return (pthread_t)-1;
608     return hthread;
609 }
610
611 #define THREAD_PRIORITY_LOWEST          PRIO_MAX
612 #define THREAD_PRIORITY_BELOW_NORMAL    2
613 #define THREAD_PRIORITY_NORMAL          0
614 #define THREAD_PRIORITY_ABOVE_NORMAL    0
615
616 inline void SetThreadPriority(int nPriority)
617 {
618     // It's unclear if it's even possible to change thread priorities on Linux,
619     // but we really and truly need it for the generation threads.
620 #ifdef PRIO_THREAD
621     setpriority(PRIO_THREAD, 0, nPriority);
622 #else
623     setpriority(PRIO_PROCESS, 0, nPriority);
624 #endif
625 }
626
627 inline bool TerminateThread(pthread_t hthread, unsigned int nExitCode)
628 {
629     return (pthread_cancel(hthread) == 0);
630 }
631
632 inline void ExitThread(unsigned int nExitCode)
633 {
634     pthread_exit((void*)nExitCode);
635 }
636 #endif
637
638
639
640
641
642 inline bool AffinityBugWorkaround(void(*pfn)(void*))
643 {
644 #ifdef __WXMSW__
645     // Sometimes after a few hours affinity gets stuck on one processor
646     DWORD dwProcessAffinityMask = -1;
647     DWORD dwSystemAffinityMask = -1;
648     GetProcessAffinityMask(GetCurrentProcess(), &dwProcessAffinityMask, &dwSystemAffinityMask);
649     DWORD dwPrev1 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
650     DWORD dwPrev2 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
651     if (dwPrev2 != dwProcessAffinityMask)
652     {
653         printf("AffinityBugWorkaround() : SetThreadAffinityMask=%d, ProcessAffinityMask=%d, restarting thread\n", dwPrev2, dwProcessAffinityMask);
654         if (!CreateThread(pfn, NULL))
655             printf("Error: CreateThread() failed\n");
656         return true;
657     }
658 #endif
659     return false;
660 }