1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Copyright (c) 2012 The PPCoin developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
12 #include <sys/types.h>
14 #include <sys/resource.h>
20 #include <boost/thread.hpp>
21 #include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>
22 #include <boost/date_time/gregorian/gregorian_types.hpp>
23 #include <boost/date_time/posix_time/posix_time_types.hpp>
25 #include <openssl/sha.h>
26 #include <openssl/ripemd.h>
29 #if defined(_MSC_VER) || defined(__BORLANDC__)
30 typedef __int64 int64;
31 typedef unsigned __int64 uint64;
33 typedef long long int64;
34 typedef unsigned long long uint64;
36 #if defined(_MSC_VER) && _MSC_VER < 1300
37 #define for if (false) ; else for
40 #define __forceinline inline
44 #define BEGIN(a) ((char*)&(a))
45 #define END(a) ((char*)&((&(a))[1]))
46 #define UBEGIN(a) ((unsigned char*)&(a))
47 #define UEND(a) ((unsigned char*)&((&(a))[1]))
48 #define ARRAYLEN(array) (sizeof(array)/sizeof((array)[0]))
49 #define printf OutputDebugStringF
54 #define snprintf my_snprintf
57 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MSVCRT__)
68 // This is needed because the foreach macro can't get over the comma in pair<t1, t2>
69 #define PAIRTYPE(t1, t2) std::pair<t1, t2>
71 // Align by increasing pointer, must have extra space at end of buffer
72 template <size_t nBytes, typename T>
81 u.n = (u.n + (nBytes-1)) & ~(nBytes-1);
86 #define MSG_NOSIGNAL 0
87 #define MSG_DONTWAIT 0
89 #define UINT64_MAX _UI64_MAX
90 #define INT64_MAX _I64_MAX
91 #define INT64_MIN _I64_MIN
97 #define unlink _unlink
98 typedef int socklen_t;
100 #define WSAGetLastError() errno
101 #define WSAEINVAL EINVAL
102 #define WSAEALREADY EALREADY
103 #define WSAEWOULDBLOCK EWOULDBLOCK
104 #define WSAEMSGSIZE EMSGSIZE
105 #define WSAEINTR EINTR
106 #define WSAEINPROGRESS EINPROGRESS
107 #define WSAEADDRINUSE EADDRINUSE
108 #define WSAENOTSOCK EBADF
109 #define INVALID_SOCKET (SOCKET)(~0)
110 #define SOCKET_ERROR -1
111 typedef u_int SOCKET;
112 #define _vsnprintf(a,b,c,d) vsnprintf(a,b,c,d)
113 #define strlwr(psz) to_lower(psz)
114 #define _strlwr(psz) to_lower(psz)
115 #define MAX_PATH 1024
116 #define Beep(n1,n2) (0)
117 inline void Sleep(int64 n)
119 boost::thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(n));
123 inline int myclosesocket(SOCKET& hSocket)
125 if (hSocket == INVALID_SOCKET)
128 int ret = closesocket(hSocket);
130 int ret = close(hSocket);
132 hSocket = INVALID_SOCKET;
135 #define closesocket(s) myclosesocket(s)
137 inline const char* _(const char* psz)
143 #ifndef THROW_WITH_STACKTRACE
144 #define THROW_WITH_STACKTRACE(exception) \
149 void LogStackTrace();
157 extern std::map<std::string, std::string> mapArgs;
158 extern std::map<std::string, std::vector<std::string> > mapMultiArgs;
160 extern bool fPrintToConsole;
161 extern bool fPrintToDebugger;
162 extern char pszSetDataDir[MAX_PATH];
163 extern bool fRequestShutdown;
164 extern bool fShutdown;
167 extern bool fCommandLine;
168 extern std::string strMiscWarning;
169 extern bool fTestNet;
170 extern bool fNoListen;
171 extern bool fLogTimestamps;
174 void RandAddSeedPerfmon();
175 int OutputDebugStringF(const char* pszFormat, ...);
176 int my_snprintf(char* buffer, size_t limit, const char* format, ...);
177 std::string strprintf(const std::string &format, ...);
178 bool error(const std::string &format, ...);
179 void LogException(std::exception* pex, const char* pszThread);
180 void PrintException(std::exception* pex, const char* pszThread);
181 void PrintExceptionContinue(std::exception* pex, const char* pszThread);
182 void ParseString(const std::string& str, char c, std::vector<std::string>& v);
183 std::string FormatMoney(int64 n, bool fPlus=false);
184 bool ParseMoney(const std::string& str, int64& nRet);
185 bool ParseMoney(const char* pszIn, int64& nRet);
186 std::vector<unsigned char> ParseHex(const char* psz);
187 std::vector<unsigned char> ParseHex(const std::string& str);
188 std::vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid = NULL);
189 std::string DecodeBase64(const std::string& str);
190 std::string EncodeBase64(const unsigned char* pch, size_t len);
191 std::string EncodeBase64(const std::string& str);
192 void ParseParameters(int argc, char* argv[]);
193 const char* wxGetTranslation(const char* psz);
194 bool WildcardMatch(const char* psz, const char* mask);
195 bool WildcardMatch(const std::string& str, const std::string& mask);
196 int GetFilesize(FILE* file);
197 void GetDataDir(char* pszDirRet);
198 std::string GetConfigFile();
199 std::string GetPidFile();
200 void CreatePidFile(std::string pidFile, pid_t pid);
201 void ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet, std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet);
203 std::string MyGetSpecialFolderPath(int nFolder, bool fCreate);
205 std::string GetDefaultDataDir();
206 std::string GetDataDir();
207 void ShrinkDebugFile();
208 int GetRandInt(int nMax);
209 uint64 GetRand(uint64 nMax);
211 void SetMockTime(int64 nMockTimeIn);
212 int64 GetAdjustedTime();
213 void AddTimeData(unsigned int ip, int64 nTime);
214 std::string FormatFullVersion();
228 // Wrapper to automatically initialize mutex
229 class CCriticalSection
232 boost::interprocess::interprocess_recursive_mutex mutex;
234 explicit CCriticalSection() { }
235 ~CCriticalSection() { }
236 void Enter(const char* pszName, const char* pszFile, int nLine);
238 bool TryEnter(const char* pszName, const char* pszFile, int nLine);
241 // Automatically leave critical section when leaving block, needed for exception safety
245 CCriticalSection* pcs;
248 CCriticalBlock(CCriticalSection& csIn, const char* pszName, const char* pszFile, int nLine)
251 pcs->Enter(pszName, pszFile, nLine);
254 operator bool() const
265 #define CRITICAL_BLOCK(cs) \
266 if (CCriticalBlock criticalblock = CCriticalBlock(cs, #cs, __FILE__, __LINE__))
268 class CTryCriticalBlock
271 CCriticalSection* pcs;
274 CTryCriticalBlock(CCriticalSection& csIn, const char* pszName, const char* pszFile, int nLine)
276 pcs = (csIn.TryEnter(pszName, pszFile, nLine) ? &csIn : NULL);
279 operator bool() const
291 bool Entered() const { return pcs != NULL; }
294 #define TRY_CRITICAL_BLOCK(cs) \
295 if (CTryCriticalBlock criticalblock = CTryCriticalBlock(cs, #cs, __FILE__, __LINE__))
302 // This is exactly like std::string, but with a custom allocator.
303 // (secure_allocator<> is defined in serialize.h)
304 typedef std::basic_string<char, std::char_traits<char>, secure_allocator<char> > SecureString;
310 inline std::string i64tostr(int64 n)
312 return strprintf("%"PRI64d, n);
315 inline std::string itostr(int n)
317 return strprintf("%d", n);
320 inline int64 atoi64(const char* psz)
325 return strtoll(psz, NULL, 10);
329 inline int64 atoi64(const std::string& str)
332 return _atoi64(str.c_str());
334 return strtoll(str.c_str(), NULL, 10);
338 inline int atoi(const std::string& str)
340 return atoi(str.c_str());
343 inline int roundint(double d)
345 return (int)(d > 0 ? d + 0.5 : d - 0.5);
348 inline int64 roundint64(double d)
350 return (int64)(d > 0 ? d + 0.5 : d - 0.5);
353 inline int64 abs64(int64 n)
355 return (n >= 0 ? n : -n);
359 std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
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]);
366 str.reserve((pend-pbegin) * (fSpaces ? 3 : 2));
367 for (const unsigned char* p = pbegin; p != pend; p++)
368 str += strprintf((fSpaces && p != pend-1 ? "%02x " : "%02x"), *p);
372 inline std::string HexStr(const std::vector<unsigned char>& vch, bool fSpaces=false)
374 return HexStr(vch.begin(), vch.end(), fSpaces);
378 std::string HexNumStr(const T itbegin, const T itend, bool f0x=true)
380 if (itbegin == itend)
382 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
383 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
384 std::string str = (f0x ? "0x" : "");
385 str.reserve(str.size() + (pend-pbegin) * 2);
386 for (const unsigned char* p = pend-1; p >= pbegin; p--)
387 str += strprintf("%02x", *p);
391 inline std::string HexNumStr(const std::vector<unsigned char>& vch, bool f0x=true)
393 return HexNumStr(vch.begin(), vch.end(), f0x);
397 void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)
399 printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());
402 inline void PrintHex(const std::vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true)
404 printf(pszFormat, HexStr(vch, fSpaces).c_str());
407 inline int64 GetPerformanceCounter()
411 QueryPerformanceCounter((LARGE_INTEGER*)&nCounter);
414 gettimeofday(&t, NULL);
415 nCounter = t.tv_sec * 1000000 + t.tv_usec;
420 inline int64 GetTimeMillis()
422 return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) -
423 boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
426 inline std::string DateTimeStrFormat(const char* pszFormat, int64 nTime)
429 struct tm* ptmTime = gmtime(&n);
431 strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime);
436 void skipspaces(T& it)
442 inline bool IsSwitchChar(char c)
445 return c == '-' || c == '/';
451 inline std::string GetArg(const std::string& strArg, const std::string& strDefault)
453 if (mapArgs.count(strArg))
454 return mapArgs[strArg];
458 inline int64 GetArg(const std::string& strArg, int64 nDefault)
460 if (mapArgs.count(strArg))
461 return atoi64(mapArgs[strArg]);
465 inline bool GetBoolArg(const std::string& strArg)
467 if (mapArgs.count(strArg))
469 if (mapArgs[strArg].empty())
471 return (atoi(mapArgs[strArg]) != 0);
485 inline void heapchk()
489 //if (_heapchk() != _HEAPOK)
494 // Randomize the stack to help protect against buffer overrun exploits
495 #define IMPLEMENT_RANDOMIZE_STACK(ThreadFn) \
497 static char nLoops; \
499 nLoops = GetRand(20) + 1; \
507 #define CATCH_PRINT_EXCEPTION(pszFn) \
508 catch (std::exception& e) { \
509 PrintException(&e, (pszFn)); \
511 PrintException(NULL, (pszFn)); \
523 template<typename T1>
524 inline uint256 Hash(const T1 pbegin, const T1 pend)
526 static unsigned char pblank[1];
528 SHA256((pbegin == pend ? pblank : (unsigned char*)&pbegin[0]), (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);
530 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
534 template<typename T1, typename T2>
535 inline uint256 Hash(const T1 p1begin, const T1 p1end,
536 const T2 p2begin, const T2 p2end)
538 static unsigned char pblank[1];
542 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
543 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
544 SHA256_Final((unsigned char*)&hash1, &ctx);
546 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
550 template<typename T1, typename T2, typename T3>
551 inline uint256 Hash(const T1 p1begin, const T1 p1end,
552 const T2 p2begin, const T2 p2end,
553 const T3 p3begin, const T3 p3end)
555 static unsigned char pblank[1];
559 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
560 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
561 SHA256_Update(&ctx, (p3begin == p3end ? pblank : (unsigned char*)&p3begin[0]), (p3end - p3begin) * sizeof(p3begin[0]));
562 SHA256_Final((unsigned char*)&hash1, &ctx);
564 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
569 uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=VERSION)
571 // Most of the time is spent allocating and deallocating CDataStream's
572 // buffer. If this ever needs to be optimized further, make a CStaticStream
573 // class with its buffer on the stack.
574 CDataStream ss(nType, nVersion);
577 return Hash(ss.begin(), ss.end());
580 inline uint160 Hash160(const std::vector<unsigned char>& vch)
583 SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);
585 RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
590 // Median filter over a stream of values
591 // Returns the median of the last N numbers
592 template <typename T> class CMedianFilter
595 std::vector<T> vValues;
596 std::vector<T> vSorted;
599 CMedianFilter(int size, T initial_value):
602 vValues.reserve(size);
603 vValues.push_back(initial_value);
609 if(vValues.size() == nSize)
611 vValues.erase(vValues.begin());
613 vValues.push_back(value);
615 vSorted.resize(vValues.size());
616 std::copy(vValues.begin(), vValues.end(), vSorted.begin());
617 std::sort(vSorted.begin(), vSorted.end());
622 int size = vSorted.size();
624 if(size & 1) // Odd number of elements
626 return vSorted[size/2];
628 else // Even number of elements
630 return (vSorted[size/2-1] + vSorted[size/2]) / 2;
644 // Note: It turns out we might have been able to use boost::thread
645 // by using TerminateThread(boost::thread.native_handle(), 0);
647 typedef HANDLE bitcoin_pthread_t;
649 inline bitcoin_pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
654 NULL, // default security
655 0, // inherit stack size from parent
656 (LPTHREAD_START_ROUTINE)pfn, // function pointer
658 0, // creation option, start immediately
659 &nUnused); // thread identifier
662 printf("Error: CreateThread() returned %d\n", GetLastError());
663 return (bitcoin_pthread_t)0;
667 CloseHandle(hthread);
668 return (bitcoin_pthread_t)-1;
673 inline void SetThreadPriority(int nPriority)
675 SetThreadPriority(GetCurrentThread(), nPriority);
678 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
680 pthread_t hthread = 0;
681 int ret = pthread_create(&hthread, NULL, (void*(*)(void*))pfn, parg);
684 printf("Error: pthread_create() returned %d\n", ret);
689 pthread_detach(hthread);
690 return (pthread_t)-1;
695 #define THREAD_PRIORITY_LOWEST PRIO_MAX
696 #define THREAD_PRIORITY_BELOW_NORMAL 2
697 #define THREAD_PRIORITY_NORMAL 0
698 #define THREAD_PRIORITY_ABOVE_NORMAL 0
700 inline void SetThreadPriority(int nPriority)
702 // It's unclear if it's even possible to change thread priorities on Linux,
703 // but we really and truly need it for the generation threads.
705 setpriority(PRIO_THREAD, 0, nPriority);
707 setpriority(PRIO_PROCESS, 0, nPriority);
711 inline bool TerminateThread(pthread_t hthread, unsigned int nExitCode)
713 return (pthread_cancel(hthread) == 0);
716 inline void ExitThread(size_t nExitCode)
718 pthread_exit((void*)nExitCode);
726 inline bool AffinityBugWorkaround(void(*pfn)(void*))
729 // Sometimes after a few hours affinity gets stuck on one processor
730 DWORD_PTR dwProcessAffinityMask = -1;
731 DWORD_PTR dwSystemAffinityMask = -1;
732 GetProcessAffinityMask(GetCurrentProcess(), &dwProcessAffinityMask, &dwSystemAffinityMask);
733 DWORD dwPrev1 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
734 DWORD dwPrev2 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
735 if (dwPrev2 != dwProcessAffinityMask)
737 printf("AffinityBugWorkaround() : SetThreadAffinityMask=%d, ProcessAffinityMask=%d, restarting thread\n", dwPrev2, dwProcessAffinityMask);
738 if (!CreateThread(pfn, NULL))
739 printf("Error: CreateThread() failed\n");
746 inline uint32_t ByteReverse(uint32_t value)
748 value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8);
749 return (value<<16) | (value>>16);