Bitcoin v0.2.0 · 2009-12-16
util.h
1// Copyright (c) 2009 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__58#define MSG_NOSIGNAL 059#define MSG_DONTWAIT 060#ifndef UINT64_MAX61#define UINT64_MAX _UI64_MAX62#define INT64_MAX _I64_MAX63#define INT64_MIN _I64_MIN64#endif65#ifndef S_IRUSR66#define S_IRUSR 040067#define S_IWUSR 020068#endif69#else70#define WSAGetLastError() errno71#define WSAEWOULDBLOCK EWOULDBLOCK72#define WSAEMSGSIZE EMSGSIZE73#define WSAEINTR EINTR74#define WSAEINPROGRESS EINPROGRESS75#define WSAEADDRINUSE EADDRINUSE76#define WSAENOTSOCK EBADF77#define INVALID_SOCKET (SOCKET)(~0)78#define SOCKET_ERROR -179typedef u_int SOCKET;80#define _vsnprintf(a,b,c,d) vsnprintf(a,b,c,d)81#define strlwr(psz) to_lower(psz)82#define _strlwr(psz) to_lower(psz)83#define _mkdir(psz) filesystem::create_directory(psz)84#define MAX_PATH 102485#define Sleep(n) wxMilliSleep(n)86#define Beep(n1,n2) (0)87#endif8889inline int myclosesocket(SOCKET& hSocket)90{91 if (hSocket == INVALID_SOCKET)92 return WSAENOTSOCK;93#ifdef __WXMSW__94 int ret = closesocket(hSocket);95#else96 int ret = close(hSocket);97#endif98 hSocket = INVALID_SOCKET;99 return ret;100}101#define closesocket(s) myclosesocket(s)102103104105106107108109110111112extern map<string, string> mapArgs;113extern map<string, vector<string> > mapMultiArgs;114extern bool fDebug;115extern bool fPrintToDebugger;116extern bool fPrintToConsole;117extern char pszSetDataDir[MAX_PATH];118extern bool fShutdown;119120void RandAddSeed();121void RandAddSeedPerfmon();122int my_snprintf(char* buffer, size_t limit, const char* format, ...);123string strprintf(const char* format, ...);124bool error(const char* format, ...);125void PrintException(std::exception* pex, const char* pszThread);126void LogException(std::exception* pex, const char* pszThread);127void ParseString(const string& str, char c, vector<string>& v);128string FormatMoney(int64 n, bool fPlus=false);129bool ParseMoney(const char* pszIn, int64& nRet);130vector<unsigned char> ParseHex(const char* psz);131vector<unsigned char> ParseHex(const std::string& str);132void ParseParameters(int argc, char* argv[]);133int GetFilesize(FILE* file);134void GetDataDir(char* pszDirRet);135string GetDataDir();136void ShrinkDebugFile();137uint64 GetRand(uint64 nMax);138int64 GetTime();139int64 GetAdjustedTime();140void AddTimeData(unsigned int ip, int64 nTime);141142143144145146147148149150151152153154// Wrapper to automatically initialize critical sections155class CCriticalSection156{157#ifdef __WXMSW__158protected:159 CRITICAL_SECTION cs;160public:161 explicit CCriticalSection() { InitializeCriticalSection(&cs); }162 ~CCriticalSection() { DeleteCriticalSection(&cs); }163 void Enter() { EnterCriticalSection(&cs); }164 void Leave() { LeaveCriticalSection(&cs); }165 bool TryEnter() { return TryEnterCriticalSection(&cs); }166#else167protected:168 wxMutex mutex;169public:170 explicit CCriticalSection() : mutex(wxMUTEX_RECURSIVE) { }171 ~CCriticalSection() { }172 void Enter() { mutex.Lock(); }173 void Leave() { mutex.Unlock(); }174 bool TryEnter() { return mutex.TryLock() == wxMUTEX_NO_ERROR; }175#endif176public:177 const char* pszFile;178 int nLine;179};180181// Automatically leave critical section when leaving block, needed for exception safety182class CCriticalBlock183{184protected:185 CCriticalSection* pcs;186public:187 CCriticalBlock(CCriticalSection& csIn) { pcs = &csIn; pcs->Enter(); }188 ~CCriticalBlock() { pcs->Leave(); }189};190191// WARNING: This will catch continue and break!192// break is caught with an assertion, but there's no way to detect continue.193// I'd rather be careful than suffer the other more error prone syntax.194// The compiler will optimise away all this loop junk.195#define CRITICAL_BLOCK(cs) \196 for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by CRITICAL_BLOCK!", !fcriticalblockonce)), fcriticalblockonce=false) \197 for (CCriticalBlock criticalblock(cs); fcriticalblockonce && (cs.pszFile=__FILE__, cs.nLine=__LINE__, true); fcriticalblockonce=false, cs.pszFile=NULL, cs.nLine=0)198199class CTryCriticalBlock200{201protected:202 CCriticalSection* pcs;203public:204 CTryCriticalBlock(CCriticalSection& csIn) { pcs = (csIn.TryEnter() ? &csIn : NULL); }205 ~CTryCriticalBlock() { if (pcs) pcs->Leave(); }206 bool Entered() { return pcs != NULL; }207};208209#define TRY_CRITICAL_BLOCK(cs) \210 for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by TRY_CRITICAL_BLOCK!", !fcriticalblockonce)), fcriticalblockonce=false) \211 for (CTryCriticalBlock criticalblock(cs); fcriticalblockonce && (fcriticalblockonce = criticalblock.Entered()) && (cs.pszFile=__FILE__, cs.nLine=__LINE__, true); fcriticalblockonce=false, cs.pszFile=NULL, cs.nLine=0)212213214215216217218219220221222inline int OutputDebugStringF(const char* pszFormat, ...)223{224 int ret = 0;225#ifdef __WXDEBUG__226 if (!fPrintToConsole)227 {228 // print to debug.log229 char pszFile[MAX_PATH+100];230 GetDataDir(pszFile);231 strlcat(pszFile, "/debug.log", sizeof(pszFile));232 FILE* fileout = fopen(pszFile, "a");233 if (fileout)234 {235 //// Debug print useful for profiling236 //fprintf(fileout, " %"PRI64d" ", wxGetLocalTimeMillis().GetValue());237 va_list arg_ptr;238 va_start(arg_ptr, pszFormat);239 ret = vfprintf(fileout, pszFormat, arg_ptr);240 va_end(arg_ptr);241 fclose(fileout);242 }243 }244245#ifdef __WXMSW__246 if (fPrintToDebugger)247 {248 // accumulate a line at a time249 static CCriticalSection cs_OutputDebugStringF;250 CRITICAL_BLOCK(cs_OutputDebugStringF)251 {252 static char pszBuffer[50000];253 static char* pend;254 if (pend == NULL)255 pend = pszBuffer;256 va_list arg_ptr;257 va_start(arg_ptr, pszFormat);258 int limit = END(pszBuffer) - pend - 2;259 int ret = _vsnprintf(pend, limit, pszFormat, arg_ptr);260 va_end(arg_ptr);261 if (ret < 0 || ret >= limit)262 {263 pend = END(pszBuffer) - 2;264 *pend++ = '\n';265 }266 else267 pend += ret;268 *pend = '\0';269 char* p1 = pszBuffer;270 char* p2;271 while (p2 = strchr(p1, '\n'))272 {273 p2++;274 char c = *p2;275 *p2 = '\0';276 OutputDebugString(p1);277 *p2 = c;278 p1 = p2;279 }280 if (p1 != pszBuffer)281 memmove(pszBuffer, p1, pend - p1 + 1);282 pend -= (p1 - pszBuffer);283 }284 }285#endif286#endif287288 if (fPrintToConsole)289 {290 // print to console291 va_list arg_ptr;292 va_start(arg_ptr, pszFormat);293 ret = vprintf(pszFormat, arg_ptr);294 va_end(arg_ptr);295 }296 return ret;297}298299300301302303304305306307308inline string i64tostr(int64 n)309{310 return strprintf("%"PRI64d, n);311}312313inline string itostr(int n)314{315 return strprintf("%d", n);316}317318inline int64 atoi64(const char* psz)319{320#ifdef _MSC_VER321 return _atoi64(psz);322#else323 return strtoll(psz, NULL, 10);324#endif325}326327inline int64 atoi64(const string& str)328{329#ifdef _MSC_VER330 return _atoi64(str.c_str());331#else332 return strtoll(str.c_str(), NULL, 10);333#endif334}335336inline int atoi(const string& str)337{338 return atoi(str.c_str());339}340341inline int roundint(double d)342{343 return (int)(d > 0 ? d + 0.5 : d - 0.5);344}345346template<typename T>347string HexStr(const T itbegin, const T itend, bool fSpaces=true)348{349 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];350 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);351 string str;352 for (const unsigned char* p = pbegin; p != pend; p++)353 str += strprintf((fSpaces && p != pend-1 ? "%02x " : "%02x"), *p);354 return str;355}356357inline string HexStr(vector<unsigned char> vch, bool fSpaces=true)358{359 return HexStr(vch.begin(), vch.end(), fSpaces);360}361362template<typename T>363string HexNumStr(const T itbegin, const T itend, bool f0x=true)364{365 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];366 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);367 string str = (f0x ? "0x" : "");368 for (const unsigned char* p = pend-1; p >= pbegin; p--)369 str += strprintf("%02X", *p);370 return str;371}372373template<typename T>374void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)375{376 printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());377}378379inline void PrintHex(vector<unsigned char> vch, const char* pszFormat="%s", bool fSpaces=true)380{381 printf(pszFormat, HexStr(vch, fSpaces).c_str());382}383384inline int64 PerformanceCounter()385{386 int64 nCounter = 0;387#ifdef __WXMSW__388 QueryPerformanceCounter((LARGE_INTEGER*)&nCounter);389#else390 timeval t;391 gettimeofday(&t, NULL);392 nCounter = t.tv_sec * 1000000 + t.tv_usec;393#endif394 return nCounter;395}396397inline int64 GetTimeMillis()398{399 return wxGetLocalTimeMillis().GetValue();400}401402inline string DateTimeStrFormat(const char* pszFormat, int64 nTime)403{404 time_t n = nTime;405 struct tm* ptmTime = gmtime(&n);406 char pszTime[200];407 strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime);408 return pszTime;409}410411412413414415416417418inline void heapchk()419{420#ifdef __WXMSW__421 if (_heapchk() != _HEAPOK)422 DebugBreak();423#endif424}425426// Randomize the stack to help protect against buffer overrun exploits427#define IMPLEMENT_RANDOMIZE_STACK(ThreadFn) \428 { \429 static char nLoops; \430 if (nLoops <= 0) \431 nLoops = GetRand(20) + 1; \432 if (nLoops-- > 1) \433 { \434 ThreadFn; \435 return; \436 } \437 }438439#define CATCH_PRINT_EXCEPTION(pszFn) \440 catch (std::exception& e) { \441 PrintException(&e, (pszFn)); \442 } catch (...) { \443 PrintException(NULL, (pszFn)); \444 }445446447448449450451452453454455template<typename T1>456inline uint256 Hash(const T1 pbegin, const T1 pend)457{458 uint256 hash1;459 SHA256((unsigned char*)&pbegin[0], (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);460 uint256 hash2;461 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);462 return hash2;463}464465template<typename T1, typename T2>466inline uint256 Hash(const T1 p1begin, const T1 p1end,467 const T2 p2begin, const T2 p2end)468{469 uint256 hash1;470 SHA256_CTX ctx;471 SHA256_Init(&ctx);472 SHA256_Update(&ctx, (unsigned char*)&p1begin[0], (p1end - p1begin) * sizeof(p1begin[0]));473 SHA256_Update(&ctx, (unsigned char*)&p2begin[0], (p2end - p2begin) * sizeof(p2begin[0]));474 SHA256_Final((unsigned char*)&hash1, &ctx);475 uint256 hash2;476 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);477 return hash2;478}479480template<typename T1, typename T2, typename T3>481inline uint256 Hash(const T1 p1begin, const T1 p1end,482 const T2 p2begin, const T2 p2end,483 const T3 p3begin, const T3 p3end)484{485 uint256 hash1;486 SHA256_CTX ctx;487 SHA256_Init(&ctx);488 SHA256_Update(&ctx, (unsigned char*)&p1begin[0], (p1end - p1begin) * sizeof(p1begin[0]));489 SHA256_Update(&ctx, (unsigned char*)&p2begin[0], (p2end - p2begin) * sizeof(p2begin[0]));490 SHA256_Update(&ctx, (unsigned char*)&p3begin[0], (p3end - p3begin) * sizeof(p3begin[0]));491 SHA256_Final((unsigned char*)&hash1, &ctx);492 uint256 hash2;493 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);494 return hash2;495}496497template<typename T>498uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=VERSION)499{500 // Most of the time is spent allocating and deallocating CDataStream's501 // buffer. If this ever needs to be optimized further, make a CStaticStream502 // class with its buffer on the stack.503 CDataStream ss(nType, nVersion);504 ss.reserve(10000);505 ss << obj;506 return Hash(ss.begin(), ss.end());507}508509inline uint160 Hash160(const vector<unsigned char>& vch)510{511 uint256 hash1;512 SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);513 uint160 hash2;514 RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);515 return hash2;516}517518519520521522523524525526527528// Note: It turns out we might have been able to use boost::thread529// by using TerminateThread(boost::thread.native_handle(), 0);530#ifdef __WXMSW__531typedef HANDLE pthread_t;532533inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)534{535 DWORD nUnused = 0;536 HANDLE hthread =537 CreateThread(538 NULL, // default security539 0, // inherit stack size from parent540 (LPTHREAD_START_ROUTINE)pfn, // function pointer541 parg, // argument542 0, // creation option, start immediately543 &nUnused); // thread identifier544 if (hthread == NULL)545 {546 printf("Error: CreateThread() returned %d\n", GetLastError());547 return (pthread_t)0;548 }549 if (!fWantHandle)550 {551 CloseHandle(hthread);552 return (pthread_t)-1;553 }554 return hthread;555}556557inline void SetThreadPriority(int nPriority)558{559 SetThreadPriority(GetCurrentThread(), nPriority);560}561#else562inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)563{564 pthread_t hthread = 0;565 int ret = pthread_create(&hthread, NULL, (void*(*)(void*))pfn, parg);566 if (ret != 0)567 {568 printf("Error: pthread_create() returned %d\n", ret);569 return (pthread_t)0;570 }571 if (!fWantHandle)572 return (pthread_t)-1;573 return hthread;574}575576#define THREAD_PRIORITY_LOWEST PRIO_MIN577#define THREAD_PRIORITY_BELOW_NORMAL 2578#define THREAD_PRIORITY_NORMAL 0579#define THREAD_PRIORITY_ABOVE_NORMAL 0580581inline void SetThreadPriority(int nPriority)582{583 // threads are processes on linux, so PRIO_PROCESS affects just the one thread584 setpriority(PRIO_PROCESS, getpid(), nPriority);585}586587inline bool TerminateThread(pthread_t hthread, unsigned int nExitCode)588{589 return (pthread_cancel(hthread) == 0);590}591592inline void ExitThread(unsigned int nExitCode)593{594 pthread_exit((void*)nExitCode);595}596#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.
