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