1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
11 #include <sys/types.h>
13 #include <sys/resource.h>
19 #include <boost/thread.hpp>
20 #include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>
21 #include <boost/date_time/gregorian/gregorian_types.hpp>
22 #include <boost/date_time/posix_time/posix_time_types.hpp>
24 #include <openssl/sha.h>
25 #include <openssl/ripemd.h>
28 #if defined(_MSC_VER) || defined(__BORLANDC__)
29 typedef __int64 int64;
30 typedef unsigned __int64 uint64;
32 typedef long long int64;
33 typedef unsigned long long uint64;
35 #if defined(_MSC_VER) && _MSC_VER < 1300
36 #define for if (false) ; else for
39 #define __forceinline inline
43 #define BEGIN(a) ((char*)&(a))
44 #define END(a) ((char*)&((&(a))[1]))
45 #define UBEGIN(a) ((unsigned char*)&(a))
46 #define UEND(a) ((unsigned char*)&((&(a))[1]))
47 #define ARRAYLEN(array) (sizeof(array)/sizeof((array)[0]))
48 #define printf OutputDebugStringF
53 #define snprintf my_snprintf
56 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MSVCRT__)
67 // This is needed because the foreach macro can't get over the comma in pair<t1, t2>
68 #define PAIRTYPE(t1, t2) pair<t1, t2>
70 // Align by increasing pointer, must have extra space at end of buffer
71 template <size_t nBytes, typename T>
80 u.n = (u.n + (nBytes-1)) & ~(nBytes-1);
85 #define MSG_NOSIGNAL 0
86 #define MSG_DONTWAIT 0
88 #define UINT64_MAX _UI64_MAX
89 #define INT64_MAX _I64_MAX
90 #define INT64_MIN _I64_MIN
96 #define unlink _unlink
97 typedef int socklen_t;
99 #define WSAGetLastError() errno
100 #define WSAEINVAL EINVAL
101 #define WSAEALREADY EALREADY
102 #define WSAEWOULDBLOCK EWOULDBLOCK
103 #define WSAEMSGSIZE EMSGSIZE
104 #define WSAEINTR EINTR
105 #define WSAEINPROGRESS EINPROGRESS
106 #define WSAEADDRINUSE EADDRINUSE
107 #define WSAENOTSOCK EBADF
108 #define INVALID_SOCKET (SOCKET)(~0)
109 #define SOCKET_ERROR -1
110 typedef u_int SOCKET;
111 #define _vsnprintf(a,b,c,d) vsnprintf(a,b,c,d)
112 #define strlwr(psz) to_lower(psz)
113 #define _strlwr(psz) to_lower(psz)
114 #define MAX_PATH 1024
115 #define Beep(n1,n2) (0)
116 inline void Sleep(int64 n)
118 boost::thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(n));
122 inline int myclosesocket(SOCKET& hSocket)
124 if (hSocket == INVALID_SOCKET)
127 int ret = closesocket(hSocket);
129 int ret = close(hSocket);
131 hSocket = INVALID_SOCKET;
134 #define closesocket(s) myclosesocket(s)
137 inline const char* _(const char* psz)
152 extern std::map<std::string, std::string> mapArgs;
153 extern std::map<std::string, std::vector<std::string> > mapMultiArgs;
155 extern bool fPrintToConsole;
156 extern bool fPrintToDebugger;
157 extern char pszSetDataDir[MAX_PATH];
158 extern bool fRequestShutdown;
159 extern bool fShutdown;
162 extern bool fCommandLine;
163 extern std::string strMiscWarning;
164 extern bool fTestNet;
165 extern bool fNoListen;
166 extern bool fLogTimestamps;
169 void RandAddSeedPerfmon();
170 int OutputDebugStringF(const char* pszFormat, ...);
171 int my_snprintf(char* buffer, size_t limit, const char* format, ...);
172 std::string strprintf(const char* format, ...);
173 bool error(const char* format, ...);
174 void LogException(std::exception* pex, const char* pszThread);
175 void PrintException(std::exception* pex, const char* pszThread);
176 void PrintExceptionContinue(std::exception* pex, const char* pszThread);
177 void ParseString(const std::string& str, char c, std::vector<std::string>& v);
178 std::string FormatMoney(int64 n, bool fPlus=false);
179 bool ParseMoney(const std::string& str, int64& nRet);
180 bool ParseMoney(const char* pszIn, int64& nRet);
181 std::vector<unsigned char> ParseHex(const char* psz);
182 std::vector<unsigned char> ParseHex(const std::string& str);
183 void ParseParameters(int argc, char* argv[]);
184 const char* wxGetTranslation(const char* psz);
185 bool WildcardMatch(const char* psz, const char* mask);
186 bool WildcardMatch(const std::string& str, const std::string& mask);
187 int GetFilesize(FILE* file);
188 void GetDataDir(char* pszDirRet);
189 std::string GetConfigFile();
190 std::string GetPidFile();
191 void CreatePidFile(std::string pidFile, pid_t pid);
192 void ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet, std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet);
194 std::string MyGetSpecialFolderPath(int nFolder, bool fCreate);
196 std::string GetDefaultDataDir();
197 std::string GetDataDir();
198 void ShrinkDebugFile();
199 int GetRandInt(int nMax);
200 uint64 GetRand(uint64 nMax);
202 void SetMockTime(int64 nMockTimeIn);
203 int64 GetAdjustedTime();
204 void AddTimeData(unsigned int ip, int64 nTime);
205 std::string FormatFullVersion();
219 // Wrapper to automatically initialize mutex
220 class CCriticalSection
223 boost::interprocess::interprocess_recursive_mutex mutex;
225 explicit CCriticalSection() { }
226 ~CCriticalSection() { }
227 void Enter(const char* pszName, const char* pszFile, int nLine);
229 bool TryEnter(const char* pszName, const char* pszFile, int nLine);
232 // Automatically leave critical section when leaving block, needed for exception safety
236 CCriticalSection* pcs;
239 CCriticalBlock(CCriticalSection& csIn, const char* pszName, const char* pszFile, int nLine)
242 pcs->Enter(pszName, pszFile, nLine);
250 // WARNING: This will catch continue and break!
251 // break is caught with an assertion, but there's no way to detect continue.
252 // I'd rather be careful than suffer the other more error prone syntax.
253 // The compiler will optimise away all this loop junk.
254 #define CRITICAL_BLOCK(cs) \
255 for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by CRITICAL_BLOCK!" && !fcriticalblockonce)), fcriticalblockonce=false) \
256 for (CCriticalBlock criticalblock(cs, #cs, __FILE__, __LINE__); fcriticalblockonce; fcriticalblockonce=false)
258 class CTryCriticalBlock
261 CCriticalSection* pcs;
264 CTryCriticalBlock(CCriticalSection& csIn, const char* pszName, const char* pszFile, int nLine)
266 pcs = (csIn.TryEnter(pszName, pszFile, nLine) ? &csIn : NULL);
275 bool Entered() { return pcs != NULL; }
278 #define TRY_CRITICAL_BLOCK(cs) \
279 for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by TRY_CRITICAL_BLOCK!" && !fcriticalblockonce)), fcriticalblockonce=false) \
280 for (CTryCriticalBlock criticalblock(cs, #cs, __FILE__, __LINE__); fcriticalblockonce && (fcriticalblockonce = criticalblock.Entered()); fcriticalblockonce=false)
291 inline std::string i64tostr(int64 n)
293 return strprintf("%"PRI64d, n);
296 inline std::string itostr(int n)
298 return strprintf("%d", n);
301 inline int64 atoi64(const char* psz)
306 return strtoll(psz, NULL, 10);
310 inline int64 atoi64(const std::string& str)
313 return _atoi64(str.c_str());
315 return strtoll(str.c_str(), NULL, 10);
319 inline int atoi(const std::string& str)
321 return atoi(str.c_str());
324 inline int roundint(double d)
326 return (int)(d > 0 ? d + 0.5 : d - 0.5);
329 inline int64 roundint64(double d)
331 return (int64)(d > 0 ? d + 0.5 : d - 0.5);
334 inline int64 abs64(int64 n)
336 return (n >= 0 ? n : -n);
340 std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
342 if (itbegin == itend)
344 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
345 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
347 str.reserve((pend-pbegin) * (fSpaces ? 3 : 2));
348 for (const unsigned char* p = pbegin; p != pend; p++)
349 str += strprintf((fSpaces && p != pend-1 ? "%02x " : "%02x"), *p);
353 inline std::string HexStr(const std::vector<unsigned char>& vch, bool fSpaces=false)
355 return HexStr(vch.begin(), vch.end(), fSpaces);
359 std::string HexNumStr(const T itbegin, const T itend, bool f0x=true)
361 if (itbegin == itend)
363 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
364 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
365 std::string str = (f0x ? "0x" : "");
366 str.reserve(str.size() + (pend-pbegin) * 2);
367 for (const unsigned char* p = pend-1; p >= pbegin; p--)
368 str += strprintf("%02x", *p);
372 inline std::string HexNumStr(const std::vector<unsigned char>& vch, bool f0x=true)
374 return HexNumStr(vch.begin(), vch.end(), f0x);
378 void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)
380 printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());
383 inline void PrintHex(const std::vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true)
385 printf(pszFormat, HexStr(vch, fSpaces).c_str());
388 inline int64 GetPerformanceCounter()
392 QueryPerformanceCounter((LARGE_INTEGER*)&nCounter);
395 gettimeofday(&t, NULL);
396 nCounter = t.tv_sec * 1000000 + t.tv_usec;
401 inline int64 GetTimeMillis()
403 return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) -
404 boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
407 inline std::string DateTimeStrFormat(const char* pszFormat, int64 nTime)
410 struct tm* ptmTime = gmtime(&n);
412 strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime);
417 void skipspaces(T& it)
423 inline bool IsSwitchChar(char c)
426 return c == '-' || c == '/';
432 inline std::string GetArg(const std::string& strArg, const std::string& strDefault)
434 if (mapArgs.count(strArg))
435 return mapArgs[strArg];
439 inline int64 GetArg(const std::string& strArg, int64 nDefault)
441 if (mapArgs.count(strArg))
442 return atoi64(mapArgs[strArg]);
446 inline bool GetBoolArg(const std::string& strArg)
448 if (mapArgs.count(strArg))
450 if (mapArgs[strArg].empty())
452 return (atoi(mapArgs[strArg]) != 0);
466 inline void heapchk()
470 //if (_heapchk() != _HEAPOK)
475 // Randomize the stack to help protect against buffer overrun exploits
476 #define IMPLEMENT_RANDOMIZE_STACK(ThreadFn) \
478 static char nLoops; \
480 nLoops = GetRand(20) + 1; \
488 #define CATCH_PRINT_EXCEPTION(pszFn) \
489 catch (std::exception& e) { \
490 PrintException(&e, (pszFn)); \
492 PrintException(NULL, (pszFn)); \
504 template<typename T1>
505 inline uint256 Hash(const T1 pbegin, const T1 pend)
507 static unsigned char pblank[1];
509 SHA256((pbegin == pend ? pblank : (unsigned char*)&pbegin[0]), (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);
511 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
515 template<typename T1, typename T2>
516 inline uint256 Hash(const T1 p1begin, const T1 p1end,
517 const T2 p2begin, const T2 p2end)
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_Final((unsigned char*)&hash1, &ctx);
527 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
531 template<typename T1, typename T2, typename T3>
532 inline uint256 Hash(const T1 p1begin, const T1 p1end,
533 const T2 p2begin, const T2 p2end,
534 const T3 p3begin, const T3 p3end)
536 static unsigned char pblank[1];
540 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
541 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
542 SHA256_Update(&ctx, (p3begin == p3end ? pblank : (unsigned char*)&p3begin[0]), (p3end - p3begin) * sizeof(p3begin[0]));
543 SHA256_Final((unsigned char*)&hash1, &ctx);
545 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
550 uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=VERSION)
552 // Most of the time is spent allocating and deallocating CDataStream's
553 // buffer. If this ever needs to be optimized further, make a CStaticStream
554 // class with its buffer on the stack.
555 CDataStream ss(nType, nVersion);
558 return Hash(ss.begin(), ss.end());
561 inline uint160 Hash160(const std::vector<unsigned char>& vch)
564 SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);
566 RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
580 // Note: It turns out we might have been able to use boost::thread
581 // by using TerminateThread(boost::thread.native_handle(), 0);
583 typedef HANDLE pthread_t;
585 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
590 NULL, // default security
591 0, // inherit stack size from parent
592 (LPTHREAD_START_ROUTINE)pfn, // function pointer
594 0, // creation option, start immediately
595 &nUnused); // thread identifier
598 printf("Error: CreateThread() returned %d\n", GetLastError());
603 CloseHandle(hthread);
604 return (pthread_t)-1;
609 inline void SetThreadPriority(int nPriority)
611 SetThreadPriority(GetCurrentThread(), nPriority);
614 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
616 pthread_t hthread = 0;
617 int ret = pthread_create(&hthread, NULL, (void*(*)(void*))pfn, parg);
620 printf("Error: pthread_create() returned %d\n", ret);
625 pthread_detach(hthread);
626 return (pthread_t)-1;
631 #define THREAD_PRIORITY_LOWEST PRIO_MAX
632 #define THREAD_PRIORITY_BELOW_NORMAL 2
633 #define THREAD_PRIORITY_NORMAL 0
634 #define THREAD_PRIORITY_ABOVE_NORMAL 0
636 inline void SetThreadPriority(int nPriority)
638 // It's unclear if it's even possible to change thread priorities on Linux,
639 // but we really and truly need it for the generation threads.
641 setpriority(PRIO_THREAD, 0, nPriority);
643 setpriority(PRIO_PROCESS, 0, nPriority);
647 inline bool TerminateThread(pthread_t hthread, unsigned int nExitCode)
649 return (pthread_cancel(hthread) == 0);
652 inline void ExitThread(size_t nExitCode)
654 pthread_exit((void*)nExitCode);
662 inline bool AffinityBugWorkaround(void(*pfn)(void*))
665 // Sometimes after a few hours affinity gets stuck on one processor
666 DWORD dwProcessAffinityMask = -1;
667 DWORD dwSystemAffinityMask = -1;
668 GetProcessAffinityMask(GetCurrentProcess(), &dwProcessAffinityMask, &dwSystemAffinityMask);
669 DWORD dwPrev1 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
670 DWORD dwPrev2 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
671 if (dwPrev2 != dwProcessAffinityMask)
673 printf("AffinityBugWorkaround() : SetThreadAffinityMask=%d, ProcessAffinityMask=%d, restarting thread\n", dwPrev2, dwProcessAffinityMask);
674 if (!CreateThread(pfn, NULL))
675 printf("Error: CreateThread() failed\n");