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