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 typedef long long int64;
29 typedef unsigned long long uint64;
32 #define BEGIN(a) ((char*)&(a))
33 #define END(a) ((char*)&((&(a))[1]))
34 #define UBEGIN(a) ((unsigned char*)&(a))
35 #define UEND(a) ((unsigned char*)&((&(a))[1]))
36 #define ARRAYLEN(array) (sizeof(array)/sizeof((array)[0]))
37 #define printf OutputDebugStringF
42 #define snprintf my_snprintf
45 #if defined(_MSC_VER) || defined(__MSVCRT__)
56 // This is needed because the foreach macro can't get over the comma in pair<t1, t2>
57 #define PAIRTYPE(t1, t2) std::pair<t1, t2>
59 // Align by increasing pointer, must have extra space at end of buffer
60 template <size_t nBytes, typename T>
69 u.n = (u.n + (nBytes-1)) & ~(nBytes-1);
74 #define MSG_NOSIGNAL 0
75 #define MSG_DONTWAIT 0
77 #define UINT64_MAX _UI64_MAX
78 #define INT64_MAX _I64_MAX
79 #define INT64_MIN _I64_MIN
85 #define unlink _unlink
86 typedef int socklen_t;
88 #define WSAGetLastError() errno
89 #define WSAEINVAL EINVAL
90 #define WSAEALREADY EALREADY
91 #define WSAEWOULDBLOCK EWOULDBLOCK
92 #define WSAEMSGSIZE EMSGSIZE
93 #define WSAEINTR EINTR
94 #define WSAEINPROGRESS EINPROGRESS
95 #define WSAEADDRINUSE EADDRINUSE
96 #define WSAENOTSOCK EBADF
97 #define INVALID_SOCKET (SOCKET)(~0)
98 #define SOCKET_ERROR -1
100 #define _vsnprintf(a,b,c,d) vsnprintf(a,b,c,d)
101 #define strlwr(psz) to_lower(psz)
102 #define _strlwr(psz) to_lower(psz)
103 #define MAX_PATH 1024
104 #define Beep(n1,n2) (0)
105 inline void Sleep(int64 n)
107 boost::thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(n));
111 inline int myclosesocket(SOCKET& hSocket)
113 if (hSocket == INVALID_SOCKET)
116 int ret = closesocket(hSocket);
118 int ret = close(hSocket);
120 hSocket = INVALID_SOCKET;
123 #define closesocket(s) myclosesocket(s)
125 inline const char* _(const char* psz)
139 extern std::map<std::string, std::string> mapArgs;
140 extern std::map<std::string, std::vector<std::string> > mapMultiArgs;
142 extern bool fPrintToConsole;
143 extern bool fPrintToDebugger;
144 extern char pszSetDataDir[MAX_PATH];
145 extern bool fRequestShutdown;
146 extern bool fShutdown;
149 extern bool fCommandLine;
150 extern std::string strMiscWarning;
151 extern bool fTestNet;
152 extern bool fNoListen;
153 extern bool fLogTimestamps;
156 void RandAddSeedPerfmon();
157 int OutputDebugStringF(const char* pszFormat, ...);
158 int my_snprintf(char* buffer, size_t limit, const char* format, ...);
159 std::string strprintf(const std::string &format, ...);
160 bool error(const std::string &format, ...);
161 void LogException(std::exception* pex, const char* pszThread);
162 void PrintException(std::exception* pex, const char* pszThread);
163 void PrintExceptionContinue(std::exception* pex, const char* pszThread);
164 void ParseString(const std::string& str, char c, std::vector<std::string>& v);
165 std::string FormatMoney(int64 n, bool fPlus=false);
166 bool ParseMoney(const std::string& str, int64& nRet);
167 bool ParseMoney(const char* pszIn, int64& nRet);
168 std::vector<unsigned char> ParseHex(const char* psz);
169 std::vector<unsigned char> ParseHex(const std::string& str);
170 std::vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid = NULL);
171 std::string DecodeBase64(const std::string& str);
172 std::string EncodeBase64(const unsigned char* pch, size_t len);
173 std::string EncodeBase64(const std::string& str);
174 void ParseParameters(int argc, char* argv[]);
175 bool WildcardMatch(const char* psz, const char* mask);
176 bool WildcardMatch(const std::string& str, const std::string& mask);
177 int GetFilesize(FILE* file);
178 void GetDataDir(char* pszDirRet);
179 std::string GetConfigFile();
180 std::string GetPidFile();
181 void CreatePidFile(std::string pidFile, pid_t pid);
182 void ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet, std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet);
184 std::string MyGetSpecialFolderPath(int nFolder, bool fCreate);
186 std::string GetDefaultDataDir();
187 std::string GetDataDir();
188 void ShrinkDebugFile();
189 int GetRandInt(int nMax);
190 uint64 GetRand(uint64 nMax);
192 void SetMockTime(int64 nMockTimeIn);
193 int64 GetAdjustedTime();
194 void AddTimeData(unsigned int ip, int64 nTime);
195 std::string FormatFullVersion();
196 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments);
209 // Wrapper to automatically initialize mutex
210 class CCriticalSection
213 boost::interprocess::interprocess_recursive_mutex mutex;
215 explicit CCriticalSection() { }
216 ~CCriticalSection() { }
217 void Enter(const char* pszName, const char* pszFile, int nLine);
219 bool TryEnter(const char* pszName, const char* pszFile, int nLine);
222 // Automatically leave critical section when leaving block, needed for exception safety
226 CCriticalSection* pcs;
229 CCriticalBlock(CCriticalSection& csIn, const char* pszName, const char* pszFile, int nLine)
232 pcs->Enter(pszName, pszFile, nLine);
235 operator bool() const
246 #define CRITICAL_BLOCK(cs) \
247 if (CCriticalBlock criticalblock = CCriticalBlock(cs, #cs, __FILE__, __LINE__))
249 class CTryCriticalBlock
252 CCriticalSection* pcs;
255 CTryCriticalBlock(CCriticalSection& csIn, const char* pszName, const char* pszFile, int nLine)
257 pcs = (csIn.TryEnter(pszName, pszFile, nLine) ? &csIn : NULL);
260 operator bool() const
272 bool Entered() const { return pcs != NULL; }
275 #define TRY_CRITICAL_BLOCK(cs) \
276 if (CTryCriticalBlock criticalblock = CTryCriticalBlock(cs, #cs, __FILE__, __LINE__))
283 // This is exactly like std::string, but with a custom allocator.
284 // (secure_allocator<> is defined in serialize.h)
285 typedef std::basic_string<char, std::char_traits<char>, secure_allocator<char> > SecureString;
291 inline std::string i64tostr(int64 n)
293 return strprintf("%"PRI64d, n);
296 inline std::string itostr(int n)
298 return strprintf("%d", n);
301 inline int64 atoi64(const char* psz)
306 return strtoll(psz, NULL, 10);
310 inline int64 atoi64(const std::string& str)
313 return _atoi64(str.c_str());
315 return strtoll(str.c_str(), NULL, 10);
319 inline int atoi(const std::string& str)
321 return atoi(str.c_str());
324 inline int roundint(double d)
326 return (int)(d > 0 ? d + 0.5 : d - 0.5);
329 inline int64 roundint64(double d)
331 return (int64)(d > 0 ? d + 0.5 : d - 0.5);
334 inline int64 abs64(int64 n)
336 return (n >= 0 ? n : -n);
340 std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
342 if (itbegin == itend)
344 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
345 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
347 str.reserve((pend-pbegin) * (fSpaces ? 3 : 2));
348 for (const unsigned char* p = pbegin; p != pend; p++)
349 str += strprintf((fSpaces && p != pend-1 ? "%02x " : "%02x"), *p);
353 inline std::string HexStr(const std::vector<unsigned char>& vch, bool fSpaces=false)
355 return HexStr(vch.begin(), vch.end(), fSpaces);
359 std::string HexNumStr(const T itbegin, const T itend, bool f0x=true)
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]);
365 std::string str = (f0x ? "0x" : "");
366 str.reserve(str.size() + (pend-pbegin) * 2);
367 for (const unsigned char* p = pend-1; p >= pbegin; p--)
368 str += strprintf("%02x", *p);
372 inline std::string HexNumStr(const std::vector<unsigned char>& vch, bool f0x=true)
374 return HexNumStr(vch.begin(), vch.end(), f0x);
378 void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)
380 printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());
383 inline void PrintHex(const std::vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true)
385 printf(pszFormat, HexStr(vch, fSpaces).c_str());
388 inline int64 GetPerformanceCounter()
392 QueryPerformanceCounter((LARGE_INTEGER*)&nCounter);
395 gettimeofday(&t, NULL);
396 nCounter = t.tv_sec * 1000000 + t.tv_usec;
401 inline int64 GetTimeMillis()
403 return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) -
404 boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
407 inline std::string DateTimeStrFormat(const char* pszFormat, int64 nTime)
410 struct tm* ptmTime = gmtime(&n);
412 strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime);
417 void skipspaces(T& it)
423 inline bool IsSwitchChar(char c)
426 return c == '-' || c == '/';
432 inline std::string GetArg(const std::string& strArg, const std::string& strDefault)
434 if (mapArgs.count(strArg))
435 return mapArgs[strArg];
439 inline int64 GetArg(const std::string& strArg, int64 nDefault)
441 if (mapArgs.count(strArg))
442 return atoi64(mapArgs[strArg]);
446 inline bool GetBoolArg(const std::string& strArg)
448 if (mapArgs.count(strArg))
450 if (mapArgs[strArg].empty())
452 return (atoi(mapArgs[strArg]) != 0);
466 // Randomize the stack to help protect against buffer overrun exploits
467 #define IMPLEMENT_RANDOMIZE_STACK(ThreadFn) \
469 static char nLoops; \
471 nLoops = GetRand(20) + 1; \
479 #define CATCH_PRINT_EXCEPTION(pszFn) \
480 catch (std::exception& e) { \
481 PrintException(&e, (pszFn)); \
483 PrintException(NULL, (pszFn)); \
495 template<typename T1>
496 inline uint256 Hash(const T1 pbegin, const T1 pend)
498 static unsigned char pblank[1];
500 SHA256((pbegin == pend ? pblank : (unsigned char*)&pbegin[0]), (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);
502 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
506 template<typename T1, typename T2>
507 inline uint256 Hash(const T1 p1begin, const T1 p1end,
508 const T2 p2begin, const T2 p2end)
510 static unsigned char pblank[1];
514 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
515 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
516 SHA256_Final((unsigned char*)&hash1, &ctx);
518 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
522 template<typename T1, typename T2, typename T3>
523 inline uint256 Hash(const T1 p1begin, const T1 p1end,
524 const T2 p2begin, const T2 p2end,
525 const T3 p3begin, const T3 p3end)
527 static unsigned char pblank[1];
531 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
532 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
533 SHA256_Update(&ctx, (p3begin == p3end ? pblank : (unsigned char*)&p3begin[0]), (p3end - p3begin) * sizeof(p3begin[0]));
534 SHA256_Final((unsigned char*)&hash1, &ctx);
536 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
541 uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=PROTOCOL_VERSION)
543 // Most of the time is spent allocating and deallocating CDataStream's
544 // buffer. If this ever needs to be optimized further, make a CStaticStream
545 // class with its buffer on the stack.
546 CDataStream ss(nType, nVersion);
549 return Hash(ss.begin(), ss.end());
552 inline uint160 Hash160(const std::vector<unsigned char>& vch)
555 SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);
557 RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
562 // Median filter over a stream of values
563 // Returns the median of the last N numbers
564 template <typename T> class CMedianFilter
567 std::vector<T> vValues;
568 std::vector<T> vSorted;
571 CMedianFilter(int size, T initial_value):
574 vValues.reserve(size);
575 vValues.push_back(initial_value);
581 if(vValues.size() == nSize)
583 vValues.erase(vValues.begin());
585 vValues.push_back(value);
587 vSorted.resize(vValues.size());
588 std::copy(vValues.begin(), vValues.end(), vSorted.begin());
589 std::sort(vSorted.begin(), vSorted.end());
594 int size = vSorted.size();
596 if(size & 1) // Odd number of elements
598 return vSorted[size/2];
600 else // Even number of elements
602 return (vSorted[size/2-1] + vSorted[size/2]) / 2;
616 // Note: It turns out we might have been able to use boost::thread
617 // by using TerminateThread(boost::thread.native_handle(), 0);
619 typedef HANDLE pthread_t;
621 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
626 NULL, // default security
627 0, // inherit stack size from parent
628 (LPTHREAD_START_ROUTINE)pfn, // function pointer
630 0, // creation option, start immediately
631 &nUnused); // thread identifier
634 printf("Error: CreateThread() returned %d\n", GetLastError());
639 CloseHandle(hthread);
640 return (pthread_t)-1;
645 inline void SetThreadPriority(int nPriority)
647 SetThreadPriority(GetCurrentThread(), nPriority);
650 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
652 pthread_t hthread = 0;
653 int ret = pthread_create(&hthread, NULL, (void*(*)(void*))pfn, parg);
656 printf("Error: pthread_create() returned %d\n", ret);
661 pthread_detach(hthread);
662 return (pthread_t)-1;
667 #define THREAD_PRIORITY_LOWEST PRIO_MAX
668 #define THREAD_PRIORITY_BELOW_NORMAL 2
669 #define THREAD_PRIORITY_NORMAL 0
670 #define THREAD_PRIORITY_ABOVE_NORMAL 0
672 inline void SetThreadPriority(int nPriority)
674 // It's unclear if it's even possible to change thread priorities on Linux,
675 // but we really and truly need it for the generation threads.
677 setpriority(PRIO_THREAD, 0, nPriority);
679 setpriority(PRIO_PROCESS, 0, nPriority);
683 inline bool TerminateThread(pthread_t hthread, unsigned int nExitCode)
685 return (pthread_cancel(hthread) == 0);
688 inline void ExitThread(size_t nExitCode)
690 pthread_exit((void*)nExitCode);
698 inline bool AffinityBugWorkaround(void(*pfn)(void*))
701 // Sometimes after a few hours affinity gets stuck on one processor
702 DWORD_PTR dwProcessAffinityMask = -1;
703 DWORD_PTR dwSystemAffinityMask = -1;
704 GetProcessAffinityMask(GetCurrentProcess(), &dwProcessAffinityMask, &dwSystemAffinityMask);
705 DWORD dwPrev1 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
706 DWORD dwPrev2 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
707 if (dwPrev2 != dwProcessAffinityMask)
709 printf("AffinityBugWorkaround() : SetThreadAffinityMask=%d, ProcessAffinityMask=%d, restarting thread\n", dwPrev2, dwProcessAffinityMask);
710 if (!CreateThread(pfn, NULL))
711 printf("Error: CreateThread() failed\n");
718 inline uint32_t ByteReverse(uint32_t value)
720 value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8);
721 return (value<<16) | (value>>16);