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)
57 // Align by increasing pointer, must have extra space at end of buffer
58 template <size_t nBytes, typename T>
67 u.n = (u.n + (nBytes-1)) & ~(nBytes-1);
72 #define MSG_NOSIGNAL 0
73 #define MSG_DONTWAIT 0
75 #define UINT64_MAX _UI64_MAX
76 #define INT64_MAX _I64_MAX
77 #define INT64_MIN _I64_MIN
83 #define unlink _unlink
84 typedef int socklen_t;
86 #define WSAGetLastError() errno
87 #define WSAEWOULDBLOCK EWOULDBLOCK
88 #define WSAEMSGSIZE EMSGSIZE
89 #define WSAEINTR EINTR
90 #define WSAEINPROGRESS EINPROGRESS
91 #define WSAEADDRINUSE EADDRINUSE
92 #define WSAENOTSOCK EBADF
93 #define INVALID_SOCKET (SOCKET)(~0)
94 #define SOCKET_ERROR -1
96 #define _vsnprintf(a,b,c,d) vsnprintf(a,b,c,d)
97 #define strlwr(psz) to_lower(psz)
98 #define _strlwr(psz) to_lower(psz)
100 #define Beep(n1,n2) (0)
101 inline void Sleep(int64 n)
103 boost::thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(n));
107 inline int myclosesocket(SOCKET& hSocket)
109 if (hSocket == INVALID_SOCKET)
112 int ret = closesocket(hSocket);
114 int ret = close(hSocket);
116 hSocket = INVALID_SOCKET;
119 #define closesocket(s) myclosesocket(s)
122 inline const char* _(const char* psz)
137 extern map<string, string> mapArgs;
138 extern map<string, vector<string> > mapMultiArgs;
140 extern bool fPrintToConsole;
141 extern bool fPrintToDebugger;
142 extern char pszSetDataDir[MAX_PATH];
143 extern bool fShutdown;
145 extern bool fCommandLine;
148 void RandAddSeedPerfmon();
149 int OutputDebugStringF(const char* pszFormat, ...);
150 int my_snprintf(char* buffer, size_t limit, const char* format, ...);
151 string strprintf(const char* format, ...);
152 bool error(const char* format, ...);
153 void PrintException(std::exception* pex, const char* pszThread);
154 void LogException(std::exception* pex, const char* pszThread);
155 void ParseString(const string& str, char c, vector<string>& v);
156 string FormatMoney(int64 n, bool fPlus=false);
157 bool ParseMoney(const string& str, int64& nRet);
158 bool ParseMoney(const char* pszIn, int64& nRet);
159 vector<unsigned char> ParseHex(const char* psz);
160 vector<unsigned char> ParseHex(const std::string& str);
161 void ParseParameters(int argc, char* argv[]);
162 const char* wxGetTranslation(const char* psz);
163 int GetFilesize(FILE* file);
164 void GetDataDir(char* pszDirRet);
165 string GetConfigFile();
166 void ReadConfigFile(map<string, string>& mapSettingsRet, map<string, vector<string> >& mapMultiSettingsRet);
168 string MyGetSpecialFolderPath(int nFolder, bool fCreate);
170 string GetDefaultDataDir();
172 void ShrinkDebugFile();
173 uint64 GetRand(uint64 nMax);
175 int64 GetAdjustedTime();
176 void AddTimeData(unsigned int ip, int64 nTime);
190 // Wrapper to automatically initialize critical sections
191 class CCriticalSection
197 explicit CCriticalSection() { InitializeCriticalSection(&cs); }
198 ~CCriticalSection() { DeleteCriticalSection(&cs); }
199 void Enter() { EnterCriticalSection(&cs); }
200 void Leave() { LeaveCriticalSection(&cs); }
201 bool TryEnter() { return TryEnterCriticalSection(&cs); }
204 boost::interprocess::interprocess_recursive_mutex mutex;
206 explicit CCriticalSection() { }
207 ~CCriticalSection() { }
208 void Enter() { mutex.lock(); }
209 void Leave() { mutex.unlock(); }
210 bool TryEnter() { return mutex.try_lock(); }
217 // Automatically leave critical section when leaving block, needed for exception safety
221 CCriticalSection* pcs;
223 CCriticalBlock(CCriticalSection& csIn) { pcs = &csIn; pcs->Enter(); }
224 ~CCriticalBlock() { pcs->Leave(); }
227 // WARNING: This will catch continue and break!
228 // break is caught with an assertion, but there's no way to detect continue.
229 // I'd rather be careful than suffer the other more error prone syntax.
230 // The compiler will optimise away all this loop junk.
231 #define CRITICAL_BLOCK(cs) \
232 for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by CRITICAL_BLOCK!", !fcriticalblockonce)), fcriticalblockonce=false) \
233 for (CCriticalBlock criticalblock(cs); fcriticalblockonce && (cs.pszFile=__FILE__, cs.nLine=__LINE__, true); fcriticalblockonce=false, cs.pszFile=NULL, cs.nLine=0)
235 class CTryCriticalBlock
238 CCriticalSection* pcs;
240 CTryCriticalBlock(CCriticalSection& csIn) { pcs = (csIn.TryEnter() ? &csIn : NULL); }
241 ~CTryCriticalBlock() { if (pcs) pcs->Leave(); }
242 bool Entered() { return pcs != NULL; }
245 #define TRY_CRITICAL_BLOCK(cs) \
246 for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by TRY_CRITICAL_BLOCK!", !fcriticalblockonce)), fcriticalblockonce=false) \
247 for (CTryCriticalBlock criticalblock(cs); fcriticalblockonce && (fcriticalblockonce = criticalblock.Entered()) && (cs.pszFile=__FILE__, cs.nLine=__LINE__, true); fcriticalblockonce=false, cs.pszFile=NULL, cs.nLine=0)
258 inline string i64tostr(int64 n)
260 return strprintf("%"PRI64d, n);
263 inline string itostr(int n)
265 return strprintf("%d", n);
268 inline int64 atoi64(const char* psz)
273 return strtoll(psz, NULL, 10);
277 inline int64 atoi64(const string& str)
280 return _atoi64(str.c_str());
282 return strtoll(str.c_str(), NULL, 10);
286 inline int atoi(const string& str)
288 return atoi(str.c_str());
291 inline int roundint(double d)
293 return (int)(d > 0 ? d + 0.5 : d - 0.5);
296 inline int64 roundint64(double d)
298 return (int64)(d > 0 ? d + 0.5 : d - 0.5);
302 string HexStr(const T itbegin, const T itend, bool fSpaces=true)
304 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
305 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
307 for (const unsigned char* p = pbegin; p != pend; p++)
308 str += strprintf((fSpaces && p != pend-1 ? "%02x " : "%02x"), *p);
312 inline string HexStr(vector<unsigned char> vch, bool fSpaces=true)
314 return HexStr(vch.begin(), vch.end(), fSpaces);
318 string HexNumStr(const T itbegin, const T itend, bool f0x=true)
320 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
321 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
322 string str = (f0x ? "0x" : "");
323 for (const unsigned char* p = pend-1; p >= pbegin; p--)
324 str += strprintf("%02X", *p);
329 void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)
331 printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());
334 inline void PrintHex(vector<unsigned char> vch, const char* pszFormat="%s", bool fSpaces=true)
336 printf(pszFormat, HexStr(vch, fSpaces).c_str());
339 inline int64 PerformanceCounter()
343 QueryPerformanceCounter((LARGE_INTEGER*)&nCounter);
346 gettimeofday(&t, NULL);
347 nCounter = t.tv_sec * 1000000 + t.tv_usec;
352 inline int64 GetTimeMillis()
354 return (posix_time::ptime(posix_time::microsec_clock::universal_time()) -
355 posix_time::ptime(gregorian::date(1970,1,1))).total_milliseconds();
358 inline string DateTimeStrFormat(const char* pszFormat, int64 nTime)
361 struct tm* ptmTime = gmtime(&n);
363 strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime);
368 void skipspaces(T& it)
374 inline bool IsSwitchChar(char c)
377 return c == '-' || c == '/';
392 inline void heapchk()
396 //if (_heapchk() != _HEAPOK)
401 // Randomize the stack to help protect against buffer overrun exploits
402 #define IMPLEMENT_RANDOMIZE_STACK(ThreadFn) \
404 static char nLoops; \
406 nLoops = GetRand(20) + 1; \
414 #define CATCH_PRINT_EXCEPTION(pszFn) \
415 catch (std::exception& e) { \
416 PrintException(&e, (pszFn)); \
418 PrintException(NULL, (pszFn)); \
430 template<typename T1>
431 inline uint256 Hash(const T1 pbegin, const T1 pend)
433 static unsigned char pblank[1];
435 SHA256((pbegin == pend ? pblank : (unsigned char*)&pbegin[0]), (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);
437 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
441 template<typename T1, typename T2>
442 inline uint256 Hash(const T1 p1begin, const T1 p1end,
443 const T2 p2begin, const T2 p2end)
445 static unsigned char pblank[1];
449 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
450 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
451 SHA256_Final((unsigned char*)&hash1, &ctx);
453 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
457 template<typename T1, typename T2, typename T3>
458 inline uint256 Hash(const T1 p1begin, const T1 p1end,
459 const T2 p2begin, const T2 p2end,
460 const T3 p3begin, const T3 p3end)
462 static unsigned char pblank[1];
466 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
467 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
468 SHA256_Update(&ctx, (p3begin == p3end ? pblank : (unsigned char*)&p3begin[0]), (p3end - p3begin) * sizeof(p3begin[0]));
469 SHA256_Final((unsigned char*)&hash1, &ctx);
471 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
476 uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=VERSION)
478 // Most of the time is spent allocating and deallocating CDataStream's
479 // buffer. If this ever needs to be optimized further, make a CStaticStream
480 // class with its buffer on the stack.
481 CDataStream ss(nType, nVersion);
484 return Hash(ss.begin(), ss.end());
487 inline uint160 Hash160(const vector<unsigned char>& vch)
490 SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);
492 RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
506 // Note: It turns out we might have been able to use boost::thread
507 // by using TerminateThread(boost::thread.native_handle(), 0);
509 typedef HANDLE pthread_t;
511 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
516 NULL, // default security
517 0, // inherit stack size from parent
518 (LPTHREAD_START_ROUTINE)pfn, // function pointer
520 0, // creation option, start immediately
521 &nUnused); // thread identifier
524 printf("Error: CreateThread() returned %d\n", GetLastError());
529 CloseHandle(hthread);
530 return (pthread_t)-1;
535 inline void SetThreadPriority(int nPriority)
537 SetThreadPriority(GetCurrentThread(), nPriority);
540 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
542 pthread_t hthread = 0;
543 int ret = pthread_create(&hthread, NULL, (void*(*)(void*))pfn, parg);
546 printf("Error: pthread_create() returned %d\n", ret);
550 return (pthread_t)-1;
554 #define THREAD_PRIORITY_LOWEST PRIO_MAX
555 #define THREAD_PRIORITY_BELOW_NORMAL 2
556 #define THREAD_PRIORITY_NORMAL 0
557 #define THREAD_PRIORITY_ABOVE_NORMAL 0
559 inline void SetThreadPriority(int nPriority)
561 // It's unclear if it's even possible to change thread priorities on Linux,
562 // but we really and truly need it for the generation threads.
564 setpriority(PRIO_THREAD, 0, nPriority);
566 setpriority(PRIO_PROCESS, 0, nPriority);
570 inline bool TerminateThread(pthread_t hthread, unsigned int nExitCode)
572 return (pthread_cancel(hthread) == 0);
575 inline void ExitThread(unsigned int nExitCode)
577 pthread_exit((void*)nExitCode);