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.
13 #include <sys/types.h>
15 #include <sys/resource.h>
21 #include <boost/thread.hpp>
22 #include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>
23 #include <boost/date_time/gregorian/gregorian_types.hpp>
24 #include <boost/date_time/posix_time/posix_time_types.hpp>
26 #include <openssl/sha.h>
27 #include <openssl/ripemd.h>
31 #define BEGIN(a) ((char*)&(a))
32 #define END(a) ((char*)&((&(a))[1]))
33 #define UBEGIN(a) ((unsigned char*)&(a))
34 #define UEND(a) ((unsigned char*)&((&(a))[1]))
35 #define ARRAYLEN(array) (sizeof(array)/sizeof((array)[0]))
36 #define printf OutputDebugStringF
41 #define snprintf my_snprintf
44 #if defined(_MSC_VER) || defined(__MSVCRT__)
55 // This is needed because the foreach macro can't get over the comma in pair<t1, t2>
56 #define PAIRTYPE(t1, t2) std::pair<t1, t2>
58 // Align by increasing pointer, must have extra space at end of buffer
59 template <size_t nBytes, typename T>
68 u.n = (u.n + (nBytes-1)) & ~(nBytes-1);
73 #define MSG_NOSIGNAL 0
74 #define MSG_DONTWAIT 0
80 #define unlink _unlink
81 typedef int socklen_t;
83 #define WSAGetLastError() errno
84 #define WSAEINVAL EINVAL
85 #define WSAEALREADY EALREADY
86 #define WSAEWOULDBLOCK EWOULDBLOCK
87 #define WSAEMSGSIZE EMSGSIZE
88 #define WSAEINTR EINTR
89 #define WSAEINPROGRESS EINPROGRESS
90 #define WSAEADDRINUSE EADDRINUSE
91 #define WSAENOTSOCK EBADF
92 #define INVALID_SOCKET (SOCKET)(~0)
93 #define SOCKET_ERROR -1
95 #define _vsnprintf(a,b,c,d) vsnprintf(a,b,c,d)
96 #define strlwr(psz) to_lower(psz)
97 #define _strlwr(psz) to_lower(psz)
99 #define Beep(n1,n2) (0)
100 inline void Sleep(int64_t n)
102 boost::thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(n));
106 inline int myclosesocket(SOCKET& hSocket)
108 if (hSocket == INVALID_SOCKET)
111 int ret = closesocket(hSocket);
113 int ret = close(hSocket);
115 hSocket = INVALID_SOCKET;
118 #define closesocket(s) myclosesocket(s)
120 inline const char* _(const char* psz)
134 extern std::map<std::string, std::string> mapArgs;
135 extern std::map<std::string, std::vector<std::string> > mapMultiArgs;
137 extern bool fPrintToConsole;
138 extern bool fPrintToDebugger;
139 extern char pszSetDataDir[MAX_PATH];
140 extern bool fRequestShutdown;
141 extern bool fShutdown;
144 extern bool fCommandLine;
145 extern std::string strMiscWarning;
146 extern bool fTestNet;
147 extern bool fNoListen;
148 extern bool fLogTimestamps;
151 void RandAddSeedPerfmon();
152 int OutputDebugStringF(const char* pszFormat, ...);
153 int my_snprintf(char* buffer, size_t limit, const char* format, ...);
154 std::string strprintf(const std::string &format, ...);
155 bool error(const std::string &format, ...);
156 void LogException(std::exception* pex, const char* pszThread);
157 void PrintException(std::exception* pex, const char* pszThread);
158 void PrintExceptionContinue(std::exception* pex, const char* pszThread);
159 void ParseString(const std::string& str, char c, std::vector<std::string>& v);
160 std::string FormatMoney(int64_t n, bool fPlus=false);
161 bool ParseMoney(const std::string& str, int64_t& nRet);
162 bool ParseMoney(const char* pszIn, int64_t& nRet);
163 std::vector<unsigned char> ParseHex(const char* psz);
164 std::vector<unsigned char> ParseHex(const std::string& str);
165 std::vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid = NULL);
166 std::string DecodeBase64(const std::string& str);
167 std::string EncodeBase64(const unsigned char* pch, size_t len);
168 std::string EncodeBase64(const std::string& str);
169 void ParseParameters(int argc, char* argv[]);
170 bool WildcardMatch(const char* psz, const char* mask);
171 bool WildcardMatch(const std::string& str, const std::string& mask);
172 int GetFilesize(FILE* file);
173 void GetDataDir(char* pszDirRet);
174 std::string GetConfigFile();
175 std::string GetPidFile();
176 void CreatePidFile(std::string pidFile, pid_t pid);
177 void ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet, std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet);
179 std::string MyGetSpecialFolderPath(int nFolder, bool fCreate);
181 std::string GetDefaultDataDir();
182 std::string GetDataDir();
183 void ShrinkDebugFile();
184 int GetRandInt(int nMax);
185 uint64_t GetRand(uint64_t nMax);
187 void SetMockTime(int64_t nMockTimeIn);
188 int64_t GetAdjustedTime();
189 void AddTimeData(unsigned int ip, int64_t nTime);
190 std::string FormatFullVersion();
191 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments);
204 // Wrapper to automatically initialize mutex
205 class CCriticalSection
208 boost::interprocess::interprocess_recursive_mutex mutex;
210 explicit CCriticalSection() { }
211 ~CCriticalSection() { }
212 void Enter(const char* pszName, const char* pszFile, int nLine);
214 bool TryEnter(const char* pszName, const char* pszFile, int nLine);
217 // Automatically leave critical section when leaving block, needed for exception safety
221 CCriticalSection* pcs;
224 CCriticalBlock(CCriticalSection& csIn, const char* pszName, const char* pszFile, int nLine)
227 pcs->Enter(pszName, pszFile, nLine);
230 operator bool() const
241 #define CRITICAL_BLOCK(cs) \
242 if (CCriticalBlock criticalblock = CCriticalBlock(cs, #cs, __FILE__, __LINE__))
244 class CTryCriticalBlock
247 CCriticalSection* pcs;
250 CTryCriticalBlock(CCriticalSection& csIn, const char* pszName, const char* pszFile, int nLine)
252 pcs = (csIn.TryEnter(pszName, pszFile, nLine) ? &csIn : NULL);
255 operator bool() const
267 bool Entered() const { return pcs != NULL; }
270 #define TRY_CRITICAL_BLOCK(cs) \
271 if (CTryCriticalBlock criticalblock = CTryCriticalBlock(cs, #cs, __FILE__, __LINE__))
278 // This is exactly like std::string, but with a custom allocator.
279 // (secure_allocator<> is defined in serialize.h)
280 typedef std::basic_string<char, std::char_traits<char>, secure_allocator<char> > SecureString;
286 inline std::string i64tostr(int64_t n)
288 return strprintf("%"PRI64d, n);
291 inline std::string itostr(int n)
293 return strprintf("%d", n);
296 inline int64_t atoi64(const char* psz)
301 return strtoll(psz, NULL, 10);
305 inline int64_t atoi64(const std::string& str)
308 return _atoi64(str.c_str());
310 return strtoll(str.c_str(), NULL, 10);
314 inline int atoi(const std::string& str)
316 return atoi(str.c_str());
319 inline int roundint(double d)
321 return (int)(d > 0 ? d + 0.5 : d - 0.5);
324 inline int64_t roundint64(double d)
326 return (int64_t)(d > 0 ? d + 0.5 : d - 0.5);
329 inline int64_t abs64(int64_t n)
331 return (n >= 0 ? n : -n);
335 std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
337 if (itbegin == itend)
339 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
340 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
342 str.reserve((pend-pbegin) * (fSpaces ? 3 : 2));
343 for (const unsigned char* p = pbegin; p != pend; p++)
344 str += strprintf((fSpaces && p != pend-1 ? "%02x " : "%02x"), *p);
348 inline std::string HexStr(const std::vector<unsigned char>& vch, bool fSpaces=false)
350 return HexStr(vch.begin(), vch.end(), fSpaces);
354 std::string HexNumStr(const T itbegin, const T itend, bool f0x=true)
356 if (itbegin == itend)
358 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
359 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
360 std::string str = (f0x ? "0x" : "");
361 str.reserve(str.size() + (pend-pbegin) * 2);
362 for (const unsigned char* p = pend-1; p >= pbegin; p--)
363 str += strprintf("%02x", *p);
367 inline std::string HexNumStr(const std::vector<unsigned char>& vch, bool f0x=true)
369 return HexNumStr(vch.begin(), vch.end(), f0x);
373 void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)
375 printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());
378 inline void PrintHex(const std::vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true)
380 printf(pszFormat, HexStr(vch, fSpaces).c_str());
383 inline int64_t GetPerformanceCounter()
385 int64_t nCounter = 0;
387 QueryPerformanceCounter((LARGE_INTEGER*)&nCounter);
390 gettimeofday(&t, NULL);
391 nCounter = t.tv_sec * 1000000 + t.tv_usec;
396 inline int64_t GetTimeMillis()
398 return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) -
399 boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
402 inline std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime)
405 struct tm* ptmTime = gmtime(&n);
407 strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime);
412 void skipspaces(T& it)
418 inline bool IsSwitchChar(char c)
421 return c == '-' || c == '/';
427 inline std::string GetArg(const std::string& strArg, const std::string& strDefault)
429 if (mapArgs.count(strArg))
430 return mapArgs[strArg];
434 inline int64_t GetArg(const std::string& strArg, int64_t nDefault)
436 if (mapArgs.count(strArg))
437 return atoi64(mapArgs[strArg]);
441 inline bool GetBoolArg(const std::string& strArg)
443 if (mapArgs.count(strArg))
445 if (mapArgs[strArg].empty())
447 return (atoi(mapArgs[strArg]) != 0);
461 // Randomize the stack to help protect against buffer overrun exploits
462 #define IMPLEMENT_RANDOMIZE_STACK(ThreadFn) \
464 static char nLoops; \
466 nLoops = GetRand(20) + 1; \
474 #define CATCH_PRINT_EXCEPTION(pszFn) \
475 catch (std::exception& e) { \
476 PrintException(&e, (pszFn)); \
478 PrintException(NULL, (pszFn)); \
490 template<typename T1>
491 inline uint256 Hash(const T1 pbegin, const T1 pend)
493 static unsigned char pblank[1];
495 SHA256((pbegin == pend ? pblank : (unsigned char*)&pbegin[0]), (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);
497 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
501 template<typename T1, typename T2>
502 inline uint256 Hash(const T1 p1begin, const T1 p1end,
503 const T2 p2begin, const T2 p2end)
505 static unsigned char pblank[1];
509 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
510 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
511 SHA256_Final((unsigned char*)&hash1, &ctx);
513 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
517 template<typename T1, typename T2, typename T3>
518 inline uint256 Hash(const T1 p1begin, const T1 p1end,
519 const T2 p2begin, const T2 p2end,
520 const T3 p3begin, const T3 p3end)
522 static unsigned char pblank[1];
526 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
527 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
528 SHA256_Update(&ctx, (p3begin == p3end ? pblank : (unsigned char*)&p3begin[0]), (p3end - p3begin) * sizeof(p3begin[0]));
529 SHA256_Final((unsigned char*)&hash1, &ctx);
531 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
536 uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=PROTOCOL_VERSION)
538 // Most of the time is spent allocating and deallocating CDataStream's
539 // buffer. If this ever needs to be optimized further, make a CStaticStream
540 // class with its buffer on the stack.
541 CDataStream ss(nType, nVersion);
544 return Hash(ss.begin(), ss.end());
547 inline uint160 Hash160(const std::vector<unsigned char>& vch)
550 SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);
552 RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
557 // Median filter over a stream of values
558 // Returns the median of the last N numbers
559 template <typename T> class CMedianFilter
562 std::vector<T> vValues;
563 std::vector<T> vSorted;
566 CMedianFilter(int size, T initial_value):
569 vValues.reserve(size);
570 vValues.push_back(initial_value);
576 if(vValues.size() == nSize)
578 vValues.erase(vValues.begin());
580 vValues.push_back(value);
582 vSorted.resize(vValues.size());
583 std::copy(vValues.begin(), vValues.end(), vSorted.begin());
584 std::sort(vSorted.begin(), vSorted.end());
589 int size = vSorted.size();
591 if(size & 1) // Odd number of elements
593 return vSorted[size/2];
595 else // Even number of elements
597 return (vSorted[size/2-1] + vSorted[size/2]) / 2;
603 return vValues.size();
606 std::vector<T> sorted () const
621 // Note: It turns out we might have been able to use boost::thread
622 // by using TerminateThread(boost::thread.native_handle(), 0);
624 typedef HANDLE pthread_t;
626 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
631 NULL, // default security
632 0, // inherit stack size from parent
633 (LPTHREAD_START_ROUTINE)pfn, // function pointer
635 0, // creation option, start immediately
636 &nUnused); // thread identifier
639 printf("Error: CreateThread() returned %d\n", GetLastError());
644 CloseHandle(hthread);
645 return (pthread_t)-1;
650 inline void SetThreadPriority(int nPriority)
652 SetThreadPriority(GetCurrentThread(), nPriority);
655 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
657 pthread_t hthread = 0;
658 int ret = pthread_create(&hthread, NULL, (void*(*)(void*))pfn, parg);
661 printf("Error: pthread_create() returned %d\n", ret);
666 pthread_detach(hthread);
667 return (pthread_t)-1;
672 #define THREAD_PRIORITY_LOWEST PRIO_MAX
673 #define THREAD_PRIORITY_BELOW_NORMAL 2
674 #define THREAD_PRIORITY_NORMAL 0
675 #define THREAD_PRIORITY_ABOVE_NORMAL 0
677 inline void SetThreadPriority(int nPriority)
679 // It's unclear if it's even possible to change thread priorities on Linux,
680 // but we really and truly need it for the generation threads.
682 setpriority(PRIO_THREAD, 0, nPriority);
684 setpriority(PRIO_PROCESS, 0, nPriority);
688 inline bool TerminateThread(pthread_t hthread, unsigned int nExitCode)
690 return (pthread_cancel(hthread) == 0);
693 inline void ExitThread(size_t nExitCode)
695 pthread_exit((void*)nExitCode);
703 inline bool AffinityBugWorkaround(void(*pfn)(void*))
706 // Sometimes after a few hours affinity gets stuck on one processor
707 DWORD_PTR dwProcessAffinityMask = -1;
708 DWORD_PTR dwSystemAffinityMask = -1;
709 GetProcessAffinityMask(GetCurrentProcess(), &dwProcessAffinityMask, &dwSystemAffinityMask);
710 DWORD dwPrev1 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
711 DWORD dwPrev2 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
712 if (dwPrev2 != dwProcessAffinityMask)
714 printf("AffinityBugWorkaround() : SetThreadAffinityMask=%d, ProcessAffinityMask=%d, restarting thread\n", dwPrev2, dwProcessAffinityMask);
715 if (!CreateThread(pfn, NULL))
716 printf("Error: CreateThread() failed\n");
723 inline uint32_t ByteReverse(uint32_t value)
725 value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8);
726 return (value<<16) | (value>>16);