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
6 #if defined(_MSC_VER) || defined(__BORLANDC__)
\r
7 typedef __int64 int64;
\r
8 typedef unsigned __int64 uint64;
\r
10 typedef long long int64;
\r
11 typedef unsigned long long uint64;
\r
13 #if defined(_MSC_VER) && _MSC_VER < 1300
\r
14 #define for if (false) ; else for
\r
17 #define __forceinline inline
\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
32 #define snprintf my_snprintf
\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
40 #define PRI64d "lld"
\r
41 #define PRI64u "llu"
\r
42 #define PRI64x "llx"
\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
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
58 static const bool fWindows = true;
\r
59 #define MSG_NOSIGNAL 0
\r
60 #define MSG_DONTWAIT 0
\r
62 #define UINT64_MAX _UI64_MAX
\r
63 #define INT64_MAX _I64_MAX
\r
64 #define INT64_MIN _I64_MIN
\r
67 #define S_IRUSR 0400
\r
68 #define S_IWUSR 0200
\r
70 #define unlink _unlink
\r
71 typedef int socklen_t;
\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
93 inline int myclosesocket(SOCKET& hSocket)
\r
95 if (hSocket == INVALID_SOCKET)
\r
98 int ret = closesocket(hSocket);
\r
100 int ret = close(hSocket);
\r
102 hSocket = INVALID_SOCKET;
\r
105 #define closesocket(s) myclosesocket(s)
\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
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 string GetDataDir();
\r
145 void ShrinkDebugFile();
\r
146 uint64 GetRand(uint64 nMax);
\r
148 int64 GetAdjustedTime();
\r
149 void AddTimeData(unsigned int ip, int64 nTime);
\r
163 // Wrapper to automatically initialize critical sections
\r
164 class CCriticalSection
\r
168 CRITICAL_SECTION cs;
\r
170 explicit CCriticalSection() { InitializeCriticalSection(&cs); }
\r
171 ~CCriticalSection() { DeleteCriticalSection(&cs); }
\r
172 void Enter() { EnterCriticalSection(&cs); }
\r
173 void Leave() { LeaveCriticalSection(&cs); }
\r
174 bool TryEnter() { return TryEnterCriticalSection(&cs); }
\r
179 explicit CCriticalSection() : mutex(wxMUTEX_RECURSIVE) { }
\r
180 ~CCriticalSection() { }
\r
181 void Enter() { mutex.Lock(); }
\r
182 void Leave() { mutex.Unlock(); }
\r
183 bool TryEnter() { return mutex.TryLock() == wxMUTEX_NO_ERROR; }
\r
186 const char* pszFile;
\r
190 // Automatically leave critical section when leaving block, needed for exception safety
\r
191 class CCriticalBlock
\r
194 CCriticalSection* pcs;
\r
196 CCriticalBlock(CCriticalSection& csIn) { pcs = &csIn; pcs->Enter(); }
\r
197 ~CCriticalBlock() { pcs->Leave(); }
\r
200 // WARNING: This will catch continue and break!
\r
201 // break is caught with an assertion, but there's no way to detect continue.
\r
202 // I'd rather be careful than suffer the other more error prone syntax.
\r
203 // The compiler will optimise away all this loop junk.
\r
204 #define CRITICAL_BLOCK(cs) \
\r
205 for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by CRITICAL_BLOCK!", !fcriticalblockonce)), fcriticalblockonce=false) \
\r
206 for (CCriticalBlock criticalblock(cs); fcriticalblockonce && (cs.pszFile=__FILE__, cs.nLine=__LINE__, true); fcriticalblockonce=false, cs.pszFile=NULL, cs.nLine=0)
\r
208 class CTryCriticalBlock
\r
211 CCriticalSection* pcs;
\r
213 CTryCriticalBlock(CCriticalSection& csIn) { pcs = (csIn.TryEnter() ? &csIn : NULL); }
\r
214 ~CTryCriticalBlock() { if (pcs) pcs->Leave(); }
\r
215 bool Entered() { return pcs != NULL; }
\r
218 #define TRY_CRITICAL_BLOCK(cs) \
\r
219 for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by TRY_CRITICAL_BLOCK!", !fcriticalblockonce)), fcriticalblockonce=false) \
\r
220 for (CTryCriticalBlock criticalblock(cs); fcriticalblockonce && (fcriticalblockonce = criticalblock.Entered()) && (cs.pszFile=__FILE__, cs.nLine=__LINE__, true); fcriticalblockonce=false, cs.pszFile=NULL, cs.nLine=0)
\r
231 inline string i64tostr(int64 n)
\r
233 return strprintf("%"PRI64d, n);
\r
236 inline string itostr(int n)
\r
238 return strprintf("%d", n);
\r
241 inline int64 atoi64(const char* psz)
\r
244 return _atoi64(psz);
\r
246 return strtoll(psz, NULL, 10);
\r
250 inline int64 atoi64(const string& str)
\r
253 return _atoi64(str.c_str());
\r
255 return strtoll(str.c_str(), NULL, 10);
\r
259 inline int atoi(const string& str)
\r
261 return atoi(str.c_str());
\r
264 inline int roundint(double d)
\r
266 return (int)(d > 0 ? d + 0.5 : d - 0.5);
\r
269 inline int64 roundint64(double d)
\r
271 return (int64)(d > 0 ? d + 0.5 : d - 0.5);
\r
274 template<typename T>
\r
275 string HexStr(const T itbegin, const T itend, bool fSpaces=true)
\r
277 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
\r
278 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
\r
280 for (const unsigned char* p = pbegin; p != pend; p++)
\r
281 str += strprintf((fSpaces && p != pend-1 ? "%02x " : "%02x"), *p);
\r
285 inline string HexStr(vector<unsigned char> vch, bool fSpaces=true)
\r
287 return HexStr(vch.begin(), vch.end(), fSpaces);
\r
290 template<typename T>
\r
291 string HexNumStr(const T itbegin, const T itend, bool f0x=true)
\r
293 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
\r
294 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
\r
295 string str = (f0x ? "0x" : "");
\r
296 for (const unsigned char* p = pend-1; p >= pbegin; p--)
\r
297 str += strprintf("%02X", *p);
\r
301 template<typename T>
\r
302 void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)
\r
304 printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());
\r
307 inline void PrintHex(vector<unsigned char> vch, const char* pszFormat="%s", bool fSpaces=true)
\r
309 printf(pszFormat, HexStr(vch, fSpaces).c_str());
\r
312 inline int64 PerformanceCounter()
\r
314 int64 nCounter = 0;
\r
316 QueryPerformanceCounter((LARGE_INTEGER*)&nCounter);
\r
319 gettimeofday(&t, NULL);
\r
320 nCounter = t.tv_sec * 1000000 + t.tv_usec;
\r
325 inline int64 GetTimeMillis()
\r
327 return wxGetLocalTimeMillis().GetValue();
\r
330 inline string DateTimeStrFormat(const char* pszFormat, int64 nTime)
\r
333 struct tm* ptmTime = gmtime(&n);
\r
335 strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime);
\r
339 template<typename T>
\r
340 void skipspaces(T& it)
\r
342 while (isspace(*it))
\r
357 inline void heapchk()
\r
361 //if (_heapchk() != _HEAPOK)
\r
366 // Randomize the stack to help protect against buffer overrun exploits
\r
367 #define IMPLEMENT_RANDOMIZE_STACK(ThreadFn) \
\r
369 static char nLoops; \
\r
371 nLoops = GetRand(20) + 1; \
\r
372 if (nLoops-- > 1) \
\r
379 #define CATCH_PRINT_EXCEPTION(pszFn) \
\r
380 catch (std::exception& e) { \
\r
381 PrintException(&e, (pszFn)); \
\r
383 PrintException(NULL, (pszFn)); \
\r
395 template<typename T1>
\r
396 inline uint256 Hash(const T1 pbegin, const T1 pend)
\r
399 SHA256((unsigned char*)&pbegin[0], (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);
\r
401 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
\r
405 template<typename T1, typename T2>
\r
406 inline uint256 Hash(const T1 p1begin, const T1 p1end,
\r
407 const T2 p2begin, const T2 p2end)
\r
412 SHA256_Update(&ctx, (unsigned char*)&p1begin[0], (p1end - p1begin) * sizeof(p1begin[0]));
\r
413 SHA256_Update(&ctx, (unsigned char*)&p2begin[0], (p2end - p2begin) * sizeof(p2begin[0]));
\r
414 SHA256_Final((unsigned char*)&hash1, &ctx);
\r
416 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
\r
420 template<typename T1, typename T2, typename T3>
\r
421 inline uint256 Hash(const T1 p1begin, const T1 p1end,
\r
422 const T2 p2begin, const T2 p2end,
\r
423 const T3 p3begin, const T3 p3end)
\r
428 SHA256_Update(&ctx, (unsigned char*)&p1begin[0], (p1end - p1begin) * sizeof(p1begin[0]));
\r
429 SHA256_Update(&ctx, (unsigned char*)&p2begin[0], (p2end - p2begin) * sizeof(p2begin[0]));
\r
430 SHA256_Update(&ctx, (unsigned char*)&p3begin[0], (p3end - p3begin) * sizeof(p3begin[0]));
\r
431 SHA256_Final((unsigned char*)&hash1, &ctx);
\r
433 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
\r
437 template<typename T>
\r
438 uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=VERSION)
\r
440 // Most of the time is spent allocating and deallocating CDataStream's
\r
441 // buffer. If this ever needs to be optimized further, make a CStaticStream
\r
442 // class with its buffer on the stack.
\r
443 CDataStream ss(nType, nVersion);
\r
446 return Hash(ss.begin(), ss.end());
\r
449 inline uint160 Hash160(const vector<unsigned char>& vch)
\r
452 SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);
\r
454 RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
\r
468 // Note: It turns out we might have been able to use boost::thread
\r
469 // by using TerminateThread(boost::thread.native_handle(), 0);
\r
471 typedef HANDLE pthread_t;
\r
473 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
\r
478 NULL, // default security
\r
479 0, // inherit stack size from parent
\r
480 (LPTHREAD_START_ROUTINE)pfn, // function pointer
\r
482 0, // creation option, start immediately
\r
483 &nUnused); // thread identifier
\r
484 if (hthread == NULL)
\r
486 printf("Error: CreateThread() returned %d\n", GetLastError());
\r
487 return (pthread_t)0;
\r
491 CloseHandle(hthread);
\r
492 return (pthread_t)-1;
\r
497 inline void SetThreadPriority(int nPriority)
\r
499 SetThreadPriority(GetCurrentThread(), nPriority);
\r
502 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
\r
504 pthread_t hthread = 0;
\r
505 int ret = pthread_create(&hthread, NULL, (void*(*)(void*))pfn, parg);
\r
508 printf("Error: pthread_create() returned %d\n", ret);
\r
509 return (pthread_t)0;
\r
512 return (pthread_t)-1;
\r
516 #define THREAD_PRIORITY_LOWEST PRIO_MIN
\r
517 #define THREAD_PRIORITY_BELOW_NORMAL 2
\r
518 #define THREAD_PRIORITY_NORMAL 0
\r
519 #define THREAD_PRIORITY_ABOVE_NORMAL 0
\r
521 inline void SetThreadPriority(int nPriority)
\r
523 // It's unclear if it's even possible to change thread priorities on Linux,
\r
524 // but we really and truly need it for the generation threads.
\r
526 setpriority(PRIO_THREAD, 0, nPriority);
\r
528 setpriority(PRIO_PROCESS, 0, nPriority);
\r
532 inline bool TerminateThread(pthread_t hthread, unsigned int nExitCode)
\r
534 return (pthread_cancel(hthread) == 0);
\r
537 inline void ExitThread(unsigned int nExitCode)
\r
539 pthread_exit((void*)nExitCode);
\r