Projects : bitcoin : bitcoin_tx_fee_cleanup

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 fVerifyAll;
114extern char pszSetDataDir[MAX_PATH];
115extern bool fRequestShutdown;
116extern bool fShutdown;
117extern bool fDaemon;
118extern bool fServer;
119extern bool fCommandLine;
120extern std::string strMiscWarning;
121extern bool fNoListen;
122extern bool fLogTimestamps;
123extern std::string CLIENT_NAME;
124extern bool fLowS;
125extern bool fHighS;
126extern bool fTestSafeMode;
127extern bool fDisableSafeMode;
128extern bool fPermissive;
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// Or we could not misdirect the compiler not to mention reader through if-statement and operator-bool() hacks.
224#define SCOPED_LOCK(cs) CCriticalBlock criticalblock(cs, #cs, __FILE__, __LINE__)
225
226#define ENTER_CRITICAL_SECTION(cs) \
227 (cs).Enter(#cs, __FILE__, __LINE__)
228
229#define LEAVE_CRITICAL_SECTION(cs) \
230 (cs).Leave()
231
232class CTryCriticalBlock
233{
234protected:
235 CCriticalSection* pcs;
236
237public:
238 CTryCriticalBlock(CCriticalSection& csIn, const char* pszName, const char* pszFile, int nLine)
239 {
240 pcs = (csIn.TryEnter(pszName, pszFile, nLine) ? &csIn : NULL);
241 }
242
243 operator bool() const
244 {
245 return Entered();
246 }
247
248 ~CTryCriticalBlock()
249 {
250 if (pcs)
251 {
252 pcs->Leave();
253 }
254 }
255 bool Entered() const { return pcs != NULL; }
256};
257
258#define TRY_CRITICAL_BLOCK(cs) \
259 if (CTryCriticalBlock criticalblock = CTryCriticalBlock(cs, #cs, __FILE__, __LINE__))
260
261
262
263
264
265
266// This is exactly like std::string, but with a custom allocator.
267// (secure_allocator<> is defined in serialize.h)
268typedef std::basic_string<char, std::char_traits<char>, secure_allocator<char> > SecureString;
269
270// This is exactly like std::string, but with a custom allocator.
271// (secure_allocator<> is defined in serialize.h)
272typedef std::basic_string<char, std::char_traits<char>, secure_allocator<char> > SecureString;
273
274
275
276
277
278inline std::string i64tostr(int64 n)
279{
280 return strprintf("%"PRI64d, n);
281}
282
283inline std::string itostr(int n)
284{
285 return strprintf("%d", n);
286}
287
288inline int64 atoi64(const char* psz)
289{
290 return strtoll(psz, NULL, 10);
291}
292
293inline int64 atoi64(const std::string& str)
294{
295 return strtoll(str.c_str(), NULL, 10);
296}
297
298inline int atoi(const std::string& str)
299{
300 return atoi(str.c_str());
301}
302
303inline int roundint(double d)
304{
305 return (int)(d > 0 ? d + 0.5 : d - 0.5);
306}
307
308inline int64 roundint64(double d)
309{
310 return (int64)(d > 0 ? d + 0.5 : d - 0.5);
311}
312
313inline int64 abs64(int64 n)
314{
315 return (n >= 0 ? n : -n);
316}
317
318template<typename T>
319std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
320{
321 if (itbegin == itend)
322 return "";
323 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
324 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
325 std::string str;
326 str.reserve((pend-pbegin) * (fSpaces ? 3 : 2));
327 for (const unsigned char* p = pbegin; p != pend; p++)
328 str += strprintf((fSpaces && p != pend-1 ? "%02x " : "%02x"), *p);
329 return str;
330}
331
332inline std::string HexStr(const std::vector<unsigned char>& vch, bool fSpaces=false)
333{
334 return HexStr(vch.begin(), vch.end(), fSpaces);
335}
336
337template<typename T>
338std::string HexNumStr(const T itbegin, const T itend, bool f0x=true)
339{
340 if (itbegin == itend)
341 return "";
342 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
343 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
344 std::string str = (f0x ? "0x" : "");
345 str.reserve(str.size() + (pend-pbegin) * 2);
346 for (const unsigned char* p = pend-1; p >= pbegin; p--)
347 str += strprintf("%02x", *p);
348 return str;
349}
350
351inline std::string HexNumStr(const std::vector<unsigned char>& vch, bool f0x=true)
352{
353 return HexNumStr(vch.begin(), vch.end(), f0x);
354}
355
356template<typename T>
357void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)
358{
359 printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());
360}
361
362inline void PrintHex(const std::vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true)
363{
364 printf(pszFormat, HexStr(vch, fSpaces).c_str());
365}
366
367inline int64 GetPerformanceCounter()
368{
369 int64 nCounter = 0;
370 timeval t;
371 gettimeofday(&t, NULL);
372 nCounter = t.tv_sec * 1000000 + t.tv_usec;
373 return nCounter;
374}
375
376inline int64 GetTimeMillis()
377{
378 return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) -
379 boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
380}
381
382inline std::string DateTimeStrFormat(const char* pszFormat, int64 nTime)
383{
384 time_t n = nTime;
385 struct tm* ptmTime = gmtime(&n);
386 char pszTime[200];
387 strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime);
388 return pszTime;
389}
390
391template<typename T>
392void skipspaces(T& it)
393{
394 while (isspace(*it))
395 ++it;
396}
397
398inline bool IsSwitchChar(char c)
399{
400 return c == '-';
401}
402
403inline std::string GetArg(const std::string& strArg, const std::string& strDefault)
404{
405 if (mapArgs.count(strArg))
406 return mapArgs[strArg];
407 return strDefault;
408}
409
410inline int64 GetArg(const std::string& strArg, int64 nDefault)
411{
412 if (mapArgs.count(strArg))
413 return atoi64(mapArgs[strArg]);
414 return nDefault;
415}
416
417inline bool GetBoolArg(const std::string& strArg, bool fDefault=false)
418{
419 if (mapArgs.count(strArg))
420 {
421 if (mapArgs[strArg].empty())
422 return true;
423 return (atoi(mapArgs[strArg]) != 0);
424 }
425 return fDefault;
426}
427
428/**
429 * Set an argument if it doesn't already have a value
430 *
431 * @param strArg Argument to set (e.g. "-foo")
432 * @param strValue Value (e.g. "1")
433 * @return true if argument gets set, false if it already had a value
434 */
435bool SoftSetArg(const std::string& strArg, const std::string& strValue);
436
437/**
438 * Set a boolean argument if it doesn't already have a value
439 *
440 * @param strArg Argument to set (e.g. "-foo")
441 * @param fValue Value (e.g. false)
442 * @return true if argument gets set, false if it already had a value
443 */
444bool SoftSetArg(const std::string& strArg, bool fValue);
445
446
447
448
449
450
451
452
453
454inline void heapchk()
455{
456}
457
458// Randomize the stack to help protect against buffer overrun exploits
459#define IMPLEMENT_RANDOMIZE_STACK(ThreadFn) \
460 { \
461 static char nLoops; \
462 if (nLoops <= 0) \
463 nLoops = GetRand(20) + 1; \
464 if (nLoops-- > 1) \
465 { \
466 ThreadFn; \
467 return; \
468 } \
469 }
470
471#define CATCH_PRINT_EXCEPTION(pszFn) \
472 catch (std::exception& e) { \
473 PrintException(&e, (pszFn)); \
474 } catch (...) { \
475 PrintException(NULL, (pszFn)); \
476 }
477
478
479
480
481
482
483
484
485
486
487template<typename T1>
488inline uint256 Hash(const T1 pbegin, const T1 pend)
489{
490 static unsigned char pblank[1];
491 uint256 hash1;
492 SHA256((pbegin == pend ? pblank : (unsigned char*)&pbegin[0]), (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);
493 uint256 hash2;
494 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
495 return hash2;
496}
497
498template<typename T1, typename T2>
499inline uint256 Hash(const T1 p1begin, const T1 p1end,
500 const T2 p2begin, const T2 p2end)
501{
502 static unsigned char pblank[1];
503 uint256 hash1;
504 SHA256_CTX ctx;
505 SHA256_Init(&ctx);
506 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
507 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
508 SHA256_Final((unsigned char*)&hash1, &ctx);
509 uint256 hash2;
510 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
511 return hash2;
512}
513
514template<typename T1, typename T2, typename T3>
515inline uint256 Hash(const T1 p1begin, const T1 p1end,
516 const T2 p2begin, const T2 p2end,
517 const T3 p3begin, const T3 p3end)
518{
519 static unsigned char pblank[1];
520 uint256 hash1;
521 SHA256_CTX ctx;
522 SHA256_Init(&ctx);
523 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
524 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
525 SHA256_Update(&ctx, (p3begin == p3end ? pblank : (unsigned char*)&p3begin[0]), (p3end - p3begin) * sizeof(p3begin[0]));
526 SHA256_Final((unsigned char*)&hash1, &ctx);
527 uint256 hash2;
528 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
529 return hash2;
530}
531
532template<typename T>
533uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=VERSION)
534{
535 // Most of the time is spent allocating and deallocating CDataStream's
536 // buffer. If this ever needs to be optimized further, make a CStaticStream
537 // class with its buffer on the stack.
538 CDataStream ss(nType, nVersion);
539 ss.reserve(10000);
540 ss << obj;
541 return Hash(ss.begin(), ss.end());
542}
543
544inline uint160 Hash160(const std::vector<unsigned char>& vch)
545{
546 uint256 hash1;
547 SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);
548 uint160 hash2;
549 RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
550 return hash2;
551}
552
553
554// Median filter over a stream of values
555// Returns the median of the last N numbers
556template <typename T> class CMedianFilter
557{
558private:
559 std::vector<T> vValues;
560 std::vector<T> vSorted;
561 int nSize;
562public:
563 CMedianFilter(int size, T initial_value):
564 nSize(size)
565 {
566 vValues.reserve(size);
567 vValues.push_back(initial_value);
568 vSorted = vValues;
569 }
570
571 void input(T value)
572 {
573 if(vValues.size() == nSize)
574 {
575 vValues.erase(vValues.begin());
576 }
577 vValues.push_back(value);
578
579 vSorted.resize(vValues.size());
580 std::copy(vValues.begin(), vValues.end(), vSorted.begin());
581 std::sort(vSorted.begin(), vSorted.end());
582 }
583
584 T median() const
585 {
586 int size = vSorted.size();
587 assert(size>0);
588 if(size & 1) // Odd number of elements
589 {
590 return vSorted[size/2];
591 }
592 else // Even number of elements
593 {
594 return (vSorted[size/2-1] + vSorted[size/2]) / 2;
595 }
596 }
597};
598
599
600
601
602
603
604
605
606
607
608// Note: It turns out we might have been able to use boost::thread
609// by using TerminateThread(boost::thread.native_handle(), 0);
610inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
611{
612 pthread_t hthread = 0;
613 int ret = pthread_create(&hthread, NULL, (void*(*)(void*))pfn, parg);
614 if (ret != 0)
615 {
616 printf("Error: pthread_create() returned %d\n", ret);
617 return (pthread_t)0;
618 }
619 if (!fWantHandle)
620 {
621 pthread_detach(hthread);
622 return (pthread_t)-1;
623 }
624 return hthread;
625}
626
627#define THREAD_PRIORITY_LOWEST PRIO_MAX
628#define THREAD_PRIORITY_BELOW_NORMAL 2
629#define THREAD_PRIORITY_NORMAL 0
630#define THREAD_PRIORITY_ABOVE_NORMAL 0
631
632inline void SetThreadPriority(int nPriority)
633{
634 // It's unclear if it's even possible to change thread priorities on Linux,
635 // but we really and truly need it for the generation threads.
636#ifdef PRIO_THREAD
637 setpriority(PRIO_THREAD, 0, nPriority);
638#else
639 setpriority(PRIO_PROCESS, 0, nPriority);
640#endif
641}
642
643inline bool TerminateThread(pthread_t hthread, unsigned int nExitCode)
644{
645 return (pthread_cancel(hthread) == 0);
646}
647
648inline void ExitThread(size_t nExitCode)
649{
650 pthread_exit((void*)nExitCode);
651}
652
653
654
655inline bool AffinityBugWorkaround(void(*pfn)(void*))
656{
657 return false;
658}
659
660inline uint32_t ByteReverse(uint32_t value)
661{
662 value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8);
663 return (value<<16) | (value>>16);
664}
665
666#endif