1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
6 #if defined(_MSC_VER) || defined(__BORLANDC__)
8 typedef unsigned __int64 uint64
;
10 typedef long long int64
;
11 typedef unsigned long long uint64
;
13 #if defined(_MSC_VER) && _MSC_VER < 1300
14 #define for if (false) ; else for
17 #define __forceinline inline
20 #define foreach BOOST_FOREACH
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 OutputDebugStringF
32 #define snprintf my_snprintf
35 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MSVCRT__)
46 // 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>
49 // Used to bypass the rule against non-const reference to temporary
50 // where it makes sense with wrappers such as CFlatData or CTxDB
52 inline T
& REF(const T
& val
)
57 // Align by increasing pointer, must have extra space at end of buffer
58 template <size_t nBytes
, typename T
>
67 u
.n
= (u
.n
+ (nBytes
-1)) & ~(nBytes
-1);
72 #define MSG_NOSIGNAL 0
73 #define MSG_DONTWAIT 0
75 #define UINT64_MAX _UI64_MAX
76 #define INT64_MAX _I64_MAX
77 #define INT64_MIN _I64_MIN
83 #define unlink _unlink
84 typedef int socklen_t
;
86 #define WSAGetLastError() errno
87 #define WSAEWOULDBLOCK EWOULDBLOCK
88 #define WSAEMSGSIZE EMSGSIZE
89 #define WSAEINTR EINTR
90 #define WSAEINPROGRESS EINPROGRESS
91 #define WSAEADDRINUSE EADDRINUSE
92 #define WSAENOTSOCK EBADF
93 #define INVALID_SOCKET (SOCKET)(~0)
94 #define SOCKET_ERROR -1
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)
100 #define Beep(n1,n2) (0)
101 inline void Sleep(int64 n
)
103 boost::thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(n
));
107 inline int myclosesocket(SOCKET
& hSocket
)
109 if (hSocket
== INVALID_SOCKET
)
112 int ret
= closesocket(hSocket
);
114 int ret
= close(hSocket
);
116 hSocket
= INVALID_SOCKET
;
119 #define closesocket(s) myclosesocket(s)
122 inline const char* _(const char* psz
)
137 extern map
<string
, string
> mapArgs
;
138 extern map
<string
, vector
<string
> > mapMultiArgs
;
140 extern bool fPrintToConsole
;
141 extern bool fPrintToDebugger
;
142 extern char pszSetDataDir
[MAX_PATH
];
143 extern bool fRequestShutdown
;
144 extern bool fShutdown
;
146 extern bool fCommandLine
;
147 extern string strMiscWarning
;
148 extern bool fTestNet
;
151 void RandAddSeedPerfmon();
152 int OutputDebugStringF(const char* pszFormat
, ...);
153 int my_snprintf(char* buffer
, size_t limit
, const char* format
, ...);
154 string
strprintf(const char* format
, ...);
155 bool error(const char* format
, ...);
156 void LogException(std::exception
* pex
, const char* pszThread
);
157 void PrintException(std::exception
* pex
, const char* pszThread
);
158 void PrintExceptionContinue(std::exception
* pex
, const char* pszThread
);
159 void ParseString(const string
& str
, char c
, vector
<string
>& v
);
160 string
FormatMoney(int64 n
, bool fPlus
=false);
161 bool ParseMoney(const string
& str
, int64
& nRet
);
162 bool ParseMoney(const char* pszIn
, int64
& nRet
);
163 vector
<unsigned char> ParseHex(const char* psz
);
164 vector
<unsigned char> ParseHex(const string
& str
);
165 void ParseParameters(int argc
, char* argv
[]);
166 const char* wxGetTranslation(const char* psz
);
167 bool WildcardMatch(const char* psz
, const char* mask
);
168 bool WildcardMatch(const string
& str
, const string
& mask
);
169 int GetFilesize(FILE* file
);
170 void GetDataDir(char* pszDirRet
);
171 string
GetConfigFile();
172 void ReadConfigFile(map
<string
, string
>& mapSettingsRet
, map
<string
, vector
<string
> >& mapMultiSettingsRet
);
174 string
MyGetSpecialFolderPath(int nFolder
, bool fCreate
);
176 string
GetDefaultDataDir();
178 void ShrinkDebugFile();
179 int GetRandInt(int nMax
);
180 uint64
GetRand(uint64 nMax
);
182 int64
GetAdjustedTime();
183 void AddTimeData(unsigned int ip
, int64 nTime
);
197 // Wrapper to automatically initialize critical sections
198 class CCriticalSection
204 explicit CCriticalSection() { InitializeCriticalSection(&cs
); }
205 ~CCriticalSection() { DeleteCriticalSection(&cs
); }
206 void Enter() { EnterCriticalSection(&cs
); }
207 void Leave() { LeaveCriticalSection(&cs
); }
208 bool TryEnter() { return TryEnterCriticalSection(&cs
); }
211 boost::interprocess::interprocess_recursive_mutex mutex
;
213 explicit CCriticalSection() { }
214 ~CCriticalSection() { }
215 void Enter() { mutex
.lock(); }
216 void Leave() { mutex
.unlock(); }
217 bool TryEnter() { return mutex
.try_lock(); }
224 // Automatically leave critical section when leaving block, needed for exception safety
228 CCriticalSection
* pcs
;
230 CCriticalBlock(CCriticalSection
& csIn
) { pcs
= &csIn
; pcs
->Enter(); }
231 ~CCriticalBlock() { pcs
->Leave(); }
234 // WARNING: This will catch continue and break!
235 // break is caught with an assertion, but there's no way to detect continue.
236 // I'd rather be careful than suffer the other more error prone syntax.
237 // The compiler will optimise away all this loop junk.
238 #define CRITICAL_BLOCK(cs) \
239 for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by CRITICAL_BLOCK!", !fcriticalblockonce)), fcriticalblockonce=false) \
240 for (CCriticalBlock criticalblock(cs); fcriticalblockonce && (cs.pszFile=__FILE__, cs.nLine=__LINE__, true); fcriticalblockonce=false, cs.pszFile=NULL, cs.nLine=0)
242 class CTryCriticalBlock
245 CCriticalSection
* pcs
;
247 CTryCriticalBlock(CCriticalSection
& csIn
) { pcs
= (csIn
.TryEnter() ? &csIn
: NULL
); }
248 ~CTryCriticalBlock() { if (pcs
) pcs
->Leave(); }
249 bool Entered() { return pcs
!= NULL
; }
252 #define TRY_CRITICAL_BLOCK(cs) \
253 for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by TRY_CRITICAL_BLOCK!", !fcriticalblockonce)), fcriticalblockonce=false) \
254 for (CTryCriticalBlock criticalblock(cs); fcriticalblockonce && (fcriticalblockonce = criticalblock.Entered()) && (cs.pszFile=__FILE__, cs.nLine=__LINE__, true); fcriticalblockonce=false, cs.pszFile=NULL, cs.nLine=0)
265 inline string
i64tostr(int64 n
)
267 return strprintf("%"PRI64d
, n
);
270 inline string
itostr(int n
)
272 return strprintf("%d", n
);
275 inline int64
atoi64(const char* psz
)
280 return strtoll(psz
, NULL
, 10);
284 inline int64
atoi64(const string
& str
)
287 return _atoi64(str
.c_str());
289 return strtoll(str
.c_str(), NULL
, 10);
293 inline int atoi(const string
& str
)
295 return atoi(str
.c_str());
298 inline int roundint(double d
)
300 return (int)(d
> 0 ? d
+ 0.5 : d
- 0.5);
303 inline int64
roundint64(double d
)
305 return (int64
)(d
> 0 ? d
+ 0.5 : d
- 0.5);
308 inline int64
abs64(int64 n
)
310 return (n
>= 0 ? n
: -n
);
314 string
HexStr(const T itbegin
, const T itend
, bool fSpaces
=false)
316 if (itbegin
== itend
)
318 const unsigned char* pbegin
= (const unsigned char*)&itbegin
[0];
319 const unsigned char* pend
= pbegin
+ (itend
- itbegin
) * sizeof(itbegin
[0]);
321 str
.reserve((pend
-pbegin
) * (fSpaces
? 3 : 2));
322 for (const unsigned char* p
= pbegin
; p
!= pend
; p
++)
323 str
+= strprintf((fSpaces
&& p
!= pend
-1 ? "%02x " : "%02x"), *p
);
327 inline string
HexStr(const vector
<unsigned char>& vch
, bool fSpaces
=false)
329 return HexStr(vch
.begin(), vch
.end(), fSpaces
);
333 string
HexNumStr(const T itbegin
, const T itend
, bool f0x
=true)
335 if (itbegin
== itend
)
337 const unsigned char* pbegin
= (const unsigned char*)&itbegin
[0];
338 const unsigned char* pend
= pbegin
+ (itend
- itbegin
) * sizeof(itbegin
[0]);
339 string str
= (f0x
? "0x" : "");
340 str
.reserve(str
.size() + (pend
-pbegin
) * 2);
341 for (const unsigned char* p
= pend
-1; p
>= pbegin
; p
--)
342 str
+= strprintf("%02x", *p
);
346 inline string
HexNumStr(const vector
<unsigned char>& vch
, bool f0x
=true)
348 return HexNumStr(vch
.begin(), vch
.end(), f0x
);
352 void PrintHex(const T pbegin
, const T pend
, const char* pszFormat
="%s", bool fSpaces
=true)
354 printf(pszFormat
, HexStr(pbegin
, pend
, fSpaces
).c_str());
357 inline void PrintHex(const vector
<unsigned char>& vch
, const char* pszFormat
="%s", bool fSpaces
=true)
359 printf(pszFormat
, HexStr(vch
, fSpaces
).c_str());
362 inline int64
GetPerformanceCounter()
366 QueryPerformanceCounter((LARGE_INTEGER
*)&nCounter
);
369 gettimeofday(&t
, NULL
);
370 nCounter
= t
.tv_sec
* 1000000 + t
.tv_usec
;
375 inline int64
GetTimeMillis()
377 return (posix_time::ptime(posix_time::microsec_clock::universal_time()) -
378 posix_time::ptime(gregorian::date(1970,1,1))).total_milliseconds();
381 inline string
DateTimeStrFormat(const char* pszFormat
, int64 nTime
)
384 struct tm
* ptmTime
= gmtime(&n
);
386 strftime(pszTime
, sizeof(pszTime
), pszFormat
, ptmTime
);
391 void skipspaces(T
& it
)
397 inline bool IsSwitchChar(char c
)
400 return c
== '-' || c
== '/';
406 inline string
GetArg(const string
& strArg
, const string
& strDefault
)
408 if (mapArgs
.count(strArg
))
409 return mapArgs
[strArg
];
413 inline int64
GetArg(const string
& strArg
, int64 nDefault
)
415 if (mapArgs
.count(strArg
))
416 return atoi64(mapArgs
[strArg
]);
420 inline string
FormatVersion(int nVersion
)
422 if (nVersion
%100 == 0)
423 return strprintf("%d.%d.%d", nVersion
/1000000, (nVersion
/10000)%100, (nVersion
/100)%100);
425 return strprintf("%d.%d.%d.%d", nVersion
/1000000, (nVersion
/10000)%100, (nVersion
/100)%100, nVersion
%100);
437 inline void heapchk()
441 //if (_heapchk() != _HEAPOK)
446 // Randomize the stack to help protect against buffer overrun exploits
447 #define IMPLEMENT_RANDOMIZE_STACK(ThreadFn) \
449 static char nLoops; \
451 nLoops = GetRand(20) + 1; \
459 #define CATCH_PRINT_EXCEPTION(pszFn) \
460 catch (std::exception& e) { \
461 PrintException(&e, (pszFn)); \
463 PrintException(NULL, (pszFn)); \
475 template<typename T1
>
476 inline uint256
Hash(const T1 pbegin
, const T1 pend
)
478 static unsigned char pblank
[1];
480 SHA256((pbegin
== pend
? pblank
: (unsigned char*)&pbegin
[0]), (pend
- pbegin
) * sizeof(pbegin
[0]), (unsigned char*)&hash1
);
482 SHA256((unsigned char*)&hash1
, sizeof(hash1
), (unsigned char*)&hash2
);
486 template<typename T1
, typename T2
>
487 inline uint256
Hash(const T1 p1begin
, const T1 p1end
,
488 const T2 p2begin
, const T2 p2end
)
490 static unsigned char pblank
[1];
494 SHA256_Update(&ctx
, (p1begin
== p1end
? pblank
: (unsigned char*)&p1begin
[0]), (p1end
- p1begin
) * sizeof(p1begin
[0]));
495 SHA256_Update(&ctx
, (p2begin
== p2end
? pblank
: (unsigned char*)&p2begin
[0]), (p2end
- p2begin
) * sizeof(p2begin
[0]));
496 SHA256_Final((unsigned char*)&hash1
, &ctx
);
498 SHA256((unsigned char*)&hash1
, sizeof(hash1
), (unsigned char*)&hash2
);
502 template<typename T1
, typename T2
, typename T3
>
503 inline uint256
Hash(const T1 p1begin
, const T1 p1end
,
504 const T2 p2begin
, const T2 p2end
,
505 const T3 p3begin
, const T3 p3end
)
507 static unsigned char pblank
[1];
511 SHA256_Update(&ctx
, (p1begin
== p1end
? pblank
: (unsigned char*)&p1begin
[0]), (p1end
- p1begin
) * sizeof(p1begin
[0]));
512 SHA256_Update(&ctx
, (p2begin
== p2end
? pblank
: (unsigned char*)&p2begin
[0]), (p2end
- p2begin
) * sizeof(p2begin
[0]));
513 SHA256_Update(&ctx
, (p3begin
== p3end
? pblank
: (unsigned char*)&p3begin
[0]), (p3end
- p3begin
) * sizeof(p3begin
[0]));
514 SHA256_Final((unsigned char*)&hash1
, &ctx
);
516 SHA256((unsigned char*)&hash1
, sizeof(hash1
), (unsigned char*)&hash2
);
521 uint256
SerializeHash(const T
& obj
, int nType
=SER_GETHASH
, int nVersion
=VERSION
)
523 // Most of the time is spent allocating and deallocating CDataStream's
524 // buffer. If this ever needs to be optimized further, make a CStaticStream
525 // class with its buffer on the stack.
526 CDataStream
ss(nType
, nVersion
);
529 return Hash(ss
.begin(), ss
.end());
532 inline uint160
Hash160(const vector
<unsigned char>& vch
)
535 SHA256(&vch
[0], vch
.size(), (unsigned char*)&hash1
);
537 RIPEMD160((unsigned char*)&hash1
, sizeof(hash1
), (unsigned char*)&hash2
);
551 // Note: It turns out we might have been able to use boost::thread
552 // by using TerminateThread(boost::thread.native_handle(), 0);
554 typedef HANDLE pthread_t
;
556 inline pthread_t
CreateThread(void(*pfn
)(void*), void* parg
, bool fWantHandle
=false)
561 NULL
, // default security
562 0, // inherit stack size from parent
563 (LPTHREAD_START_ROUTINE
)pfn
, // function pointer
565 0, // creation option, start immediately
566 &nUnused
); // thread identifier
569 printf("Error: CreateThread() returned %d\n", GetLastError());
574 CloseHandle(hthread
);
575 return (pthread_t
)-1;
580 inline void SetThreadPriority(int nPriority
)
582 SetThreadPriority(GetCurrentThread(), nPriority
);
585 inline pthread_t
CreateThread(void(*pfn
)(void*), void* parg
, bool fWantHandle
=false)
587 pthread_t hthread
= 0;
588 int ret
= pthread_create(&hthread
, NULL
, (void*(*)(void*))pfn
, parg
);
591 printf("Error: pthread_create() returned %d\n", ret
);
595 return (pthread_t
)-1;
599 #define THREAD_PRIORITY_LOWEST PRIO_MAX
600 #define THREAD_PRIORITY_BELOW_NORMAL 2
601 #define THREAD_PRIORITY_NORMAL 0
602 #define THREAD_PRIORITY_ABOVE_NORMAL 0
604 inline void SetThreadPriority(int nPriority
)
606 // It's unclear if it's even possible to change thread priorities on Linux,
607 // but we really and truly need it for the generation threads.
609 setpriority(PRIO_THREAD
, 0, nPriority
);
611 setpriority(PRIO_PROCESS
, 0, nPriority
);
615 inline bool TerminateThread(pthread_t hthread
, unsigned int nExitCode
)
617 return (pthread_cancel(hthread
) == 0);
620 inline void ExitThread(unsigned int nExitCode
)
622 pthread_exit((void*)nExitCode
);
630 inline bool AffinityBugWorkaround(void(*pfn
)(void*))
633 // Sometimes after a few hours affinity gets stuck on one processor
634 DWORD dwProcessAffinityMask
= -1;
635 DWORD dwSystemAffinityMask
= -1;
636 GetProcessAffinityMask(GetCurrentProcess(), &dwProcessAffinityMask
, &dwSystemAffinityMask
);
637 DWORD dwPrev1
= SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask
);
638 DWORD dwPrev2
= SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask
);
639 if (dwPrev2
!= dwProcessAffinityMask
)
641 printf("AffinityBugWorkaround() : SetThreadAffinityMask=%d, ProcessAffinityMask=%d, restarting thread\n", dwPrev2
, dwProcessAffinityMask
);
642 if (!CreateThread(pfn
, NULL
))
643 printf("Error: CreateThread() failed\n");