1 // Copyright (c) 2009-2010 Satoshi Nakamoto
\r
2 // Distributed under the MIT/X11 software license, see the accompanying
\r
3 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
\r
6 #if defined(_MSC_VER) || defined(__BORLANDC__)
\r
7 typedef __int64 int64;
\r
8 typedef unsigned __int64 uint64;
\r
10 typedef long long int64;
\r
11 typedef unsigned long long uint64;
\r
13 #if defined(_MSC_VER) && _MSC_VER < 1300
\r
14 #define for if (false) ; else for
\r
17 #define __forceinline inline
\r
20 #define foreach BOOST_FOREACH
\r
21 #define loop for (;;)
\r
22 #define BEGIN(a) ((char*)&(a))
\r
23 #define END(a) ((char*)&((&(a))[1]))
\r
24 #define UBEGIN(a) ((unsigned char*)&(a))
\r
25 #define UEND(a) ((unsigned char*)&((&(a))[1]))
\r
26 #define ARRAYLEN(array) (sizeof(array)/sizeof((array)[0]))
\r
27 #define printf OutputDebugStringF
\r
32 #define snprintf my_snprintf
\r
35 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MSVCRT__)
\r
36 #define PRI64d "I64d"
\r
37 #define PRI64u "I64u"
\r
38 #define PRI64x "I64x"
\r
40 #define PRI64d "lld"
\r
41 #define PRI64u "llu"
\r
42 #define PRI64x "llx"
\r
46 // This is needed because the foreach macro can't get over the comma in pair<t1, t2>
\r
47 #define PAIRTYPE(t1, t2) pair<t1, t2>
\r
49 // Used to bypass the rule against non-const reference to temporary
\r
50 // where it makes sense with wrappers such as CFlatData or CTxDB
\r
51 template<typename T>
\r
52 inline T& REF(const T& val)
\r
57 // Align by increasing pointer, must have extra space at end of buffer
\r
58 template <size_t nBytes, typename T>
\r
67 u.n = (u.n + (nBytes-1)) & ~(nBytes-1);
\r
72 #define MSG_NOSIGNAL 0
\r
73 #define MSG_DONTWAIT 0
\r
75 #define UINT64_MAX _UI64_MAX
\r
76 #define INT64_MAX _I64_MAX
\r
77 #define INT64_MIN _I64_MIN
\r
80 #define S_IRUSR 0400
\r
81 #define S_IWUSR 0200
\r
83 #define unlink _unlink
\r
84 typedef int socklen_t;
\r
86 #define WSAGetLastError() errno
\r
87 #define WSAEWOULDBLOCK EWOULDBLOCK
\r
88 #define WSAEMSGSIZE EMSGSIZE
\r
89 #define WSAEINTR EINTR
\r
90 #define WSAEINPROGRESS EINPROGRESS
\r
91 #define WSAEADDRINUSE EADDRINUSE
\r
92 #define WSAENOTSOCK EBADF
\r
93 #define INVALID_SOCKET (SOCKET)(~0)
\r
94 #define SOCKET_ERROR -1
\r
95 typedef u_int SOCKET;
\r
96 #define _vsnprintf(a,b,c,d) vsnprintf(a,b,c,d)
\r
97 #define strlwr(psz) to_lower(psz)
\r
98 #define _strlwr(psz) to_lower(psz)
\r
99 #define MAX_PATH 1024
\r
100 #define Beep(n1,n2) (0)
\r
101 inline void Sleep(int64 n)
\r
103 boost::thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(n));
\r
107 inline int myclosesocket(SOCKET& hSocket)
\r
109 if (hSocket == INVALID_SOCKET)
\r
110 return WSAENOTSOCK;
\r
112 int ret = closesocket(hSocket);
\r
114 int ret = close(hSocket);
\r
116 hSocket = INVALID_SOCKET;
\r
119 #define closesocket(s) myclosesocket(s)
\r
122 inline const char* _(const char* psz)
\r
137 extern map<string, string> mapArgs;
\r
138 extern map<string, vector<string> > mapMultiArgs;
\r
139 extern bool fDebug;
\r
140 extern bool fPrintToConsole;
\r
141 extern bool fPrintToDebugger;
\r
142 extern char pszSetDataDir[MAX_PATH];
\r
143 extern bool fShutdown;
\r
144 extern bool fDaemon;
\r
145 extern bool fCommandLine;
\r
147 void RandAddSeed();
\r
148 void RandAddSeedPerfmon();
\r
149 int OutputDebugStringF(const char* pszFormat, ...);
\r
150 int my_snprintf(char* buffer, size_t limit, const char* format, ...);
\r
151 string strprintf(const char* format, ...);
\r
152 bool error(const char* format, ...);
\r
153 void PrintException(std::exception* pex, const char* pszThread);
\r
154 void LogException(std::exception* pex, const char* pszThread);
\r
155 void ParseString(const string& str, char c, vector<string>& v);
\r
156 string FormatMoney(int64 n, bool fPlus=false);
\r
157 bool ParseMoney(const string& str, int64& nRet);
\r
158 bool ParseMoney(const char* pszIn, int64& nRet);
\r
159 vector<unsigned char> ParseHex(const char* psz);
\r
160 vector<unsigned char> ParseHex(const std::string& str);
\r
161 void ParseParameters(int argc, char* argv[]);
\r
162 const char* wxGetTranslation(const char* psz);
\r
163 int GetFilesize(FILE* file);
\r
164 void GetDataDir(char* pszDirRet);
\r
165 string GetConfigFile();
\r
166 void ReadConfigFile(map<string, string>& mapSettingsRet, map<string, vector<string> >& mapMultiSettingsRet);
\r
168 string MyGetSpecialFolderPath(int nFolder, bool fCreate);
\r
170 string GetDefaultDataDir();
\r
171 string GetDataDir();
\r
172 void ShrinkDebugFile();
\r
173 uint64 GetRand(uint64 nMax);
\r
175 int64 GetAdjustedTime();
\r
176 void AddTimeData(unsigned int ip, int64 nTime);
\r
190 // Wrapper to automatically initialize critical sections
\r
191 class CCriticalSection
\r
195 CRITICAL_SECTION cs;
\r
197 explicit CCriticalSection() { InitializeCriticalSection(&cs); }
\r
198 ~CCriticalSection() { DeleteCriticalSection(&cs); }
\r
199 void Enter() { EnterCriticalSection(&cs); }
\r
200 void Leave() { LeaveCriticalSection(&cs); }
\r
201 bool TryEnter() { return TryEnterCriticalSection(&cs); }
\r
204 boost::interprocess::interprocess_recursive_mutex mutex;
\r
206 explicit CCriticalSection() { }
\r
207 ~CCriticalSection() { }
\r
208 void Enter() { mutex.lock(); }
\r
209 void Leave() { mutex.unlock(); }
\r
210 bool TryEnter() { return mutex.try_lock(); }
\r
213 const char* pszFile;
\r
217 // Automatically leave critical section when leaving block, needed for exception safety
\r
218 class CCriticalBlock
\r
221 CCriticalSection* pcs;
\r
223 CCriticalBlock(CCriticalSection& csIn) { pcs = &csIn; pcs->Enter(); }
\r
224 ~CCriticalBlock() { pcs->Leave(); }
\r
227 // WARNING: This will catch continue and break!
\r
228 // break is caught with an assertion, but there's no way to detect continue.
\r
229 // I'd rather be careful than suffer the other more error prone syntax.
\r
230 // The compiler will optimise away all this loop junk.
\r
231 #define CRITICAL_BLOCK(cs) \
\r
232 for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by CRITICAL_BLOCK!", !fcriticalblockonce)), fcriticalblockonce=false) \
\r
233 for (CCriticalBlock criticalblock(cs); fcriticalblockonce && (cs.pszFile=__FILE__, cs.nLine=__LINE__, true); fcriticalblockonce=false, cs.pszFile=NULL, cs.nLine=0)
\r
235 class CTryCriticalBlock
\r
238 CCriticalSection* pcs;
\r
240 CTryCriticalBlock(CCriticalSection& csIn) { pcs = (csIn.TryEnter() ? &csIn : NULL); }
\r
241 ~CTryCriticalBlock() { if (pcs) pcs->Leave(); }
\r
242 bool Entered() { return pcs != NULL; }
\r
245 #define TRY_CRITICAL_BLOCK(cs) \
\r
246 for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by TRY_CRITICAL_BLOCK!", !fcriticalblockonce)), fcriticalblockonce=false) \
\r
247 for (CTryCriticalBlock criticalblock(cs); fcriticalblockonce && (fcriticalblockonce = criticalblock.Entered()) && (cs.pszFile=__FILE__, cs.nLine=__LINE__, true); fcriticalblockonce=false, cs.pszFile=NULL, cs.nLine=0)
\r
258 inline string i64tostr(int64 n)
\r
260 return strprintf("%"PRI64d, n);
\r
263 inline string itostr(int n)
\r
265 return strprintf("%d", n);
\r
268 inline int64 atoi64(const char* psz)
\r
271 return _atoi64(psz);
\r
273 return strtoll(psz, NULL, 10);
\r
277 inline int64 atoi64(const string& str)
\r
280 return _atoi64(str.c_str());
\r
282 return strtoll(str.c_str(), NULL, 10);
\r
286 inline int atoi(const string& str)
\r
288 return atoi(str.c_str());
\r
291 inline int roundint(double d)
\r
293 return (int)(d > 0 ? d + 0.5 : d - 0.5);
\r
296 inline int64 roundint64(double d)
\r
298 return (int64)(d > 0 ? d + 0.5 : d - 0.5);
\r
301 template<typename T>
\r
302 string HexStr(const T itbegin, const T itend, bool fSpaces=true)
\r
304 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
\r
305 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
\r
307 for (const unsigned char* p = pbegin; p != pend; p++)
\r
308 str += strprintf((fSpaces && p != pend-1 ? "%02x " : "%02x"), *p);
\r
312 inline string HexStr(vector<unsigned char> vch, bool fSpaces=true)
\r
314 return HexStr(vch.begin(), vch.end(), fSpaces);
\r
317 template<typename T>
\r
318 string HexNumStr(const T itbegin, const T itend, bool f0x=true)
\r
320 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
\r
321 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
\r
322 string str = (f0x ? "0x" : "");
\r
323 for (const unsigned char* p = pend-1; p >= pbegin; p--)
\r
324 str += strprintf("%02X", *p);
\r
328 template<typename T>
\r
329 void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)
\r
331 printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());
\r
334 inline void PrintHex(vector<unsigned char> vch, const char* pszFormat="%s", bool fSpaces=true)
\r
336 printf(pszFormat, HexStr(vch, fSpaces).c_str());
\r
339 inline int64 PerformanceCounter()
\r
341 int64 nCounter = 0;
\r
343 QueryPerformanceCounter((LARGE_INTEGER*)&nCounter);
\r
346 gettimeofday(&t, NULL);
\r
347 nCounter = t.tv_sec * 1000000 + t.tv_usec;
\r
352 inline int64 GetTimeMillis()
\r
354 return (posix_time::ptime(posix_time::microsec_clock::universal_time()) -
\r
355 posix_time::ptime(gregorian::date(1970,1,1))).total_milliseconds();
\r
358 inline string DateTimeStrFormat(const char* pszFormat, int64 nTime)
\r
361 struct tm* ptmTime = gmtime(&n);
\r
363 strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime);
\r
367 template<typename T>
\r
368 void skipspaces(T& it)
\r
370 while (isspace(*it))
\r
374 inline bool IsSwitchChar(char c)
\r
377 return c == '-' || c == '/';
\r
392 inline void heapchk()
\r
396 //if (_heapchk() != _HEAPOK)
\r
401 // Randomize the stack to help protect against buffer overrun exploits
\r
402 #define IMPLEMENT_RANDOMIZE_STACK(ThreadFn) \
\r
404 static char nLoops; \
\r
406 nLoops = GetRand(20) + 1; \
\r
407 if (nLoops-- > 1) \
\r
414 #define CATCH_PRINT_EXCEPTION(pszFn) \
\r
415 catch (std::exception& e) { \
\r
416 PrintException(&e, (pszFn)); \
\r
418 PrintException(NULL, (pszFn)); \
\r
430 template<typename T1>
\r
431 inline uint256 Hash(const T1 pbegin, const T1 pend)
\r
433 static unsigned char pblank[1];
\r
435 SHA256((pbegin == pend ? pblank : (unsigned char*)&pbegin[0]), (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);
\r
437 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
\r
441 template<typename T1, typename T2>
\r
442 inline uint256 Hash(const T1 p1begin, const T1 p1end,
\r
443 const T2 p2begin, const T2 p2end)
\r
445 static unsigned char pblank[1];
\r
449 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
\r
450 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
\r
451 SHA256_Final((unsigned char*)&hash1, &ctx);
\r
453 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
\r
457 template<typename T1, typename T2, typename T3>
\r
458 inline uint256 Hash(const T1 p1begin, const T1 p1end,
\r
459 const T2 p2begin, const T2 p2end,
\r
460 const T3 p3begin, const T3 p3end)
\r
462 static unsigned char pblank[1];
\r
466 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
\r
467 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
\r
468 SHA256_Update(&ctx, (p3begin == p3end ? pblank : (unsigned char*)&p3begin[0]), (p3end - p3begin) * sizeof(p3begin[0]));
\r
469 SHA256_Final((unsigned char*)&hash1, &ctx);
\r
471 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
\r
475 template<typename T>
\r
476 uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=VERSION)
\r
478 // Most of the time is spent allocating and deallocating CDataStream's
\r
479 // buffer. If this ever needs to be optimized further, make a CStaticStream
\r
480 // class with its buffer on the stack.
\r
481 CDataStream ss(nType, nVersion);
\r
484 return Hash(ss.begin(), ss.end());
\r
487 inline uint160 Hash160(const vector<unsigned char>& vch)
\r
490 SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);
\r
492 RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
\r
506 // Note: It turns out we might have been able to use boost::thread
\r
507 // by using TerminateThread(boost::thread.native_handle(), 0);
\r
509 typedef HANDLE pthread_t;
\r
511 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
\r
516 NULL, // default security
\r
517 0, // inherit stack size from parent
\r
518 (LPTHREAD_START_ROUTINE)pfn, // function pointer
\r
520 0, // creation option, start immediately
\r
521 &nUnused); // thread identifier
\r
522 if (hthread == NULL)
\r
524 printf("Error: CreateThread() returned %d\n", GetLastError());
\r
525 return (pthread_t)0;
\r
529 CloseHandle(hthread);
\r
530 return (pthread_t)-1;
\r
535 inline void SetThreadPriority(int nPriority)
\r
537 SetThreadPriority(GetCurrentThread(), nPriority);
\r
540 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
\r
542 pthread_t hthread = 0;
\r
543 int ret = pthread_create(&hthread, NULL, (void*(*)(void*))pfn, parg);
\r
546 printf("Error: pthread_create() returned %d\n", ret);
\r
547 return (pthread_t)0;
\r
550 return (pthread_t)-1;
\r
554 #define THREAD_PRIORITY_LOWEST PRIO_MAX
\r
555 #define THREAD_PRIORITY_BELOW_NORMAL 2
\r
556 #define THREAD_PRIORITY_NORMAL 0
\r
557 #define THREAD_PRIORITY_ABOVE_NORMAL 0
\r
559 inline void SetThreadPriority(int nPriority)
\r
561 // It's unclear if it's even possible to change thread priorities on Linux,
\r
562 // but we really and truly need it for the generation threads.
\r
564 setpriority(PRIO_THREAD, 0, nPriority);
\r
566 setpriority(PRIO_PROCESS, 0, nPriority);
\r
570 inline bool TerminateThread(pthread_t hthread, unsigned int nExitCode)
\r
572 return (pthread_cancel(hthread) == 0);
\r
575 inline void ExitThread(unsigned int nExitCode)
\r
577 pthread_exit((void*)nExitCode);
\r