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 // 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)
136 inline const char* _(const char* psz)
150 extern std::map<std::string, std::string> mapArgs;
151 extern std::map<std::string, std::vector<std::string> > mapMultiArgs;
153 extern bool fPrintToConsole;
154 extern bool fPrintToDebugger;
155 extern char pszSetDataDir[MAX_PATH];
156 extern bool fRequestShutdown;
157 extern bool fShutdown;
160 extern bool fCommandLine;
161 extern std::string strMiscWarning;
162 extern bool fTestNet;
163 extern bool fNoListen;
164 extern bool fLogTimestamps;
167 void RandAddSeedPerfmon();
168 int OutputDebugStringF(const char* pszFormat, ...);
169 int my_snprintf(char* buffer, size_t limit, const char* format, ...);
170 std::string strprintf(const std::string &format, ...);
171 bool error(const std::string &format, ...);
172 void LogException(std::exception* pex, const char* pszThread);
173 void PrintException(std::exception* pex, const char* pszThread);
174 void PrintExceptionContinue(std::exception* pex, const char* pszThread);
175 void ParseString(const std::string& str, char c, std::vector<std::string>& v);
176 std::string FormatMoney(int64 n, bool fPlus=false);
177 bool ParseMoney(const std::string& str, int64& nRet);
178 bool ParseMoney(const char* pszIn, int64& nRet);
179 std::vector<unsigned char> ParseHex(const char* psz);
180 std::vector<unsigned char> ParseHex(const std::string& str);
181 std::vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid = NULL);
182 std::string DecodeBase64(const std::string& str);
183 std::string EncodeBase64(const unsigned char* pch, size_t len);
184 std::string EncodeBase64(const std::string& str);
185 void ParseParameters(int argc, char* argv[]);
186 const char* wxGetTranslation(const char* psz);
187 bool WildcardMatch(const char* psz, const char* mask);
188 bool WildcardMatch(const std::string& str, const std::string& mask);
189 int GetFilesize(FILE* file);
190 void GetDataDir(char* pszDirRet);
191 std::string GetConfigFile();
192 std::string GetPidFile();
193 void CreatePidFile(std::string pidFile, pid_t pid);
194 void ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet, std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet);
196 std::string MyGetSpecialFolderPath(int nFolder, bool fCreate);
198 std::string GetDefaultDataDir();
199 std::string GetDataDir();
200 void ShrinkDebugFile();
201 int GetRandInt(int nMax);
202 uint64 GetRand(uint64 nMax);
204 void SetMockTime(int64 nMockTimeIn);
205 int64 GetAdjustedTime();
206 void AddTimeData(unsigned int ip, int64 nTime);
207 std::string FormatFullVersion();
221 // Wrapper to automatically initialize mutex
222 class CCriticalSection
225 boost::interprocess::interprocess_recursive_mutex mutex;
227 explicit CCriticalSection() { }
228 ~CCriticalSection() { }
229 void Enter(const char* pszName, const char* pszFile, int nLine);
231 bool TryEnter(const char* pszName, const char* pszFile, int nLine);
234 // Automatically leave critical section when leaving block, needed for exception safety
238 CCriticalSection* pcs;
241 CCriticalBlock(CCriticalSection& csIn, const char* pszName, const char* pszFile, int nLine)
244 pcs->Enter(pszName, pszFile, nLine);
247 operator bool() const
258 #define CRITICAL_BLOCK(cs) \
259 if (CCriticalBlock criticalblock = CCriticalBlock(cs, #cs, __FILE__, __LINE__))
261 class CTryCriticalBlock
264 CCriticalSection* pcs;
267 CTryCriticalBlock(CCriticalSection& csIn, const char* pszName, const char* pszFile, int nLine)
269 pcs = (csIn.TryEnter(pszName, pszFile, nLine) ? &csIn : NULL);
272 operator bool() const
284 bool Entered() const { return pcs != NULL; }
287 #define TRY_CRITICAL_BLOCK(cs) \
288 if (CTryCriticalBlock criticalblock = CTryCriticalBlock(cs, #cs, __FILE__, __LINE__))
295 // This is exactly like std::string, but with a custom allocator.
296 // (secure_allocator<> is defined in serialize.h)
297 typedef std::basic_string<char, std::char_traits<char>, secure_allocator<char> > SecureString;
303 inline std::string i64tostr(int64 n)
305 return strprintf("%"PRI64d, n);
308 inline std::string itostr(int n)
310 return strprintf("%d", n);
313 inline int64 atoi64(const char* psz)
318 return strtoll(psz, NULL, 10);
322 inline int64 atoi64(const std::string& str)
325 return _atoi64(str.c_str());
327 return strtoll(str.c_str(), NULL, 10);
331 inline int atoi(const std::string& str)
333 return atoi(str.c_str());
336 inline int roundint(double d)
338 return (int)(d > 0 ? d + 0.5 : d - 0.5);
341 inline int64 roundint64(double d)
343 return (int64)(d > 0 ? d + 0.5 : d - 0.5);
346 inline int64 abs64(int64 n)
348 return (n >= 0 ? n : -n);
352 std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
354 if (itbegin == itend)
356 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
357 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
359 str.reserve((pend-pbegin) * (fSpaces ? 3 : 2));
360 for (const unsigned char* p = pbegin; p != pend; p++)
361 str += strprintf((fSpaces && p != pend-1 ? "%02x " : "%02x"), *p);
365 inline std::string HexStr(const std::vector<unsigned char>& vch, bool fSpaces=false)
367 return HexStr(vch.begin(), vch.end(), fSpaces);
371 std::string HexNumStr(const T itbegin, const T itend, bool f0x=true)
373 if (itbegin == itend)
375 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
376 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
377 std::string str = (f0x ? "0x" : "");
378 str.reserve(str.size() + (pend-pbegin) * 2);
379 for (const unsigned char* p = pend-1; p >= pbegin; p--)
380 str += strprintf("%02x", *p);
384 inline std::string HexNumStr(const std::vector<unsigned char>& vch, bool f0x=true)
386 return HexNumStr(vch.begin(), vch.end(), f0x);
390 void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)
392 printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());
395 inline void PrintHex(const std::vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true)
397 printf(pszFormat, HexStr(vch, fSpaces).c_str());
400 inline int64 GetPerformanceCounter()
404 QueryPerformanceCounter((LARGE_INTEGER*)&nCounter);
407 gettimeofday(&t, NULL);
408 nCounter = t.tv_sec * 1000000 + t.tv_usec;
413 inline int64 GetTimeMillis()
415 return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) -
416 boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
419 inline std::string DateTimeStrFormat(const char* pszFormat, int64 nTime)
422 struct tm* ptmTime = gmtime(&n);
424 strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime);
429 void skipspaces(T& it)
435 inline bool IsSwitchChar(char c)
438 return c == '-' || c == '/';
444 inline std::string GetArg(const std::string& strArg, const std::string& strDefault)
446 if (mapArgs.count(strArg))
447 return mapArgs[strArg];
451 inline int64 GetArg(const std::string& strArg, int64 nDefault)
453 if (mapArgs.count(strArg))
454 return atoi64(mapArgs[strArg]);
458 inline bool GetBoolArg(const std::string& strArg)
460 if (mapArgs.count(strArg))
462 if (mapArgs[strArg].empty())
464 return (atoi(mapArgs[strArg]) != 0);
478 inline void heapchk()
482 //if (_heapchk() != _HEAPOK)
487 // Randomize the stack to help protect against buffer overrun exploits
488 #define IMPLEMENT_RANDOMIZE_STACK(ThreadFn) \
490 static char nLoops; \
492 nLoops = GetRand(20) + 1; \
500 #define CATCH_PRINT_EXCEPTION(pszFn) \
501 catch (std::exception& e) { \
502 PrintException(&e, (pszFn)); \
504 PrintException(NULL, (pszFn)); \
516 template<typename T1>
517 inline uint256 Hash(const T1 pbegin, const T1 pend)
519 static unsigned char pblank[1];
521 SHA256((pbegin == pend ? pblank : (unsigned char*)&pbegin[0]), (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);
523 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
527 template<typename T1, typename T2>
528 inline uint256 Hash(const T1 p1begin, const T1 p1end,
529 const T2 p2begin, const T2 p2end)
531 static unsigned char pblank[1];
535 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
536 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
537 SHA256_Final((unsigned char*)&hash1, &ctx);
539 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
543 template<typename T1, typename T2, typename T3>
544 inline uint256 Hash(const T1 p1begin, const T1 p1end,
545 const T2 p2begin, const T2 p2end,
546 const T3 p3begin, const T3 p3end)
548 static unsigned char pblank[1];
552 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
553 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
554 SHA256_Update(&ctx, (p3begin == p3end ? pblank : (unsigned char*)&p3begin[0]), (p3end - p3begin) * sizeof(p3begin[0]));
555 SHA256_Final((unsigned char*)&hash1, &ctx);
557 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
562 uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=VERSION)
564 // Most of the time is spent allocating and deallocating CDataStream's
565 // buffer. If this ever needs to be optimized further, make a CStaticStream
566 // class with its buffer on the stack.
567 CDataStream ss(nType, nVersion);
570 return Hash(ss.begin(), ss.end());
573 inline uint160 Hash160(const std::vector<unsigned char>& vch)
576 SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);
578 RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
583 // Median filter over a stream of values
584 // Returns the median of the last N numbers
585 template <typename T> class CMedianFilter
588 std::vector<T> vValues;
589 std::vector<T> vSorted;
592 CMedianFilter(int size, T initial_value):
595 vValues.reserve(size);
596 vValues.push_back(initial_value);
602 if(vValues.size() == nSize)
604 vValues.erase(vValues.begin());
606 vValues.push_back(value);
608 vSorted.resize(vValues.size());
609 std::copy(vValues.begin(), vValues.end(), vSorted.begin());
610 std::sort(vSorted.begin(), vSorted.end());
615 int size = vSorted.size();
617 if(size & 1) // Odd number of elements
619 return vSorted[size/2];
621 else // Even number of elements
623 return (vSorted[size/2-1] + vSorted[size/2]) / 2;
637 // Note: It turns out we might have been able to use boost::thread
638 // by using TerminateThread(boost::thread.native_handle(), 0);
640 typedef HANDLE pthread_t;
642 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
647 NULL, // default security
648 0, // inherit stack size from parent
649 (LPTHREAD_START_ROUTINE)pfn, // function pointer
651 0, // creation option, start immediately
652 &nUnused); // thread identifier
655 printf("Error: CreateThread() returned %d\n", GetLastError());
660 CloseHandle(hthread);
661 return (pthread_t)-1;
666 inline void SetThreadPriority(int nPriority)
668 SetThreadPriority(GetCurrentThread(), nPriority);
671 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
673 pthread_t hthread = 0;
674 int ret = pthread_create(&hthread, NULL, (void*(*)(void*))pfn, parg);
677 printf("Error: pthread_create() returned %d\n", ret);
682 pthread_detach(hthread);
683 return (pthread_t)-1;
688 #define THREAD_PRIORITY_LOWEST PRIO_MAX
689 #define THREAD_PRIORITY_BELOW_NORMAL 2
690 #define THREAD_PRIORITY_NORMAL 0
691 #define THREAD_PRIORITY_ABOVE_NORMAL 0
693 inline void SetThreadPriority(int nPriority)
695 // It's unclear if it's even possible to change thread priorities on Linux,
696 // but we really and truly need it for the generation threads.
698 setpriority(PRIO_THREAD, 0, nPriority);
700 setpriority(PRIO_PROCESS, 0, nPriority);
704 inline bool TerminateThread(pthread_t hthread, unsigned int nExitCode)
706 return (pthread_cancel(hthread) == 0);
709 inline void ExitThread(size_t nExitCode)
711 pthread_exit((void*)nExitCode);
719 inline bool AffinityBugWorkaround(void(*pfn)(void*))
722 // Sometimes after a few hours affinity gets stuck on one processor
723 DWORD_PTR dwProcessAffinityMask = -1;
724 DWORD_PTR dwSystemAffinityMask = -1;
725 GetProcessAffinityMask(GetCurrentProcess(), &dwProcessAffinityMask, &dwSystemAffinityMask);
726 DWORD dwPrev1 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
727 DWORD dwPrev2 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
728 if (dwPrev2 != dwProcessAffinityMask)
730 printf("AffinityBugWorkaround() : SetThreadAffinityMask=%d, ProcessAffinityMask=%d, restarting thread\n", dwPrev2, dwProcessAffinityMask);
731 if (!CreateThread(pfn, NULL))
732 printf("Error: CreateThread() failed\n");
739 inline uint32_t ByteReverse(uint32_t value)
741 value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8);
742 return (value<<16) | (value>>16);