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/filesystem.hpp>
23 #include <boost/filesystem/path.hpp>
24 #include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>
25 #include <boost/interprocess/sync/scoped_lock.hpp>
26 #include <boost/interprocess/sync/interprocess_condition.hpp>
27 #include <boost/interprocess/sync/lock_options.hpp>
28 #include <boost/date_time/gregorian/gregorian_types.hpp>
29 #include <boost/date_time/posix_time/posix_time_types.hpp>
31 #include <openssl/sha.h>
32 #include <openssl/ripemd.h>
34 #include "netbase.h" // for AddTimeData
35 #include "ui_interface.h"
37 typedef long long int64;
38 typedef unsigned long long uint64;
40 static const int64 COIN = 100000000;
41 static const int64 CENT = 1000000;
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(__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
93 #define unlink _unlink
95 #define _vsnprintf(a,b,c,d) vsnprintf(a,b,c,d)
96 #define strlwr(psz) to_lower(psz)
97 #define _strlwr(psz) to_lower(psz)
99 inline void Sleep(int64 n)
101 /*Boost has a year 2038 problem— if the request sleep time is past epoch+2^31 seconds the sleep returns instantly.
102 So we clamp our sleeps here to 10 years and hope that boost is fixed by 2028.*/
103 boost::thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(n>315576000000LL?315576000000LL:n));
115 extern std::map<std::string, std::string> mapArgs;
116 extern std::map<std::string, std::vector<std::string> > mapMultiArgs;
118 extern bool fPrintToConsole;
119 extern bool fPrintToDebugger;
120 extern bool fRequestShutdown;
121 extern bool fShutdown;
124 extern bool fCommandLine;
125 extern std::string strMiscWarning;
126 extern bool fTestNet;
127 extern bool fNoListen;
128 extern bool fLogTimestamps;
131 void RandAddSeedPerfmon();
132 int OutputDebugStringF(const char* pszFormat, ...);
133 int my_snprintf(char* buffer, size_t limit, const char* format, ...);
135 /* It is not allowed to use va_start with a pass-by-reference argument.
136 (C++ standard, 18.7, paragraph 3). Use a dummy argument to work around this, and use a
137 macro to keep similar semantics.
139 std::string real_strprintf(const std::string &format, int dummy, ...);
140 #define strprintf(format, ...) real_strprintf(format, 0, __VA_ARGS__)
142 bool error(const char *format, ...);
143 void LogException(std::exception* pex, const char* pszThread);
144 void PrintException(std::exception* pex, const char* pszThread);
145 void PrintExceptionContinue(std::exception* pex, const char* pszThread);
146 void ParseString(const std::string& str, char c, std::vector<std::string>& v);
147 std::string FormatMoney(int64 n, bool fPlus=false);
148 bool ParseMoney(const std::string& str, int64& nRet);
149 bool ParseMoney(const char* pszIn, int64& nRet);
150 std::vector<unsigned char> ParseHex(const char* psz);
151 std::vector<unsigned char> ParseHex(const std::string& str);
152 bool IsHex(const std::string& str);
153 std::vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid = NULL);
154 std::string DecodeBase64(const std::string& str);
155 std::string EncodeBase64(const unsigned char* pch, size_t len);
156 std::string EncodeBase64(const std::string& str);
157 void ParseParameters(int argc, const char*const argv[]);
158 bool WildcardMatch(const char* psz, const char* mask);
159 bool WildcardMatch(const std::string& str, const std::string& mask);
160 int GetFilesize(FILE* file);
161 boost::filesystem::path GetDefaultDataDir();
162 const boost::filesystem::path &GetDataDir(bool fNetSpecific = true);
163 boost::filesystem::path GetConfigFile();
164 boost::filesystem::path GetPidFile();
165 void CreatePidFile(const boost::filesystem::path &path, pid_t pid);
166 bool ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet, std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet);
167 bool GetStartOnSystemStartup();
168 bool SetStartOnSystemStartup(bool fAutoStart);
169 void ShrinkDebugFile();
170 int GetRandInt(int nMax);
171 uint64 GetRand(uint64 nMax);
173 void SetMockTime(int64 nMockTimeIn);
174 int64 GetAdjustedTime();
175 std::string FormatFullVersion();
176 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments);
177 void AddTimeData(const CNetAddr& ip, int64 nTime);
189 /** Wrapped boost mutex: supports recursive locking, but no waiting */
190 typedef boost::interprocess::interprocess_recursive_mutex CCriticalSection;
192 /** Wrapped boost mutex: supports waiting but not recursive locking */
193 typedef boost::interprocess::interprocess_mutex CWaitableCriticalSection;
195 #ifdef DEBUG_LOCKORDER
196 void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry = false);
197 void LeaveCritical();
199 void static inline EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry = false) {}
200 void static inline LeaveCritical() {}
203 /** Wrapper around boost::interprocess::scoped_lock */
204 template<typename Mutex>
208 boost::interprocess::scoped_lock<Mutex> lock;
211 void Enter(const char* pszName, const char* pszFile, int nLine)
215 EnterCritical(pszName, pszFile, nLine, (void*)(lock.mutex()));
216 #ifdef DEBUG_LOCKCONTENTION
217 if (!lock.try_lock())
219 printf("LOCKCONTENTION: %s\n", pszName);
220 printf("Locker: %s:%d\n", pszFile, nLine);
236 bool TryEnter(const char* pszName, const char* pszFile, int nLine)
240 EnterCritical(pszName, pszFile, nLine, (void*)(lock.mutex()), true);
248 CMutexLock(Mutex& mutexIn, const char* pszName, const char* pszFile, int nLine, bool fTry = false) : lock(mutexIn, boost::interprocess::defer_lock)
251 TryEnter(pszName, pszFile, nLine);
253 Enter(pszName, pszFile, nLine);
267 boost::interprocess::scoped_lock<Mutex> &GetLock()
273 typedef CMutexLock<CCriticalSection> CCriticalBlock;
274 typedef CMutexLock<CWaitableCriticalSection> CWaitableCriticalBlock;
275 typedef boost::interprocess::interprocess_condition CConditionVariable;
277 /** Wait for a given condition inside a WAITABLE_CRITICAL_BLOCK */
278 #define WAIT(name,condition) \
279 do { while(!(condition)) { (name).wait(waitablecriticalblock.GetLock()); } } while(0)
281 /** Notify waiting threads that a condition may hold now */
282 #define NOTIFY(name) \
283 do { (name).notify_one(); } while(0)
285 #define NOTIFY_ALL(name) \
286 do { (name).notify_all(); } while(0)
288 #define LOCK(cs) CCriticalBlock criticalblock(cs, #cs, __FILE__, __LINE__)
289 #define LOCK2(cs1,cs2) CCriticalBlock criticalblock1(cs1, #cs1, __FILE__, __LINE__),criticalblock2(cs2, #cs2, __FILE__, __LINE__)
290 #define TRY_LOCK(cs,name) CCriticalBlock name(cs, #cs, __FILE__, __LINE__, true)
291 #define WAITABLE_LOCK(cs) CWaitableCriticalBlock waitablecriticalblock(cs, #cs, __FILE__, __LINE__)
293 #define ENTER_CRITICAL_SECTION(cs) \
295 EnterCritical(#cs, __FILE__, __LINE__, (void*)(&cs)); \
299 #define LEAVE_CRITICAL_SECTION(cs) \
306 // This is exactly like std::string, but with a custom allocator.
307 // (secure_allocator<> is defined in serialize.h)
308 typedef std::basic_string<char, std::char_traits<char>, secure_allocator<char> > SecureString;
314 inline std::string i64tostr(int64 n)
316 return strprintf("%"PRI64d, n);
319 inline std::string itostr(int n)
321 return strprintf("%d", n);
324 inline int64 atoi64(const char* psz)
329 return strtoll(psz, NULL, 10);
333 inline int64 atoi64(const std::string& str)
336 return _atoi64(str.c_str());
338 return strtoll(str.c_str(), NULL, 10);
342 inline int atoi(const std::string& str)
344 return atoi(str.c_str());
347 inline int roundint(double d)
349 return (int)(d > 0 ? d + 0.5 : d - 0.5);
352 inline int64 roundint64(double d)
354 return (int64)(d > 0 ? d + 0.5 : d - 0.5);
357 inline int64 abs64(int64 n)
359 return (n >= 0 ? n : -n);
363 std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
365 if (itbegin == itend)
367 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
368 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
370 str.reserve((pend-pbegin) * (fSpaces ? 3 : 2));
371 for (const unsigned char* p = pbegin; p != pend; p++)
372 str += strprintf((fSpaces && p != pend-1 ? "%02x " : "%02x"), *p);
376 inline std::string HexStr(const std::vector<unsigned char>& vch, bool fSpaces=false)
378 return HexStr(vch.begin(), vch.end(), fSpaces);
382 void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)
384 printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());
387 inline void PrintHex(const std::vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true)
389 printf(pszFormat, HexStr(vch, fSpaces).c_str());
392 inline int64 GetPerformanceCounter()
396 QueryPerformanceCounter((LARGE_INTEGER*)&nCounter);
399 gettimeofday(&t, NULL);
400 nCounter = t.tv_sec * 1000000 + t.tv_usec;
405 inline int64 GetTimeMillis()
407 return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) -
408 boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
411 inline std::string DateTimeStrFormat(const char* pszFormat, int64 nTime)
414 struct tm* ptmTime = gmtime(&n);
416 strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime);
421 void skipspaces(T& it)
427 inline bool IsSwitchChar(char c)
430 return c == '-' || c == '/';
437 * Return string argument or default value
439 * @param strArg Argument to get (e.g. "-foo")
440 * @param default (e.g. "1")
441 * @return command-line argument or default value
443 std::string GetArg(const std::string& strArg, const std::string& strDefault);
446 * Return integer argument or default value
448 * @param strArg Argument to get (e.g. "-foo")
449 * @param default (e.g. 1)
450 * @return command-line argument (0 if invalid number) or default value
452 int64 GetArg(const std::string& strArg, int64 nDefault);
455 * Return boolean argument or default value
457 * @param strArg Argument to get (e.g. "-foo")
458 * @param default (true or false)
459 * @return command-line argument or default value
461 bool GetBoolArg(const std::string& strArg, bool fDefault=false);
464 * Set an argument if it doesn't already have a value
466 * @param strArg Argument to set (e.g. "-foo")
467 * @param strValue Value (e.g. "1")
468 * @return true if argument gets set, false if it already had a value
470 bool SoftSetArg(const std::string& strArg, const std::string& strValue);
473 * Set a boolean argument if it doesn't already have a value
475 * @param strArg Argument to set (e.g. "-foo")
476 * @param fValue Value (e.g. false)
477 * @return true if argument gets set, false if it already had a value
479 bool SoftSetBoolArg(const std::string& strArg, bool fValue);
489 // Randomize the stack to help protect against buffer overrun exploits
490 #define IMPLEMENT_RANDOMIZE_STACK(ThreadFn) \
492 static char nLoops; \
494 nLoops = GetRand(20) + 1; \
503 template<typename T1>
504 inline uint256 Hash(const T1 pbegin, const T1 pend)
506 static unsigned char pblank[1];
508 SHA256((pbegin == pend ? pblank : (unsigned char*)&pbegin[0]), (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);
510 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
514 template<typename T1, typename T2>
515 inline uint256 Hash(const T1 p1begin, const T1 p1end,
516 const T2 p2begin, const T2 p2end)
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_Final((unsigned char*)&hash1, &ctx);
526 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
530 template<typename T1, typename T2, typename T3>
531 inline uint256 Hash(const T1 p1begin, const T1 p1end,
532 const T2 p2begin, const T2 p2end,
533 const T3 p3begin, const T3 p3end)
535 static unsigned char pblank[1];
539 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
540 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
541 SHA256_Update(&ctx, (p3begin == p3end ? pblank : (unsigned char*)&p3begin[0]), (p3end - p3begin) * sizeof(p3begin[0]));
542 SHA256_Final((unsigned char*)&hash1, &ctx);
544 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
549 uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=PROTOCOL_VERSION)
551 // Most of the time is spent allocating and deallocating CDataStream's
552 // buffer. If this ever needs to be optimized further, make a CStaticStream
553 // class with its buffer on the stack.
554 CDataStream ss(nType, nVersion);
557 return Hash(ss.begin(), ss.end());
560 inline uint160 Hash160(const std::vector<unsigned char>& vch)
563 SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);
565 RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
570 /** Median filter over a stream of values.
571 * Returns the median of the last N numbers
573 template <typename T> class CMedianFilter
576 std::vector<T> vValues;
577 std::vector<T> vSorted;
580 CMedianFilter(int size, T initial_value):
583 vValues.reserve(size);
584 vValues.push_back(initial_value);
590 if(vValues.size() == nSize)
592 vValues.erase(vValues.begin());
594 vValues.push_back(value);
596 vSorted.resize(vValues.size());
597 std::copy(vValues.begin(), vValues.end(), vSorted.begin());
598 std::sort(vSorted.begin(), vSorted.end());
603 int size = vSorted.size();
605 if(size & 1) // Odd number of elements
607 return vSorted[size/2];
609 else // Even number of elements
611 return (vSorted[size/2-1] + vSorted[size/2]) / 2;
617 return vValues.size();
620 std::vector<T> sorted () const
635 // Note: It turns out we might have been able to use boost::thread
636 // by using TerminateThread(boost::thread.native_handle(), 0);
638 typedef HANDLE pthread_t;
640 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
645 NULL, // default security
646 0, // inherit stack size from parent
647 (LPTHREAD_START_ROUTINE)pfn, // function pointer
649 0, // creation option, start immediately
650 &nUnused); // thread identifier
653 printf("Error: CreateThread() returned %d\n", GetLastError());
658 CloseHandle(hthread);
659 return (pthread_t)-1;
664 inline void SetThreadPriority(int nPriority)
666 SetThreadPriority(GetCurrentThread(), nPriority);
669 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
671 pthread_t hthread = 0;
672 int ret = pthread_create(&hthread, NULL, (void*(*)(void*))pfn, parg);
675 printf("Error: pthread_create() returned %d\n", ret);
680 pthread_detach(hthread);
681 return (pthread_t)-1;
686 #define THREAD_PRIORITY_LOWEST PRIO_MAX
687 #define THREAD_PRIORITY_BELOW_NORMAL 2
688 #define THREAD_PRIORITY_NORMAL 0
689 #define THREAD_PRIORITY_ABOVE_NORMAL 0
691 inline void SetThreadPriority(int nPriority)
693 // It's unclear if it's even possible to change thread priorities on Linux,
694 // but we really and truly need it for the generation threads.
696 setpriority(PRIO_THREAD, 0, nPriority);
698 setpriority(PRIO_PROCESS, 0, nPriority);
702 inline void ExitThread(size_t nExitCode)
704 pthread_exit((void*)nExitCode);
712 inline uint32_t ByteReverse(uint32_t value)
714 value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8);
715 return (value<<16) | (value>>16);