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