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