1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Copyright (c) 2012 The PPCoin developers
4 // Copyright (c) 2012-2013 The NovaCoin developers
5 // Distributed under the MIT/X11 software license, see the accompanying
6 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
13 #include <sys/types.h>
15 #include <sys/resource.h>
17 typedef int pid_t; /* define for windows compatiblity */
23 #include <boost/thread.hpp>
24 #include <boost/filesystem.hpp>
25 #include <boost/filesystem/path.hpp>
26 #include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>
27 #include <boost/interprocess/sync/scoped_lock.hpp>
28 #include <boost/interprocess/sync/interprocess_semaphore.hpp>
29 #include <boost/interprocess/sync/lock_options.hpp>
30 #include <boost/date_time/gregorian/gregorian_types.hpp>
31 #include <boost/date_time/posix_time/posix_time_types.hpp>
33 #include <openssl/sha.h>
34 #include <openssl/ripemd.h>
36 #include "netbase.h" // for AddTimeData
38 typedef long long int64;
39 typedef unsigned long long uint64;
41 static const int64 COIN = 1000000;
42 static const int64 CENT = 10000;
45 #define BEGIN(a) ((char*)&(a))
46 #define END(a) ((char*)&((&(a))[1]))
47 #define UBEGIN(a) ((unsigned char*)&(a))
48 #define UEND(a) ((unsigned char*)&((&(a))[1]))
49 #define ARRAYLEN(array) (sizeof(array)/sizeof((array)[0]))
51 #define UVOIDBEGIN(a) ((void*)&(a))
52 #define CVOIDBEGIN(a) ((const void*)&(a))
53 #define UINTBEGIN(a) ((uint32_t*)&(a))
54 #define CUINTBEGIN(a) ((const uint32_t*)&(a))
56 #define printf OutputDebugStringF
61 #define snprintf my_snprintf
64 #if defined(_MSC_VER) || defined(__MSVCRT__)
75 // This is needed because the foreach macro can't get over the comma in pair<t1, t2>
76 #define PAIRTYPE(t1, t2) std::pair<t1, t2>
78 // Align by increasing pointer, must have extra space at end of buffer
79 template <size_t nBytes, typename T>
88 u.n = (u.n + (nBytes-1)) & ~(nBytes-1);
93 #define MSG_NOSIGNAL 0
94 #define MSG_DONTWAIT 0
100 #define unlink _unlink
102 #define _vsnprintf(a,b,c,d) vsnprintf(a,b,c,d)
103 #define strlwr(psz) to_lower(psz)
104 #define _strlwr(psz) to_lower(psz)
105 #define MAX_PATH 1024
106 inline void Sleep(int64 n)
108 /*Boost has a year 2038 problem— if the request sleep time is past epoch+2^31 seconds the sleep returns instantly.
109 So we clamp our sleeps here to 10 years and hope that boost is fixed by 2028.*/
110 boost::thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(n>315576000000LL?315576000000LL:n));
114 #ifndef THROW_WITH_STACKTRACE
115 #define THROW_WITH_STACKTRACE(exception) \
120 void LogStackTrace();
128 extern std::map<std::string, std::string> mapArgs;
129 extern std::map<std::string, std::vector<std::string> > mapMultiArgs;
131 extern bool fPrintToConsole;
132 extern bool fPrintToDebugger;
133 extern bool fRequestShutdown;
134 extern bool fShutdown;
137 extern bool fCommandLine;
138 extern std::string strMiscWarning;
139 extern bool fTestNet;
140 extern bool fNoListen;
141 extern bool fLogTimestamps;
144 void RandAddSeedPerfmon();
145 int OutputDebugStringF(const char* pszFormat, ...);
146 int my_snprintf(char* buffer, size_t limit, const char* format, ...);
148 /* It is not allowed to use va_start with a pass-by-reference argument.
149 (C++ standard, 18.7, paragraph 3). Use a dummy argument to work around this, and use a
150 macro to keep similar semantics.
152 std::string real_strprintf(const std::string &format, int dummy, ...);
153 #define strprintf(format, ...) real_strprintf(format, 0, __VA_ARGS__)
155 bool error(const char *format, ...);
156 void LogException(std::exception* pex, const char* pszThread);
157 void PrintException(std::exception* pex, const char* pszThread);
158 void PrintExceptionContinue(std::exception* pex, const char* pszThread);
159 void ParseString(const std::string& str, char c, std::vector<std::string>& v);
160 std::string FormatMoney(int64 n, bool fPlus=false);
161 bool ParseMoney(const std::string& str, int64& nRet);
162 bool ParseMoney(const char* pszIn, int64& nRet);
163 std::vector<unsigned char> ParseHex(const char* psz);
164 std::vector<unsigned char> ParseHex(const std::string& str);
165 bool IsHex(const std::string& str);
166 std::vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid = NULL);
167 std::string DecodeBase64(const std::string& str);
168 std::string EncodeBase64(const unsigned char* pch, size_t len);
169 std::string EncodeBase64(const std::string& str);
170 void ParseParameters(int argc, const char*const argv[]);
171 bool WildcardMatch(const char* psz, const char* mask);
172 bool WildcardMatch(const std::string& str, const std::string& mask);
173 int GetFilesize(FILE* file);
174 boost::filesystem::path GetDefaultDataDir();
175 const boost::filesystem::path &GetDataDir(bool fNetSpecific = true);
176 boost::filesystem::path GetConfigFile();
177 boost::filesystem::path GetPidFile();
178 void CreatePidFile(const boost::filesystem::path &path, pid_t pid);
179 void ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet, std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet);
180 bool GetStartOnSystemStartup();
181 bool SetStartOnSystemStartup(bool fAutoStart);
182 void ShrinkDebugFile();
183 int GetRandInt(int nMax);
184 uint64 GetRand(uint64 nMax);
185 uint256 GetRandHash();
187 void SetMockTime(int64 nMockTimeIn);
188 int64 GetAdjustedTime();
189 std::string FormatFullVersion();
190 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments);
191 void AddTimeData(const CNetAddr& ip, int64 nTime);
203 /** Wrapped boost mutex: supports recursive locking, but no waiting */
204 typedef boost::interprocess::interprocess_recursive_mutex CCriticalSection;
206 /** Wrapped boost mutex: supports waiting but not recursive locking */
207 typedef boost::interprocess::interprocess_mutex CWaitableCriticalSection;
209 #ifdef DEBUG_LOCKORDER
210 void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry = false);
211 void LeaveCritical();
213 void static inline EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry = false) {}
214 void static inline LeaveCritical() {}
217 /** Wrapper around boost::interprocess::scoped_lock */
218 template<typename Mutex>
222 boost::interprocess::scoped_lock<Mutex> lock;
225 void Enter(const char* pszName, const char* pszFile, int nLine)
229 EnterCritical(pszName, pszFile, nLine, (void*)(lock.mutex()));
230 #ifdef DEBUG_LOCKCONTENTION
231 if (!lock.try_lock())
233 printf("LOCKCONTENTION: %s\n", pszName);
234 printf("Locker: %s:%d\n", pszFile, nLine);
237 #ifdef DEBUG_LOCKCONTENTION
252 bool TryEnter(const char* pszName, const char* pszFile, int nLine)
256 EnterCritical(pszName, pszFile, nLine, (void*)(lock.mutex()), true);
264 CMutexLock(Mutex& mutexIn, const char* pszName, const char* pszFile, int nLine, bool fTry = false) : lock(mutexIn, boost::interprocess::defer_lock)
267 TryEnter(pszName, pszFile, nLine);
269 Enter(pszName, pszFile, nLine);
283 boost::interprocess::scoped_lock<Mutex> &GetLock()
289 typedef CMutexLock<CCriticalSection> CCriticalBlock;
291 #define LOCK(cs) CCriticalBlock criticalblock(cs, #cs, __FILE__, __LINE__)
292 #define LOCK2(cs1,cs2) CCriticalBlock criticalblock1(cs1, #cs1, __FILE__, __LINE__),criticalblock2(cs2, #cs2, __FILE__, __LINE__)
293 #define TRY_LOCK(cs,name) CCriticalBlock name(cs, #cs, __FILE__, __LINE__, true)
295 #define ENTER_CRITICAL_SECTION(cs) \
297 EnterCritical(#cs, __FILE__, __LINE__, (void*)(&cs)); \
301 #define LEAVE_CRITICAL_SECTION(cs) \
308 // boost::interprocess::interprocess_semaphore seems to spinlock on OSX; prefer polling instead
316 CSemaphore(int init) : val(init) {}
346 typedef boost::interprocess::interprocess_semaphore CSemaphore;
349 inline std::string i64tostr(int64 n)
351 return strprintf("%"PRI64d, n);
354 inline std::string itostr(int n)
356 return strprintf("%d", n);
359 inline int64 atoi64(const char* psz)
364 return strtoll(psz, NULL, 10);
368 inline int64 atoi64(const std::string& str)
371 return _atoi64(str.c_str());
373 return strtoll(str.c_str(), NULL, 10);
377 inline int atoi(const std::string& str)
379 return atoi(str.c_str());
382 inline int roundint(double d)
384 return (int)(d > 0 ? d + 0.5 : d - 0.5);
387 inline int64 roundint64(double d)
389 return (int64)(d > 0 ? d + 0.5 : d - 0.5);
392 inline int64 abs64(int64 n)
394 return (n >= 0 ? n : -n);
398 std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
400 std::vector<char> rv;
401 static char hexmap[16] = { '0', '1', '2', '3', '4', '5', '6', '7',
402 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
403 rv.reserve((itend-itbegin)*3);
404 for(T it = itbegin; it < itend; ++it)
406 unsigned char val = (unsigned char)(*it);
407 if(fSpaces && it != itbegin)
409 rv.push_back(hexmap[val>>4]);
410 rv.push_back(hexmap[val&15]);
413 return std::string(rv.begin(), rv.end());
416 inline std::string HexStr(const std::vector<unsigned char>& vch, bool fSpaces=false)
418 return HexStr(vch.begin(), vch.end(), fSpaces);
422 void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)
424 printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());
427 inline void PrintHex(const std::vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true)
429 printf(pszFormat, HexStr(vch, fSpaces).c_str());
432 inline int64 GetPerformanceCounter()
436 QueryPerformanceCounter((LARGE_INTEGER*)&nCounter);
439 gettimeofday(&t, NULL);
440 nCounter = t.tv_sec * 1000000 + t.tv_usec;
445 inline int64 GetTimeMillis()
447 return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) -
448 boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
451 inline std::string DateTimeStrFormat(const char* pszFormat, int64 nTime)
454 struct tm* ptmTime = gmtime(&n);
456 strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime);
460 static const std::string strTimestampFormat = "%Y-%m-%d %H:%M:%S UTC";
461 inline std::string DateTimeStrFormat(int64 nTime)
463 return DateTimeStrFormat(strTimestampFormat.c_str(), nTime);
467 void skipspaces(T& it)
473 inline bool IsSwitchChar(char c)
476 return c == '-' || c == '/';
483 * Return string argument or default value
485 * @param strArg Argument to get (e.g. "-foo")
486 * @param default (e.g. "1")
487 * @return command-line argument or default value
489 std::string GetArg(const std::string& strArg, const std::string& strDefault);
492 * Return integer argument or default value
494 * @param strArg Argument to get (e.g. "-foo")
495 * @param default (e.g. 1)
496 * @return command-line argument (0 if invalid number) or default value
498 int64 GetArg(const std::string& strArg, int64 nDefault);
501 * Return boolean argument or default value
503 * @param strArg Argument to get (e.g. "-foo")
504 * @param default (true or false)
505 * @return command-line argument or default value
507 bool GetBoolArg(const std::string& strArg, bool fDefault=false);
510 * Set an argument if it doesn't already have a value
512 * @param strArg Argument to set (e.g. "-foo")
513 * @param strValue Value (e.g. "1")
514 * @return true if argument gets set, false if it already had a value
516 bool SoftSetArg(const std::string& strArg, const std::string& strValue);
519 * Set a boolean argument if it doesn't already have a value
521 * @param strArg Argument to set (e.g. "-foo")
522 * @param fValue Value (e.g. false)
523 * @return true if argument gets set, false if it already had a value
525 bool SoftSetBoolArg(const std::string& strArg, bool fValue);
535 // Randomize the stack to help protect against buffer overrun exploits
536 #define IMPLEMENT_RANDOMIZE_STACK(ThreadFn) \
538 static char nLoops; \
540 nLoops = GetRand(20) + 1; \
549 template<typename T1>
550 inline uint256 Hash(const T1 pbegin, const T1 pend)
552 static unsigned char pblank[1];
554 SHA256((pbegin == pend ? pblank : (unsigned char*)&pbegin[0]), (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);
556 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
560 template<typename T1, typename T2>
561 inline uint256 Hash(const T1 p1begin, const T1 p1end,
562 const T2 p2begin, const T2 p2end)
564 static unsigned char pblank[1];
568 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
569 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
570 SHA256_Final((unsigned char*)&hash1, &ctx);
572 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
576 template<typename T1, typename T2, typename T3>
577 inline uint256 Hash(const T1 p1begin, const T1 p1end,
578 const T2 p2begin, const T2 p2end,
579 const T3 p3begin, const T3 p3end)
581 static unsigned char pblank[1];
585 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
586 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
587 SHA256_Update(&ctx, (p3begin == p3end ? pblank : (unsigned char*)&p3begin[0]), (p3end - p3begin) * sizeof(p3begin[0]));
588 SHA256_Final((unsigned char*)&hash1, &ctx);
590 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
595 uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=PROTOCOL_VERSION)
597 // Most of the time is spent allocating and deallocating CDataStream's
598 // buffer. If this ever needs to be optimized further, make a CStaticStream
599 // class with its buffer on the stack.
600 CDataStream ss(nType, nVersion);
603 return Hash(ss.begin(), ss.end());
606 inline uint160 Hash160(const std::vector<unsigned char>& vch)
609 SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);
611 RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
616 /** Median filter over a stream of values.
617 * Returns the median of the last N numbers
619 template <typename T> class CMedianFilter
622 std::vector<T> vValues;
623 std::vector<T> vSorted;
626 CMedianFilter(unsigned int size, T initial_value):
629 vValues.reserve(size);
630 vValues.push_back(initial_value);
636 if(vValues.size() == nSize)
638 vValues.erase(vValues.begin());
640 vValues.push_back(value);
642 vSorted.resize(vValues.size());
643 std::copy(vValues.begin(), vValues.end(), vSorted.begin());
644 std::sort(vSorted.begin(), vSorted.end());
649 int size = vSorted.size();
651 if(size & 1) // Odd number of elements
653 return vSorted[size/2];
655 else // Even number of elements
657 return (vSorted[size/2-1] + vSorted[size/2]) / 2;
663 return vValues.size();
666 std::vector<T> sorted () const
681 // Note: It turns out we might have been able to use boost::thread
682 // by using TerminateThread(boost::thread.native_handle(), 0);
684 typedef HANDLE bitcoin_pthread_t;
686 inline bitcoin_pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
691 NULL, // default security
692 0, // inherit stack size from parent
693 (LPTHREAD_START_ROUTINE)pfn, // function pointer
695 0, // creation option, start immediately
696 &nUnused); // thread identifier
699 printf("Error: CreateThread() returned %d\n", GetLastError());
700 return (bitcoin_pthread_t)0;
704 CloseHandle(hthread);
705 return (bitcoin_pthread_t)-1;
710 inline void SetThreadPriority(int nPriority)
712 SetThreadPriority(GetCurrentThread(), nPriority);
715 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
717 pthread_t hthread = 0;
718 int ret = pthread_create(&hthread, NULL, (void*(*)(void*))pfn, parg);
721 printf("Error: pthread_create() returned %d\n", ret);
726 pthread_detach(hthread);
727 return (pthread_t)-1;
732 #define THREAD_PRIORITY_LOWEST PRIO_MAX
733 #define THREAD_PRIORITY_BELOW_NORMAL 2
734 #define THREAD_PRIORITY_NORMAL 0
735 #define THREAD_PRIORITY_ABOVE_NORMAL 0
737 inline void SetThreadPriority(int nPriority)
739 // It's unclear if it's even possible to change thread priorities on Linux,
740 // but we really and truly need it for the generation threads.
742 setpriority(PRIO_THREAD, 0, nPriority);
744 setpriority(PRIO_PROCESS, 0, nPriority);
748 inline void ExitThread(size_t nExitCode)
750 pthread_exit((void*)nExitCode);
758 inline uint32_t ByteReverse(uint32_t value)
760 value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8);
761 return (value<<16) | (value>>16);