port code from +17 branch, fix operator *=
[novacoin.git] / src / util.h
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 COPYING or http://www.opensource.org/licenses/mit-license.php.
5 #ifndef BITCOIN_UTIL_H
6 #define BITCOIN_UTIL_H
7
8
9 #ifndef WIN32
10 #include <sys/types.h>
11 #include <sys/time.h>
12 #include <sys/resource.h>
13 #endif
14
15 #include <map>
16 #include <vector>
17 #include <string>
18
19 #ifndef Q_MOC_RUN
20 #include <boost/thread.hpp>
21 #include <boost/filesystem.hpp>
22 #include <boost/filesystem/path.hpp>
23 #include <boost/date_time/gregorian/gregorian_types.hpp>
24 #include <boost/date_time/posix_time/posix_time_types.hpp>
25 #endif
26
27 #include <stdarg.h>
28
29 #if defined(__USE_MINGW_ANSI_STDIO)
30 #undef __USE_MINGW_ANSI_STDIO // This constant forces MinGW to conduct stupid behavior
31 #endif
32 #include <inttypes.h>
33
34 #include "netbase.h" // for AddTimeData
35
36 static const int32_t nOneHour = 60 * 60;
37 static const int32_t nOneDay = 24 * 60 * 60;
38 static const int64_t nOneWeek = 7 * 24 * 60 * 60;
39
40 static const int64_t COIN = 1000000;
41 static const int64_t CENT = 10000;
42
43 #define BEGIN(a)            ((char*)&(a))
44 #define END(a)              ((char*)&((&(a))[1]))
45 #define UBEGIN(a)           ((unsigned char*)&(a))
46 #define UEND(a)             ((unsigned char*)&((&(a))[1]))
47 #define ARRAYLEN(array)     (sizeof(array)/sizeof((array)[0]))
48
49 #define UVOIDBEGIN(a)        ((void*)&(a))
50 #define CVOIDBEGIN(a)        ((const void*)&(a))
51 #define UINTBEGIN(a)        ((uint32_t*)&(a))
52 #define CUINTBEGIN(a)        ((const uint32_t*)&(a))
53
54 #ifndef THROW_WITH_STACKTRACE
55 #define THROW_WITH_STACKTRACE(exception)  \
56 {                                         \
57     LogStackTrace();                      \
58     throw (exception);                    \
59 }
60 void LogStackTrace();
61 #endif
62
63 #if defined(_MSC_VER) || defined(__MSVCRT__)
64  /* Silence compiler warnings on Windows 
65      related to MinGWs inttypes.h */
66  #undef PRIu64
67  #undef PRId64
68  #undef PRIx64
69
70  #define PRIu64 "I64u"
71  #define PRId64 "I64d"
72  #define PRIx64 "I64x"
73
74 #endif
75
76 /* Format characters for (s)size_t and ptrdiff_t */
77 #if defined(_MSC_VER) || defined(__MSVCRT__)
78   /* (s)size_t and ptrdiff_t have the same size specifier in MSVC:
79      http://msdn.microsoft.com/en-us/library/tcxf1dw6%28v=vs.100%29.aspx
80    */
81   #define PRIszx    "Ix"
82   #define PRIszu    "Iu"
83   #define PRIszd    "Id"
84   #define PRIpdx    "Ix"
85   #define PRIpdu    "Iu"
86   #define PRIpdd    "Id"
87 #else /* C99 standard */
88   #define PRIszx    "zx"
89   #define PRIszu    "zu"
90   #define PRIszd    "zd"
91   #define PRIpdx    "tx"
92   #define PRIpdu    "tu"
93   #define PRIpdd    "td"
94 #endif
95
96 // This is needed because the foreach macro can't get over the comma in pair<t1, t2>
97 #define PAIRTYPE(t1, t2)    std::pair<t1, t2>
98
99 // Align by increasing pointer, must have extra space at end of buffer
100 template <size_t nBytes, typename T>
101 T* alignup(T* p)
102 {
103     union
104     {
105         T* ptr;
106         size_t n;
107     } u;
108     u.ptr = p;
109     u.n = (u.n + (nBytes-1)) & ~(nBytes-1);
110     return u.ptr;
111 }
112
113 #ifdef WIN32
114 #define MSG_NOSIGNAL        0
115 #define MSG_DONTWAIT        0
116
117 #ifndef S_IRUSR
118 #define S_IRUSR             0400
119 #define S_IWUSR             0200
120 #endif
121 #else
122 #define MAX_PATH            1024
123 inline void Sleep(int64_t n)
124 {
125     /*Boost has a year 2038 problem— if the request sleep time is past epoch+2^31 seconds the sleep returns instantly.
126       So we clamp our sleeps here to 10 years and hope that boost is fixed by 2028.*/
127     boost::thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(n>315576000000LL?315576000000LL:n));
128 }
129 #endif
130
131 /* This GNU C extension enables the compiler to check the format string against the parameters provided.
132  * X is the number of the "format string" parameter, and Y is the number of the first variadic parameter.
133  * Parameters count from 1.
134  */
135 #ifdef __GNUC__
136 #define ATTR_WARN_PRINTF(X,Y) __attribute__((format(printf,X,Y)))
137 #else
138 #define ATTR_WARN_PRINTF(X,Y)
139 #endif
140
141
142
143
144
145
146
147
148 extern std::map<std::string, std::string> mapArgs;
149 extern std::map<std::string, std::vector<std::string> > mapMultiArgs;
150 extern bool fDebug;
151 extern bool fDebugNet;
152 extern bool fPrintToConsole;
153 extern bool fPrintToDebugger;
154 extern bool fRequestShutdown;
155 extern bool fShutdown;
156 extern bool fDaemon;
157 extern bool fServer;
158 extern bool fCommandLine;
159 extern std::string strMiscWarning;
160 extern bool fTestNet;
161 extern bool fNoListen;
162 extern bool fLogTimestamps;
163 extern bool fReopenDebugLog;
164
165 void RandAddSeed();
166 void RandAddSeedPerfmon();
167 int ATTR_WARN_PRINTF(1,2) OutputDebugStringF(const char* pszFormat, ...);
168
169 /*
170   Rationale for the real_strprintf / strprintf construction:
171     It is not allowed to use va_start with a pass-by-reference argument.
172     (C++ standard, 18.7, paragraph 3). Use a dummy argument to work around this, and use a
173     macro to keep similar semantics.
174 */
175
176 /** Overload strprintf for char*, so that GCC format type warnings can be given */
177 std::string ATTR_WARN_PRINTF(1,3) real_strprintf(const char *format, int dummy, ...);
178 /** Overload strprintf for std::string, to be able to use it with _ (translation).
179  * This will not support GCC format type warnings (-Wformat) so be careful.
180  */
181 std::string real_strprintf(const std::string &format, int dummy, ...);
182 #define strprintf(format, ...) real_strprintf(format, 0, __VA_ARGS__)
183 std::string vstrprintf(const char *format, va_list ap);
184
185 bool ATTR_WARN_PRINTF(1,2) error(const char *format, ...);
186
187 /* Redefine printf so that it directs output to debug.log
188  *
189  * Do this *after* defining the other printf-like functions, because otherwise the
190  * __attribute__((format(printf,X,Y))) gets expanded to __attribute__((format(OutputDebugStringF,X,Y)))
191  * which confuses gcc.
192  */
193 #define printf OutputDebugStringF
194
195 void LogException(std::exception* pex, const char* pszThread);
196 void PrintException(std::exception* pex, const char* pszThread);
197 void PrintExceptionContinue(std::exception* pex, const char* pszThread);
198 void ParseString(const std::string& str, char c, std::vector<std::string>& v);
199 std::string FormatMoney(int64_t n, bool fPlus=false);
200 bool ParseMoney(const std::string& str, int64_t& nRet);
201 bool ParseMoney(const char* pszIn, int64_t& nRet);
202 std::vector<unsigned char> ParseHex(const char* psz);
203 std::vector<unsigned char> ParseHex(const std::string& str);
204 bool IsHex(const std::string& str);
205 std::vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid = NULL);
206 std::string DecodeBase64(const std::string& str);
207 std::string EncodeBase64(const unsigned char* pch, size_t len);
208 std::string EncodeBase64(const std::string& str);
209 std::vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid = NULL);
210 std::string DecodeBase32(const std::string& str);
211 std::string EncodeBase32(const unsigned char* pch, size_t len);
212 std::string EncodeBase32(const std::string& str);
213 std::string EncodeDumpTime(int64_t nTime);
214 int64_t DecodeDumpTime(const std::string& s);
215 std::string EncodeDumpString(const std::string &str);
216 std::string DecodeDumpString(const std::string &str);
217 void ParseParameters(int argc, const char*const argv[]);
218 bool WildcardMatch(const char* psz, const char* mask);
219 bool WildcardMatch(const std::string& str, const std::string& mask);
220 void FileCommit(FILE *fileout);
221 int GetFilesize(FILE* file);
222 bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest);
223 boost::filesystem::path GetDefaultDataDir();
224 const boost::filesystem::path &GetDataDir(bool fNetSpecific = true);
225 boost::filesystem::path GetConfigFile();
226 boost::filesystem::path GetPidFile();
227 #ifndef WIN32
228 void CreatePidFile(const boost::filesystem::path &path, pid_t pid);
229 #endif
230 void ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet, std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet);
231 #ifdef WIN32
232 boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate = true);
233 #endif
234 void ShrinkDebugFile();
235 int GetRandInt(int nMax);
236 uint64_t GetRand(uint64_t nMax);
237 int64_t GetTime();
238 int64_t GetTimeMillis();
239 int64_t GetTimeMicros();
240
241 int64_t GetAdjustedTime();
242 int64_t GetTimeOffset();
243 int64_t GetNodesOffset();
244 std::string FormatFullVersion();
245 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments);
246 void AddTimeData(const CNetAddr& ip, int64_t nTime);
247 void runCommand(std::string strCommand);
248
249
250
251
252
253
254
255
256
257 inline std::string i64tostr(int64_t n)
258 {
259     return strprintf("%" PRId64, n);
260 }
261
262 inline std::string itostr(int n)
263 {
264     return strprintf("%d", n);
265 }
266
267 inline int64_t atoi64(const char* psz)
268 {
269 #ifdef _MSC_VER
270     return _atoi64(psz);
271 #else
272     return strtoll(psz, NULL, 10);
273 #endif
274 }
275
276 inline int64_t atoi64(const std::string& str)
277 {
278 #ifdef _MSC_VER
279     return _atoi64(str.c_str());
280 #else
281     return strtoll(str.c_str(), NULL, 10);
282 #endif
283 }
284
285 inline int32_t strtol(const char* psz)
286 {
287     return strtol(psz, NULL, 10);
288 }
289
290 inline int32_t strtol(const std::string& str)
291 {
292     return strtol(str.c_str(), NULL, 10);
293 }
294
295 inline uint32_t strtoul(const char* psz)
296 {
297     return strtoul(psz, NULL, 10);
298 }
299
300 inline uint32_t strtoul(const std::string& str)
301 {
302     return strtoul(str.c_str(), NULL, 10);
303 }
304
305 inline int atoi(const std::string& str)
306 {
307     return atoi(str.c_str());
308 }
309
310 inline int roundint(double d)
311 {
312     return (int)(d > 0 ? d + 0.5 : d - 0.5);
313 }
314
315 inline int64_t roundint64(double d)
316 {
317     return (int64_t)(d > 0 ? d + 0.5 : d - 0.5);
318 }
319
320 inline int64_t abs64(int64_t n)
321 {
322     return (n >= 0 ? n : -n);
323 }
324
325 inline std::string leftTrim(std::string src, char chr)
326 {
327     std::string::size_type pos = src.find_first_not_of(chr, 0);
328
329     if(pos > 0)
330         src.erase(0, pos);
331
332     return src;
333 }
334
335 template<typename T>
336 std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
337 {
338     std::string rv;
339     static const char hexmap[16] = { '0', '1', '2', '3', '4', '5', '6', '7',
340                                      '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
341     rv.reserve((itend-itbegin)*3);
342     for(T it = itbegin; it < itend; ++it)
343     {
344         unsigned char val = (unsigned char)(*it);
345         if(fSpaces && it != itbegin)
346             rv.push_back(' ');
347         rv.push_back(hexmap[val>>4]);
348         rv.push_back(hexmap[val&15]);
349     }
350
351     return rv;
352 }
353
354 inline std::string HexStr(const std::vector<unsigned char>& vch, bool fSpaces=false)
355 {
356     return HexStr(vch.begin(), vch.end(), fSpaces);
357 }
358
359 template<typename T>
360 void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)
361 {
362     printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());
363 }
364
365 inline void PrintHex(const std::vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true)
366 {
367     printf(pszFormat, HexStr(vch, fSpaces).c_str());
368 }
369
370 inline int64_t GetPerformanceCounter()
371 {
372     int64_t nCounter = 0;
373 #ifdef WIN32
374     QueryPerformanceCounter((LARGE_INTEGER*)&nCounter);
375 #else
376     timeval t;
377     gettimeofday(&t, NULL);
378     nCounter = (int64_t) t.tv_sec * 1000000 + t.tv_usec;
379 #endif
380     return nCounter;
381 }
382
383 inline int64_t GetTimeMillis()
384 {
385     return (boost::posix_time::microsec_clock::universal_time() -
386             boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
387 }
388
389 inline int64_t GetTimeMicros()
390 {
391     return (boost::posix_time::microsec_clock::universal_time() -
392                    boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_microseconds();
393 }
394
395 std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime);
396
397 static const std::string strTimestampFormat = "%Y-%m-%d %H:%M:%S UTC";
398 inline std::string DateTimeStrFormat(int64_t nTime)
399 {
400     return DateTimeStrFormat(strTimestampFormat.c_str(), nTime);
401 }
402
403
404 template<typename T>
405 void skipspaces(T& it)
406 {
407     while (isspace(*it))
408         ++it;
409 }
410
411 inline bool IsSwitchChar(char c)
412 {
413 #ifdef WIN32
414     return c == '-' || c == '/';
415 #else
416     return c == '-';
417 #endif
418 }
419
420 /**
421  * Return string argument or default value
422  *
423  * @param strArg Argument to get (e.g. "-foo")
424  * @param default (e.g. "1")
425  * @return command-line argument or default value
426  */
427 std::string GetArg(const std::string& strArg, const std::string& strDefault);
428
429 /**
430  * Return 64-bit integer argument or default value
431  *
432  * @param strArg Argument to get (e.g. "-foo")
433  * @param default (e.g. 1)
434  * @return command-line argument (0 if invalid number) or default value
435  */
436 int64_t GetArg(const std::string& strArg, int64_t nDefault);
437
438 /**
439  * Return 32-bit integer argument or default value
440  *
441  * @param strArg Argument to get (e.g. "-foo")
442  * @param default (e.g. 1)
443  * @return command-line argument (0 if invalid number) or default value
444  */
445 int32_t GetArgInt(const std::string& strArg, int32_t nDefault);
446
447 /**
448  * Return 32-bit unsigned integer argument or default value
449  *
450  * @param strArg Argument to get (e.g. "-foo")
451  * @param default (e.g. 1)
452  * @return command-line argument (0 if invalid number) or default value
453  */
454 uint32_t GetArgUInt(const std::string& strArg, uint32_t nDefault);
455
456 /**
457  * Return boolean argument or default value
458  *
459  * @param strArg Argument to get (e.g. "-foo")
460  * @param default (true or false)
461  * @return command-line argument or default value
462  */
463 bool GetBoolArg(const std::string& strArg, bool fDefault=false);
464
465 /**
466  * Set an argument if it doesn't already have a value
467  *
468  * @param strArg Argument to set (e.g. "-foo")
469  * @param strValue Value (e.g. "1")
470  * @return true if argument gets set, false if it already had a value
471  */
472 bool SoftSetArg(const std::string& strArg, const std::string& strValue);
473
474 /**
475  * Set a boolean argument if it doesn't already have a value
476  *
477  * @param strArg Argument to set (e.g. "-foo")
478  * @param fValue Value (e.g. false)
479  * @return true if argument gets set, false if it already had a value
480  */
481 bool SoftSetBoolArg(const std::string& strArg, bool fValue);
482
483 /**
484  * Timing-attack-resistant comparison.
485  * Takes time proportional to length
486  * of first argument.
487  */
488 template <typename T>
489 bool TimingResistantEqual(const T& a, const T& b)
490 {
491     if (b.size() == 0) return a.size() == 0;
492     size_t accumulator = a.size() ^ b.size();
493     for (size_t i = 0; i < a.size(); i++)
494         accumulator |= a[i] ^ b[i%b.size()];
495     return accumulator == 0;
496 }
497
498 /** Median filter over a stream of values.
499  * Returns the median of the last N numbers
500  */
501 template <typename T> class CMedianFilter
502 {
503 private:
504     std::vector<T> vValues;
505     std::vector<T> vSorted;
506     unsigned int nSize;
507 public:
508     CMedianFilter(unsigned int size, T initial_value):
509         nSize(size)
510     {
511         vValues.reserve(size);
512         vValues.push_back(initial_value);
513         vSorted = vValues;
514     }
515
516     void input(T value)
517     {
518         if(vValues.size() == nSize)
519         {
520             vValues.erase(vValues.begin());
521         }
522         vValues.push_back(value);
523
524         vSorted.resize(vValues.size());
525         std::copy(vValues.begin(), vValues.end(), vSorted.begin());
526         std::sort(vSorted.begin(), vSorted.end());
527     }
528
529     T median() const
530     {
531         size_t size = vSorted.size();
532         assert(size>0);
533         if(size & 1) // Odd number of elements
534         {
535             return vSorted[size/2];
536         }
537         else // Even number of elements
538         {
539             return (vSorted[size/2-1] + vSorted[size/2]) / 2;
540         }
541     }
542
543     int size() const
544     {
545         return static_cast<int>(vValues.size());
546     }
547
548     std::vector<T> sorted () const
549     {
550         return vSorted;
551     }
552 };
553
554 bool NewThread(void(*pfn)(void*), void* parg);
555
556 #ifdef WIN32
557 inline void SetThreadPriority(int nPriority)
558 {
559     SetThreadPriority(GetCurrentThread(), nPriority);
560 }
561 #else
562
563 #define THREAD_PRIORITY_LOWEST          PRIO_MAX
564 #define THREAD_PRIORITY_BELOW_NORMAL    2
565 #define THREAD_PRIORITY_NORMAL          0
566 #define THREAD_PRIORITY_ABOVE_NORMAL    0
567
568 inline void SetThreadPriority(int nPriority)
569 {
570     // It's unclear if it's even possible to change thread priorities on Linux,
571     // but we really and truly need it for the generation threads.
572 #ifdef PRIO_THREAD
573     setpriority(PRIO_THREAD, 0, nPriority);
574 #else
575     setpriority(PRIO_PROCESS, 0, nPriority);
576 #endif
577 }
578
579 inline void ExitThread(size_t nExitCode)
580 {
581     pthread_exit((void*)nExitCode);
582 }
583 #endif
584
585 void RenameThread(const char* name);
586
587 inline uint32_t ByteReverse(uint32_t value)
588 {
589     value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8);
590     return (value<<16) | (value>>16);
591 }
592
593 #endif
594