Projects : bitcoin : bitcoin_help_tuneups

bitcoin/src/util.h

Dir - Raw

1// Copyright (c) 2009-2010 Satoshi Nakamoto
2// Copyright (c) 2009-2012 The Bitcoin developers
3// Distributed under the MIT/X11 software license, see the accompanying
4// file license.txt or http://www.opensource.org/licenses/mit-license.php.
5#ifndef BITCOIN_UTIL_H
6#define BITCOIN_UTIL_H
7
8#include "uint256.h"
9
10#include <stdint.h>
11#include <sys/types.h>
12#include <sys/time.h>
13#include <sys/resource.h>
14#include <map>
15#include <vector>
16#include <string>
17
18#include <boost/thread.hpp>
19#include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>
20#include <boost/date_time/gregorian/gregorian_types.hpp>
21#include <boost/date_time/posix_time/posix_time_types.hpp>
22
23#include <openssl/sha.h>
24#include <openssl/ripemd.h>
25
26
27typedef long long int64;
28typedef unsigned long long uint64;
29
30#define __forceinline inline
31
32#define loop for (;;)
33#define BEGIN(a) ((char*)&(a))
34#define END(a) ((char*)&((&(a))[1]))
35#define UBEGIN(a) ((unsigned char*)&(a))
36#define UEND(a) ((unsigned char*)&((&(a))[1]))
37#define ARRAYLEN(array) (sizeof(array)/sizeof((array)[0]))
38#define printf OutputDebugStringF
39
40#ifdef snprintf
41#undef snprintf
42#endif
43#define snprintf my_snprintf
44
45#ifndef PRI64d
46#define PRI64d "lld"
47#define PRI64u "llu"
48#define PRI64x "llx"
49#endif
50
51// This is needed because the foreach macro can't get over the comma in pair<t1, t2>
52#define PAIRTYPE(t1, t2) std::pair<t1, t2>
53
54// Align by increasing pointer, must have extra space at end of buffer
55template <size_t nBytes, typename T>
56T* alignup(T* p)
57{
58 union
59 {
60 T* ptr;
61 size_t n;
62 } u;
63 u.ptr = p;
64 u.n = (u.n + (nBytes-1)) & ~(nBytes-1);
65 return u.ptr;
66}
67
68#define WSAGetLastError() errno
69#define WSAEINVAL EINVAL
70#define WSAEALREADY EALREADY
71#define WSAEWOULDBLOCK EWOULDBLOCK
72#define WSAEMSGSIZE EMSGSIZE
73#define WSAEINTR EINTR
74#define WSAEINPROGRESS EINPROGRESS
75#define WSAEADDRINUSE EADDRINUSE
76#define WSAENOTSOCK EBADF
77#define INVALID_SOCKET (SOCKET)(~0)
78#define SOCKET_ERROR -1
79typedef 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 MAX_PATH 1024
84#define Beep(n1,n2) (0)
85inline void Sleep(int64 n)
86{
87 /*Boost has a year 2038 problem- if the request sleep time is past epoch+2^31 seconds the sleep returns instantly.
88 So we clamp our sleeps here to 10 years and hope that boost is fixed by 2028.*/
89 boost::thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(n>315576000000LL?315576000000LL:n));
90}
91
92
93inline int myclosesocket(SOCKET& hSocket)
94{
95 if (hSocket == INVALID_SOCKET)
96 return WSAENOTSOCK;
97 int ret = close(hSocket);
98 hSocket = INVALID_SOCKET;
99 return ret;
100}
101#define closesocket(s) myclosesocket(s)
102inline const char* _(const char* psz)
103{
104 return psz;
105}
106
107
108extern std::map<std::string, std::string> mapArgs;
109extern std::map<std::string, std::vector<std::string> > mapMultiArgs;
110extern bool fDebug;
111extern bool fPrintToConsole;
112extern bool fPrintToDebugger;
113extern bool fCanEat;
114extern bool fVerifyAll;
115extern char pszSetDataDir[MAX_PATH];
116extern bool fRequestShutdown;
117extern bool fShutdown;
118extern bool fDaemon;
119extern bool fServer;
120extern bool fCommandLine;
121extern std::string strMiscWarning;
122extern bool fNoListen;
123extern bool fLogTimestamps;
124extern std::string CLIENT_NAME;
125extern bool fLowS;
126extern bool fHighS;
127extern bool fTestSafeMode;
128extern bool fDisableSafeMode;
129
130void RandAddSeed();
131void RandAddSeedPerfmon();
132int OutputDebugStringF(const char* pszFormat, ...);
133int my_snprintf(char* buffer, size_t limit, const char* format, ...);
134std::string strprintf(const std::string &format, ...);
135bool error(const std::string &format, ...);
136void LogException(std::exception* pex, const char* pszThread);
137void PrintException(std::exception* pex, const char* pszThread);
138void PrintExceptionContinue(std::exception* pex, const char* pszThread);
139void ParseString(const std::string& str, char c, std::vector<std::string>& v);
140std::string FormatMoney(int64 n, bool fPlus=false);
141bool ParseMoney(const std::string& str, int64& nRet);
142bool ParseMoney(const char* pszIn, int64& nRet);
143std::vector<unsigned char> ParseHex(const char* psz);
144std::vector<unsigned char> ParseHex(const std::string& str);
145std::vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid = NULL);
146std::string DecodeBase64(const std::string& str);
147std::string EncodeBase64(const unsigned char* pch, size_t len);
148std::string EncodeBase64(const std::string& str);
149void ParseParameters(int argc, char* argv[]);
150const char* wxGetTranslation(const char* psz);
151bool WildcardMatch(const char* psz, const char* mask);
152bool WildcardMatch(const std::string& str, const std::string& mask);
153int GetFilesize(FILE* file);
154void GetDataDir(char* pszDirRet);
155std::string GetConfigFile();
156std::string GetPidFile();
157void CreatePidFile(std::string pidFile, pid_t pid);
158void ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet, std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet);
159std::string GetDefaultDataDir();
160std::string GetDataDir();
161void ShrinkDebugFile();
162int GetRandInt(int nMax);
163uint64 GetRand(uint64 nMax);
164int64 GetTime();
165void SetMockTime(int64 nMockTimeIn);
166int64 GetAdjustedTime();
167void AddTimeData(unsigned int ip, int64 nTime);
168std::string FormatFullVersion();
169std::string FormatSubVersion(const std::string& name, int nClientVersion);
170
171
172
173
174
175
176
177
178
179
180
181
182
183// Wrapper to automatically initialize mutex
184class CCriticalSection
185{
186protected:
187 boost::interprocess::interprocess_recursive_mutex mutex;
188public:
189 explicit CCriticalSection() { }
190 ~CCriticalSection() { }
191 void Enter(const char* pszName, const char* pszFile, int nLine);
192 void Leave();
193 bool TryEnter(const char* pszName, const char* pszFile, int nLine);
194};
195
196// Automatically leave critical section when leaving block, needed for exception safety
197class CCriticalBlock
198{
199protected:
200 CCriticalSection* pcs;
201
202public:
203 CCriticalBlock(CCriticalSection& csIn, const char* pszName, const char* pszFile, int nLine)
204 {
205 pcs = &csIn;
206 pcs->Enter(pszName, pszFile, nLine);
207 }
208
209 operator bool() const
210 {
211 return true;
212 }
213
214 ~CCriticalBlock()
215 {
216 pcs->Leave();
217 }
218};
219
220#define CRITICAL_BLOCK(cs) \
221 if (CCriticalBlock criticalblock = CCriticalBlock(cs, #cs, __FILE__, __LINE__))
222
223#define ENTER_CRITICAL_SECTION(cs) \
224 (cs).Enter(#cs, __FILE__, __LINE__)
225
226#define LEAVE_CRITICAL_SECTION(cs) \
227 (cs).Leave()
228
229class CTryCriticalBlock
230{
231protected:
232 CCriticalSection* pcs;
233
234public:
235 CTryCriticalBlock(CCriticalSection& csIn, const char* pszName, const char* pszFile, int nLine)
236 {
237 pcs = (csIn.TryEnter(pszName, pszFile, nLine) ? &csIn : NULL);
238 }
239
240 operator bool() const
241 {
242 return Entered();
243 }
244
245 ~CTryCriticalBlock()
246 {
247 if (pcs)
248 {
249 pcs->Leave();
250 }
251 }
252 bool Entered() const { return pcs != NULL; }
253};
254
255#define TRY_CRITICAL_BLOCK(cs) \
256 if (CTryCriticalBlock criticalblock = CTryCriticalBlock(cs, #cs, __FILE__, __LINE__))
257
258
259
260
261
262
263// This is exactly like std::string, but with a custom allocator.
264// (secure_allocator<> is defined in serialize.h)
265typedef std::basic_string<char, std::char_traits<char>, secure_allocator<char> > SecureString;
266
267// This is exactly like std::string, but with a custom allocator.
268// (secure_allocator<> is defined in serialize.h)
269typedef std::basic_string<char, std::char_traits<char>, secure_allocator<char> > SecureString;
270
271
272
273
274
275inline std::string i64tostr(int64 n)
276{
277 return strprintf("%"PRI64d, n);
278}
279
280inline std::string itostr(int n)
281{
282 return strprintf("%d", n);
283}
284
285inline int64 atoi64(const char* psz)
286{
287 return strtoll(psz, NULL, 10);
288}
289
290inline int64 atoi64(const std::string& str)
291{
292 return strtoll(str.c_str(), NULL, 10);
293}
294
295inline int atoi(const std::string& str)
296{
297 return atoi(str.c_str());
298}
299
300inline int roundint(double d)
301{
302 return (int)(d > 0 ? d + 0.5 : d - 0.5);
303}
304
305inline int64 roundint64(double d)
306{
307 return (int64)(d > 0 ? d + 0.5 : d - 0.5);
308}
309
310inline int64 abs64(int64 n)
311{
312 return (n >= 0 ? n : -n);
313}
314
315template<typename T>
316std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
317{
318 if (itbegin == itend)
319 return "";
320 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
321 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
322 std::string str;
323 str.reserve((pend-pbegin) * (fSpaces ? 3 : 2));
324 for (const unsigned char* p = pbegin; p != pend; p++)
325 str += strprintf((fSpaces && p != pend-1 ? "%02x " : "%02x"), *p);
326 return str;
327}
328
329inline std::string HexStr(const std::vector<unsigned char>& vch, bool fSpaces=false)
330{
331 return HexStr(vch.begin(), vch.end(), fSpaces);
332}
333
334template<typename T>
335std::string HexNumStr(const T itbegin, const T itend, bool f0x=true)
336{
337 if (itbegin == itend)
338 return "";
339 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
340 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
341 std::string str = (f0x ? "0x" : "");
342 str.reserve(str.size() + (pend-pbegin) * 2);
343 for (const unsigned char* p = pend-1; p >= pbegin; p--)
344 str += strprintf("%02x", *p);
345 return str;
346}
347
348inline std::string HexNumStr(const std::vector<unsigned char>& vch, bool f0x=true)
349{
350 return HexNumStr(vch.begin(), vch.end(), f0x);
351}
352
353template<typename T>
354void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)
355{
356 printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());
357}
358
359inline void PrintHex(const std::vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true)
360{
361 printf(pszFormat, HexStr(vch, fSpaces).c_str());
362}
363
364inline int64 GetPerformanceCounter()
365{
366 int64 nCounter = 0;
367 timeval t;
368 gettimeofday(&t, NULL);
369 nCounter = t.tv_sec * 1000000 + t.tv_usec;
370 return nCounter;
371}
372
373inline int64 GetTimeMillis()
374{
375 return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) -
376 boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
377}
378
379inline std::string DateTimeStrFormat(const char* pszFormat, int64 nTime)
380{
381 time_t n = nTime;
382 struct tm* ptmTime = gmtime(&n);
383 char pszTime[200];
384 strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime);
385 return pszTime;
386}
387
388template<typename T>
389void skipspaces(T& it)
390{
391 while (isspace(*it))
392 ++it;
393}
394
395inline bool IsSwitchChar(char c)
396{
397 return c == '-';
398}
399
400inline std::string GetArg(const std::string& strArg, const std::string& strDefault)
401{
402 if (mapArgs.count(strArg))
403 return mapArgs[strArg];
404 return strDefault;
405}
406
407inline int64 GetArg(const std::string& strArg, int64 nDefault)
408{
409 if (mapArgs.count(strArg))
410 return atoi64(mapArgs[strArg]);
411 return nDefault;
412}
413
414inline bool GetBoolArg(const std::string& strArg, bool fDefault=false)
415{
416 if (mapArgs.count(strArg))
417 {
418 if (mapArgs[strArg].empty())
419 return true;
420 return (atoi(mapArgs[strArg]) != 0);
421 }
422 return fDefault;
423}
424
425/**
426 * Set an argument if it doesn't already have a value
427 *
428 * @param strArg Argument to set (e.g. "-foo")
429 * @param strValue Value (e.g. "1")
430 * @return true if argument gets set, false if it already had a value
431 */
432bool SoftSetArg(const std::string& strArg, const std::string& strValue);
433
434/**
435 * Set a boolean argument if it doesn't already have a value
436 *
437 * @param strArg Argument to set (e.g. "-foo")
438 * @param fValue Value (e.g. false)
439 * @return true if argument gets set, false if it already had a value
440 */
441bool SoftSetArg(const std::string& strArg, bool fValue);
442
443
444
445
446
447
448
449
450
451inline void heapchk()
452{
453}
454
455// Randomize the stack to help protect against buffer overrun exploits
456#define IMPLEMENT_RANDOMIZE_STACK(ThreadFn) \
457 { \
458 static char nLoops; \
459 if (nLoops <= 0) \
460 nLoops = GetRand(20) + 1; \
461 if (nLoops-- > 1) \
462 { \
463 ThreadFn; \
464 return; \
465 } \
466 }
467
468#define CATCH_PRINT_EXCEPTION(pszFn) \
469 catch (std::exception& e) { \
470 PrintException(&e, (pszFn)); \
471 } catch (...) { \
472 PrintException(NULL, (pszFn)); \
473 }
474
475
476
477
478
479
480
481
482
483
484template<typename T1>
485inline uint256 Hash(const T1 pbegin, const T1 pend)
486{
487 static unsigned char pblank[1];
488 uint256 hash1;
489 SHA256((pbegin == pend ? pblank : (unsigned char*)&pbegin[0]), (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);
490 uint256 hash2;
491 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
492 return hash2;
493}
494
495template<typename T1, typename T2>
496inline uint256 Hash(const T1 p1begin, const T1 p1end,
497 const T2 p2begin, const T2 p2end)
498{
499 static unsigned char pblank[1];
500 uint256 hash1;
501 SHA256_CTX ctx;
502 SHA256_Init(&ctx);
503 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
504 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
505 SHA256_Final((unsigned char*)&hash1, &ctx);
506 uint256 hash2;
507 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
508 return hash2;
509}
510
511template<typename T1, typename T2, typename T3>
512inline uint256 Hash(const T1 p1begin, const T1 p1end,
513 const T2 p2begin, const T2 p2end,
514 const T3 p3begin, const T3 p3end)
515{
516 static unsigned char pblank[1];
517 uint256 hash1;
518 SHA256_CTX ctx;
519 SHA256_Init(&ctx);
520 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
521 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
522 SHA256_Update(&ctx, (p3begin == p3end ? pblank : (unsigned char*)&p3begin[0]), (p3end - p3begin) * sizeof(p3begin[0]));
523 SHA256_Final((unsigned char*)&hash1, &ctx);
524 uint256 hash2;
525 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
526 return hash2;
527}
528
529template<typename T>
530uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=VERSION)
531{
532 // Most of the time is spent allocating and deallocating CDataStream's
533 // buffer. If this ever needs to be optimized further, make a CStaticStream
534 // class with its buffer on the stack.
535 CDataStream ss(nType, nVersion);
536 ss.reserve(10000);
537 ss << obj;
538 return Hash(ss.begin(), ss.end());
539}
540
541inline uint160 Hash160(const std::vector<unsigned char>& vch)
542{
543 uint256 hash1;
544 SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);
545 uint160 hash2;
546 RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
547 return hash2;
548}
549
550
551// Median filter over a stream of values
552// Returns the median of the last N numbers
553template <typename T> class CMedianFilter
554{
555private:
556 std::vector<T> vValues;
557 std::vector<T> vSorted;
558 int nSize;
559public:
560 CMedianFilter(int size, T initial_value):
561 nSize(size)
562 {
563 vValues.reserve(size);
564 vValues.push_back(initial_value);
565 vSorted = vValues;
566 }
567
568 void input(T value)
569 {
570 if(vValues.size() == nSize)
571 {
572 vValues.erase(vValues.begin());
573 }
574 vValues.push_back(value);
575
576 vSorted.resize(vValues.size());
577 std::copy(vValues.begin(), vValues.end(), vSorted.begin());
578 std::sort(vSorted.begin(), vSorted.end());
579 }
580
581 T median() const
582 {
583 int size = vSorted.size();
584 assert(size>0);
585 if(size & 1) // Odd number of elements
586 {
587 return vSorted[size/2];
588 }
589 else // Even number of elements
590 {
591 return (vSorted[size/2-1] + vSorted[size/2]) / 2;
592 }
593 }
594};
595
596
597
598
599
600
601
602
603
604
605// Note: It turns out we might have been able to use boost::thread
606// by using TerminateThread(boost::thread.native_handle(), 0);
607inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
608{
609 pthread_t hthread = 0;
610 int ret = pthread_create(&hthread, NULL, (void*(*)(void*))pfn, parg);
611 if (ret != 0)
612 {
613 printf("Error: pthread_create() returned %d\n", ret);
614 return (pthread_t)0;
615 }
616 if (!fWantHandle)
617 {
618 pthread_detach(hthread);
619 return (pthread_t)-1;
620 }
621 return hthread;
622}
623
624#define THREAD_PRIORITY_LOWEST PRIO_MAX
625#define THREAD_PRIORITY_BELOW_NORMAL 2
626#define THREAD_PRIORITY_NORMAL 0
627#define THREAD_PRIORITY_ABOVE_NORMAL 0
628
629inline void SetThreadPriority(int nPriority)
630{
631 // It's unclear if it's even possible to change thread priorities on Linux,
632 // but we really and truly need it for the generation threads.
633#ifdef PRIO_THREAD
634 setpriority(PRIO_THREAD, 0, nPriority);
635#else
636 setpriority(PRIO_PROCESS, 0, nPriority);
637#endif
638}
639
640inline bool TerminateThread(pthread_t hthread, unsigned int nExitCode)
641{
642 return (pthread_cancel(hthread) == 0);
643}
644
645inline void ExitThread(size_t nExitCode)
646{
647 pthread_exit((void*)nExitCode);
648}
649
650
651
652inline bool AffinityBugWorkaround(void(*pfn)(void*))
653{
654 return false;
655}
656
657inline uint32_t ByteReverse(uint32_t value)
658{
659 value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8);
660 return (value<<16) | (value>>16);
661}
662
663#endif