Bitcoin r202 (last Satoshi commit) · 2010-12-15
util.h
1// Copyright (c) 2009-2010 Satoshi Nakamoto2// Distributed under the MIT/X11 software license, see the accompanying3// file license.txt or http://www.opensource.org/licenses/mit-license.php.456#if defined(_MSC_VER) || defined(__BORLANDC__)7typedef __int64 int64;8typedef unsigned __int64 uint64;9#else10typedef long long int64;11typedef unsigned long long uint64;12#endif13#if defined(_MSC_VER) && _MSC_VER < 130014#define for if (false) ; else for15#endif16#ifndef _MSC_VER17#define __forceinline inline18#endif1920#define foreach BOOST_FOREACH21#define loop for (;;)22#define BEGIN(a) ((char*)&(a))23#define END(a) ((char*)&((&(a))[1]))24#define UBEGIN(a) ((unsigned char*)&(a))25#define UEND(a) ((unsigned char*)&((&(a))[1]))26#define ARRAYLEN(array) (sizeof(array)/sizeof((array)[0]))27#define printf OutputDebugStringF2829#ifdef snprintf30#undef snprintf31#endif32#define snprintf my_snprintf3334#ifndef PRI64d35#if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MSVCRT__)36#define PRI64d "I64d"37#define PRI64u "I64u"38#define PRI64x "I64x"39#else40#define PRI64d "lld"41#define PRI64u "llu"42#define PRI64x "llx"43#endif44#endif4546// This is needed because the foreach macro can't get over the comma in pair<t1, t2>47#define PAIRTYPE(t1, t2) pair<t1, t2>4849// Used to bypass the rule against non-const reference to temporary50// where it makes sense with wrappers such as CFlatData or CTxDB51template<typename T>52inline T& REF(const T& val)53{54 return (T&)val;55}5657// Align by increasing pointer, must have extra space at end of buffer58template <size_t nBytes, typename T>59T* alignup(T* p)60{61 union62 {63 T* ptr;64 size_t n;65 } u;66 u.ptr = p;67 u.n = (u.n + (nBytes-1)) & ~(nBytes-1);68 return u.ptr;69}7071#ifdef __WXMSW__72#define MSG_NOSIGNAL 073#define MSG_DONTWAIT 074#ifndef UINT64_MAX75#define UINT64_MAX _UI64_MAX76#define INT64_MAX _I64_MAX77#define INT64_MIN _I64_MIN78#endif79#ifndef S_IRUSR80#define S_IRUSR 040081#define S_IWUSR 020082#endif83#define unlink _unlink84typedef int socklen_t;85#else86#define WSAGetLastError() errno87#define WSAEWOULDBLOCK EWOULDBLOCK88#define WSAEMSGSIZE EMSGSIZE89#define WSAEINTR EINTR90#define WSAEINPROGRESS EINPROGRESS91#define WSAEADDRINUSE EADDRINUSE92#define WSAENOTSOCK EBADF93#define INVALID_SOCKET (SOCKET)(~0)94#define SOCKET_ERROR -195typedef u_int SOCKET;96#define _vsnprintf(a,b,c,d) vsnprintf(a,b,c,d)97#define strlwr(psz) to_lower(psz)98#define _strlwr(psz) to_lower(psz)99#define MAX_PATH 1024100#define Beep(n1,n2) (0)101inline void Sleep(int64 n)102{103 boost::thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(n));104}105#endif106107inline int myclosesocket(SOCKET& hSocket)108{109 if (hSocket == INVALID_SOCKET)110 return WSAENOTSOCK;111#ifdef __WXMSW__112 int ret = closesocket(hSocket);113#else114 int ret = close(hSocket);115#endif116 hSocket = INVALID_SOCKET;117 return ret;118}119#define closesocket(s) myclosesocket(s)120121#ifndef GUI122inline const char* _(const char* psz)123{124 return psz;125}126#endif127128129130131132133134135136137extern map<string, string> mapArgs;138extern map<string, vector<string> > mapMultiArgs;139extern bool fDebug;140extern bool fPrintToConsole;141extern bool fPrintToDebugger;142extern char pszSetDataDir[MAX_PATH];143extern bool fRequestShutdown;144extern bool fShutdown;145extern bool fDaemon;146extern bool fCommandLine;147extern string strMiscWarning;148extern bool fTestNet;149150void RandAddSeed();151void RandAddSeedPerfmon();152int OutputDebugStringF(const char* pszFormat, ...);153int my_snprintf(char* buffer, size_t limit, const char* format, ...);154string strprintf(const char* format, ...);155bool error(const char* format, ...);156void LogException(std::exception* pex, const char* pszThread);157void PrintException(std::exception* pex, const char* pszThread);158void PrintExceptionContinue(std::exception* pex, const char* pszThread);159void ParseString(const string& str, char c, vector<string>& v);160string FormatMoney(int64 n, bool fPlus=false);161bool ParseMoney(const string& str, int64& nRet);162bool ParseMoney(const char* pszIn, int64& nRet);163vector<unsigned char> ParseHex(const char* psz);164vector<unsigned char> ParseHex(const string& str);165void ParseParameters(int argc, char* argv[]);166const char* wxGetTranslation(const char* psz);167bool WildcardMatch(const char* psz, const char* mask);168bool WildcardMatch(const string& str, const string& mask);169int GetFilesize(FILE* file);170void GetDataDir(char* pszDirRet);171string GetConfigFile();172void ReadConfigFile(map<string, string>& mapSettingsRet, map<string, vector<string> >& mapMultiSettingsRet);173#ifdef __WXMSW__174string MyGetSpecialFolderPath(int nFolder, bool fCreate);175#endif176string GetDefaultDataDir();177string GetDataDir();178void ShrinkDebugFile();179int GetRandInt(int nMax);180uint64 GetRand(uint64 nMax);181int64 GetTime();182int64 GetAdjustedTime();183void AddTimeData(unsigned int ip, int64 nTime);184185186187188189190191192193194195196197// Wrapper to automatically initialize critical sections198class CCriticalSection199{200#ifdef __WXMSW__201protected:202 CRITICAL_SECTION cs;203public:204 explicit CCriticalSection() { InitializeCriticalSection(&cs); }205 ~CCriticalSection() { DeleteCriticalSection(&cs); }206 void Enter() { EnterCriticalSection(&cs); }207 void Leave() { LeaveCriticalSection(&cs); }208 bool TryEnter() { return TryEnterCriticalSection(&cs); }209#else210protected:211 boost::interprocess::interprocess_recursive_mutex mutex;212public:213 explicit CCriticalSection() { }214 ~CCriticalSection() { }215 void Enter() { mutex.lock(); }216 void Leave() { mutex.unlock(); }217 bool TryEnter() { return mutex.try_lock(); }218#endif219public:220 const char* pszFile;221 int nLine;222};223224// Automatically leave critical section when leaving block, needed for exception safety225class CCriticalBlock226{227protected:228 CCriticalSection* pcs;229public:230 CCriticalBlock(CCriticalSection& csIn) { pcs = &csIn; pcs->Enter(); }231 ~CCriticalBlock() { pcs->Leave(); }232};233234// WARNING: This will catch continue and break!235// break is caught with an assertion, but there's no way to detect continue.236// I'd rather be careful than suffer the other more error prone syntax.237// The compiler will optimise away all this loop junk.238#define CRITICAL_BLOCK(cs) \239 for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by CRITICAL_BLOCK!", !fcriticalblockonce)), fcriticalblockonce=false) \240 for (CCriticalBlock criticalblock(cs); fcriticalblockonce && (cs.pszFile=__FILE__, cs.nLine=__LINE__, true); fcriticalblockonce=false, cs.pszFile=NULL, cs.nLine=0)241242class CTryCriticalBlock243{244protected:245 CCriticalSection* pcs;246public:247 CTryCriticalBlock(CCriticalSection& csIn) { pcs = (csIn.TryEnter() ? &csIn : NULL); }248 ~CTryCriticalBlock() { if (pcs) pcs->Leave(); }249 bool Entered() { return pcs != NULL; }250};251252#define TRY_CRITICAL_BLOCK(cs) \253 for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by TRY_CRITICAL_BLOCK!", !fcriticalblockonce)), fcriticalblockonce=false) \254 for (CTryCriticalBlock criticalblock(cs); fcriticalblockonce && (fcriticalblockonce = criticalblock.Entered()) && (cs.pszFile=__FILE__, cs.nLine=__LINE__, true); fcriticalblockonce=false, cs.pszFile=NULL, cs.nLine=0)255256257258259260261262263264265inline string i64tostr(int64 n)266{267 return strprintf("%"PRI64d, n);268}269270inline string itostr(int n)271{272 return strprintf("%d", n);273}274275inline int64 atoi64(const char* psz)276{277#ifdef _MSC_VER278 return _atoi64(psz);279#else280 return strtoll(psz, NULL, 10);281#endif282}283284inline int64 atoi64(const string& str)285{286#ifdef _MSC_VER287 return _atoi64(str.c_str());288#else289 return strtoll(str.c_str(), NULL, 10);290#endif291}292293inline int atoi(const string& str)294{295 return atoi(str.c_str());296}297298inline int roundint(double d)299{300 return (int)(d > 0 ? d + 0.5 : d - 0.5);301}302303inline int64 roundint64(double d)304{305 return (int64)(d > 0 ? d + 0.5 : d - 0.5);306}307308inline int64 abs64(int64 n)309{310 return (n >= 0 ? n : -n);311}312313template<typename T>314string HexStr(const T itbegin, const T itend, bool fSpaces=false)315{316 if (itbegin == itend)317 return "";318 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];319 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);320 string str;321 str.reserve((pend-pbegin) * (fSpaces ? 3 : 2));322 for (const unsigned char* p = pbegin; p != pend; p++)323 str += strprintf((fSpaces && p != pend-1 ? "%02x " : "%02x"), *p);324 return str;325}326327inline string HexStr(const vector<unsigned char>& vch, bool fSpaces=false)328{329 return HexStr(vch.begin(), vch.end(), fSpaces);330}331332template<typename T>333string HexNumStr(const T itbegin, const T itend, bool f0x=true)334{335 if (itbegin == itend)336 return "";337 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];338 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);339 string str = (f0x ? "0x" : "");340 str.reserve(str.size() + (pend-pbegin) * 2);341 for (const unsigned char* p = pend-1; p >= pbegin; p--)342 str += strprintf("%02x", *p);343 return str;344}345346inline string HexNumStr(const vector<unsigned char>& vch, bool f0x=true)347{348 return HexNumStr(vch.begin(), vch.end(), f0x);349}350351template<typename T>352void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)353{354 printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());355}356357inline void PrintHex(const vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true)358{359 printf(pszFormat, HexStr(vch, fSpaces).c_str());360}361362inline int64 GetPerformanceCounter()363{364 int64 nCounter = 0;365#ifdef __WXMSW__366 QueryPerformanceCounter((LARGE_INTEGER*)&nCounter);367#else368 timeval t;369 gettimeofday(&t, NULL);370 nCounter = t.tv_sec * 1000000 + t.tv_usec;371#endif372 return nCounter;373}374375inline int64 GetTimeMillis()376{377 return (posix_time::ptime(posix_time::microsec_clock::universal_time()) -378 posix_time::ptime(gregorian::date(1970,1,1))).total_milliseconds();379}380381inline string DateTimeStrFormat(const char* pszFormat, int64 nTime)382{383 time_t n = nTime;384 struct tm* ptmTime = gmtime(&n);385 char pszTime[200];386 strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime);387 return pszTime;388}389390template<typename T>391void skipspaces(T& it)392{393 while (isspace(*it))394 ++it;395}396397inline bool IsSwitchChar(char c)398{399#ifdef __WXMSW__400 return c == '-' || c == '/';401#else402 return c == '-';403#endif404}405406inline string GetArg(const string& strArg, const string& strDefault)407{408 if (mapArgs.count(strArg))409 return mapArgs[strArg];410 return strDefault;411}412413inline int64 GetArg(const string& strArg, int64 nDefault)414{415 if (mapArgs.count(strArg))416 return atoi64(mapArgs[strArg]);417 return nDefault;418}419420inline bool GetBoolArg(const string& strArg)421{422 if (mapArgs.count(strArg))423 {424 if (mapArgs[strArg].empty())425 return true;426 return (atoi(mapArgs[strArg]) != 0);427 }428 return false;429}430431inline string FormatVersion(int nVersion)432{433 if (nVersion%100 == 0)434 return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);435 else436 return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);437}438439440441442443444445446447448inline void heapchk()449{450#ifdef __WXMSW__451 /// for debugging452 //if (_heapchk() != _HEAPOK)453 // DebugBreak();454#endif455}456457// Randomize the stack to help protect against buffer overrun exploits458#define IMPLEMENT_RANDOMIZE_STACK(ThreadFn) \459 { \460 static char nLoops; \461 if (nLoops <= 0) \462 nLoops = GetRand(20) + 1; \463 if (nLoops-- > 1) \464 { \465 ThreadFn; \466 return; \467 } \468 }469470#define CATCH_PRINT_EXCEPTION(pszFn) \471 catch (std::exception& e) { \472 PrintException(&e, (pszFn)); \473 } catch (...) { \474 PrintException(NULL, (pszFn)); \475 }476477478479480481482483484485486template<typename T1>487inline uint256 Hash(const T1 pbegin, const T1 pend)488{489 static unsigned char pblank[1];490 uint256 hash1;491 SHA256((pbegin == pend ? pblank : (unsigned char*)&pbegin[0]), (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);492 uint256 hash2;493 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);494 return hash2;495}496497template<typename T1, typename T2>498inline uint256 Hash(const T1 p1begin, const T1 p1end,499 const T2 p2begin, const T2 p2end)500{501 static unsigned char pblank[1];502 uint256 hash1;503 SHA256_CTX ctx;504 SHA256_Init(&ctx);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);508 uint256 hash2;509 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);510 return hash2;511}512513template<typename T1, typename T2, typename T3>514inline uint256 Hash(const T1 p1begin, const T1 p1end,515 const T2 p2begin, const T2 p2end,516 const T3 p3begin, const T3 p3end)517{518 static unsigned char pblank[1];519 uint256 hash1;520 SHA256_CTX ctx;521 SHA256_Init(&ctx);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);526 uint256 hash2;527 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);528 return hash2;529}530531template<typename T>532uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=VERSION)533{534 // Most of the time is spent allocating and deallocating CDataStream's535 // buffer. If this ever needs to be optimized further, make a CStaticStream536 // class with its buffer on the stack.537 CDataStream ss(nType, nVersion);538 ss.reserve(10000);539 ss << obj;540 return Hash(ss.begin(), ss.end());541}542543inline uint160 Hash160(const vector<unsigned char>& vch)544{545 uint256 hash1;546 SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);547 uint160 hash2;548 RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);549 return hash2;550}551552553554555556557558559560561562// Note: It turns out we might have been able to use boost::thread563// by using TerminateThread(boost::thread.native_handle(), 0);564#ifdef __WXMSW__565typedef HANDLE pthread_t;566567inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)568{569 DWORD nUnused = 0;570 HANDLE hthread =571 CreateThread(572 NULL, // default security573 0, // inherit stack size from parent574 (LPTHREAD_START_ROUTINE)pfn, // function pointer575 parg, // argument576 0, // creation option, start immediately577 &nUnused); // thread identifier578 if (hthread == NULL)579 {580 printf("Error: CreateThread() returned %d\n", GetLastError());581 return (pthread_t)0;582 }583 if (!fWantHandle)584 {585 CloseHandle(hthread);586 return (pthread_t)-1;587 }588 return hthread;589}590591inline void SetThreadPriority(int nPriority)592{593 SetThreadPriority(GetCurrentThread(), nPriority);594}595#else596inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)597{598 pthread_t hthread = 0;599 int ret = pthread_create(&hthread, NULL, (void*(*)(void*))pfn, parg);600 if (ret != 0)601 {602 printf("Error: pthread_create() returned %d\n", ret);603 return (pthread_t)0;604 }605 if (!fWantHandle)606 return (pthread_t)-1;607 return hthread;608}609610#define THREAD_PRIORITY_LOWEST PRIO_MAX611#define THREAD_PRIORITY_BELOW_NORMAL 2612#define THREAD_PRIORITY_NORMAL 0613#define THREAD_PRIORITY_ABOVE_NORMAL 0614615inline void SetThreadPriority(int nPriority)616{617 // It's unclear if it's even possible to change thread priorities on Linux,618 // but we really and truly need it for the generation threads.619#ifdef PRIO_THREAD620 setpriority(PRIO_THREAD, 0, nPriority);621#else622 setpriority(PRIO_PROCESS, 0, nPriority);623#endif624}625626inline bool TerminateThread(pthread_t hthread, unsigned int nExitCode)627{628 return (pthread_cancel(hthread) == 0);629}630631inline void ExitThread(unsigned int nExitCode)632{633 pthread_exit((void*)nExitCode);634}635#endif636637638639640641inline bool AffinityBugWorkaround(void(*pfn)(void*))642{643#ifdef __WXMSW__644 // Sometimes after a few hours affinity gets stuck on one processor645 DWORD dwProcessAffinityMask = -1;646 DWORD dwSystemAffinityMask = -1;647 GetProcessAffinityMask(GetCurrentProcess(), &dwProcessAffinityMask, &dwSystemAffinityMask);648 DWORD dwPrev1 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);649 DWORD dwPrev2 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);650 if (dwPrev2 != dwProcessAffinityMask)651 {652 printf("AffinityBugWorkaround() : SetThreadAffinityMask=%d, ProcessAffinityMask=%d, restarting thread\n", dwPrev2, dwProcessAffinityMask);653 if (!CreateThread(pfn, NULL))654 printf("Error: CreateThread() failed\n");655 return true;656 }657#endif658 return false;659}
Click a line number to link to it; use #L10-L20 for a range. "=" next to a version means the file is identical there.
