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 #define Beep(n1,n2) (0)
89 inline void Sleep(int64 n)
91 boost::thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(n));
96 inline const char* _(const char* psz)
110 extern std::map<std::string, std::string> mapArgs;
111 extern std::map<std::string, std::vector<std::string> > mapMultiArgs;
113 extern bool fPrintToConsole;
114 extern bool fPrintToDebugger;
115 extern char pszSetDataDir[MAX_PATH];
116 extern bool fRequestShutdown;
117 extern bool fShutdown;
120 extern bool fCommandLine;
121 extern std::string strMiscWarning;
122 extern bool fTestNet;
123 extern bool fNoListen;
124 extern bool fLogTimestamps;
127 void RandAddSeedPerfmon();
128 int OutputDebugStringF(const char* pszFormat, ...);
129 int my_snprintf(char* buffer, size_t limit, const char* format, ...);
130 std::string strprintf(const std::string &format, ...);
131 bool error(const std::string &format, ...);
132 void LogException(std::exception* pex, const char* pszThread);
133 void PrintException(std::exception* pex, const char* pszThread);
134 void PrintExceptionContinue(std::exception* pex, const char* pszThread);
135 void ParseString(const std::string& str, char c, std::vector<std::string>& v);
136 std::string FormatMoney(int64 n, bool fPlus=false);
137 bool ParseMoney(const std::string& str, int64& nRet);
138 bool ParseMoney(const char* pszIn, int64& nRet);
139 std::vector<unsigned char> ParseHex(const char* psz);
140 std::vector<unsigned char> ParseHex(const std::string& str);
141 bool IsHex(const std::string& str);
142 std::vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid = NULL);
143 std::string DecodeBase64(const std::string& str);
144 std::string EncodeBase64(const unsigned char* pch, size_t len);
145 std::string EncodeBase64(const std::string& str);
146 void ParseParameters(int argc, const char*const argv[]);
147 bool WildcardMatch(const char* psz, const char* mask);
148 bool WildcardMatch(const std::string& str, const std::string& mask);
149 int GetFilesize(FILE* file);
150 void GetDataDir(char* pszDirRet);
151 std::string GetConfigFile();
152 std::string GetPidFile();
153 void CreatePidFile(std::string pidFile, pid_t pid);
154 void ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet, std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet);
156 std::string MyGetSpecialFolderPath(int nFolder, bool fCreate);
158 std::string GetDefaultDataDir();
159 std::string GetDataDir();
160 void ShrinkDebugFile();
161 int GetRandInt(int nMax);
162 uint64 GetRand(uint64 nMax);
164 void SetMockTime(int64 nMockTimeIn);
165 int64 GetAdjustedTime();
166 std::string FormatFullVersion();
167 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments);
168 void AddTimeData(const CNetAddr& ip, int64 nTime);
181 // Wrapper to automatically initialize mutex
182 class CCriticalSection
185 boost::interprocess::interprocess_recursive_mutex mutex;
187 explicit CCriticalSection() { }
188 ~CCriticalSection() { }
189 void Enter(const char* pszName, const char* pszFile, int nLine);
191 bool TryEnter(const char* pszName, const char* pszFile, int nLine);
194 // Automatically leave critical section when leaving block, needed for exception safety
198 CCriticalSection* pcs;
201 CCriticalBlock(CCriticalSection& csIn, const char* pszName, const char* pszFile, int nLine)
204 pcs->Enter(pszName, pszFile, nLine);
207 operator bool() const
218 #define CRITICAL_BLOCK(cs) \
219 if (CCriticalBlock criticalblock = CCriticalBlock(cs, #cs, __FILE__, __LINE__))
221 class CTryCriticalBlock
224 CCriticalSection* pcs;
227 CTryCriticalBlock(CCriticalSection& csIn, const char* pszName, const char* pszFile, int nLine)
229 pcs = (csIn.TryEnter(pszName, pszFile, nLine) ? &csIn : NULL);
232 operator bool() const
244 bool Entered() const { return pcs != NULL; }
247 #define TRY_CRITICAL_BLOCK(cs) \
248 if (CTryCriticalBlock criticalblock = CTryCriticalBlock(cs, #cs, __FILE__, __LINE__))
255 // This is exactly like std::string, but with a custom allocator.
256 // (secure_allocator<> is defined in serialize.h)
257 typedef std::basic_string<char, std::char_traits<char>, secure_allocator<char> > SecureString;
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 std::string HexNumStr(const T itbegin, const T itend, bool f0x=true)
333 if (itbegin == itend)
335 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
336 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
337 std::string str = (f0x ? "0x" : "");
338 str.reserve(str.size() + (pend-pbegin) * 2);
339 for (const unsigned char* p = pend-1; p >= pbegin; p--)
340 str += strprintf("%02x", *p);
344 inline std::string HexNumStr(const std::vector<unsigned char>& vch, bool f0x=true)
346 return HexNumStr(vch.begin(), vch.end(), f0x);
350 void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)
352 printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());
355 inline void PrintHex(const std::vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true)
357 printf(pszFormat, HexStr(vch, fSpaces).c_str());
360 inline int64 GetPerformanceCounter()
364 QueryPerformanceCounter((LARGE_INTEGER*)&nCounter);
367 gettimeofday(&t, NULL);
368 nCounter = t.tv_sec * 1000000 + t.tv_usec;
373 inline int64 GetTimeMillis()
375 return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) -
376 boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
379 inline std::string DateTimeStrFormat(const char* pszFormat, int64 nTime)
382 struct tm* ptmTime = gmtime(&n);
384 strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime);
389 void skipspaces(T& it)
395 inline bool IsSwitchChar(char c)
398 return c == '-' || c == '/';
405 * Return string argument or default value
407 * @param strArg Argument to get (e.g. "-foo")
408 * @param default (e.g. "1")
409 * @return command-line argument or default value
411 std::string GetArg(const std::string& strArg, const std::string& strDefault);
414 * Return integer argument or default value
416 * @param strArg Argument to get (e.g. "-foo")
417 * @param default (e.g. 1)
418 * @return command-line argument (0 if invalid number) or default value
420 int64 GetArg(const std::string& strArg, int64 nDefault);
423 * Return boolean argument or default value
425 * @param strArg Argument to get (e.g. "-foo")
426 * @param default (true or false)
427 * @return command-line argument or default value
429 bool GetBoolArg(const std::string& strArg, bool fDefault=false);
432 * Set an argument if it doesn't already have a value
434 * @param strArg Argument to set (e.g. "-foo")
435 * @param strValue Value (e.g. "1")
436 * @return true if argument gets set, false if it already had a value
438 bool SoftSetArg(const std::string& strArg, const std::string& strValue);
441 * Set a boolean argument if it doesn't already have a value
443 * @param strArg Argument to set (e.g. "-foo")
444 * @param fValue Value (e.g. false)
445 * @return true if argument gets set, false if it already had a value
447 bool SoftSetBoolArg(const std::string& strArg, bool fValue);
457 // Randomize the stack to help protect against buffer overrun exploits
458 #define IMPLEMENT_RANDOMIZE_STACK(ThreadFn) \
460 static char nLoops; \
462 nLoops = GetRand(20) + 1; \
470 #define CATCH_PRINT_EXCEPTION(pszFn) \
471 catch (std::exception& e) { \
472 PrintException(&e, (pszFn)); \
474 PrintException(NULL, (pszFn)); \
486 template<typename T1>
487 inline uint256 Hash(const T1 pbegin, const T1 pend)
489 static unsigned char pblank[1];
491 SHA256((pbegin == pend ? pblank : (unsigned char*)&pbegin[0]), (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);
493 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
497 template<typename T1, typename T2>
498 inline uint256 Hash(const T1 p1begin, const T1 p1end,
499 const T2 p2begin, const T2 p2end)
501 static unsigned char pblank[1];
505 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
506 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
507 SHA256_Final((unsigned char*)&hash1, &ctx);
509 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
513 template<typename T1, typename T2, typename T3>
514 inline uint256 Hash(const T1 p1begin, const T1 p1end,
515 const T2 p2begin, const T2 p2end,
516 const T3 p3begin, const T3 p3end)
518 static unsigned char pblank[1];
522 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
523 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
524 SHA256_Update(&ctx, (p3begin == p3end ? pblank : (unsigned char*)&p3begin[0]), (p3end - p3begin) * sizeof(p3begin[0]));
525 SHA256_Final((unsigned char*)&hash1, &ctx);
527 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
532 uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=PROTOCOL_VERSION)
534 // Most of the time is spent allocating and deallocating CDataStream's
535 // buffer. If this ever needs to be optimized further, make a CStaticStream
536 // class with its buffer on the stack.
537 CDataStream ss(nType, nVersion);
540 return Hash(ss.begin(), ss.end());
543 inline uint160 Hash160(const std::vector<unsigned char>& vch)
546 SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);
548 RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
553 // Median filter over a stream of values
554 // Returns the median of the last N numbers
555 template <typename T> class CMedianFilter
558 std::vector<T> vValues;
559 std::vector<T> vSorted;
562 CMedianFilter(int size, T initial_value):
565 vValues.reserve(size);
566 vValues.push_back(initial_value);
572 if(vValues.size() == nSize)
574 vValues.erase(vValues.begin());
576 vValues.push_back(value);
578 vSorted.resize(vValues.size());
579 std::copy(vValues.begin(), vValues.end(), vSorted.begin());
580 std::sort(vSorted.begin(), vSorted.end());
585 int size = vSorted.size();
587 if(size & 1) // Odd number of elements
589 return vSorted[size/2];
591 else // Even number of elements
593 return (vSorted[size/2-1] + vSorted[size/2]) / 2;
599 return vValues.size();
602 std::vector<T> sorted () const
617 // Note: It turns out we might have been able to use boost::thread
618 // by using TerminateThread(boost::thread.native_handle(), 0);
620 typedef HANDLE pthread_t;
622 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
627 NULL, // default security
628 0, // inherit stack size from parent
629 (LPTHREAD_START_ROUTINE)pfn, // function pointer
631 0, // creation option, start immediately
632 &nUnused); // thread identifier
635 printf("Error: CreateThread() returned %d\n", GetLastError());
640 CloseHandle(hthread);
641 return (pthread_t)-1;
646 inline void SetThreadPriority(int nPriority)
648 SetThreadPriority(GetCurrentThread(), nPriority);
651 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
653 pthread_t hthread = 0;
654 int ret = pthread_create(&hthread, NULL, (void*(*)(void*))pfn, parg);
657 printf("Error: pthread_create() returned %d\n", ret);
662 pthread_detach(hthread);
663 return (pthread_t)-1;
668 #define THREAD_PRIORITY_LOWEST PRIO_MAX
669 #define THREAD_PRIORITY_BELOW_NORMAL 2
670 #define THREAD_PRIORITY_NORMAL 0
671 #define THREAD_PRIORITY_ABOVE_NORMAL 0
673 inline void SetThreadPriority(int nPriority)
675 // It's unclear if it's even possible to change thread priorities on Linux,
676 // but we really and truly need it for the generation threads.
678 setpriority(PRIO_THREAD, 0, nPriority);
680 setpriority(PRIO_PROCESS, 0, nPriority);
684 inline bool TerminateThread(pthread_t hthread, unsigned int nExitCode)
686 return (pthread_cancel(hthread) == 0);
689 inline void ExitThread(size_t nExitCode)
691 pthread_exit((void*)nExitCode);
699 inline bool AffinityBugWorkaround(void(*pfn)(void*))
702 // Sometimes after a few hours affinity gets stuck on one processor
703 DWORD_PTR dwProcessAffinityMask = -1;
704 DWORD_PTR dwSystemAffinityMask = -1;
705 GetProcessAffinityMask(GetCurrentProcess(), &dwProcessAffinityMask, &dwSystemAffinityMask);
706 DWORD dwPrev1 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
707 DWORD dwPrev2 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
708 if (dwPrev2 != dwProcessAffinityMask)
710 printf("AffinityBugWorkaround() : SetThreadAffinityMask=%d, ProcessAffinityMask=%d, restarting thread\n", dwPrev2, dwProcessAffinityMask);
711 if (!CreateThread(pfn, NULL))
712 printf("Error: CreateThread() failed\n");
719 inline uint32_t ByteReverse(uint32_t value)
721 value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8);
722 return (value<<16) | (value>>16);