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>
29 typedef long long int64;
30 typedef unsigned long long uint64;
33 #define BEGIN(a) ((char*)&(a))
34 #define END(a) ((char*)&((&(a))[1]))
35 #define UBEGIN(a) ((unsigned char*)&(a))
36 #define UEND(a) ((unsigned char*)&((&(a))[1]))
37 #define ARRAYLEN(array) (sizeof(array)/sizeof((array)[0]))
38 #define printf OutputDebugStringF
43 #define snprintf my_snprintf
46 #if defined(_MSC_VER) || defined(__MSVCRT__)
57 // This is needed because the foreach macro can't get over the comma in pair<t1, t2>
58 #define PAIRTYPE(t1, t2) std::pair<t1, t2>
60 // Align by increasing pointer, must have extra space at end of buffer
61 template <size_t nBytes, typename T>
70 u.n = (u.n + (nBytes-1)) & ~(nBytes-1);
75 #define MSG_NOSIGNAL 0
76 #define MSG_DONTWAIT 0
82 #define unlink _unlink
84 #define _vsnprintf(a,b,c,d) vsnprintf(a,b,c,d)
85 #define strlwr(psz) to_lower(psz)
86 #define _strlwr(psz) to_lower(psz)
88 inline void Sleep(int64 n)
90 /*Boost has a year 2038 problem— if the request sleep time is past epoch+2^31 seconds the sleep returns instantly.
91 So we clamp our sleeps here to 10 years and hope that boost is fixed by 2028.*/
92 boost::thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(n>315576000000LL?315576000000LL:n));
97 inline const char* _(const char* psz)
111 extern std::map<std::string, std::string> mapArgs;
112 extern std::map<std::string, std::vector<std::string> > mapMultiArgs;
114 extern bool fPrintToConsole;
115 extern bool fPrintToDebugger;
116 extern char pszSetDataDir[MAX_PATH];
117 extern bool fRequestShutdown;
118 extern bool fShutdown;
121 extern bool fCommandLine;
122 extern std::string strMiscWarning;
123 extern bool fTestNet;
124 extern bool fNoListen;
125 extern bool fLogTimestamps;
128 void RandAddSeedPerfmon();
129 int OutputDebugStringF(const char* pszFormat, ...);
130 int my_snprintf(char* buffer, size_t limit, const char* format, ...);
131 std::string strprintf(const std::string &format, ...);
132 bool error(const std::string &format, ...);
133 void LogException(std::exception* pex, const char* pszThread);
134 void PrintException(std::exception* pex, const char* pszThread);
135 void PrintExceptionContinue(std::exception* pex, const char* pszThread);
136 void ParseString(const std::string& str, char c, std::vector<std::string>& v);
137 std::string FormatMoney(int64 n, bool fPlus=false);
138 bool ParseMoney(const std::string& str, int64& nRet);
139 bool ParseMoney(const char* pszIn, int64& nRet);
140 std::vector<unsigned char> ParseHex(const char* psz);
141 std::vector<unsigned char> ParseHex(const std::string& str);
142 bool IsHex(const std::string& str);
143 std::vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid = NULL);
144 std::string DecodeBase64(const std::string& str);
145 std::string EncodeBase64(const unsigned char* pch, size_t len);
146 std::string EncodeBase64(const std::string& str);
147 void ParseParameters(int argc, const char*const argv[]);
148 bool WildcardMatch(const char* psz, const char* mask);
149 bool WildcardMatch(const std::string& str, const std::string& mask);
150 int GetFilesize(FILE* file);
151 void GetDataDir(char* pszDirRet);
152 std::string GetConfigFile();
153 std::string GetPidFile();
154 void CreatePidFile(std::string pidFile, pid_t pid);
155 bool ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet, std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet);
157 std::string MyGetSpecialFolderPath(int nFolder, bool fCreate);
159 std::string GetDefaultDataDir();
160 std::string GetDataDir();
161 void ShrinkDebugFile();
162 int GetRandInt(int nMax);
163 uint64 GetRand(uint64 nMax);
165 void SetMockTime(int64 nMockTimeIn);
166 int64 GetAdjustedTime();
167 std::string FormatFullVersion();
168 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments);
169 void AddTimeData(const CNetAddr& ip, int64 nTime);
182 /** Wrapper to automatically initialize mutex. */
183 class CCriticalSection
186 boost::interprocess::interprocess_recursive_mutex mutex;
188 explicit CCriticalSection() { }
189 ~CCriticalSection() { }
190 void Enter(const char* pszName, const char* pszFile, int nLine);
192 bool TryEnter(const char* pszName, const char* pszFile, int nLine);
195 /** RAII object that acquires mutex. Needed for exception safety. */
199 CCriticalSection* pcs;
202 CCriticalBlock(CCriticalSection& csIn, const char* pszName, const char* pszFile, int nLine)
205 pcs->Enter(pszName, pszFile, nLine);
208 operator bool() const
219 #define CRITICAL_BLOCK(cs) \
220 if (CCriticalBlock criticalblock = CCriticalBlock(cs, #cs, __FILE__, __LINE__))
222 #define ENTER_CRITICAL_SECTION(cs) \
223 (cs).Enter(#cs, __FILE__, __LINE__)
225 #define LEAVE_CRITICAL_SECTION(cs) \
228 /** RAII object that tries to acquire mutex. Needed for exception safety. */
229 class CTryCriticalBlock
232 CCriticalSection* pcs;
235 CTryCriticalBlock(CCriticalSection& csIn, const char* pszName, const char* pszFile, int nLine)
237 pcs = (csIn.TryEnter(pszName, pszFile, nLine) ? &csIn : NULL);
240 operator bool() const
252 bool Entered() const { return pcs != NULL; }
255 #define TRY_CRITICAL_BLOCK(cs) \
256 if (CTryCriticalBlock criticalblock = CTryCriticalBlock(cs, #cs, __FILE__, __LINE__))
263 // This is exactly like std::string, but with a custom allocator.
264 // (secure_allocator<> is defined in serialize.h)
265 typedef std::basic_string<char, std::char_traits<char>, secure_allocator<char> > SecureString;
271 inline std::string i64tostr(int64 n)
273 return strprintf("%"PRI64d, n);
276 inline std::string itostr(int n)
278 return strprintf("%d", n);
281 inline int64 atoi64(const char* psz)
286 return strtoll(psz, NULL, 10);
290 inline int64 atoi64(const std::string& str)
293 return _atoi64(str.c_str());
295 return strtoll(str.c_str(), NULL, 10);
299 inline int atoi(const std::string& str)
301 return atoi(str.c_str());
304 inline int roundint(double d)
306 return (int)(d > 0 ? d + 0.5 : d - 0.5);
309 inline int64 roundint64(double d)
311 return (int64)(d > 0 ? d + 0.5 : d - 0.5);
314 inline int64 abs64(int64 n)
316 return (n >= 0 ? n : -n);
320 std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
322 if (itbegin == itend)
324 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
325 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
327 str.reserve((pend-pbegin) * (fSpaces ? 3 : 2));
328 for (const unsigned char* p = pbegin; p != pend; p++)
329 str += strprintf((fSpaces && p != pend-1 ? "%02x " : "%02x"), *p);
333 inline std::string HexStr(const std::vector<unsigned char>& vch, bool fSpaces=false)
335 return HexStr(vch.begin(), vch.end(), fSpaces);
339 void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)
341 printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());
344 inline void PrintHex(const std::vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true)
346 printf(pszFormat, HexStr(vch, fSpaces).c_str());
349 inline int64 GetPerformanceCounter()
353 QueryPerformanceCounter((LARGE_INTEGER*)&nCounter);
356 gettimeofday(&t, NULL);
357 nCounter = t.tv_sec * 1000000 + t.tv_usec;
362 inline int64 GetTimeMillis()
364 return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) -
365 boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
368 inline std::string DateTimeStrFormat(const char* pszFormat, int64 nTime)
371 struct tm* ptmTime = gmtime(&n);
373 strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime);
378 void skipspaces(T& it)
384 inline bool IsSwitchChar(char c)
387 return c == '-' || c == '/';
394 * Return string argument or default value
396 * @param strArg Argument to get (e.g. "-foo")
397 * @param default (e.g. "1")
398 * @return command-line argument or default value
400 std::string GetArg(const std::string& strArg, const std::string& strDefault);
403 * Return integer argument or default value
405 * @param strArg Argument to get (e.g. "-foo")
406 * @param default (e.g. 1)
407 * @return command-line argument (0 if invalid number) or default value
409 int64 GetArg(const std::string& strArg, int64 nDefault);
412 * Return boolean argument or default value
414 * @param strArg Argument to get (e.g. "-foo")
415 * @param default (true or false)
416 * @return command-line argument or default value
418 bool GetBoolArg(const std::string& strArg, bool fDefault=false);
421 * Set an argument if it doesn't already have a value
423 * @param strArg Argument to set (e.g. "-foo")
424 * @param strValue Value (e.g. "1")
425 * @return true if argument gets set, false if it already had a value
427 bool SoftSetArg(const std::string& strArg, const std::string& strValue);
430 * Set a boolean argument if it doesn't already have a value
432 * @param strArg Argument to set (e.g. "-foo")
433 * @param fValue Value (e.g. false)
434 * @return true if argument gets set, false if it already had a value
436 bool SoftSetBoolArg(const std::string& strArg, bool fValue);
446 // Randomize the stack to help protect against buffer overrun exploits
447 #define IMPLEMENT_RANDOMIZE_STACK(ThreadFn) \
449 static char nLoops; \
451 nLoops = GetRand(20) + 1; \
460 template<typename T1>
461 inline uint256 Hash(const T1 pbegin, const T1 pend)
463 static unsigned char pblank[1];
465 SHA256((pbegin == pend ? pblank : (unsigned char*)&pbegin[0]), (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);
467 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
471 template<typename T1, typename T2>
472 inline uint256 Hash(const T1 p1begin, const T1 p1end,
473 const T2 p2begin, const T2 p2end)
475 static unsigned char pblank[1];
479 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
480 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
481 SHA256_Final((unsigned char*)&hash1, &ctx);
483 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
487 template<typename T1, typename T2, typename T3>
488 inline uint256 Hash(const T1 p1begin, const T1 p1end,
489 const T2 p2begin, const T2 p2end,
490 const T3 p3begin, const T3 p3end)
492 static unsigned char pblank[1];
496 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
497 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
498 SHA256_Update(&ctx, (p3begin == p3end ? pblank : (unsigned char*)&p3begin[0]), (p3end - p3begin) * sizeof(p3begin[0]));
499 SHA256_Final((unsigned char*)&hash1, &ctx);
501 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
506 uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=PROTOCOL_VERSION)
508 // Most of the time is spent allocating and deallocating CDataStream's
509 // buffer. If this ever needs to be optimized further, make a CStaticStream
510 // class with its buffer on the stack.
511 CDataStream ss(nType, nVersion);
514 return Hash(ss.begin(), ss.end());
517 inline uint160 Hash160(const std::vector<unsigned char>& vch)
520 SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);
522 RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
527 /** Median filter over a stream of values.
528 * Returns the median of the last N numbers
530 template <typename T> class CMedianFilter
533 std::vector<T> vValues;
534 std::vector<T> vSorted;
537 CMedianFilter(int size, T initial_value):
540 vValues.reserve(size);
541 vValues.push_back(initial_value);
547 if(vValues.size() == nSize)
549 vValues.erase(vValues.begin());
551 vValues.push_back(value);
553 vSorted.resize(vValues.size());
554 std::copy(vValues.begin(), vValues.end(), vSorted.begin());
555 std::sort(vSorted.begin(), vSorted.end());
560 int size = vSorted.size();
562 if(size & 1) // Odd number of elements
564 return vSorted[size/2];
566 else // Even number of elements
568 return (vSorted[size/2-1] + vSorted[size/2]) / 2;
574 return vValues.size();
577 std::vector<T> sorted () const
592 // Note: It turns out we might have been able to use boost::thread
593 // by using TerminateThread(boost::thread.native_handle(), 0);
595 typedef HANDLE pthread_t;
597 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
602 NULL, // default security
603 0, // inherit stack size from parent
604 (LPTHREAD_START_ROUTINE)pfn, // function pointer
606 0, // creation option, start immediately
607 &nUnused); // thread identifier
610 printf("Error: CreateThread() returned %d\n", GetLastError());
615 CloseHandle(hthread);
616 return (pthread_t)-1;
621 inline void SetThreadPriority(int nPriority)
623 SetThreadPriority(GetCurrentThread(), nPriority);
626 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
628 pthread_t hthread = 0;
629 int ret = pthread_create(&hthread, NULL, (void*(*)(void*))pfn, parg);
632 printf("Error: pthread_create() returned %d\n", ret);
637 pthread_detach(hthread);
638 return (pthread_t)-1;
643 #define THREAD_PRIORITY_LOWEST PRIO_MAX
644 #define THREAD_PRIORITY_BELOW_NORMAL 2
645 #define THREAD_PRIORITY_NORMAL 0
646 #define THREAD_PRIORITY_ABOVE_NORMAL 0
648 inline void SetThreadPriority(int nPriority)
650 // It's unclear if it's even possible to change thread priorities on Linux,
651 // but we really and truly need it for the generation threads.
653 setpriority(PRIO_THREAD, 0, nPriority);
655 setpriority(PRIO_PROCESS, 0, nPriority);
659 inline void ExitThread(size_t nExitCode)
661 pthread_exit((void*)nExitCode);
669 inline bool AffinityBugWorkaround(void(*pfn)(void*))
672 // Sometimes after a few hours affinity gets stuck on one processor
673 DWORD_PTR dwProcessAffinityMask = -1;
674 DWORD_PTR dwSystemAffinityMask = -1;
675 GetProcessAffinityMask(GetCurrentProcess(), &dwProcessAffinityMask, &dwSystemAffinityMask);
676 DWORD dwPrev1 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
677 DWORD dwPrev2 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
678 if (dwPrev2 != dwProcessAffinityMask)
680 printf("AffinityBugWorkaround() : SetThreadAffinityMask=%d, ProcessAffinityMask=%d, restarting thread\n", dwPrev2, dwProcessAffinityMask);
681 if (!CreateThread(pfn, NULL))
682 printf("Error: CreateThread() failed\n");
689 inline uint32_t ByteReverse(uint32_t value)
691 value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8);
692 return (value<<16) | (value>>16);