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.
6 #if defined(_MSC_VER) || defined(__BORLANDC__)
8 typedef unsigned __int64 uint64;
10 typedef long long int64;
11 typedef unsigned long long uint64;
13 #if defined(_MSC_VER) && _MSC_VER < 1300
14 #define for if (false) ; else for
17 #define __forceinline inline
20 #define foreach BOOST_FOREACH
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
32 #define snprintf my_snprintf
35 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MSVCRT__)
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>
49 // Used to bypass the rule against non-const reference to temporary
50 // where it makes sense with wrappers such as CFlatData or CTxDB
52 inline T& REF(const T& val)
58 static const bool fWindows = true;
59 #define MSG_NOSIGNAL 0
60 #define MSG_DONTWAIT 0
62 #define UINT64_MAX _UI64_MAX
63 #define INT64_MAX _I64_MAX
64 #define INT64_MIN _I64_MIN
70 #define unlink _unlink
71 typedef int socklen_t;
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
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)
89 #define Sleep(n) wxMilliSleep(n)
90 #define Beep(n1,n2) (0)
93 inline int myclosesocket(SOCKET& hSocket)
95 if (hSocket == INVALID_SOCKET)
98 int ret = closesocket(hSocket);
100 int ret = close(hSocket);
102 hSocket = INVALID_SOCKET;
105 #define closesocket(s) myclosesocket(s)
116 extern map<string, string> mapArgs;
117 extern map<string, vector<string> > mapMultiArgs;
119 extern bool fPrintToConsole;
120 extern bool fPrintToDebugger;
121 extern char pszSetDataDir[MAX_PATH];
122 extern bool fShutdown;
124 extern bool fCommandLine;
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);
145 string MyGetSpecialFolderPath(int nFolder, bool fCreate);
147 string GetDefaultDataDir();
149 void ShrinkDebugFile();
150 uint64 GetRand(uint64 nMax);
152 int64 GetAdjustedTime();
153 void AddTimeData(unsigned int ip, int64 nTime);
167 // Wrapper to automatically initialize critical sections
168 class CCriticalSection
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); }
181 boost::interprocess::interprocess_recursive_mutex mutex;
183 explicit CCriticalSection() { }
184 ~CCriticalSection() { }
185 void Enter() { mutex.lock(); }
186 void Leave() { mutex.unlock(); }
187 bool TryEnter() { return mutex.try_lock(); }
194 // Automatically leave critical section when leaving block, needed for exception safety
198 CCriticalSection* pcs;
200 CCriticalBlock(CCriticalSection& csIn) { pcs = &csIn; pcs->Enter(); }
201 ~CCriticalBlock() { pcs->Leave(); }
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)
212 class CTryCriticalBlock
215 CCriticalSection* pcs;
217 CTryCriticalBlock(CCriticalSection& csIn) { pcs = (csIn.TryEnter() ? &csIn : NULL); }
218 ~CTryCriticalBlock() { if (pcs) pcs->Leave(); }
219 bool Entered() { return pcs != NULL; }
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)
235 inline string i64tostr(int64 n)
237 return strprintf("%"PRI64d, n);
240 inline string itostr(int n)
242 return strprintf("%d", n);
245 inline int64 atoi64(const char* psz)
250 return strtoll(psz, NULL, 10);
254 inline int64 atoi64(const string& str)
257 return _atoi64(str.c_str());
259 return strtoll(str.c_str(), NULL, 10);
263 inline int atoi(const string& str)
265 return atoi(str.c_str());
268 inline int roundint(double d)
270 return (int)(d > 0 ? d + 0.5 : d - 0.5);
273 inline int64 roundint64(double d)
275 return (int64)(d > 0 ? d + 0.5 : d - 0.5);
279 string HexStr(const T itbegin, const T itend, bool fSpaces=true)
281 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
282 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
284 for (const unsigned char* p = pbegin; p != pend; p++)
285 str += strprintf((fSpaces && p != pend-1 ? "%02x " : "%02x"), *p);
289 inline string HexStr(vector<unsigned char> vch, bool fSpaces=true)
291 return HexStr(vch.begin(), vch.end(), fSpaces);
295 string HexNumStr(const T itbegin, const T itend, bool f0x=true)
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);
306 void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)
308 printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());
311 inline void PrintHex(vector<unsigned char> vch, const char* pszFormat="%s", bool fSpaces=true)
313 printf(pszFormat, HexStr(vch, fSpaces).c_str());
316 inline int64 PerformanceCounter()
320 QueryPerformanceCounter((LARGE_INTEGER*)&nCounter);
323 gettimeofday(&t, NULL);
324 nCounter = t.tv_sec * 1000000 + t.tv_usec;
329 inline int64 GetTimeMillis()
331 return (posix_time::ptime(posix_time::microsec_clock::universal_time()) -
332 posix_time::ptime(gregorian::date(1970,1,1))).total_milliseconds();
335 inline string DateTimeStrFormat(const char* pszFormat, int64 nTime)
338 struct tm* ptmTime = gmtime(&n);
340 strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime);
345 void skipspaces(T& it)
362 inline void heapchk()
366 //if (_heapchk() != _HEAPOK)
371 // Randomize the stack to help protect against buffer overrun exploits
372 #define IMPLEMENT_RANDOMIZE_STACK(ThreadFn) \
374 static char nLoops; \
376 nLoops = GetRand(20) + 1; \
384 #define CATCH_PRINT_EXCEPTION(pszFn) \
385 catch (std::exception& e) { \
386 PrintException(&e, (pszFn)); \
388 PrintException(NULL, (pszFn)); \
400 template<typename T1>
401 inline uint256 Hash(const T1 pbegin, const T1 pend)
404 SHA256((unsigned char*)&pbegin[0], (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);
406 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
410 template<typename T1, typename T2>
411 inline uint256 Hash(const T1 p1begin, const T1 p1end,
412 const T2 p2begin, const T2 p2end)
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);
421 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
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)
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);
438 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
443 uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=VERSION)
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);
451 return Hash(ss.begin(), ss.end());
454 inline uint160 Hash160(const vector<unsigned char>& vch)
457 SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);
459 RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
473 // Note: It turns out we might have been able to use boost::thread
474 // by using TerminateThread(boost::thread.native_handle(), 0);
476 typedef HANDLE pthread_t;
478 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
483 NULL, // default security
484 0, // inherit stack size from parent
485 (LPTHREAD_START_ROUTINE)pfn, // function pointer
487 0, // creation option, start immediately
488 &nUnused); // thread identifier
491 printf("Error: CreateThread() returned %d\n", GetLastError());
496 CloseHandle(hthread);
497 return (pthread_t)-1;
502 inline void SetThreadPriority(int nPriority)
504 SetThreadPriority(GetCurrentThread(), nPriority);
507 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
509 pthread_t hthread = 0;
510 int ret = pthread_create(&hthread, NULL, (void*(*)(void*))pfn, parg);
513 printf("Error: pthread_create() returned %d\n", ret);
517 return (pthread_t)-1;
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
526 inline void SetThreadPriority(int nPriority)
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.
531 setpriority(PRIO_THREAD, 0, nPriority);
533 setpriority(PRIO_PROCESS, 0, nPriority);
537 inline bool TerminateThread(pthread_t hthread, unsigned int nExitCode)
539 return (pthread_cancel(hthread) == 0);
542 inline void ExitThread(unsigned int nExitCode)
544 pthread_exit((void*)nExitCode);