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>
15 typedef int pid_t; /* define for windows compatiblity */
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 typedef long long int64;
32 typedef unsigned long long uint64;
35 #define BEGIN(a) ((char*)&(a))
36 #define END(a) ((char*)&((&(a))[1]))
37 #define UBEGIN(a) ((unsigned char*)&(a))
38 #define UEND(a) ((unsigned char*)&((&(a))[1]))
39 #define ARRAYLEN(array) (sizeof(array)/sizeof((array)[0]))
40 #define printf OutputDebugStringF
45 #define snprintf my_snprintf
48 #if defined(_MSC_VER) || defined(__MSVCRT__)
59 // This is needed because the foreach macro can't get over the comma in pair<t1, t2>
60 #define PAIRTYPE(t1, t2) std::pair<t1, t2>
62 // Align by increasing pointer, must have extra space at end of buffer
63 template <size_t nBytes, typename T>
72 u.n = (u.n + (nBytes-1)) & ~(nBytes-1);
77 #define MSG_NOSIGNAL 0
78 #define MSG_DONTWAIT 0
84 #define unlink _unlink
86 #define _vsnprintf(a,b,c,d) vsnprintf(a,b,c,d)
87 #define strlwr(psz) to_lower(psz)
88 #define _strlwr(psz) to_lower(psz)
90 inline void Sleep(int64 n)
92 /*Boost has a year 2038 problem— if the request sleep time is past epoch+2^31 seconds the sleep returns instantly.
93 So we clamp our sleeps here to 10 years and hope that boost is fixed by 2028.*/
94 boost::thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(n>315576000000LL?315576000000LL:n));
106 extern std::map<std::string, std::string> mapArgs;
107 extern std::map<std::string, std::vector<std::string> > mapMultiArgs;
109 extern bool fPrintToConsole;
110 extern bool fPrintToDebugger;
111 extern char pszSetDataDir[MAX_PATH];
112 extern bool fRequestShutdown;
113 extern bool fShutdown;
116 extern bool fCommandLine;
117 extern std::string strMiscWarning;
118 extern bool fTestNet;
119 extern bool fNoListen;
120 extern bool fLogTimestamps;
123 void RandAddSeedPerfmon();
124 int OutputDebugStringF(const char* pszFormat, ...);
125 int my_snprintf(char* buffer, size_t limit, const char* format, ...);
127 /* It is not allowed to use va_start with a pass-by-reference argument.
128 (C++ standard, 18.7, paragraph 3). Use a dummy argument to work around this, and use a
129 macro to keep similar semantics.
131 std::string real_strprintf(const std::string &format, int dummy, ...);
132 #define strprintf(format, ...) real_strprintf(format, 0, __VA_ARGS__)
134 bool error(const char *format, ...);
135 void LogException(std::exception* pex, const char* pszThread);
136 void PrintException(std::exception* pex, const char* pszThread);
137 void PrintExceptionContinue(std::exception* pex, const char* pszThread);
138 void ParseString(const std::string& str, char c, std::vector<std::string>& v);
139 std::string FormatMoney(int64 n, bool fPlus=false);
140 bool ParseMoney(const std::string& str, int64& nRet);
141 bool ParseMoney(const char* pszIn, int64& nRet);
142 std::vector<unsigned char> ParseHex(const char* psz);
143 std::vector<unsigned char> ParseHex(const std::string& str);
144 bool IsHex(const std::string& str);
145 std::vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid = NULL);
146 std::string DecodeBase64(const std::string& str);
147 std::string EncodeBase64(const unsigned char* pch, size_t len);
148 std::string EncodeBase64(const std::string& str);
149 void ParseParameters(int argc, const char*const argv[]);
150 bool WildcardMatch(const char* psz, const char* mask);
151 bool WildcardMatch(const std::string& str, const std::string& mask);
152 int GetFilesize(FILE* file);
153 void GetDataDir(char* pszDirRet);
154 std::string GetConfigFile();
155 std::string GetPidFile();
156 void CreatePidFile(std::string pidFile, pid_t pid);
157 bool ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet, std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet);
159 std::string MyGetSpecialFolderPath(int nFolder, bool fCreate);
161 std::string GetDefaultDataDir();
162 std::string GetDataDir();
163 void ShrinkDebugFile();
164 int GetRandInt(int nMax);
165 uint64 GetRand(uint64 nMax);
167 void SetMockTime(int64 nMockTimeIn);
168 int64 GetAdjustedTime();
169 std::string FormatFullVersion();
170 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments);
171 void AddTimeData(const CNetAddr& ip, int64 nTime);
184 /** Wrapper to automatically initialize mutex. */
185 class CCriticalSection
188 boost::interprocess::interprocess_recursive_mutex mutex;
190 explicit CCriticalSection() { }
191 ~CCriticalSection() { }
192 void Enter(const char* pszName, const char* pszFile, int nLine);
194 bool TryEnter(const char* pszName, const char* pszFile, int nLine);
197 /** RAII object that acquires mutex. Needed for exception safety. */
201 CCriticalSection* pcs;
204 CCriticalBlock(CCriticalSection& csIn, const char* pszName, const char* pszFile, int nLine)
207 pcs->Enter(pszName, pszFile, nLine);
210 operator bool() const
221 #define CRITICAL_BLOCK(cs) \
222 if (CCriticalBlock criticalblock = CCriticalBlock(cs, #cs, __FILE__, __LINE__))
224 #define ENTER_CRITICAL_SECTION(cs) \
225 (cs).Enter(#cs, __FILE__, __LINE__)
227 #define LEAVE_CRITICAL_SECTION(cs) \
230 /** RAII object that tries to acquire mutex. Needed for exception safety. */
231 class CTryCriticalBlock
234 CCriticalSection* pcs;
237 CTryCriticalBlock(CCriticalSection& csIn, const char* pszName, const char* pszFile, int nLine)
239 pcs = (csIn.TryEnter(pszName, pszFile, nLine) ? &csIn : NULL);
242 operator bool() const
254 bool Entered() const { return pcs != NULL; }
257 #define TRY_CRITICAL_BLOCK(cs) \
258 if (CTryCriticalBlock criticalblock = CTryCriticalBlock(cs, #cs, __FILE__, __LINE__))
263 inline std::string i64tostr(int64 n)
265 return strprintf("%"PRI64d, n);
268 inline std::string itostr(int n)
270 return strprintf("%d", n);
273 inline int64 atoi64(const char* psz)
278 return strtoll(psz, NULL, 10);
282 inline int64 atoi64(const std::string& str)
285 return _atoi64(str.c_str());
287 return strtoll(str.c_str(), NULL, 10);
291 inline int atoi(const std::string& str)
293 return atoi(str.c_str());
296 inline int roundint(double d)
298 return (int)(d > 0 ? d + 0.5 : d - 0.5);
301 inline int64 roundint64(double d)
303 return (int64)(d > 0 ? d + 0.5 : d - 0.5);
306 inline int64 abs64(int64 n)
308 return (n >= 0 ? n : -n);
312 std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
314 if (itbegin == itend)
316 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
317 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
319 str.reserve((pend-pbegin) * (fSpaces ? 3 : 2));
320 for (const unsigned char* p = pbegin; p != pend; p++)
321 str += strprintf((fSpaces && p != pend-1 ? "%02x " : "%02x"), *p);
325 inline std::string HexStr(const std::vector<unsigned char>& vch, bool fSpaces=false)
327 return HexStr(vch.begin(), vch.end(), fSpaces);
331 void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)
333 printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());
336 inline void PrintHex(const std::vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true)
338 printf(pszFormat, HexStr(vch, fSpaces).c_str());
341 inline int64 GetPerformanceCounter()
345 QueryPerformanceCounter((LARGE_INTEGER*)&nCounter);
348 gettimeofday(&t, NULL);
349 nCounter = t.tv_sec * 1000000 + t.tv_usec;
354 inline int64 GetTimeMillis()
356 return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) -
357 boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
360 inline std::string DateTimeStrFormat(const char* pszFormat, int64 nTime)
363 struct tm* ptmTime = gmtime(&n);
365 strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime);
370 void skipspaces(T& it)
376 inline bool IsSwitchChar(char c)
379 return c == '-' || c == '/';
386 * Return string argument or default value
388 * @param strArg Argument to get (e.g. "-foo")
389 * @param default (e.g. "1")
390 * @return command-line argument or default value
392 std::string GetArg(const std::string& strArg, const std::string& strDefault);
395 * Return integer argument or default value
397 * @param strArg Argument to get (e.g. "-foo")
398 * @param default (e.g. 1)
399 * @return command-line argument (0 if invalid number) or default value
401 int64 GetArg(const std::string& strArg, int64 nDefault);
404 * Return boolean argument or default value
406 * @param strArg Argument to get (e.g. "-foo")
407 * @param default (true or false)
408 * @return command-line argument or default value
410 bool GetBoolArg(const std::string& strArg, bool fDefault=false);
413 * Set an argument if it doesn't already have a value
415 * @param strArg Argument to set (e.g. "-foo")
416 * @param strValue Value (e.g. "1")
417 * @return true if argument gets set, false if it already had a value
419 bool SoftSetArg(const std::string& strArg, const std::string& strValue);
422 * Set a boolean argument if it doesn't already have a value
424 * @param strArg Argument to set (e.g. "-foo")
425 * @param fValue Value (e.g. false)
426 * @return true if argument gets set, false if it already had a value
428 bool SoftSetBoolArg(const std::string& strArg, bool fValue);
438 // Randomize the stack to help protect against buffer overrun exploits
439 #define IMPLEMENT_RANDOMIZE_STACK(ThreadFn) \
441 static char nLoops; \
443 nLoops = GetRand(20) + 1; \
452 template<typename T1>
453 inline uint256 Hash(const T1 pbegin, const T1 pend)
455 static unsigned char pblank[1];
457 SHA256((pbegin == pend ? pblank : (unsigned char*)&pbegin[0]), (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);
459 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
463 template<typename T1, typename T2>
464 inline uint256 Hash(const T1 p1begin, const T1 p1end,
465 const T2 p2begin, const T2 p2end)
467 static unsigned char pblank[1];
471 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
472 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
473 SHA256_Final((unsigned char*)&hash1, &ctx);
475 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
479 template<typename T1, typename T2, typename T3>
480 inline uint256 Hash(const T1 p1begin, const T1 p1end,
481 const T2 p2begin, const T2 p2end,
482 const T3 p3begin, const T3 p3end)
484 static unsigned char pblank[1];
488 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
489 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
490 SHA256_Update(&ctx, (p3begin == p3end ? pblank : (unsigned char*)&p3begin[0]), (p3end - p3begin) * sizeof(p3begin[0]));
491 SHA256_Final((unsigned char*)&hash1, &ctx);
493 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
498 uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=PROTOCOL_VERSION)
500 // Most of the time is spent allocating and deallocating CDataStream's
501 // buffer. If this ever needs to be optimized further, make a CStaticStream
502 // class with its buffer on the stack.
503 CDataStream ss(nType, nVersion);
506 return Hash(ss.begin(), ss.end());
509 inline uint160 Hash160(const std::vector<unsigned char>& vch)
512 SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);
514 RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
519 /** Median filter over a stream of values.
520 * Returns the median of the last N numbers
522 template <typename T> class CMedianFilter
525 std::vector<T> vValues;
526 std::vector<T> vSorted;
529 CMedianFilter(int size, T initial_value):
532 vValues.reserve(size);
533 vValues.push_back(initial_value);
539 if(vValues.size() == nSize)
541 vValues.erase(vValues.begin());
543 vValues.push_back(value);
545 vSorted.resize(vValues.size());
546 std::copy(vValues.begin(), vValues.end(), vSorted.begin());
547 std::sort(vSorted.begin(), vSorted.end());
552 int size = vSorted.size();
554 if(size & 1) // Odd number of elements
556 return vSorted[size/2];
558 else // Even number of elements
560 return (vSorted[size/2-1] + vSorted[size/2]) / 2;
566 return vValues.size();
569 std::vector<T> sorted () const
584 // Note: It turns out we might have been able to use boost::thread
585 // by using TerminateThread(boost::thread.native_handle(), 0);
587 typedef HANDLE pthread_t;
589 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
594 NULL, // default security
595 0, // inherit stack size from parent
596 (LPTHREAD_START_ROUTINE)pfn, // function pointer
598 0, // creation option, start immediately
599 &nUnused); // thread identifier
602 printf("Error: CreateThread() returned %d\n", GetLastError());
607 CloseHandle(hthread);
608 return (pthread_t)-1;
613 inline void SetThreadPriority(int nPriority)
615 SetThreadPriority(GetCurrentThread(), nPriority);
618 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
620 pthread_t hthread = 0;
621 int ret = pthread_create(&hthread, NULL, (void*(*)(void*))pfn, parg);
624 printf("Error: pthread_create() returned %d\n", ret);
629 pthread_detach(hthread);
630 return (pthread_t)-1;
635 #define THREAD_PRIORITY_LOWEST PRIO_MAX
636 #define THREAD_PRIORITY_BELOW_NORMAL 2
637 #define THREAD_PRIORITY_NORMAL 0
638 #define THREAD_PRIORITY_ABOVE_NORMAL 0
640 inline void SetThreadPriority(int nPriority)
642 // It's unclear if it's even possible to change thread priorities on Linux,
643 // but we really and truly need it for the generation threads.
645 setpriority(PRIO_THREAD, 0, nPriority);
647 setpriority(PRIO_PROCESS, 0, nPriority);
651 inline void ExitThread(size_t nExitCode)
653 pthread_exit((void*)nExitCode);
661 inline bool AffinityBugWorkaround(void(*pfn)(void*))
664 // Sometimes after a few hours affinity gets stuck on one processor
665 DWORD_PTR dwProcessAffinityMask = -1;
666 DWORD_PTR dwSystemAffinityMask = -1;
667 GetProcessAffinityMask(GetCurrentProcess(), &dwProcessAffinityMask, &dwSystemAffinityMask);
668 DWORD dwPrev1 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
669 DWORD dwPrev2 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
670 if (dwPrev2 != dwProcessAffinityMask)
672 printf("AffinityBugWorkaround() : SetThreadAffinityMask=%d, ProcessAffinityMask=%d, restarting thread\n", dwPrev2, dwProcessAffinityMask);
673 if (!CreateThread(pfn, NULL))
674 printf("Error: CreateThread() failed\n");
681 inline uint32_t ByteReverse(uint32_t value)
683 value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8);
684 return (value<<16) | (value>>16);