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) std::pair<t1, t2>
70 // Used to bypass the rule against non-const reference to temporary
71 // where it makes sense with wrappers such as CFlatData or CTxDB
73 inline T& REF(const T& val)
78 // Align by increasing pointer, must have extra space at end of buffer
79 template <size_t nBytes, typename T>
88 u.n = (u.n + (nBytes-1)) & ~(nBytes-1);
93 #define MSG_NOSIGNAL 0
94 #define MSG_DONTWAIT 0
96 #define UINT64_MAX _UI64_MAX
97 #define INT64_MAX _I64_MAX
98 #define INT64_MIN _I64_MIN
104 #define unlink _unlink
105 typedef int socklen_t;
107 #define WSAGetLastError() errno
108 #define WSAEINVAL EINVAL
109 #define WSAEALREADY EALREADY
110 #define WSAEWOULDBLOCK EWOULDBLOCK
111 #define WSAEMSGSIZE EMSGSIZE
112 #define WSAEINTR EINTR
113 #define WSAEINPROGRESS EINPROGRESS
114 #define WSAEADDRINUSE EADDRINUSE
115 #define WSAENOTSOCK EBADF
116 #define INVALID_SOCKET (SOCKET)(~0)
117 #define SOCKET_ERROR -1
118 typedef u_int SOCKET;
119 #define _vsnprintf(a,b,c,d) vsnprintf(a,b,c,d)
120 #define strlwr(psz) to_lower(psz)
121 #define _strlwr(psz) to_lower(psz)
122 #define MAX_PATH 1024
123 #define Beep(n1,n2) (0)
124 inline void Sleep(int64 n)
126 boost::thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(n));
130 inline int myclosesocket(SOCKET& hSocket)
132 if (hSocket == INVALID_SOCKET)
135 int ret = closesocket(hSocket);
137 int ret = close(hSocket);
139 hSocket = INVALID_SOCKET;
142 #define closesocket(s) myclosesocket(s)
143 #if !defined(QT_GUI) && !defined(GUI)
144 inline const char* _(const char* psz)
158 extern std::map<std::string, std::string> mapArgs;
159 extern std::map<std::string, std::vector<std::string> > mapMultiArgs;
161 extern bool fPrintToConsole;
162 extern bool fPrintToDebugger;
163 extern char pszSetDataDir[MAX_PATH];
164 extern bool fRequestShutdown;
165 extern bool fShutdown;
168 extern bool fCommandLine;
169 extern std::string strMiscWarning;
170 extern bool fTestNet;
171 extern bool fNoListen;
172 extern bool fLogTimestamps;
175 void RandAddSeedPerfmon();
176 int OutputDebugStringF(const char* pszFormat, ...);
177 int my_snprintf(char* buffer, size_t limit, const char* format, ...);
178 std::string strprintf(const std::string &format, ...);
179 bool error(const std::string &format, ...);
180 void LogException(std::exception* pex, const char* pszThread);
181 void PrintException(std::exception* pex, const char* pszThread);
182 void PrintExceptionContinue(std::exception* pex, const char* pszThread);
183 void ParseString(const std::string& str, char c, std::vector<std::string>& v);
184 std::string FormatMoney(int64 n, bool fPlus=false);
185 bool ParseMoney(const std::string& str, int64& nRet);
186 bool ParseMoney(const char* pszIn, int64& nRet);
187 std::vector<unsigned char> ParseHex(const char* psz);
188 std::vector<unsigned char> ParseHex(const std::string& str);
189 void ParseParameters(int argc, char* argv[]);
190 const char* wxGetTranslation(const char* psz);
191 bool WildcardMatch(const char* psz, const char* mask);
192 bool WildcardMatch(const std::string& str, const std::string& mask);
193 int GetFilesize(FILE* file);
194 void GetDataDir(char* pszDirRet);
195 std::string GetConfigFile();
196 std::string GetPidFile();
197 void CreatePidFile(std::string pidFile, pid_t pid);
198 void ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet, std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet);
200 std::string MyGetSpecialFolderPath(int nFolder, bool fCreate);
202 std::string GetDefaultDataDir();
203 std::string GetDataDir();
204 void ShrinkDebugFile();
205 int GetRandInt(int nMax);
206 uint64 GetRand(uint64 nMax);
208 int64 GetAdjustedTime();
209 void AddTimeData(unsigned int ip, int64 nTime);
210 std::string FormatFullVersion();
224 // Wrapper to automatically initialize mutex
225 class CCriticalSection
228 boost::interprocess::interprocess_recursive_mutex mutex;
230 explicit CCriticalSection() { }
231 ~CCriticalSection() { }
232 void Enter(const char* pszName, const char* pszFile, int nLine);
234 bool TryEnter(const char* pszName, const char* pszFile, int nLine);
237 // Automatically leave critical section when leaving block, needed for exception safety
241 CCriticalSection* pcs;
244 CCriticalBlock(CCriticalSection& csIn, const char* pszName, const char* pszFile, int nLine)
247 pcs->Enter(pszName, pszFile, nLine);
255 // WARNING: This will catch continue and break!
256 // break is caught with an assertion, but there's no way to detect continue.
257 // I'd rather be careful than suffer the other more error prone syntax.
258 // The compiler will optimise away all this loop junk.
259 #define CRITICAL_BLOCK(cs) \
260 for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by CRITICAL_BLOCK!" && !fcriticalblockonce)), fcriticalblockonce=false) \
261 for (CCriticalBlock criticalblock(cs, #cs, __FILE__, __LINE__); fcriticalblockonce; fcriticalblockonce=false)
263 class CTryCriticalBlock
266 CCriticalSection* pcs;
269 CTryCriticalBlock(CCriticalSection& csIn, const char* pszName, const char* pszFile, int nLine)
271 pcs = (csIn.TryEnter(pszName, pszFile, nLine) ? &csIn : NULL);
280 bool Entered() { return pcs != NULL; }
283 #define TRY_CRITICAL_BLOCK(cs) \
284 for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by TRY_CRITICAL_BLOCK!" && !fcriticalblockonce)), fcriticalblockonce=false) \
285 for (CTryCriticalBlock criticalblock(cs, #cs, __FILE__, __LINE__); fcriticalblockonce && (fcriticalblockonce = criticalblock.Entered()); fcriticalblockonce=false)
296 inline std::string i64tostr(int64 n)
298 return strprintf("%"PRI64d, n);
301 inline std::string itostr(int n)
303 return strprintf("%d", n);
306 inline int64 atoi64(const char* psz)
311 return strtoll(psz, NULL, 10);
315 inline int64 atoi64(const std::string& str)
318 return _atoi64(str.c_str());
320 return strtoll(str.c_str(), NULL, 10);
324 inline int atoi(const std::string& str)
326 return atoi(str.c_str());
329 inline int roundint(double d)
331 return (int)(d > 0 ? d + 0.5 : d - 0.5);
334 inline int64 roundint64(double d)
336 return (int64)(d > 0 ? d + 0.5 : d - 0.5);
339 inline int64 abs64(int64 n)
341 return (n >= 0 ? n : -n);
345 std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
347 if (itbegin == itend)
349 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
350 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
352 str.reserve((pend-pbegin) * (fSpaces ? 3 : 2));
353 for (const unsigned char* p = pbegin; p != pend; p++)
354 str += strprintf((fSpaces && p != pend-1 ? "%02x " : "%02x"), *p);
358 inline std::string HexStr(const std::vector<unsigned char>& vch, bool fSpaces=false)
360 return HexStr(vch.begin(), vch.end(), fSpaces);
364 std::string HexNumStr(const T itbegin, const T itend, bool f0x=true)
366 if (itbegin == itend)
368 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
369 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
370 std::string str = (f0x ? "0x" : "");
371 str.reserve(str.size() + (pend-pbegin) * 2);
372 for (const unsigned char* p = pend-1; p >= pbegin; p--)
373 str += strprintf("%02x", *p);
377 inline std::string HexNumStr(const std::vector<unsigned char>& vch, bool f0x=true)
379 return HexNumStr(vch.begin(), vch.end(), f0x);
383 void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)
385 printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());
388 inline void PrintHex(const std::vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true)
390 printf(pszFormat, HexStr(vch, fSpaces).c_str());
393 inline int64 GetPerformanceCounter()
397 QueryPerformanceCounter((LARGE_INTEGER*)&nCounter);
400 gettimeofday(&t, NULL);
401 nCounter = t.tv_sec * 1000000 + t.tv_usec;
406 inline int64 GetTimeMillis()
408 return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) -
409 boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
412 inline std::string DateTimeStrFormat(const char* pszFormat, int64 nTime)
415 struct tm* ptmTime = gmtime(&n);
417 strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime);
422 void skipspaces(T& it)
428 inline bool IsSwitchChar(char c)
431 return c == '-' || c == '/';
437 inline std::string GetArg(const std::string& strArg, const std::string& strDefault)
439 if (mapArgs.count(strArg))
440 return mapArgs[strArg];
444 inline int64 GetArg(const std::string& strArg, int64 nDefault)
446 if (mapArgs.count(strArg))
447 return atoi64(mapArgs[strArg]);
451 inline bool GetBoolArg(const std::string& strArg)
453 if (mapArgs.count(strArg))
455 if (mapArgs[strArg].empty())
457 return (atoi(mapArgs[strArg]) != 0);
471 inline void heapchk()
475 //if (_heapchk() != _HEAPOK)
480 // Randomize the stack to help protect against buffer overrun exploits
481 #define IMPLEMENT_RANDOMIZE_STACK(ThreadFn) \
483 static char nLoops; \
485 nLoops = GetRand(20) + 1; \
493 #define CATCH_PRINT_EXCEPTION(pszFn) \
494 catch (std::exception& e) { \
495 PrintException(&e, (pszFn)); \
497 PrintException(NULL, (pszFn)); \
509 template<typename T1>
510 inline uint256 Hash(const T1 pbegin, const T1 pend)
512 static unsigned char pblank[1];
514 SHA256((pbegin == pend ? pblank : (unsigned char*)&pbegin[0]), (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);
516 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
520 template<typename T1, typename T2>
521 inline uint256 Hash(const T1 p1begin, const T1 p1end,
522 const T2 p2begin, const T2 p2end)
524 static unsigned char pblank[1];
528 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
529 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
530 SHA256_Final((unsigned char*)&hash1, &ctx);
532 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
536 template<typename T1, typename T2, typename T3>
537 inline uint256 Hash(const T1 p1begin, const T1 p1end,
538 const T2 p2begin, const T2 p2end,
539 const T3 p3begin, const T3 p3end)
541 static unsigned char pblank[1];
545 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
546 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
547 SHA256_Update(&ctx, (p3begin == p3end ? pblank : (unsigned char*)&p3begin[0]), (p3end - p3begin) * sizeof(p3begin[0]));
548 SHA256_Final((unsigned char*)&hash1, &ctx);
550 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
555 uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=VERSION)
557 // Most of the time is spent allocating and deallocating CDataStream's
558 // buffer. If this ever needs to be optimized further, make a CStaticStream
559 // class with its buffer on the stack.
560 CDataStream ss(nType, nVersion);
563 return Hash(ss.begin(), ss.end());
566 inline uint160 Hash160(const std::vector<unsigned char>& vch)
569 SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);
571 RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
585 // Note: It turns out we might have been able to use boost::thread
586 // by using TerminateThread(boost::thread.native_handle(), 0);
588 typedef HANDLE pthread_t;
590 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
595 NULL, // default security
596 0, // inherit stack size from parent
597 (LPTHREAD_START_ROUTINE)pfn, // function pointer
599 0, // creation option, start immediately
600 &nUnused); // thread identifier
603 printf("Error: CreateThread() returned %d\n", GetLastError());
608 CloseHandle(hthread);
609 return (pthread_t)-1;
614 inline void SetThreadPriority(int nPriority)
616 SetThreadPriority(GetCurrentThread(), nPriority);
619 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
621 pthread_t hthread = 0;
622 int ret = pthread_create(&hthread, NULL, (void*(*)(void*))pfn, parg);
625 printf("Error: pthread_create() returned %d\n", ret);
630 pthread_detach(hthread);
631 return (pthread_t)-1;
636 #define THREAD_PRIORITY_LOWEST PRIO_MAX
637 #define THREAD_PRIORITY_BELOW_NORMAL 2
638 #define THREAD_PRIORITY_NORMAL 0
639 #define THREAD_PRIORITY_ABOVE_NORMAL 0
641 inline void SetThreadPriority(int nPriority)
643 // It's unclear if it's even possible to change thread priorities on Linux,
644 // but we really and truly need it for the generation threads.
646 setpriority(PRIO_THREAD, 0, nPriority);
648 setpriority(PRIO_PROCESS, 0, nPriority);
652 inline bool TerminateThread(pthread_t hthread, unsigned int nExitCode)
654 return (pthread_cancel(hthread) == 0);
657 inline void ExitThread(size_t nExitCode)
659 pthread_exit((void*)nExitCode);
667 inline bool AffinityBugWorkaround(void(*pfn)(void*))
670 // Sometimes after a few hours affinity gets stuck on one processor
671 DWORD dwProcessAffinityMask = -1;
672 DWORD dwSystemAffinityMask = -1;
673 GetProcessAffinityMask(GetCurrentProcess(), &dwProcessAffinityMask, &dwSystemAffinityMask);
674 DWORD dwPrev1 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
675 DWORD dwPrev2 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
676 if (dwPrev2 != dwProcessAffinityMask)
678 printf("AffinityBugWorkaround() : SetThreadAffinityMask=%d, ProcessAffinityMask=%d, restarting thread\n", dwPrev2, dwProcessAffinityMask);
679 if (!CreateThread(pfn, NULL))
680 printf("Error: CreateThread() failed\n");