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