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 fRequestShutdown;
144 extern bool fShutdown;
146 extern bool fCommandLine;
147 extern string strMiscWarning;
148 extern bool fTestNet;
149 extern bool fNoListen;
152 void RandAddSeedPerfmon();
153 int OutputDebugStringF(const char* pszFormat, ...);
154 int my_snprintf(char* buffer, size_t limit, const char* format, ...);
155 string strprintf(const char* format, ...);
156 bool error(const char* format, ...);
157 void LogException(std::exception* pex, const char* pszThread);
158 void PrintException(std::exception* pex, const char* pszThread);
159 void PrintExceptionContinue(std::exception* pex, const char* pszThread);
160 void ParseString(const string& str, char c, vector<string>& v);
161 string FormatMoney(int64 n, bool fPlus=false);
162 bool ParseMoney(const string& str, int64& nRet);
163 bool ParseMoney(const char* pszIn, int64& nRet);
164 vector<unsigned char> ParseHex(const char* psz);
165 vector<unsigned char> ParseHex(const string& str);
166 void ParseParameters(int argc, char* argv[]);
167 const char* wxGetTranslation(const char* psz);
168 bool WildcardMatch(const char* psz, const char* mask);
169 bool WildcardMatch(const string& str, const string& mask);
170 int GetFilesize(FILE* file);
171 void GetDataDir(char* pszDirRet);
172 string GetConfigFile();
173 void ReadConfigFile(map<string, string>& mapSettingsRet, map<string, vector<string> >& mapMultiSettingsRet);
175 string MyGetSpecialFolderPath(int nFolder, bool fCreate);
177 string GetDefaultDataDir();
179 void ShrinkDebugFile();
180 int GetRandInt(int nMax);
181 uint64 GetRand(uint64 nMax);
183 int64 GetAdjustedTime();
184 void AddTimeData(unsigned int ip, int64 nTime);
198 // Wrapper to automatically initialize critical sections
199 class CCriticalSection
205 explicit CCriticalSection() { InitializeCriticalSection(&cs); }
206 ~CCriticalSection() { DeleteCriticalSection(&cs); }
207 void Enter() { EnterCriticalSection(&cs); }
208 void Leave() { LeaveCriticalSection(&cs); }
209 bool TryEnter() { return TryEnterCriticalSection(&cs); }
212 boost::interprocess::interprocess_recursive_mutex mutex;
214 explicit CCriticalSection() { }
215 ~CCriticalSection() { }
216 void Enter() { mutex.lock(); }
217 void Leave() { mutex.unlock(); }
218 bool TryEnter() { return mutex.try_lock(); }
225 // Automatically leave critical section when leaving block, needed for exception safety
229 CCriticalSection* pcs;
231 CCriticalBlock(CCriticalSection& csIn) { pcs = &csIn; pcs->Enter(); }
232 ~CCriticalBlock() { pcs->Leave(); }
235 // WARNING: This will catch continue and break!
236 // break is caught with an assertion, but there's no way to detect continue.
237 // I'd rather be careful than suffer the other more error prone syntax.
238 // The compiler will optimise away all this loop junk.
239 #define CRITICAL_BLOCK(cs) \
240 for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by CRITICAL_BLOCK!", !fcriticalblockonce)), fcriticalblockonce=false) \
241 for (CCriticalBlock criticalblock(cs); fcriticalblockonce && (cs.pszFile=__FILE__, cs.nLine=__LINE__, true); fcriticalblockonce=false, cs.pszFile=NULL, cs.nLine=0)
243 class CTryCriticalBlock
246 CCriticalSection* pcs;
248 CTryCriticalBlock(CCriticalSection& csIn) { pcs = (csIn.TryEnter() ? &csIn : NULL); }
249 ~CTryCriticalBlock() { if (pcs) pcs->Leave(); }
250 bool Entered() { return pcs != NULL; }
253 #define TRY_CRITICAL_BLOCK(cs) \
254 for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by TRY_CRITICAL_BLOCK!", !fcriticalblockonce)), fcriticalblockonce=false) \
255 for (CTryCriticalBlock criticalblock(cs); fcriticalblockonce && (fcriticalblockonce = criticalblock.Entered()) && (cs.pszFile=__FILE__, cs.nLine=__LINE__, true); fcriticalblockonce=false, cs.pszFile=NULL, cs.nLine=0)
266 inline string i64tostr(int64 n)
268 return strprintf("%"PRI64d, n);
271 inline string itostr(int n)
273 return strprintf("%d", n);
276 inline int64 atoi64(const char* psz)
281 return strtoll(psz, NULL, 10);
285 inline int64 atoi64(const string& str)
288 return _atoi64(str.c_str());
290 return strtoll(str.c_str(), NULL, 10);
294 inline int atoi(const string& str)
296 return atoi(str.c_str());
299 inline int roundint(double d)
301 return (int)(d > 0 ? d + 0.5 : d - 0.5);
304 inline int64 roundint64(double d)
306 return (int64)(d > 0 ? d + 0.5 : d - 0.5);
309 inline int64 abs64(int64 n)
311 return (n >= 0 ? n : -n);
315 string HexStr(const T itbegin, const T itend, bool fSpaces=false)
317 if (itbegin == itend)
319 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
320 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
322 str.reserve((pend-pbegin) * (fSpaces ? 3 : 2));
323 for (const unsigned char* p = pbegin; p != pend; p++)
324 str += strprintf((fSpaces && p != pend-1 ? "%02x " : "%02x"), *p);
328 inline string HexStr(const vector<unsigned char>& vch, bool fSpaces=false)
330 return HexStr(vch.begin(), vch.end(), fSpaces);
334 string HexNumStr(const T itbegin, const T itend, bool f0x=true)
336 if (itbegin == itend)
338 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
339 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
340 string str = (f0x ? "0x" : "");
341 str.reserve(str.size() + (pend-pbegin) * 2);
342 for (const unsigned char* p = pend-1; p >= pbegin; p--)
343 str += strprintf("%02x", *p);
347 inline string HexNumStr(const vector<unsigned char>& vch, bool f0x=true)
349 return HexNumStr(vch.begin(), vch.end(), f0x);
353 void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)
355 printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());
358 inline void PrintHex(const vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true)
360 printf(pszFormat, HexStr(vch, fSpaces).c_str());
363 inline int64 GetPerformanceCounter()
367 QueryPerformanceCounter((LARGE_INTEGER*)&nCounter);
370 gettimeofday(&t, NULL);
371 nCounter = t.tv_sec * 1000000 + t.tv_usec;
376 inline int64 GetTimeMillis()
378 return (posix_time::ptime(posix_time::microsec_clock::universal_time()) -
379 posix_time::ptime(gregorian::date(1970,1,1))).total_milliseconds();
382 inline string DateTimeStrFormat(const char* pszFormat, int64 nTime)
385 struct tm* ptmTime = gmtime(&n);
387 strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime);
392 void skipspaces(T& it)
398 inline bool IsSwitchChar(char c)
401 return c == '-' || c == '/';
407 inline string GetArg(const string& strArg, const string& strDefault)
409 if (mapArgs.count(strArg))
410 return mapArgs[strArg];
414 inline int64 GetArg(const string& strArg, int64 nDefault)
416 if (mapArgs.count(strArg))
417 return atoi64(mapArgs[strArg]);
421 inline bool GetBoolArg(const string& strArg)
423 if (mapArgs.count(strArg))
425 if (mapArgs[strArg].empty())
427 return (atoi(mapArgs[strArg]) != 0);
432 inline string FormatVersion(int nVersion)
434 if (nVersion%100 == 0)
435 return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
437 return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
449 inline void heapchk()
453 //if (_heapchk() != _HEAPOK)
458 // Randomize the stack to help protect against buffer overrun exploits
459 #define IMPLEMENT_RANDOMIZE_STACK(ThreadFn) \
461 static char nLoops; \
463 nLoops = GetRand(20) + 1; \
471 #define CATCH_PRINT_EXCEPTION(pszFn) \
472 catch (std::exception& e) { \
473 PrintException(&e, (pszFn)); \
475 PrintException(NULL, (pszFn)); \
487 template<typename T1>
488 inline uint256 Hash(const T1 pbegin, const T1 pend)
490 static unsigned char pblank[1];
492 SHA256((pbegin == pend ? pblank : (unsigned char*)&pbegin[0]), (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);
494 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
498 template<typename T1, typename T2>
499 inline uint256 Hash(const T1 p1begin, const T1 p1end,
500 const T2 p2begin, const T2 p2end)
502 static unsigned char pblank[1];
506 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
507 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
508 SHA256_Final((unsigned char*)&hash1, &ctx);
510 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
514 template<typename T1, typename T2, typename T3>
515 inline uint256 Hash(const T1 p1begin, const T1 p1end,
516 const T2 p2begin, const T2 p2end,
517 const T3 p3begin, const T3 p3end)
519 static unsigned char pblank[1];
523 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
524 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
525 SHA256_Update(&ctx, (p3begin == p3end ? pblank : (unsigned char*)&p3begin[0]), (p3end - p3begin) * sizeof(p3begin[0]));
526 SHA256_Final((unsigned char*)&hash1, &ctx);
528 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
533 uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=VERSION)
535 // Most of the time is spent allocating and deallocating CDataStream's
536 // buffer. If this ever needs to be optimized further, make a CStaticStream
537 // class with its buffer on the stack.
538 CDataStream ss(nType, nVersion);
541 return Hash(ss.begin(), ss.end());
544 inline uint160 Hash160(const vector<unsigned char>& vch)
547 SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);
549 RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
563 // Note: It turns out we might have been able to use boost::thread
564 // by using TerminateThread(boost::thread.native_handle(), 0);
566 typedef HANDLE pthread_t;
568 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
573 NULL, // default security
574 0, // inherit stack size from parent
575 (LPTHREAD_START_ROUTINE)pfn, // function pointer
577 0, // creation option, start immediately
578 &nUnused); // thread identifier
581 printf("Error: CreateThread() returned %d\n", GetLastError());
586 CloseHandle(hthread);
587 return (pthread_t)-1;
592 inline void SetThreadPriority(int nPriority)
594 SetThreadPriority(GetCurrentThread(), nPriority);
597 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
599 pthread_t hthread = 0;
600 int ret = pthread_create(&hthread, NULL, (void*(*)(void*))pfn, parg);
603 printf("Error: pthread_create() returned %d\n", ret);
607 return (pthread_t)-1;
611 #define THREAD_PRIORITY_LOWEST PRIO_MAX
612 #define THREAD_PRIORITY_BELOW_NORMAL 2
613 #define THREAD_PRIORITY_NORMAL 0
614 #define THREAD_PRIORITY_ABOVE_NORMAL 0
616 inline void SetThreadPriority(int nPriority)
618 // It's unclear if it's even possible to change thread priorities on Linux,
619 // but we really and truly need it for the generation threads.
621 setpriority(PRIO_THREAD, 0, nPriority);
623 setpriority(PRIO_PROCESS, 0, nPriority);
627 inline bool TerminateThread(pthread_t hthread, unsigned int nExitCode)
629 return (pthread_cancel(hthread) == 0);
632 inline void ExitThread(unsigned int nExitCode)
634 pthread_exit((void*)nExitCode);
642 inline bool AffinityBugWorkaround(void(*pfn)(void*))
645 // Sometimes after a few hours affinity gets stuck on one processor
646 DWORD dwProcessAffinityMask = -1;
647 DWORD dwSystemAffinityMask = -1;
648 GetProcessAffinityMask(GetCurrentProcess(), &dwProcessAffinityMask, &dwSystemAffinityMask);
649 DWORD dwPrev1 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
650 DWORD dwPrev2 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
651 if (dwPrev2 != dwProcessAffinityMask)
653 printf("AffinityBugWorkaround() : SetThreadAffinityMask=%d, ProcessAffinityMask=%d, restarting thread\n", dwPrev2, dwProcessAffinityMask);
654 if (!CreateThread(pfn, NULL))
655 printf("Error: CreateThread() failed\n");