1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 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 // 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 has a year 2038 problem— if the request sleep time is past epoch+2^31 seconds the sleep returns instantly.
119 So we clamp our sleeps here to 10 years and hope that boost is fixed by 2028.*/
120 boost::thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(n>315576000000LL?315576000000LL:n));
124 inline int myclosesocket(SOCKET& hSocket)
126 if (hSocket == INVALID_SOCKET)
129 int ret = closesocket(hSocket);
131 int ret = close(hSocket);
133 hSocket = INVALID_SOCKET;
136 #define closesocket(s) myclosesocket(s)
138 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 std::string &format, ...);
173 bool error(const std::string &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 std::vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid = NULL);
184 std::string DecodeBase64(const std::string& str);
185 std::string EncodeBase64(const unsigned char* pch, size_t len);
186 std::string EncodeBase64(const std::string& str);
187 void ParseParameters(int argc, char* argv[]);
188 const char* wxGetTranslation(const char* psz);
189 bool WildcardMatch(const char* psz, const char* mask);
190 bool WildcardMatch(const std::string& str, const std::string& mask);
191 int GetFilesize(FILE* file);
192 void GetDataDir(char* pszDirRet);
193 std::string GetConfigFile();
194 std::string GetPidFile();
195 void CreatePidFile(std::string pidFile, pid_t pid);
196 void ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet, std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet);
198 std::string MyGetSpecialFolderPath(int nFolder, bool fCreate);
200 std::string GetDefaultDataDir();
201 std::string GetDataDir();
202 void ShrinkDebugFile();
203 int GetRandInt(int nMax);
204 uint64 GetRand(uint64 nMax);
206 void SetMockTime(int64 nMockTimeIn);
207 int64 GetAdjustedTime();
208 void AddTimeData(unsigned int ip, int64 nTime);
209 std::string FormatFullVersion();
223 // Wrapper to automatically initialize mutex
224 class CCriticalSection
227 boost::interprocess::interprocess_recursive_mutex mutex;
229 explicit CCriticalSection() { }
230 ~CCriticalSection() { }
231 void Enter(const char* pszName, const char* pszFile, int nLine);
233 bool TryEnter(const char* pszName, const char* pszFile, int nLine);
236 // Automatically leave critical section when leaving block, needed for exception safety
240 CCriticalSection* pcs;
243 CCriticalBlock(CCriticalSection& csIn, const char* pszName, const char* pszFile, int nLine)
246 pcs->Enter(pszName, pszFile, nLine);
249 operator bool() const
260 #define CRITICAL_BLOCK(cs) \
261 if (CCriticalBlock criticalblock = CCriticalBlock(cs, #cs, __FILE__, __LINE__))
263 #define ENTER_CRITICAL_SECTION(cs) \
264 (cs).Enter(#cs, __FILE__, __LINE__)
266 #define LEAVE_CRITICAL_SECTION(cs) \
269 class CTryCriticalBlock
272 CCriticalSection* pcs;
275 CTryCriticalBlock(CCriticalSection& csIn, const char* pszName, const char* pszFile, int nLine)
277 pcs = (csIn.TryEnter(pszName, pszFile, nLine) ? &csIn : NULL);
280 operator bool() const
292 bool Entered() const { return pcs != NULL; }
295 #define TRY_CRITICAL_BLOCK(cs) \
296 if (CTryCriticalBlock criticalblock = CTryCriticalBlock(cs, #cs, __FILE__, __LINE__))
303 // This is exactly like std::string, but with a custom allocator.
304 // (secure_allocator<> is defined in serialize.h)
305 typedef std::basic_string<char, std::char_traits<char>, secure_allocator<char> > SecureString;
307 // This is exactly like std::string, but with a custom allocator.
308 // (secure_allocator<> is defined in serialize.h)
309 typedef std::basic_string<char, std::char_traits<char>, secure_allocator<char> > SecureString;
315 inline std::string i64tostr(int64 n)
317 return strprintf("%"PRI64d, n);
320 inline std::string itostr(int n)
322 return strprintf("%d", n);
325 inline int64 atoi64(const char* psz)
330 return strtoll(psz, NULL, 10);
334 inline int64 atoi64(const std::string& str)
337 return _atoi64(str.c_str());
339 return strtoll(str.c_str(), NULL, 10);
343 inline int atoi(const std::string& str)
345 return atoi(str.c_str());
348 inline int roundint(double d)
350 return (int)(d > 0 ? d + 0.5 : d - 0.5);
353 inline int64 roundint64(double d)
355 return (int64)(d > 0 ? d + 0.5 : d - 0.5);
358 inline int64 abs64(int64 n)
360 return (n >= 0 ? n : -n);
364 std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
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]);
371 str.reserve((pend-pbegin) * (fSpaces ? 3 : 2));
372 for (const unsigned char* p = pbegin; p != pend; p++)
373 str += strprintf((fSpaces && p != pend-1 ? "%02x " : "%02x"), *p);
377 inline std::string HexStr(const std::vector<unsigned char>& vch, bool fSpaces=false)
379 return HexStr(vch.begin(), vch.end(), fSpaces);
383 std::string HexNumStr(const T itbegin, const T itend, bool f0x=true)
385 if (itbegin == itend)
387 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
388 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
389 std::string str = (f0x ? "0x" : "");
390 str.reserve(str.size() + (pend-pbegin) * 2);
391 for (const unsigned char* p = pend-1; p >= pbegin; p--)
392 str += strprintf("%02x", *p);
396 inline std::string HexNumStr(const std::vector<unsigned char>& vch, bool f0x=true)
398 return HexNumStr(vch.begin(), vch.end(), f0x);
402 void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)
404 printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());
407 inline void PrintHex(const std::vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true)
409 printf(pszFormat, HexStr(vch, fSpaces).c_str());
412 inline int64 GetPerformanceCounter()
416 QueryPerformanceCounter((LARGE_INTEGER*)&nCounter);
419 gettimeofday(&t, NULL);
420 nCounter = t.tv_sec * 1000000 + t.tv_usec;
425 inline int64 GetTimeMillis()
427 return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) -
428 boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
431 inline std::string DateTimeStrFormat(const char* pszFormat, int64 nTime)
434 struct tm* ptmTime = gmtime(&n);
436 strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime);
441 void skipspaces(T& it)
447 inline bool IsSwitchChar(char c)
450 return c == '-' || c == '/';
456 inline std::string GetArg(const std::string& strArg, const std::string& strDefault)
458 if (mapArgs.count(strArg))
459 return mapArgs[strArg];
463 inline int64 GetArg(const std::string& strArg, int64 nDefault)
465 if (mapArgs.count(strArg))
466 return atoi64(mapArgs[strArg]);
470 inline bool GetBoolArg(const std::string& strArg, bool fDefault=false)
472 if (mapArgs.count(strArg))
474 if (mapArgs[strArg].empty())
476 return (atoi(mapArgs[strArg]) != 0);
482 * Set an argument if it doesn't already have a value
484 * @param strArg Argument to set (e.g. "-foo")
485 * @param strValue Value (e.g. "1")
486 * @return true if argument gets set, false if it already had a value
488 bool SoftSetArg(const std::string& strArg, const std::string& strValue);
491 * Set a boolean argument if it doesn't already have a value
493 * @param strArg Argument to set (e.g. "-foo")
494 * @param fValue Value (e.g. false)
495 * @return true if argument gets set, false if it already had a value
497 bool SoftSetArg(const std::string& strArg, bool fValue);
507 inline void heapchk()
511 //if (_heapchk() != _HEAPOK)
516 // Randomize the stack to help protect against buffer overrun exploits
517 #define IMPLEMENT_RANDOMIZE_STACK(ThreadFn) \
519 static char nLoops; \
521 nLoops = GetRand(20) + 1; \
529 #define CATCH_PRINT_EXCEPTION(pszFn) \
530 catch (std::exception& e) { \
531 PrintException(&e, (pszFn)); \
533 PrintException(NULL, (pszFn)); \
545 template<typename T1>
546 inline uint256 Hash(const T1 pbegin, const T1 pend)
548 static unsigned char pblank[1];
550 SHA256((pbegin == pend ? pblank : (unsigned char*)&pbegin[0]), (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);
552 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
556 template<typename T1, typename T2>
557 inline uint256 Hash(const T1 p1begin, const T1 p1end,
558 const T2 p2begin, const T2 p2end)
560 static unsigned char pblank[1];
564 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
565 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
566 SHA256_Final((unsigned char*)&hash1, &ctx);
568 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
572 template<typename T1, typename T2, typename T3>
573 inline uint256 Hash(const T1 p1begin, const T1 p1end,
574 const T2 p2begin, const T2 p2end,
575 const T3 p3begin, const T3 p3end)
577 static unsigned char pblank[1];
581 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
582 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
583 SHA256_Update(&ctx, (p3begin == p3end ? pblank : (unsigned char*)&p3begin[0]), (p3end - p3begin) * sizeof(p3begin[0]));
584 SHA256_Final((unsigned char*)&hash1, &ctx);
586 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
591 uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=VERSION)
593 // Most of the time is spent allocating and deallocating CDataStream's
594 // buffer. If this ever needs to be optimized further, make a CStaticStream
595 // class with its buffer on the stack.
596 CDataStream ss(nType, nVersion);
599 return Hash(ss.begin(), ss.end());
602 inline uint160 Hash160(const std::vector<unsigned char>& vch)
605 SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);
607 RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
612 // Median filter over a stream of values
613 // Returns the median of the last N numbers
614 template <typename T> class CMedianFilter
617 std::vector<T> vValues;
618 std::vector<T> vSorted;
621 CMedianFilter(int size, T initial_value):
624 vValues.reserve(size);
625 vValues.push_back(initial_value);
631 if(vValues.size() == nSize)
633 vValues.erase(vValues.begin());
635 vValues.push_back(value);
637 vSorted.resize(vValues.size());
638 std::copy(vValues.begin(), vValues.end(), vSorted.begin());
639 std::sort(vSorted.begin(), vSorted.end());
644 int size = vSorted.size();
646 if(size & 1) // Odd number of elements
648 return vSorted[size/2];
650 else // Even number of elements
652 return (vSorted[size/2-1] + vSorted[size/2]) / 2;
666 // Note: It turns out we might have been able to use boost::thread
667 // by using TerminateThread(boost::thread.native_handle(), 0);
669 typedef HANDLE pthread_t;
671 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
676 NULL, // default security
677 0, // inherit stack size from parent
678 (LPTHREAD_START_ROUTINE)pfn, // function pointer
680 0, // creation option, start immediately
681 &nUnused); // thread identifier
684 printf("Error: CreateThread() returned %d\n", GetLastError());
689 CloseHandle(hthread);
690 return (pthread_t)-1;
695 inline void SetThreadPriority(int nPriority)
697 SetThreadPriority(GetCurrentThread(), nPriority);
700 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
702 pthread_t hthread = 0;
703 int ret = pthread_create(&hthread, NULL, (void*(*)(void*))pfn, parg);
706 printf("Error: pthread_create() returned %d\n", ret);
711 pthread_detach(hthread);
712 return (pthread_t)-1;
717 #define THREAD_PRIORITY_LOWEST PRIO_MAX
718 #define THREAD_PRIORITY_BELOW_NORMAL 2
719 #define THREAD_PRIORITY_NORMAL 0
720 #define THREAD_PRIORITY_ABOVE_NORMAL 0
722 inline void SetThreadPriority(int nPriority)
724 // It's unclear if it's even possible to change thread priorities on Linux,
725 // but we really and truly need it for the generation threads.
727 setpriority(PRIO_THREAD, 0, nPriority);
729 setpriority(PRIO_PROCESS, 0, nPriority);
733 inline bool TerminateThread(pthread_t hthread, unsigned int nExitCode)
735 return (pthread_cancel(hthread) == 0);
738 inline void ExitThread(size_t nExitCode)
740 pthread_exit((void*)nExitCode);
748 inline bool AffinityBugWorkaround(void(*pfn)(void*))
751 // Sometimes after a few hours affinity gets stuck on one processor
752 DWORD_PTR dwProcessAffinityMask = -1;
753 DWORD_PTR dwSystemAffinityMask = -1;
754 GetProcessAffinityMask(GetCurrentProcess(), &dwProcessAffinityMask, &dwSystemAffinityMask);
755 DWORD dwPrev1 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
756 DWORD dwPrev2 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
757 if (dwPrev2 != dwProcessAffinityMask)
759 printf("AffinityBugWorkaround() : SetThreadAffinityMask=%d, ProcessAffinityMask=%d, restarting thread\n", dwPrev2, dwProcessAffinityMask);
760 if (!CreateThread(pfn, NULL))
761 printf("Error: CreateThread() failed\n");
768 inline uint32_t ByteReverse(uint32_t value)
770 value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8);
771 return (value<<16) | (value>>16);