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.
10 #include <sys/types.h>
12 #include <sys/resource.h>
18 #include <boost/thread.hpp>
19 #include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>
20 #include <boost/date_time/gregorian/gregorian_types.hpp>
21 #include <boost/date_time/posix_time/posix_time_types.hpp>
23 #include <openssl/sha.h>
24 #include <openssl/ripemd.h>
27 #if defined(_MSC_VER) || defined(__BORLANDC__)
28 typedef __int64 int64;
29 typedef unsigned __int64 uint64;
31 typedef long long int64;
32 typedef unsigned long long uint64;
34 #if defined(_MSC_VER) && _MSC_VER < 1300
35 #define for if (false) ; else for
38 #define __forceinline inline
42 #define BEGIN(a) ((char*)&(a))
43 #define END(a) ((char*)&((&(a))[1]))
44 #define UBEGIN(a) ((unsigned char*)&(a))
45 #define UEND(a) ((unsigned char*)&((&(a))[1]))
46 #define ARRAYLEN(array) (sizeof(array)/sizeof((array)[0]))
47 #define printf OutputDebugStringF
52 #define snprintf my_snprintf
55 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MSVCRT__)
66 // This is needed because the foreach macro can't get over the comma in pair<t1, t2>
67 #define PAIRTYPE(t1, t2) pair<t1, t2>
69 // Used to bypass the rule against non-const reference to temporary
70 // where it makes sense with wrappers such as CFlatData or CTxDB
72 inline T& REF(const T& val)
77 // Align by increasing pointer, must have extra space at end of buffer
78 template <size_t nBytes, typename T>
87 u.n = (u.n + (nBytes-1)) & ~(nBytes-1);
92 #define MSG_NOSIGNAL 0
93 #define MSG_DONTWAIT 0
95 #define UINT64_MAX _UI64_MAX
96 #define INT64_MAX _I64_MAX
97 #define INT64_MIN _I64_MIN
103 #define unlink _unlink
104 typedef int socklen_t;
106 #define WSAGetLastError() errno
107 #define WSAEINVAL EINVAL
108 #define WSAEALREADY EALREADY
109 #define WSAEWOULDBLOCK EWOULDBLOCK
110 #define WSAEMSGSIZE EMSGSIZE
111 #define WSAEINTR EINTR
112 #define WSAEINPROGRESS EINPROGRESS
113 #define WSAEADDRINUSE EADDRINUSE
114 #define WSAENOTSOCK EBADF
115 #define INVALID_SOCKET (SOCKET)(~0)
116 #define SOCKET_ERROR -1
117 typedef u_int SOCKET;
118 #define _vsnprintf(a,b,c,d) vsnprintf(a,b,c,d)
119 #define strlwr(psz) to_lower(psz)
120 #define _strlwr(psz) to_lower(psz)
121 #define MAX_PATH 1024
122 #define Beep(n1,n2) (0)
123 inline void Sleep(int64 n)
125 boost::thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(n));
129 inline int myclosesocket(SOCKET& hSocket)
131 if (hSocket == INVALID_SOCKET)
134 int ret = closesocket(hSocket);
136 int ret = close(hSocket);
138 hSocket = INVALID_SOCKET;
141 #define closesocket(s) myclosesocket(s)
144 inline const char* _(const char* psz)
159 extern std::map<std::string, std::string> mapArgs;
160 extern std::map<std::string, std::vector<std::string> > mapMultiArgs;
162 extern bool fPrintToConsole;
163 extern bool fPrintToDebugger;
164 extern char pszSetDataDir[MAX_PATH];
165 extern bool fRequestShutdown;
166 extern bool fShutdown;
169 extern bool fCommandLine;
170 extern std::string strMiscWarning;
171 extern bool fTestNet;
172 extern bool fNoListen;
173 extern bool fLogTimestamps;
176 void RandAddSeedPerfmon();
177 int OutputDebugStringF(const char* pszFormat, ...);
178 int my_snprintf(char* buffer, size_t limit, const char* format, ...);
179 std::string strprintf(const char* format, ...);
180 bool error(const char* format, ...);
181 void LogException(std::exception* pex, const char* pszThread);
182 void PrintException(std::exception* pex, const char* pszThread);
183 void PrintExceptionContinue(std::exception* pex, const char* pszThread);
184 void ParseString(const std::string& str, char c, std::vector<std::string>& v);
185 std::string FormatMoney(int64 n, bool fPlus=false);
186 bool ParseMoney(const std::string& str, int64& nRet);
187 bool ParseMoney(const char* pszIn, int64& nRet);
188 std::vector<unsigned char> ParseHex(const char* psz);
189 std::vector<unsigned char> ParseHex(const std::string& str);
190 void ParseParameters(int argc, char* argv[]);
191 const char* wxGetTranslation(const char* psz);
192 bool WildcardMatch(const char* psz, const char* mask);
193 bool WildcardMatch(const std::string& str, const std::string& mask);
194 int GetFilesize(FILE* file);
195 void GetDataDir(char* pszDirRet);
196 std::string GetConfigFile();
197 std::string GetPidFile();
198 void CreatePidFile(std::string pidFile, pid_t pid);
199 void ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet, std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet);
201 std::string MyGetSpecialFolderPath(int nFolder, bool fCreate);
203 std::string GetDefaultDataDir();
204 std::string GetDataDir();
205 void ShrinkDebugFile();
206 int GetRandInt(int nMax);
207 uint64 GetRand(uint64 nMax);
209 int64 GetAdjustedTime();
210 void AddTimeData(unsigned int ip, int64 nTime);
211 std::string FormatFullVersion();
225 // Wrapper to automatically initialize critical sections
226 class CCriticalSection
232 explicit CCriticalSection() { InitializeCriticalSection(&cs); }
233 ~CCriticalSection() { DeleteCriticalSection(&cs); }
234 void Enter() { EnterCriticalSection(&cs); }
235 void Leave() { LeaveCriticalSection(&cs); }
236 bool TryEnter() { return TryEnterCriticalSection(&cs); }
239 boost::interprocess::interprocess_recursive_mutex mutex;
241 explicit CCriticalSection() { }
242 ~CCriticalSection() { }
243 void Enter() { mutex.lock(); }
244 void Leave() { mutex.unlock(); }
245 bool TryEnter() { return mutex.try_lock(); }
252 // Automatically leave critical section when leaving block, needed for exception safety
256 CCriticalSection* pcs;
258 CCriticalBlock(CCriticalSection& csIn) { pcs = &csIn; pcs->Enter(); }
259 ~CCriticalBlock() { pcs->Leave(); }
262 // WARNING: This will catch continue and break!
263 // break is caught with an assertion, but there's no way to detect continue.
264 // I'd rather be careful than suffer the other more error prone syntax.
265 // The compiler will optimise away all this loop junk.
266 #define CRITICAL_BLOCK(cs) \
267 for (bool fcriticalblockonce=true; fcriticalblockonce; assert("break caught by CRITICAL_BLOCK!" && !fcriticalblockonce), fcriticalblockonce=false) \
268 for (CCriticalBlock criticalblock(cs); fcriticalblockonce && (cs.pszFile=__FILE__, cs.nLine=__LINE__, true); fcriticalblockonce=false, cs.pszFile=NULL, cs.nLine=0)
270 class CTryCriticalBlock
273 CCriticalSection* pcs;
275 CTryCriticalBlock(CCriticalSection& csIn) { pcs = (csIn.TryEnter() ? &csIn : NULL); }
276 ~CTryCriticalBlock() { if (pcs) pcs->Leave(); }
277 bool Entered() { return pcs != NULL; }
280 #define TRY_CRITICAL_BLOCK(cs) \
281 for (bool fcriticalblockonce=true; fcriticalblockonce; assert("break caught by TRY_CRITICAL_BLOCK!" && !fcriticalblockonce), fcriticalblockonce=false) \
282 for (CTryCriticalBlock criticalblock(cs); fcriticalblockonce && (fcriticalblockonce = criticalblock.Entered()) && (cs.pszFile=__FILE__, cs.nLine=__LINE__, true); fcriticalblockonce=false, cs.pszFile=NULL, cs.nLine=0)
293 inline std::string i64tostr(int64 n)
295 return strprintf("%"PRI64d, n);
298 inline std::string itostr(int n)
300 return strprintf("%d", n);
303 inline int64 atoi64(const char* psz)
308 return strtoll(psz, NULL, 10);
312 inline int64 atoi64(const std::string& str)
315 return _atoi64(str.c_str());
317 return strtoll(str.c_str(), NULL, 10);
321 inline int atoi(const std::string& str)
323 return atoi(str.c_str());
326 inline int roundint(double d)
328 return (int)(d > 0 ? d + 0.5 : d - 0.5);
331 inline int64 roundint64(double d)
333 return (int64)(d > 0 ? d + 0.5 : d - 0.5);
336 inline int64 abs64(int64 n)
338 return (n >= 0 ? n : -n);
342 std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
344 if (itbegin == itend)
346 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
347 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
349 str.reserve((pend-pbegin) * (fSpaces ? 3 : 2));
350 for (const unsigned char* p = pbegin; p != pend; p++)
351 str += strprintf((fSpaces && p != pend-1 ? "%02x " : "%02x"), *p);
355 inline std::string HexStr(const std::vector<unsigned char>& vch, bool fSpaces=false)
357 return HexStr(vch.begin(), vch.end(), fSpaces);
361 std::string HexNumStr(const T itbegin, const T itend, bool f0x=true)
363 if (itbegin == itend)
365 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
366 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
367 std::string str = (f0x ? "0x" : "");
368 str.reserve(str.size() + (pend-pbegin) * 2);
369 for (const unsigned char* p = pend-1; p >= pbegin; p--)
370 str += strprintf("%02x", *p);
374 inline std::string HexNumStr(const std::vector<unsigned char>& vch, bool f0x=true)
376 return HexNumStr(vch.begin(), vch.end(), f0x);
380 void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)
382 printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());
385 inline void PrintHex(const std::vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true)
387 printf(pszFormat, HexStr(vch, fSpaces).c_str());
390 inline int64 GetPerformanceCounter()
394 QueryPerformanceCounter((LARGE_INTEGER*)&nCounter);
397 gettimeofday(&t, NULL);
398 nCounter = t.tv_sec * 1000000 + t.tv_usec;
403 inline int64 GetTimeMillis()
405 return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) -
406 boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
409 inline std::string DateTimeStrFormat(const char* pszFormat, int64 nTime)
412 struct tm* ptmTime = gmtime(&n);
414 strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime);
419 void skipspaces(T& it)
425 inline bool IsSwitchChar(char c)
428 return c == '-' || c == '/';
434 inline std::string GetArg(const std::string& strArg, const std::string& strDefault)
436 if (mapArgs.count(strArg))
437 return mapArgs[strArg];
441 inline int64 GetArg(const std::string& strArg, int64 nDefault)
443 if (mapArgs.count(strArg))
444 return atoi64(mapArgs[strArg]);
448 inline bool GetBoolArg(const std::string& strArg)
450 if (mapArgs.count(strArg))
452 if (mapArgs[strArg].empty())
454 return (atoi(mapArgs[strArg]) != 0);
468 inline void heapchk()
472 //if (_heapchk() != _HEAPOK)
477 // Randomize the stack to help protect against buffer overrun exploits
478 #define IMPLEMENT_RANDOMIZE_STACK(ThreadFn) \
480 static char nLoops; \
482 nLoops = GetRand(20) + 1; \
490 #define CATCH_PRINT_EXCEPTION(pszFn) \
491 catch (std::exception& e) { \
492 PrintException(&e, (pszFn)); \
494 PrintException(NULL, (pszFn)); \
506 template<typename T1>
507 inline uint256 Hash(const T1 pbegin, const T1 pend)
509 static unsigned char pblank[1];
511 SHA256((pbegin == pend ? pblank : (unsigned char*)&pbegin[0]), (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);
513 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
517 template<typename T1, typename T2>
518 inline uint256 Hash(const T1 p1begin, const T1 p1end,
519 const T2 p2begin, const T2 p2end)
521 static unsigned char pblank[1];
525 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
526 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
527 SHA256_Final((unsigned char*)&hash1, &ctx);
529 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
533 template<typename T1, typename T2, typename T3>
534 inline uint256 Hash(const T1 p1begin, const T1 p1end,
535 const T2 p2begin, const T2 p2end,
536 const T3 p3begin, const T3 p3end)
538 static unsigned char pblank[1];
542 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
543 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
544 SHA256_Update(&ctx, (p3begin == p3end ? pblank : (unsigned char*)&p3begin[0]), (p3end - p3begin) * sizeof(p3begin[0]));
545 SHA256_Final((unsigned char*)&hash1, &ctx);
547 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
552 uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=VERSION)
554 // Most of the time is spent allocating and deallocating CDataStream's
555 // buffer. If this ever needs to be optimized further, make a CStaticStream
556 // class with its buffer on the stack.
557 CDataStream ss(nType, nVersion);
560 return Hash(ss.begin(), ss.end());
563 inline uint160 Hash160(const std::vector<unsigned char>& vch)
566 SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);
568 RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
582 // Note: It turns out we might have been able to use boost::thread
583 // by using TerminateThread(boost::thread.native_handle(), 0);
585 typedef HANDLE pthread_t;
587 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
592 NULL, // default security
593 0, // inherit stack size from parent
594 (LPTHREAD_START_ROUTINE)pfn, // function pointer
596 0, // creation option, start immediately
597 &nUnused); // thread identifier
600 printf("Error: CreateThread() returned %d\n", GetLastError());
605 CloseHandle(hthread);
606 return (pthread_t)-1;
611 inline void SetThreadPriority(int nPriority)
613 SetThreadPriority(GetCurrentThread(), nPriority);
616 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
618 pthread_t hthread = 0;
619 int ret = pthread_create(&hthread, NULL, (void*(*)(void*))pfn, parg);
622 printf("Error: pthread_create() returned %d\n", ret);
626 return (pthread_t)-1;
630 #define THREAD_PRIORITY_LOWEST PRIO_MAX
631 #define THREAD_PRIORITY_BELOW_NORMAL 2
632 #define THREAD_PRIORITY_NORMAL 0
633 #define THREAD_PRIORITY_ABOVE_NORMAL 0
635 inline void SetThreadPriority(int nPriority)
637 // It's unclear if it's even possible to change thread priorities on Linux,
638 // but we really and truly need it for the generation threads.
640 setpriority(PRIO_THREAD, 0, nPriority);
642 setpriority(PRIO_PROCESS, 0, nPriority);
646 inline bool TerminateThread(pthread_t hthread, unsigned int nExitCode)
648 return (pthread_cancel(hthread) == 0);
651 inline void ExitThread(size_t nExitCode)
653 pthread_exit((void*)nExitCode);
661 inline bool AffinityBugWorkaround(void(*pfn)(void*))
664 // Sometimes after a few hours affinity gets stuck on one processor
665 DWORD dwProcessAffinityMask = -1;
666 DWORD dwSystemAffinityMask = -1;
667 GetProcessAffinityMask(GetCurrentProcess(), &dwProcessAffinityMask, &dwSystemAffinityMask);
668 DWORD dwPrev1 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
669 DWORD dwPrev2 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
670 if (dwPrev2 != dwProcessAffinityMask)
672 printf("AffinityBugWorkaround() : SetThreadAffinityMask=%d, ProcessAffinityMask=%d, restarting thread\n", dwPrev2, dwProcessAffinityMask);
673 if (!CreateThread(pfn, NULL))
674 printf("Error: CreateThread() failed\n");