Bitcoin v0.3.10 · 2010-08-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 fShutdown;144extern bool fDaemon;145extern bool fCommandLine;146147void RandAddSeed();148void RandAddSeedPerfmon();149int OutputDebugStringF(const char* pszFormat, ...);150int my_snprintf(char* buffer, size_t limit, const char* format, ...);151string strprintf(const char* format, ...);152bool error(const char* format, ...);153void PrintException(std::exception* pex, const char* pszThread);154void LogException(std::exception* pex, const char* pszThread);155void ParseString(const string& str, char c, vector<string>& v);156string FormatMoney(int64 n, bool fPlus=false);157bool ParseMoney(const string& str, int64& nRet);158bool ParseMoney(const char* pszIn, int64& nRet);159vector<unsigned char> ParseHex(const char* psz);160vector<unsigned char> ParseHex(const std::string& str);161void ParseParameters(int argc, char* argv[]);162const char* wxGetTranslation(const char* psz);163int GetFilesize(FILE* file);164void GetDataDir(char* pszDirRet);165string GetConfigFile();166void ReadConfigFile(map<string, string>& mapSettingsRet, map<string, vector<string> >& mapMultiSettingsRet);167#ifdef __WXMSW__168string MyGetSpecialFolderPath(int nFolder, bool fCreate);169#endif170string GetDefaultDataDir();171string GetDataDir();172void ShrinkDebugFile();173uint64 GetRand(uint64 nMax);174int64 GetTime();175int64 GetAdjustedTime();176void AddTimeData(unsigned int ip, int64 nTime);177178179180181182183184185186187188189190// Wrapper to automatically initialize critical sections191class CCriticalSection192{193#ifdef __WXMSW__194protected:195 CRITICAL_SECTION cs;196public:197 explicit CCriticalSection() { InitializeCriticalSection(&cs); }198 ~CCriticalSection() { DeleteCriticalSection(&cs); }199 void Enter() { EnterCriticalSection(&cs); }200 void Leave() { LeaveCriticalSection(&cs); }201 bool TryEnter() { return TryEnterCriticalSection(&cs); }202#else203protected:204 boost::interprocess::interprocess_recursive_mutex mutex;205public:206 explicit CCriticalSection() { }207 ~CCriticalSection() { }208 void Enter() { mutex.lock(); }209 void Leave() { mutex.unlock(); }210 bool TryEnter() { return mutex.try_lock(); }211#endif212public:213 const char* pszFile;214 int nLine;215};216217// Automatically leave critical section when leaving block, needed for exception safety218class CCriticalBlock219{220protected:221 CCriticalSection* pcs;222public:223 CCriticalBlock(CCriticalSection& csIn) { pcs = &csIn; pcs->Enter(); }224 ~CCriticalBlock() { pcs->Leave(); }225};226227// WARNING: This will catch continue and break!228// break is caught with an assertion, but there's no way to detect continue.229// I'd rather be careful than suffer the other more error prone syntax.230// The compiler will optimise away all this loop junk.231#define CRITICAL_BLOCK(cs) \232 for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by CRITICAL_BLOCK!", !fcriticalblockonce)), fcriticalblockonce=false) \233 for (CCriticalBlock criticalblock(cs); fcriticalblockonce && (cs.pszFile=__FILE__, cs.nLine=__LINE__, true); fcriticalblockonce=false, cs.pszFile=NULL, cs.nLine=0)234235class CTryCriticalBlock236{237protected:238 CCriticalSection* pcs;239public:240 CTryCriticalBlock(CCriticalSection& csIn) { pcs = (csIn.TryEnter() ? &csIn : NULL); }241 ~CTryCriticalBlock() { if (pcs) pcs->Leave(); }242 bool Entered() { return pcs != NULL; }243};244245#define TRY_CRITICAL_BLOCK(cs) \246 for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by TRY_CRITICAL_BLOCK!", !fcriticalblockonce)), fcriticalblockonce=false) \247 for (CTryCriticalBlock criticalblock(cs); fcriticalblockonce && (fcriticalblockonce = criticalblock.Entered()) && (cs.pszFile=__FILE__, cs.nLine=__LINE__, true); fcriticalblockonce=false, cs.pszFile=NULL, cs.nLine=0)248249250251252253254255256257258inline string i64tostr(int64 n)259{260 return strprintf("%"PRI64d, n);261}262263inline string itostr(int n)264{265 return strprintf("%d", n);266}267268inline int64 atoi64(const char* psz)269{270#ifdef _MSC_VER271 return _atoi64(psz);272#else273 return strtoll(psz, NULL, 10);274#endif275}276277inline int64 atoi64(const string& str)278{279#ifdef _MSC_VER280 return _atoi64(str.c_str());281#else282 return strtoll(str.c_str(), NULL, 10);283#endif284}285286inline int atoi(const string& str)287{288 return atoi(str.c_str());289}290291inline int roundint(double d)292{293 return (int)(d > 0 ? d + 0.5 : d - 0.5);294}295296inline int64 roundint64(double d)297{298 return (int64)(d > 0 ? d + 0.5 : d - 0.5);299}300301template<typename T>302string HexStr(const T itbegin, const T itend, bool fSpaces=true)303{304 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];305 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);306 string str;307 for (const unsigned char* p = pbegin; p != pend; p++)308 str += strprintf((fSpaces && p != pend-1 ? "%02x " : "%02x"), *p);309 return str;310}311312inline string HexStr(vector<unsigned char> vch, bool fSpaces=true)313{314 return HexStr(vch.begin(), vch.end(), fSpaces);315}316317template<typename T>318string HexNumStr(const T itbegin, const T itend, bool f0x=true)319{320 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];321 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);322 string str = (f0x ? "0x" : "");323 for (const unsigned char* p = pend-1; p >= pbegin; p--)324 str += strprintf("%02X", *p);325 return str;326}327328template<typename T>329void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)330{331 printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());332}333334inline void PrintHex(vector<unsigned char> vch, const char* pszFormat="%s", bool fSpaces=true)335{336 printf(pszFormat, HexStr(vch, fSpaces).c_str());337}338339inline int64 PerformanceCounter()340{341 int64 nCounter = 0;342#ifdef __WXMSW__343 QueryPerformanceCounter((LARGE_INTEGER*)&nCounter);344#else345 timeval t;346 gettimeofday(&t, NULL);347 nCounter = t.tv_sec * 1000000 + t.tv_usec;348#endif349 return nCounter;350}351352inline int64 GetTimeMillis()353{354 return (posix_time::ptime(posix_time::microsec_clock::universal_time()) -355 posix_time::ptime(gregorian::date(1970,1,1))).total_milliseconds();356}357358inline string DateTimeStrFormat(const char* pszFormat, int64 nTime)359{360 time_t n = nTime;361 struct tm* ptmTime = gmtime(&n);362 char pszTime[200];363 strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime);364 return pszTime;365}366367template<typename T>368void skipspaces(T& it)369{370 while (isspace(*it))371 ++it;372}373374inline bool IsSwitchChar(char c)375{376#ifdef __WXMSW__377 return c == '-' || c == '/';378#else379 return c == '-';380#endif381}382383384385386387388389390391392inline void heapchk()393{394#ifdef __WXMSW__395 /// for debugging396 //if (_heapchk() != _HEAPOK)397 // DebugBreak();398#endif399}400401// Randomize the stack to help protect against buffer overrun exploits402#define IMPLEMENT_RANDOMIZE_STACK(ThreadFn) \403 { \404 static char nLoops; \405 if (nLoops <= 0) \406 nLoops = GetRand(20) + 1; \407 if (nLoops-- > 1) \408 { \409 ThreadFn; \410 return; \411 } \412 }413414#define CATCH_PRINT_EXCEPTION(pszFn) \415 catch (std::exception& e) { \416 PrintException(&e, (pszFn)); \417 } catch (...) { \418 PrintException(NULL, (pszFn)); \419 }420421422423424425426427428429430template<typename T1>431inline uint256 Hash(const T1 pbegin, const T1 pend)432{433 static unsigned char pblank[1];434 uint256 hash1;435 SHA256((pbegin == pend ? pblank : (unsigned char*)&pbegin[0]), (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);436 uint256 hash2;437 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);438 return hash2;439}440441template<typename T1, typename T2>442inline uint256 Hash(const T1 p1begin, const T1 p1end,443 const T2 p2begin, const T2 p2end)444{445 static unsigned char pblank[1];446 uint256 hash1;447 SHA256_CTX ctx;448 SHA256_Init(&ctx);449 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));450 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));451 SHA256_Final((unsigned char*)&hash1, &ctx);452 uint256 hash2;453 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);454 return hash2;455}456457template<typename T1, typename T2, typename T3>458inline uint256 Hash(const T1 p1begin, const T1 p1end,459 const T2 p2begin, const T2 p2end,460 const T3 p3begin, const T3 p3end)461{462 static unsigned char pblank[1];463 uint256 hash1;464 SHA256_CTX ctx;465 SHA256_Init(&ctx);466 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));467 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));468 SHA256_Update(&ctx, (p3begin == p3end ? pblank : (unsigned char*)&p3begin[0]), (p3end - p3begin) * sizeof(p3begin[0]));469 SHA256_Final((unsigned char*)&hash1, &ctx);470 uint256 hash2;471 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);472 return hash2;473}474475template<typename T>476uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=VERSION)477{478 // Most of the time is spent allocating and deallocating CDataStream's479 // buffer. If this ever needs to be optimized further, make a CStaticStream480 // class with its buffer on the stack.481 CDataStream ss(nType, nVersion);482 ss.reserve(10000);483 ss << obj;484 return Hash(ss.begin(), ss.end());485}486487inline uint160 Hash160(const vector<unsigned char>& vch)488{489 uint256 hash1;490 SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);491 uint160 hash2;492 RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);493 return hash2;494}495496497498499500501502503504505506// Note: It turns out we might have been able to use boost::thread507// by using TerminateThread(boost::thread.native_handle(), 0);508#ifdef __WXMSW__509typedef HANDLE pthread_t;510511inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)512{513 DWORD nUnused = 0;514 HANDLE hthread =515 CreateThread(516 NULL, // default security517 0, // inherit stack size from parent518 (LPTHREAD_START_ROUTINE)pfn, // function pointer519 parg, // argument520 0, // creation option, start immediately521 &nUnused); // thread identifier522 if (hthread == NULL)523 {524 printf("Error: CreateThread() returned %d\n", GetLastError());525 return (pthread_t)0;526 }527 if (!fWantHandle)528 {529 CloseHandle(hthread);530 return (pthread_t)-1;531 }532 return hthread;533}534535inline void SetThreadPriority(int nPriority)536{537 SetThreadPriority(GetCurrentThread(), nPriority);538}539#else540inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)541{542 pthread_t hthread = 0;543 int ret = pthread_create(&hthread, NULL, (void*(*)(void*))pfn, parg);544 if (ret != 0)545 {546 printf("Error: pthread_create() returned %d\n", ret);547 return (pthread_t)0;548 }549 if (!fWantHandle)550 return (pthread_t)-1;551 return hthread;552}553554#define THREAD_PRIORITY_LOWEST PRIO_MAX555#define THREAD_PRIORITY_BELOW_NORMAL 2556#define THREAD_PRIORITY_NORMAL 0557#define THREAD_PRIORITY_ABOVE_NORMAL 0558559inline void SetThreadPriority(int nPriority)560{561 // It's unclear if it's even possible to change thread priorities on Linux,562 // but we really and truly need it for the generation threads.563#ifdef PRIO_THREAD564 setpriority(PRIO_THREAD, 0, nPriority);565#else566 setpriority(PRIO_PROCESS, 0, nPriority);567#endif568}569570inline bool TerminateThread(pthread_t hthread, unsigned int nExitCode)571{572 return (pthread_cancel(hthread) == 0);573}574575inline void ExitThread(unsigned int nExitCode)576{577 pthread_exit((void*)nExitCode);578}579#endif
Click a line number to link to it; use #L10-L20 for a range. "=" next to a version means the file is identical there.
