Bitcoin v0.3.0 · 2010-07-06
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#ifdef __WXMSW__58static const bool fWindows = true;59#define MSG_NOSIGNAL 060#define MSG_DONTWAIT 061#ifndef UINT64_MAX62#define UINT64_MAX _UI64_MAX63#define INT64_MAX _I64_MAX64#define INT64_MIN _I64_MIN65#endif66#ifndef S_IRUSR67#define S_IRUSR 040068#define S_IWUSR 020069#endif70#define unlink _unlink71typedef int socklen_t;72#else73static const bool fWindows = false;74#define WSAGetLastError() errno75#define WSAEWOULDBLOCK EWOULDBLOCK76#define WSAEMSGSIZE EMSGSIZE77#define WSAEINTR EINTR78#define WSAEINPROGRESS EINPROGRESS79#define WSAEADDRINUSE EADDRINUSE80#define WSAENOTSOCK EBADF81#define INVALID_SOCKET (SOCKET)(~0)82#define SOCKET_ERROR -183typedef u_int SOCKET;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)87#define _mkdir(psz) filesystem::create_directory(psz)88#define MAX_PATH 102489#define Sleep(n) wxMilliSleep(n)90#define Beep(n1,n2) (0)91#endif9293inline int myclosesocket(SOCKET& hSocket)94{95 if (hSocket == INVALID_SOCKET)96 return WSAENOTSOCK;97#ifdef __WXMSW__98 int ret = closesocket(hSocket);99#else100 int ret = close(hSocket);101#endif102 hSocket = INVALID_SOCKET;103 return ret;104}105#define closesocket(s) myclosesocket(s)106107108109110111112113114115116extern map<string, string> mapArgs;117extern map<string, vector<string> > mapMultiArgs;118extern bool fDebug;119extern bool fPrintToConsole;120extern bool fPrintToDebugger;121extern char pszSetDataDir[MAX_PATH];122extern bool fShutdown;123extern bool fDaemon;124extern bool fCommandLine;125126void RandAddSeed();127void RandAddSeedPerfmon();128int OutputDebugStringF(const char* pszFormat, ...);129int my_snprintf(char* buffer, size_t limit, const char* format, ...);130string strprintf(const char* format, ...);131bool error(const char* format, ...);132void PrintException(std::exception* pex, const char* pszThread);133void LogException(std::exception* pex, const char* pszThread);134void ParseString(const string& str, char c, vector<string>& v);135string FormatMoney(int64 n, bool fPlus=false);136bool ParseMoney(const string& str, int64& nRet);137bool ParseMoney(const char* pszIn, int64& nRet);138vector<unsigned char> ParseHex(const char* psz);139vector<unsigned char> ParseHex(const std::string& str);140void ParseParameters(int argc, char* argv[]);141const char* wxGetTranslation(const char* psz);142int GetFilesize(FILE* file);143void GetDataDir(char* pszDirRet);144string GetDataDir();145void ShrinkDebugFile();146uint64 GetRand(uint64 nMax);147int64 GetTime();148int64 GetAdjustedTime();149void AddTimeData(unsigned int ip, int64 nTime);150151152153154155156157158159160161162163// Wrapper to automatically initialize critical sections164class CCriticalSection165{166#ifdef __WXMSW__167protected:168 CRITICAL_SECTION cs;169public:170 explicit CCriticalSection() { InitializeCriticalSection(&cs); }171 ~CCriticalSection() { DeleteCriticalSection(&cs); }172 void Enter() { EnterCriticalSection(&cs); }173 void Leave() { LeaveCriticalSection(&cs); }174 bool TryEnter() { return TryEnterCriticalSection(&cs); }175#else176protected:177 wxMutex mutex;178public:179 explicit CCriticalSection() : mutex(wxMUTEX_RECURSIVE) { }180 ~CCriticalSection() { }181 void Enter() { mutex.Lock(); }182 void Leave() { mutex.Unlock(); }183 bool TryEnter() { return mutex.TryLock() == wxMUTEX_NO_ERROR; }184#endif185public:186 const char* pszFile;187 int nLine;188};189190// Automatically leave critical section when leaving block, needed for exception safety191class CCriticalBlock192{193protected:194 CCriticalSection* pcs;195public:196 CCriticalBlock(CCriticalSection& csIn) { pcs = &csIn; pcs->Enter(); }197 ~CCriticalBlock() { pcs->Leave(); }198};199200// WARNING: This will catch continue and break!201// break is caught with an assertion, but there's no way to detect continue.202// I'd rather be careful than suffer the other more error prone syntax.203// The compiler will optimise away all this loop junk.204#define CRITICAL_BLOCK(cs) \205 for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by CRITICAL_BLOCK!", !fcriticalblockonce)), fcriticalblockonce=false) \206 for (CCriticalBlock criticalblock(cs); fcriticalblockonce && (cs.pszFile=__FILE__, cs.nLine=__LINE__, true); fcriticalblockonce=false, cs.pszFile=NULL, cs.nLine=0)207208class CTryCriticalBlock209{210protected:211 CCriticalSection* pcs;212public:213 CTryCriticalBlock(CCriticalSection& csIn) { pcs = (csIn.TryEnter() ? &csIn : NULL); }214 ~CTryCriticalBlock() { if (pcs) pcs->Leave(); }215 bool Entered() { return pcs != NULL; }216};217218#define TRY_CRITICAL_BLOCK(cs) \219 for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by TRY_CRITICAL_BLOCK!", !fcriticalblockonce)), fcriticalblockonce=false) \220 for (CTryCriticalBlock criticalblock(cs); fcriticalblockonce && (fcriticalblockonce = criticalblock.Entered()) && (cs.pszFile=__FILE__, cs.nLine=__LINE__, true); fcriticalblockonce=false, cs.pszFile=NULL, cs.nLine=0)221222223224225226227228229230231inline string i64tostr(int64 n)232{233 return strprintf("%"PRI64d, n);234}235236inline string itostr(int n)237{238 return strprintf("%d", n);239}240241inline int64 atoi64(const char* psz)242{243#ifdef _MSC_VER244 return _atoi64(psz);245#else246 return strtoll(psz, NULL, 10);247#endif248}249250inline int64 atoi64(const string& str)251{252#ifdef _MSC_VER253 return _atoi64(str.c_str());254#else255 return strtoll(str.c_str(), NULL, 10);256#endif257}258259inline int atoi(const string& str)260{261 return atoi(str.c_str());262}263264inline int roundint(double d)265{266 return (int)(d > 0 ? d + 0.5 : d - 0.5);267}268269inline int64 roundint64(double d)270{271 return (int64)(d > 0 ? d + 0.5 : d - 0.5);272}273274template<typename T>275string HexStr(const T itbegin, const T itend, bool fSpaces=true)276{277 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];278 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);279 string str;280 for (const unsigned char* p = pbegin; p != pend; p++)281 str += strprintf((fSpaces && p != pend-1 ? "%02x " : "%02x"), *p);282 return str;283}284285inline string HexStr(vector<unsigned char> vch, bool fSpaces=true)286{287 return HexStr(vch.begin(), vch.end(), fSpaces);288}289290template<typename T>291string HexNumStr(const T itbegin, const T itend, bool f0x=true)292{293 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];294 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);295 string str = (f0x ? "0x" : "");296 for (const unsigned char* p = pend-1; p >= pbegin; p--)297 str += strprintf("%02X", *p);298 return str;299}300301template<typename T>302void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)303{304 printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());305}306307inline void PrintHex(vector<unsigned char> vch, const char* pszFormat="%s", bool fSpaces=true)308{309 printf(pszFormat, HexStr(vch, fSpaces).c_str());310}311312inline int64 PerformanceCounter()313{314 int64 nCounter = 0;315#ifdef __WXMSW__316 QueryPerformanceCounter((LARGE_INTEGER*)&nCounter);317#else318 timeval t;319 gettimeofday(&t, NULL);320 nCounter = t.tv_sec * 1000000 + t.tv_usec;321#endif322 return nCounter;323}324325inline int64 GetTimeMillis()326{327 return wxGetLocalTimeMillis().GetValue();328}329330inline string DateTimeStrFormat(const char* pszFormat, int64 nTime)331{332 time_t n = nTime;333 struct tm* ptmTime = gmtime(&n);334 char pszTime[200];335 strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime);336 return pszTime;337}338339template<typename T>340void skipspaces(T& it)341{342 while (isspace(*it))343 ++it;344}345346347348349350351352353354355356357inline void heapchk()358{359#ifdef __WXMSW__360 /// for debugging361 //if (_heapchk() != _HEAPOK)362 // DebugBreak();363#endif364}365366// Randomize the stack to help protect against buffer overrun exploits367#define IMPLEMENT_RANDOMIZE_STACK(ThreadFn) \368 { \369 static char nLoops; \370 if (nLoops <= 0) \371 nLoops = GetRand(20) + 1; \372 if (nLoops-- > 1) \373 { \374 ThreadFn; \375 return; \376 } \377 }378379#define CATCH_PRINT_EXCEPTION(pszFn) \380 catch (std::exception& e) { \381 PrintException(&e, (pszFn)); \382 } catch (...) { \383 PrintException(NULL, (pszFn)); \384 }385386387388389390391392393394395template<typename T1>396inline uint256 Hash(const T1 pbegin, const T1 pend)397{398 uint256 hash1;399 SHA256((unsigned char*)&pbegin[0], (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);400 uint256 hash2;401 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);402 return hash2;403}404405template<typename T1, typename T2>406inline uint256 Hash(const T1 p1begin, const T1 p1end,407 const T2 p2begin, const T2 p2end)408{409 uint256 hash1;410 SHA256_CTX ctx;411 SHA256_Init(&ctx);412 SHA256_Update(&ctx, (unsigned char*)&p1begin[0], (p1end - p1begin) * sizeof(p1begin[0]));413 SHA256_Update(&ctx, (unsigned char*)&p2begin[0], (p2end - p2begin) * sizeof(p2begin[0]));414 SHA256_Final((unsigned char*)&hash1, &ctx);415 uint256 hash2;416 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);417 return hash2;418}419420template<typename T1, typename T2, typename T3>421inline uint256 Hash(const T1 p1begin, const T1 p1end,422 const T2 p2begin, const T2 p2end,423 const T3 p3begin, const T3 p3end)424{425 uint256 hash1;426 SHA256_CTX ctx;427 SHA256_Init(&ctx);428 SHA256_Update(&ctx, (unsigned char*)&p1begin[0], (p1end - p1begin) * sizeof(p1begin[0]));429 SHA256_Update(&ctx, (unsigned char*)&p2begin[0], (p2end - p2begin) * sizeof(p2begin[0]));430 SHA256_Update(&ctx, (unsigned char*)&p3begin[0], (p3end - p3begin) * sizeof(p3begin[0]));431 SHA256_Final((unsigned char*)&hash1, &ctx);432 uint256 hash2;433 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);434 return hash2;435}436437template<typename T>438uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=VERSION)439{440 // Most of the time is spent allocating and deallocating CDataStream's441 // buffer. If this ever needs to be optimized further, make a CStaticStream442 // class with its buffer on the stack.443 CDataStream ss(nType, nVersion);444 ss.reserve(10000);445 ss << obj;446 return Hash(ss.begin(), ss.end());447}448449inline uint160 Hash160(const vector<unsigned char>& vch)450{451 uint256 hash1;452 SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);453 uint160 hash2;454 RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);455 return hash2;456}457458459460461462463464465466467468// Note: It turns out we might have been able to use boost::thread469// by using TerminateThread(boost::thread.native_handle(), 0);470#ifdef __WXMSW__471typedef HANDLE pthread_t;472473inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)474{475 DWORD nUnused = 0;476 HANDLE hthread =477 CreateThread(478 NULL, // default security479 0, // inherit stack size from parent480 (LPTHREAD_START_ROUTINE)pfn, // function pointer481 parg, // argument482 0, // creation option, start immediately483 &nUnused); // thread identifier484 if (hthread == NULL)485 {486 printf("Error: CreateThread() returned %d\n", GetLastError());487 return (pthread_t)0;488 }489 if (!fWantHandle)490 {491 CloseHandle(hthread);492 return (pthread_t)-1;493 }494 return hthread;495}496497inline void SetThreadPriority(int nPriority)498{499 SetThreadPriority(GetCurrentThread(), nPriority);500}501#else502inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)503{504 pthread_t hthread = 0;505 int ret = pthread_create(&hthread, NULL, (void*(*)(void*))pfn, parg);506 if (ret != 0)507 {508 printf("Error: pthread_create() returned %d\n", ret);509 return (pthread_t)0;510 }511 if (!fWantHandle)512 return (pthread_t)-1;513 return hthread;514}515516#define THREAD_PRIORITY_LOWEST PRIO_MIN517#define THREAD_PRIORITY_BELOW_NORMAL 2518#define THREAD_PRIORITY_NORMAL 0519#define THREAD_PRIORITY_ABOVE_NORMAL 0520521inline void SetThreadPriority(int nPriority)522{523 // It's unclear if it's even possible to change thread priorities on Linux,524 // but we really and truly need it for the generation threads.525#ifdef PRIO_THREAD526 setpriority(PRIO_THREAD, 0, nPriority);527#else528 setpriority(PRIO_PROCESS, 0, nPriority);529#endif530}531532inline bool TerminateThread(pthread_t hthread, unsigned int nExitCode)533{534 return (pthread_cancel(hthread) == 0);535}536537inline void ExitThread(unsigned int nExitCode)538{539 pthread_exit((void*)nExitCode);540}541#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.
