]> Git Repo - VerusCoin.git/blame - src/util.h
Parallelize script verification
[VerusCoin.git] / src / util.h
CommitLineData
1f2e0df8 1// Copyright (c) 2009-2010 Satoshi Nakamoto
88216419 2// Copyright (c) 2009-2012 The Bitcoin developers
1f2e0df8 3// Distributed under the MIT/X11 software license, see the accompanying
3a25a2b9 4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
1f2e0df8
WL
5#ifndef BITCOIN_UTIL_H
6#define BITCOIN_UTIL_H
7
8#include "uint256.h"
9
6853e627 10#ifndef WIN32
1f2e0df8 11#include <sys/types.h>
6644d98d
WL
12#include <sys/time.h>
13#include <sys/resource.h>
52d3a481 14#else
efdcf941 15typedef int pid_t; /* define for Windows compatibility */
85663f2c 16#endif
1f2e0df8
WL
17#include <map>
18#include <vector>
19#include <string>
20
21#include <boost/thread.hpp>
ee12c3d6
PW
22#include <boost/filesystem.hpp>
23#include <boost/filesystem/path.hpp>
1f2e0df8
WL
24#include <boost/date_time/gregorian/gregorian_types.hpp>
25#include <boost/date_time/posix_time/posix_time_types.hpp>
26
ed6d0b5f 27#include "netbase.h" // for AddTimeData
1f2e0df8 28
bde280b9
WL
29typedef long long int64;
30typedef unsigned long long uint64;
31
ed6d0b5f
PW
32static const int64 COIN = 100000000;
33static const int64 CENT = 1000000;
34
1f2e0df8
WL
35#define loop for (;;)
36#define BEGIN(a) ((char*)&(a))
37#define END(a) ((char*)&((&(a))[1]))
38#define UBEGIN(a) ((unsigned char*)&(a))
39#define UEND(a) ((unsigned char*)&((&(a))[1]))
40#define ARRAYLEN(array) (sizeof(array)/sizeof((array)[0]))
1f2e0df8 41
1f2e0df8 42#ifndef PRI64d
bd846c0e 43#if defined(_MSC_VER) || defined(__MSVCRT__)
1f2e0df8
WL
44#define PRI64d "I64d"
45#define PRI64u "I64u"
46#define PRI64x "I64x"
47#else
48#define PRI64d "lld"
49#define PRI64u "llu"
50#define PRI64x "llx"
51#endif
52#endif
53
3b3d9996
WL
54/* Format characters for (s)size_t and ptrdiff_t */
55#if defined(_MSC_VER) || defined(__MSVCRT__)
bcc292b2
WL
56 /* (s)size_t and ptrdiff_t have the same size specifier in MSVC:
57 http://msdn.microsoft.com/en-us/library/tcxf1dw6%28v=vs.100%29.aspx
58 */
9c8dc7ca
PK
59 #define PRIszx "Ix"
60 #define PRIszu "Iu"
61 #define PRIszd "Id"
bcc292b2
WL
62 #define PRIpdx "Ix"
63 #define PRIpdu "Iu"
64 #define PRIpdd "Id"
65#else /* C99 standard */
9c8dc7ca
PK
66 #define PRIszx "zx"
67 #define PRIszu "zu"
68 #define PRIszd "zd"
bcc292b2
WL
69 #define PRIpdx "tx"
70 #define PRIpdu "tu"
71 #define PRIpdd "td"
3b3d9996
WL
72#endif
73
1f2e0df8 74// This is needed because the foreach macro can't get over the comma in pair<t1, t2>
9aef9bca 75#define PAIRTYPE(t1, t2) std::pair<t1, t2>
1f2e0df8 76
1f2e0df8
WL
77// Align by increasing pointer, must have extra space at end of buffer
78template <size_t nBytes, typename T>
79T* alignup(T* p)
80{
81 union
82 {
83 T* ptr;
84 size_t n;
85 } u;
86 u.ptr = p;
87 u.n = (u.n + (nBytes-1)) & ~(nBytes-1);
88 return u.ptr;
89}
90
6853e627 91#ifdef WIN32
1f2e0df8
WL
92#define MSG_NOSIGNAL 0
93#define MSG_DONTWAIT 0
26ce92b3 94
1f2e0df8
WL
95#ifndef S_IRUSR
96#define S_IRUSR 0400
97#define S_IWUSR 0200
98#endif
1f2e0df8 99#else
1f2e0df8 100#define MAX_PATH 1024
bde280b9 101inline void Sleep(int64 n)
1f2e0df8 102{
82a10c81
GM
103 /*Boost has a year 2038 problem— if the request sleep time is past epoch+2^31 seconds the sleep returns instantly.
104 So we clamp our sleeps here to 10 years and hope that boost is fixed by 2028.*/
105 boost::thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(n>315576000000LL?315576000000LL:n));
1f2e0df8
WL
106}
107#endif
108
b0a90fbb
WL
109/* This GNU C extension enables the compiler to check the format string against the parameters provided.
110 * X is the number of the "format string" parameter, and Y is the number of the first variadic parameter.
111 * Parameters count from 1.
112 */
113#ifdef __GNUC__
114#define ATTR_WARN_PRINTF(X,Y) __attribute__((format(printf,X,Y)))
115#else
116#define ATTR_WARN_PRINTF(X,Y)
117#endif
1f2e0df8
WL
118
119
120
121
122
123
124
125
126extern std::map<std::string, std::string> mapArgs;
127extern std::map<std::string, std::vector<std::string> > mapMultiArgs;
128extern bool fDebug;
d07eaba1 129extern bool fDebugNet;
1f2e0df8
WL
130extern bool fPrintToConsole;
131extern bool fPrintToDebugger;
3fb9b99c 132extern volatile bool fRequestShutdown;
1f2e0df8
WL
133extern bool fShutdown;
134extern bool fDaemon;
135extern bool fServer;
136extern bool fCommandLine;
137extern std::string strMiscWarning;
138extern bool fTestNet;
139extern bool fNoListen;
140extern bool fLogTimestamps;
9af080c3 141extern bool fReopenDebugLog;
1f2e0df8
WL
142
143void RandAddSeed();
144void RandAddSeedPerfmon();
b0a90fbb 145int ATTR_WARN_PRINTF(1,2) OutputDebugStringF(const char* pszFormat, ...);
52d3a481 146
b0a90fbb
WL
147/*
148 Rationale for the real_strprintf / strprintf construction:
149 It is not allowed to use va_start with a pass-by-reference argument.
150 (C++ standard, 18.7, paragraph 3). Use a dummy argument to work around this, and use a
151 macro to keep similar semantics.
52d3a481 152*/
b0a90fbb
WL
153
154/** Overload strprintf for char*, so that GCC format type warnings can be given */
155std::string ATTR_WARN_PRINTF(1,3) real_strprintf(const char *format, int dummy, ...);
156/** Overload strprintf for std::string, to be able to use it with _ (translation).
157 * This will not support GCC format type warnings (-Wformat) so be careful.
158 */
52d3a481
WL
159std::string real_strprintf(const std::string &format, int dummy, ...);
160#define strprintf(format, ...) real_strprintf(format, 0, __VA_ARGS__)
b0a90fbb
WL
161std::string vstrprintf(const char *format, va_list ap);
162
bcc292b2
WL
163bool ATTR_WARN_PRINTF(1,2) error(const char *format, ...);
164
b0a90fbb
WL
165/* Redefine printf so that it directs output to debug.log
166 *
167 * Do this *after* defining the other printf-like functions, because otherwise the
168 * __attribute__((format(printf,X,Y))) gets expanded to __attribute__((format(OutputDebugStringF,X,Y)))
169 * which confuses gcc.
170 */
171#define printf OutputDebugStringF
52d3a481 172
1f2e0df8
WL
173void LogException(std::exception* pex, const char* pszThread);
174void PrintException(std::exception* pex, const char* pszThread);
175void PrintExceptionContinue(std::exception* pex, const char* pszThread);
176void ParseString(const std::string& str, char c, std::vector<std::string>& v);
bde280b9
WL
177std::string FormatMoney(int64 n, bool fPlus=false);
178bool ParseMoney(const std::string& str, int64& nRet);
179bool ParseMoney(const char* pszIn, int64& nRet);
1f2e0df8
WL
180std::vector<unsigned char> ParseHex(const char* psz);
181std::vector<unsigned char> ParseHex(const std::string& str);
922e8e29 182bool IsHex(const std::string& str);
4b603f1c
PW
183std::vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid = NULL);
184std::string DecodeBase64(const std::string& str);
185std::string EncodeBase64(const unsigned char* pch, size_t len);
186std::string EncodeBase64(const std::string& str);
c4c99ade
PW
187std::vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid = NULL);
188std::string DecodeBase32(const std::string& str);
189std::string EncodeBase32(const unsigned char* pch, size_t len);
190std::string EncodeBase32(const std::string& str);
3ae07355 191void ParseParameters(int argc, const char*const argv[]);
1f2e0df8
WL
192bool WildcardMatch(const char* psz, const char* mask);
193bool WildcardMatch(const std::string& str, const std::string& mask);
768e5d52 194void FileCommit(FILE *fileout);
1f2e0df8 195int GetFilesize(FILE* file);
bba89aa8 196void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length);
768e5d52 197bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest);
ee12c3d6
PW
198boost::filesystem::path GetDefaultDataDir();
199const boost::filesystem::path &GetDataDir(bool fNetSpecific = true);
200boost::filesystem::path GetConfigFile();
201boost::filesystem::path GetPidFile();
202void CreatePidFile(const boost::filesystem::path &path, pid_t pid);
f4203de3 203void ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet, std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet);
3e468840
PK
204#ifdef WIN32
205boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate = true);
206#endif
597fa4cd 207boost::filesystem::path GetTempPath();
1f2e0df8
WL
208void ShrinkDebugFile();
209int GetRandInt(int nMax);
bde280b9 210uint64 GetRand(uint64 nMax);
f718aedd 211uint256 GetRandHash();
bde280b9
WL
212int64 GetTime();
213void SetMockTime(int64 nMockTimeIn);
214int64 GetAdjustedTime();
1f2e0df8 215std::string FormatFullVersion();
f8ded588 216std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments);
67a42f92 217void AddTimeData(const CNetAddr& ip, int64 nTime);
429039d4 218void runCommand(std::string strCommand);
1f2e0df8
WL
219
220
221
222
223
224
225
226
227
bde280b9 228inline std::string i64tostr(int64 n)
1f2e0df8
WL
229{
230 return strprintf("%"PRI64d, n);
231}
232
233inline std::string itostr(int n)
234{
235 return strprintf("%d", n);
236}
237
bde280b9 238inline int64 atoi64(const char* psz)
1f2e0df8
WL
239{
240#ifdef _MSC_VER
241 return _atoi64(psz);
242#else
243 return strtoll(psz, NULL, 10);
244#endif
245}
246
bde280b9 247inline int64 atoi64(const std::string& str)
1f2e0df8
WL
248{
249#ifdef _MSC_VER
250 return _atoi64(str.c_str());
251#else
252 return strtoll(str.c_str(), NULL, 10);
253#endif
254}
255
256inline int atoi(const std::string& str)
257{
258 return atoi(str.c_str());
259}
260
261inline int roundint(double d)
262{
263 return (int)(d > 0 ? d + 0.5 : d - 0.5);
264}
265
bde280b9 266inline int64 roundint64(double d)
1f2e0df8 267{
bde280b9 268 return (int64)(d > 0 ? d + 0.5 : d - 0.5);
1f2e0df8
WL
269}
270
bde280b9 271inline int64 abs64(int64 n)
1f2e0df8
WL
272{
273 return (n >= 0 ? n : -n);
274}
275
276template<typename T>
277std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
278{
ac4e7f62
WL
279 std::string rv;
280 static const char hexmap[16] = { '0', '1', '2', '3', '4', '5', '6', '7',
281 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
88dc2d6c
WL
282 rv.reserve((itend-itbegin)*3);
283 for(T it = itbegin; it < itend; ++it)
284 {
285 unsigned char val = (unsigned char)(*it);
286 if(fSpaces && it != itbegin)
287 rv.push_back(' ');
288 rv.push_back(hexmap[val>>4]);
289 rv.push_back(hexmap[val&15]);
290 }
291
ac4e7f62 292 return rv;
1f2e0df8
WL
293}
294
295inline std::string HexStr(const std::vector<unsigned char>& vch, bool fSpaces=false)
296{
297 return HexStr(vch.begin(), vch.end(), fSpaces);
298}
299
1f2e0df8
WL
300template<typename T>
301void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)
302{
303 printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());
304}
305
306inline void PrintHex(const std::vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true)
307{
308 printf(pszFormat, HexStr(vch, fSpaces).c_str());
309}
310
bde280b9 311inline int64 GetPerformanceCounter()
1f2e0df8 312{
bde280b9 313 int64 nCounter = 0;
6853e627 314#ifdef WIN32
1f2e0df8
WL
315 QueryPerformanceCounter((LARGE_INTEGER*)&nCounter);
316#else
317 timeval t;
318 gettimeofday(&t, NULL);
43346904 319 nCounter = (int64) t.tv_sec * 1000000 + t.tv_usec;
1f2e0df8
WL
320#endif
321 return nCounter;
322}
323
bde280b9 324inline int64 GetTimeMillis()
1f2e0df8
WL
325{
326 return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) -
327 boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
328}
329
0ae0712b
PW
330inline int64 GetTimeMicros()
331{
332 return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) -
333 boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_microseconds();
334}
335
bde280b9 336inline std::string DateTimeStrFormat(const char* pszFormat, int64 nTime)
1f2e0df8
WL
337{
338 time_t n = nTime;
339 struct tm* ptmTime = gmtime(&n);
340 char pszTime[200];
341 strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime);
342 return pszTime;
343}
344
345template<typename T>
346void skipspaces(T& it)
347{
348 while (isspace(*it))
349 ++it;
350}
351
352inline bool IsSwitchChar(char c)
353{
6853e627 354#ifdef WIN32
1f2e0df8
WL
355 return c == '-' || c == '/';
356#else
357 return c == '-';
358#endif
359}
360
3ae07355
GA
361/**
362 * Return string argument or default value
363 *
364 * @param strArg Argument to get (e.g. "-foo")
365 * @param default (e.g. "1")
366 * @return command-line argument or default value
367 */
368std::string GetArg(const std::string& strArg, const std::string& strDefault);
1f2e0df8 369
3ae07355
GA
370/**
371 * Return integer argument or default value
372 *
373 * @param strArg Argument to get (e.g. "-foo")
374 * @param default (e.g. 1)
375 * @return command-line argument (0 if invalid number) or default value
376 */
377int64 GetArg(const std::string& strArg, int64 nDefault);
1f2e0df8 378
3ae07355
GA
379/**
380 * Return boolean argument or default value
381 *
382 * @param strArg Argument to get (e.g. "-foo")
383 * @param default (true or false)
384 * @return command-line argument or default value
385 */
386bool GetBoolArg(const std::string& strArg, bool fDefault=false);
1f2e0df8 387
0fcf91ea
GA
388/**
389 * Set an argument if it doesn't already have a value
390 *
391 * @param strArg Argument to set (e.g. "-foo")
392 * @param strValue Value (e.g. "1")
393 * @return true if argument gets set, false if it already had a value
394 */
395bool SoftSetArg(const std::string& strArg, const std::string& strValue);
396
397/**
398 * Set a boolean argument if it doesn't already have a value
399 *
400 * @param strArg Argument to set (e.g. "-foo")
401 * @param fValue Value (e.g. false)
402 * @return true if argument gets set, false if it already had a value
403 */
7bf8b7c2 404bool SoftSetBoolArg(const std::string& strArg, bool fValue);
1f2e0df8
WL
405
406
407
408
409
410
411
412
413
ea0796bd 414/** Median filter over a stream of values.
6b8de05d
PW
415 * Returns the median of the last N numbers
416 */
a8b95ce6
WL
417template <typename T> class CMedianFilter
418{
419private:
420 std::vector<T> vValues;
421 std::vector<T> vSorted;
735a6069 422 unsigned int nSize;
a8b95ce6 423public:
735a6069 424 CMedianFilter(unsigned int size, T initial_value):
a8b95ce6
WL
425 nSize(size)
426 {
427 vValues.reserve(size);
428 vValues.push_back(initial_value);
429 vSorted = vValues;
430 }
ea0796bd 431
a8b95ce6
WL
432 void input(T value)
433 {
434 if(vValues.size() == nSize)
435 {
436 vValues.erase(vValues.begin());
437 }
438 vValues.push_back(value);
439
440 vSorted.resize(vValues.size());
441 std::copy(vValues.begin(), vValues.end(), vSorted.begin());
442 std::sort(vSorted.begin(), vSorted.end());
443 }
444
445 T median() const
446 {
447 int size = vSorted.size();
20091df7 448 assert(size>0);
a8b95ce6
WL
449 if(size & 1) // Odd number of elements
450 {
451 return vSorted[size/2];
452 }
453 else // Even number of elements
454 {
455 return (vSorted[size/2-1] + vSorted[size/2]) / 2;
456 }
457 }
1c4aab92
MH
458
459 int size() const
460 {
461 return vValues.size();
462 }
463
464 std::vector<T> sorted () const
465 {
466 return vSorted;
467 }
a8b95ce6
WL
468};
469
4d1d94c5 470bool NewThread(void(*pfn)(void*), void* parg);
1f2e0df8 471
6853e627 472#ifdef WIN32
1f2e0df8
WL
473inline void SetThreadPriority(int nPriority)
474{
475 SetThreadPriority(GetCurrentThread(), nPriority);
476}
477#else
1f2e0df8
WL
478
479#define THREAD_PRIORITY_LOWEST PRIO_MAX
480#define THREAD_PRIORITY_BELOW_NORMAL 2
481#define THREAD_PRIORITY_NORMAL 0
482#define THREAD_PRIORITY_ABOVE_NORMAL 0
483
484inline void SetThreadPriority(int nPriority)
485{
486 // It's unclear if it's even possible to change thread priorities on Linux,
487 // but we really and truly need it for the generation threads.
488#ifdef PRIO_THREAD
489 setpriority(PRIO_THREAD, 0, nPriority);
490#else
491 setpriority(PRIO_PROCESS, 0, nPriority);
492#endif
493}
494
df401814 495inline void ExitThread(size_t nExitCode)
1f2e0df8
WL
496{
497 pthread_exit((void*)nExitCode);
498}
499#endif
500
96931d6f 501void RenameThread(const char* name);
1f2e0df8 502
6ccff2cb
NS
503inline uint32_t ByteReverse(uint32_t value)
504{
b985efaa
LR
505 value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8);
506 return (value<<16) | (value>>16);
6ccff2cb
NS
507}
508
1f2e0df8 509#endif
67a42f92 510
This page took 0.184398 seconds and 4 git commands to generate.