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