Bitcoin v0.1.5 · 2009-02-04
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#endif1617#ifndef _MSC_VER18#define __forceinline inline19#endif2021#define foreach BOOST_FOREACH22#define loop for (;;)23#define BEGIN(a) ((char*)&(a))24#define END(a) ((char*)&((&(a))[1]))25#define UBEGIN(a) ((unsigned char*)&(a))26#define UEND(a) ((unsigned char*)&((&(a))[1]))27#define ARRAYLEN(array) (sizeof(array)/sizeof((array)[0]))2829#ifdef _WINDOWS30#define printf OutputDebugStringF31#endif3233#ifdef snprintf34#undef snprintf35#endif36#define snprintf my_snprintf3738#ifndef PRId6439#if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MSVCRT__)40#define PRId64 "I64d"41#define PRIu64 "I64u"42#define PRIx64 "I64x"43#else44#define PRId64 "lld"45#define PRIu64 "llu"46#define PRIx64 "llx"47#endif48#endif4950// This is needed because the foreach macro can't get over the comma in pair<t1, t2>51#define PAIRTYPE(t1, t2) pair<t1, t2>5253// Used to bypass the rule against non-const reference to temporary54// where it makes sense with wrappers such as CFlatData or CTxDB55template<typename T>56inline T& REF(const T& val)57{58 return (T&)val;59}60616263646566676869extern bool fDebug;7071void RandAddSeed(bool fPerfmon=false);72int my_snprintf(char* buffer, size_t limit, const char* format, ...);73string strprintf(const char* format, ...);74bool error(const char* format, ...);75void PrintException(std::exception* pex, const char* pszThread);76void ParseString(const string& str, char c, vector<string>& v);77string FormatMoney(int64 n, bool fPlus=false);78bool ParseMoney(const char* pszIn, int64& nRet);79bool FileExists(const char* psz);80int GetFilesize(FILE* file);81uint64 GetRand(uint64 nMax);82int64 GetTime();83int64 GetAdjustedTime();84void AddTimeData(unsigned int ip, int64 nTime);85868788899091929394959697// Wrapper to automatically initialize critical section98// Could use wxCriticalSection for portability, but it doesn't support TryEnterCriticalSection99class CCriticalSection100{101protected:102 CRITICAL_SECTION cs;103public:104 char* pszFile;105 int nLine;106 explicit CCriticalSection() { InitializeCriticalSection(&cs); }107 ~CCriticalSection() { DeleteCriticalSection(&cs); }108 void Enter() { EnterCriticalSection(&cs); }109 void Leave() { LeaveCriticalSection(&cs); }110 bool TryEnter() { return TryEnterCriticalSection(&cs); }111 CRITICAL_SECTION* operator&() { return &cs; }112};113114// Automatically leave critical section when leaving block, needed for exception safety115class CCriticalBlock116{117protected:118 CRITICAL_SECTION* pcs;119public:120 CCriticalBlock(CRITICAL_SECTION& csIn) { pcs = &csIn; EnterCriticalSection(pcs); }121 CCriticalBlock(CCriticalSection& csIn) { pcs = &csIn; EnterCriticalSection(pcs); }122 ~CCriticalBlock() { LeaveCriticalSection(pcs); }123};124125// WARNING: This will catch continue and break!126// break is caught with an assertion, but there's no way to detect continue.127// I'd rather be careful than suffer the other more error prone syntax.128// The compiler will optimise away all this loop junk.129#define CRITICAL_BLOCK(cs) \130 for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by CRITICAL_BLOCK!", !fcriticalblockonce)), fcriticalblockonce=false) \131 for (CCriticalBlock criticalblock(cs); fcriticalblockonce && (cs.pszFile=__FILE__, cs.nLine=__LINE__, true); fcriticalblockonce=false, cs.pszFile=NULL, cs.nLine=0)132133class CTryCriticalBlock134{135protected:136 CRITICAL_SECTION* pcs;137public:138 CTryCriticalBlock(CRITICAL_SECTION& csIn) { pcs = (TryEnterCriticalSection(&csIn) ? &csIn : NULL); }139 CTryCriticalBlock(CCriticalSection& csIn) { pcs = (TryEnterCriticalSection(&csIn) ? &csIn : NULL); }140 ~CTryCriticalBlock() { if (pcs) LeaveCriticalSection(pcs); }141 bool Entered() { return pcs != NULL; }142};143144#define TRY_CRITICAL_BLOCK(cs) \145 for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by TRY_CRITICAL_BLOCK!", !fcriticalblockonce)), fcriticalblockonce=false) \146 for (CTryCriticalBlock criticalblock(cs); fcriticalblockonce && (fcriticalblockonce = criticalblock.Entered()) && (cs.pszFile=__FILE__, cs.nLine=__LINE__, true); fcriticalblockonce=false, cs.pszFile=NULL, cs.nLine=0)147148149150151152153154155156157158159inline string i64tostr(int64 n)160{161 return strprintf("%"PRId64, n);162}163164inline string itostr(int n)165{166 return strprintf("%d", n);167}168169inline int64 atoi64(const char* psz)170{171#ifdef _MSC_VER172 return _atoi64(psz);173#else174 return strtoll(psz, NULL, 10);175#endif176}177178inline int64 atoi64(const string& str)179{180#ifdef _MSC_VER181 return _atoi64(str.c_str());182#else183 return strtoll(str.c_str(), NULL, 10);184#endif185}186187inline int atoi(const string& str)188{189 return atoi(str.c_str());190}191192inline int roundint(double d)193{194 return (int)(d > 0 ? d + 0.5 : d - 0.5);195}196197template<typename T>198string HexStr(const T itbegin, const T itend, bool fSpaces=true)199{200 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];201 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);202 string str;203 for (const unsigned char* p = pbegin; p != pend; p++)204 str += strprintf((fSpaces && p != pend-1 ? "%02x " : "%02x"), *p);205 return str;206}207208template<typename T>209string HexNumStr(const T itbegin, const T itend, bool f0x=true)210{211 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];212 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);213 string str = (f0x ? "0x" : "");214 for (const unsigned char* p = pend-1; p >= pbegin; p--)215 str += strprintf("%02X", *p);216 return str;217}218219template<typename T>220void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)221{222 printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());223}224225226227228229230231232inline int OutputDebugStringF(const char* pszFormat, ...)233{234#ifdef __WXDEBUG__235 // log file236 FILE* fileout = fopen("debug.log", "a");237 if (fileout)238 {239 va_list arg_ptr;240 va_start(arg_ptr, pszFormat);241 vfprintf(fileout, pszFormat, arg_ptr);242 va_end(arg_ptr);243 fclose(fileout);244 }245246 // accumulate a line at a time247 static CCriticalSection cs_OutputDebugStringF;248 CRITICAL_BLOCK(cs_OutputDebugStringF)249 {250 static char pszBuffer[50000];251 static char* pend;252 if (pend == NULL)253 pend = pszBuffer;254 va_list arg_ptr;255 va_start(arg_ptr, pszFormat);256 int limit = END(pszBuffer) - pend - 2;257 int ret = _vsnprintf(pend, limit, pszFormat, arg_ptr);258 va_end(arg_ptr);259 if (ret < 0 || ret >= limit)260 {261 pend = END(pszBuffer) - 2;262 *pend++ = '\n';263 }264 else265 pend += ret;266 *pend = '\0';267 char* p1 = pszBuffer;268 char* p2;269 while (p2 = strchr(p1, '\n'))270 {271 p2++;272 char c = *p2;273 *p2 = '\0';274 OutputDebugString(p1);275 *p2 = c;276 p1 = p2;277 }278 if (p1 != pszBuffer)279 memmove(pszBuffer, p1, pend - p1 + 1);280 pend -= (p1 - pszBuffer);281 return ret;282 }283#endif284285 if (!wxTheApp)286 {287 // print to console288 va_list arg_ptr;289 va_start(arg_ptr, pszFormat);290 vprintf(pszFormat, arg_ptr);291 va_end(arg_ptr);292 }293 return 0;294}295296297298299300301302303304inline void heapchk()305{306 if (_heapchk() != _HEAPOK)307 DebugBreak();308}309310// Randomize the stack to help protect against buffer overrun exploits311#define IMPLEMENT_RANDOMIZE_STACK(ThreadFn) \312 { \313 static char nLoops; \314 if (nLoops <= 0) \315 nLoops = GetRand(50) + 1; \316 if (nLoops-- > 1) \317 { \318 ThreadFn; \319 return; \320 } \321 }322323#define CATCH_PRINT_EXCEPTION(pszFn) \324 catch (std::exception& e) { \325 PrintException(&e, (pszFn)); \326 } catch (...) { \327 PrintException(NULL, (pszFn)); \328 }329330331332333334335336337338template<typename T1>339inline uint256 Hash(const T1 pbegin, const T1 pend)340{341 uint256 hash1;342 SHA256((unsigned char*)&pbegin[0], (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);343 uint256 hash2;344 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);345 return hash2;346}347348template<typename T1, typename T2>349inline uint256 Hash(const T1 p1begin, const T1 p1end,350 const T2 p2begin, const T2 p2end)351{352 uint256 hash1;353 SHA256_CTX ctx;354 SHA256_Init(&ctx);355 SHA256_Update(&ctx, (unsigned char*)&p1begin[0], (p1end - p1begin) * sizeof(p1begin[0]));356 SHA256_Update(&ctx, (unsigned char*)&p2begin[0], (p2end - p2begin) * sizeof(p2begin[0]));357 SHA256_Final((unsigned char*)&hash1, &ctx);358 uint256 hash2;359 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);360 return hash2;361}362363template<typename T1, typename T2, typename T3>364inline uint256 Hash(const T1 p1begin, const T1 p1end,365 const T2 p2begin, const T2 p2end,366 const T3 p3begin, const T3 p3end)367{368 uint256 hash1;369 SHA256_CTX ctx;370 SHA256_Init(&ctx);371 SHA256_Update(&ctx, (unsigned char*)&p1begin[0], (p1end - p1begin) * sizeof(p1begin[0]));372 SHA256_Update(&ctx, (unsigned char*)&p2begin[0], (p2end - p2begin) * sizeof(p2begin[0]));373 SHA256_Update(&ctx, (unsigned char*)&p3begin[0], (p3end - p3begin) * sizeof(p3begin[0]));374 SHA256_Final((unsigned char*)&hash1, &ctx);375 uint256 hash2;376 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);377 return hash2;378}379380template<typename T>381uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=VERSION)382{383 // Most of the time is spent allocating and deallocating CDataStream's384 // buffer. If this ever needs to be optimized further, make a CStaticStream385 // class with its buffer on the stack.386 CDataStream ss(nType, nVersion);387 ss.reserve(10000);388 ss << obj;389 return Hash(ss.begin(), ss.end());390}391392inline uint160 Hash160(const vector<unsigned char>& vch)393{394 uint256 hash1;395 SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);396 uint160 hash2;397 RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);398 return hash2;399}
Click a line number to link to it; use #L10-L20 for a range. "=" next to a version means the file is identical there.
