Resolves issue #922 - "wallet passphrase timeout of several years doesn't work"
[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 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 #ifndef WIN32
11 #include <sys/types.h>
12 #include <sys/time.h>
13 #include <sys/resource.h>
14 #endif
15 #include <map>
16 #include <vector>
17 #include <string>
18
19 #include <boost/thread.hpp>
20 #include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>
21 #include <boost/date_time/gregorian/gregorian_types.hpp>
22 #include <boost/date_time/posix_time/posix_time_types.hpp>
23
24 #include <openssl/sha.h>
25 #include <openssl/ripemd.h>
26
27 #include "netbase.h"
28
29 typedef long long  int64;
30 typedef unsigned long long  uint64;
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 #if defined(_MSC_VER) || defined(__MSVCRT__)
47 #define PRI64d  "I64d"
48 #define PRI64u  "I64u"
49 #define PRI64x  "I64x"
50 #else
51 #define PRI64d  "lld"
52 #define PRI64u  "llu"
53 #define PRI64x  "llx"
54 #endif
55 #endif
56
57 // This is needed because the foreach macro can't get over the comma in pair<t1, t2>
58 #define PAIRTYPE(t1, t2)    std::pair<t1, t2>
59
60 // Align by increasing pointer, must have extra space at end of buffer
61 template <size_t nBytes, typename T>
62 T* alignup(T* p)
63 {
64     union
65     {
66         T* ptr;
67         size_t n;
68     } u;
69     u.ptr = p;
70     u.n = (u.n + (nBytes-1)) & ~(nBytes-1);
71     return u.ptr;
72 }
73
74 #ifdef WIN32
75 #define MSG_NOSIGNAL        0
76 #define MSG_DONTWAIT        0
77
78 #ifndef S_IRUSR
79 #define S_IRUSR             0400
80 #define S_IWUSR             0200
81 #endif
82 #define unlink              _unlink
83 #else
84 #define _vsnprintf(a,b,c,d) vsnprintf(a,b,c,d)
85 #define strlwr(psz)         to_lower(psz)
86 #define _strlwr(psz)        to_lower(psz)
87 #define MAX_PATH            1024
88 #define Beep(n1,n2)         (0)
89 inline void Sleep(int64 n)
90 {
91     /*Boost has a year 2038 problem— if the request sleep time is past epoch+2^31 seconds the sleep returns instantly.
92       So we clamp our sleeps here to 10 years and hope that boost is fixed by 2028.*/
93     boost::thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(n>315576000000LL?315576000000LL:n));
94 }
95 #endif
96
97 #if !defined(QT_GUI)
98 inline const char* _(const char* psz)
99 {
100     return psz;
101 }
102 #endif
103
104
105
106
107
108
109
110
111
112 extern std::map<std::string, std::string> mapArgs;
113 extern std::map<std::string, std::vector<std::string> > mapMultiArgs;
114 extern bool fDebug;
115 extern bool fPrintToConsole;
116 extern bool fPrintToDebugger;
117 extern char pszSetDataDir[MAX_PATH];
118 extern bool fRequestShutdown;
119 extern bool fShutdown;
120 extern bool fDaemon;
121 extern bool fServer;
122 extern bool fCommandLine;
123 extern std::string strMiscWarning;
124 extern bool fTestNet;
125 extern bool fNoListen;
126 extern bool fLogTimestamps;
127
128 void RandAddSeed();
129 void RandAddSeedPerfmon();
130 int OutputDebugStringF(const char* pszFormat, ...);
131 int my_snprintf(char* buffer, size_t limit, const char* format, ...);
132 std::string strprintf(const std::string &format, ...);
133 bool error(const std::string &format, ...);
134 void LogException(std::exception* pex, const char* pszThread);
135 void PrintException(std::exception* pex, const char* pszThread);
136 void PrintExceptionContinue(std::exception* pex, const char* pszThread);
137 void ParseString(const std::string& str, char c, std::vector<std::string>& v);
138 std::string FormatMoney(int64 n, bool fPlus=false);
139 bool ParseMoney(const std::string& str, int64& nRet);
140 bool ParseMoney(const char* pszIn, int64& nRet);
141 std::vector<unsigned char> ParseHex(const char* psz);
142 std::vector<unsigned char> ParseHex(const std::string& str);
143 bool IsHex(const std::string& str);
144 std::vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid = NULL);
145 std::string DecodeBase64(const std::string& str);
146 std::string EncodeBase64(const unsigned char* pch, size_t len);
147 std::string EncodeBase64(const std::string& str);
148 void ParseParameters(int argc, const char*const argv[]);
149 bool WildcardMatch(const char* psz, const char* mask);
150 bool WildcardMatch(const std::string& str, const std::string& mask);
151 int GetFilesize(FILE* file);
152 void GetDataDir(char* pszDirRet);
153 std::string GetConfigFile();
154 std::string GetPidFile();
155 void CreatePidFile(std::string pidFile, pid_t pid);
156 bool ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet, std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet);
157 #ifdef WIN32
158 std::string MyGetSpecialFolderPath(int nFolder, bool fCreate);
159 #endif
160 std::string GetDefaultDataDir();
161 std::string GetDataDir();
162 void ShrinkDebugFile();
163 int GetRandInt(int nMax);
164 uint64 GetRand(uint64 nMax);
165 int64 GetTime();
166 void SetMockTime(int64 nMockTimeIn);
167 int64 GetAdjustedTime();
168 std::string FormatFullVersion();
169 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments);
170 void AddTimeData(const CNetAddr& ip, int64 nTime);
171
172
173
174
175
176
177
178
179
180
181
182
183 // Wrapper to automatically initialize mutex
184 class CCriticalSection
185 {
186 protected:
187     boost::interprocess::interprocess_recursive_mutex mutex;
188 public:
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
197 class CCriticalBlock
198 {
199 protected:
200     CCriticalSection* pcs;
201
202 public:
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
229 class CTryCriticalBlock
230 {
231 protected:
232     CCriticalSection* pcs;
233
234 public:
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)
265 typedef std::basic_string<char, std::char_traits<char>, secure_allocator<char> > SecureString;
266
267
268
269
270
271 inline std::string i64tostr(int64 n)
272 {
273     return strprintf("%"PRI64d, n);
274 }
275
276 inline std::string itostr(int n)
277 {
278     return strprintf("%d", n);
279 }
280
281 inline int64 atoi64(const char* psz)
282 {
283 #ifdef _MSC_VER
284     return _atoi64(psz);
285 #else
286     return strtoll(psz, NULL, 10);
287 #endif
288 }
289
290 inline int64 atoi64(const std::string& str)
291 {
292 #ifdef _MSC_VER
293     return _atoi64(str.c_str());
294 #else
295     return strtoll(str.c_str(), NULL, 10);
296 #endif
297 }
298
299 inline int atoi(const std::string& str)
300 {
301     return atoi(str.c_str());
302 }
303
304 inline int roundint(double d)
305 {
306     return (int)(d > 0 ? d + 0.5 : d - 0.5);
307 }
308
309 inline int64 roundint64(double d)
310 {
311     return (int64)(d > 0 ? d + 0.5 : d - 0.5);
312 }
313
314 inline int64 abs64(int64 n)
315 {
316     return (n >= 0 ? n : -n);
317 }
318
319 template<typename T>
320 std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
321 {
322     if (itbegin == itend)
323         return "";
324     const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
325     const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
326     std::string str;
327     str.reserve((pend-pbegin) * (fSpaces ? 3 : 2));
328     for (const unsigned char* p = pbegin; p != pend; p++)
329         str += strprintf((fSpaces && p != pend-1 ? "%02x " : "%02x"), *p);
330     return str;
331 }
332
333 inline std::string HexStr(const std::vector<unsigned char>& vch, bool fSpaces=false)
334 {
335     return HexStr(vch.begin(), vch.end(), fSpaces);
336 }
337
338 template<typename T>
339 std::string HexNumStr(const T itbegin, const T itend, bool f0x=true)
340 {
341     if (itbegin == itend)
342         return "";
343     const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
344     const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
345     std::string str = (f0x ? "0x" : "");
346     str.reserve(str.size() + (pend-pbegin) * 2);
347     for (const unsigned char* p = pend-1; p >= pbegin; p--)
348         str += strprintf("%02x", *p);
349     return str;
350 }
351
352 inline std::string HexNumStr(const std::vector<unsigned char>& vch, bool f0x=true)
353 {
354     return HexNumStr(vch.begin(), vch.end(), f0x);
355 }
356
357 template<typename T>
358 void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)
359 {
360     printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());
361 }
362
363 inline void PrintHex(const std::vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true)
364 {
365     printf(pszFormat, HexStr(vch, fSpaces).c_str());
366 }
367
368 inline int64 GetPerformanceCounter()
369 {
370     int64 nCounter = 0;
371 #ifdef WIN32
372     QueryPerformanceCounter((LARGE_INTEGER*)&nCounter);
373 #else
374     timeval t;
375     gettimeofday(&t, NULL);
376     nCounter = t.tv_sec * 1000000 + t.tv_usec;
377 #endif
378     return nCounter;
379 }
380
381 inline int64 GetTimeMillis()
382 {
383     return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) -
384             boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
385 }
386
387 inline std::string DateTimeStrFormat(const char* pszFormat, int64 nTime)
388 {
389     time_t n = nTime;
390     struct tm* ptmTime = gmtime(&n);
391     char pszTime[200];
392     strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime);
393     return pszTime;
394 }
395
396 template<typename T>
397 void skipspaces(T& it)
398 {
399     while (isspace(*it))
400         ++it;
401 }
402
403 inline bool IsSwitchChar(char c)
404 {
405 #ifdef WIN32
406     return c == '-' || c == '/';
407 #else
408     return c == '-';
409 #endif
410 }
411
412 /**
413  * Return string argument or default value
414  *
415  * @param strArg Argument to get (e.g. "-foo")
416  * @param default (e.g. "1")
417  * @return command-line argument or default value
418  */
419 std::string GetArg(const std::string& strArg, const std::string& strDefault);
420
421 /**
422  * Return integer argument or default value
423  *
424  * @param strArg Argument to get (e.g. "-foo")
425  * @param default (e.g. 1)
426  * @return command-line argument (0 if invalid number) or default value
427  */
428 int64 GetArg(const std::string& strArg, int64 nDefault);
429
430 /**
431  * Return boolean argument or default value
432  *
433  * @param strArg Argument to get (e.g. "-foo")
434  * @param default (true or false)
435  * @return command-line argument or default value
436  */
437 bool GetBoolArg(const std::string& strArg, bool fDefault=false);
438
439 /**
440  * Set an argument if it doesn't already have a value
441  *
442  * @param strArg Argument to set (e.g. "-foo")
443  * @param strValue Value (e.g. "1")
444  * @return true if argument gets set, false if it already had a value
445  */
446 bool SoftSetArg(const std::string& strArg, const std::string& strValue);
447
448 /**
449  * Set a boolean argument if it doesn't already have a value
450  *
451  * @param strArg Argument to set (e.g. "-foo")
452  * @param fValue Value (e.g. false)
453  * @return true if argument gets set, false if it already had a value
454  */
455 bool SoftSetBoolArg(const std::string& strArg, bool fValue);
456
457
458
459
460
461
462
463
464
465 // Randomize the stack to help protect against buffer overrun exploits
466 #define IMPLEMENT_RANDOMIZE_STACK(ThreadFn)     \
467     {                                           \
468         static char nLoops;                     \
469         if (nLoops <= 0)                        \
470             nLoops = GetRand(20) + 1;           \
471         if (nLoops-- > 1)                       \
472         {                                       \
473             ThreadFn;                           \
474             return;                             \
475         }                                       \
476     }
477
478 #define CATCH_PRINT_EXCEPTION(pszFn)     \
479     catch (std::exception& e) {          \
480         PrintException(&e, (pszFn));     \
481     } catch (...) {                      \
482         PrintException(NULL, (pszFn));   \
483     }
484
485
486
487
488
489
490
491
492
493
494 template<typename T1>
495 inline uint256 Hash(const T1 pbegin, const T1 pend)
496 {
497     static unsigned char pblank[1];
498     uint256 hash1;
499     SHA256((pbegin == pend ? pblank : (unsigned char*)&pbegin[0]), (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);
500     uint256 hash2;
501     SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
502     return hash2;
503 }
504
505 template<typename T1, typename T2>
506 inline uint256 Hash(const T1 p1begin, const T1 p1end,
507                     const T2 p2begin, const T2 p2end)
508 {
509     static unsigned char pblank[1];
510     uint256 hash1;
511     SHA256_CTX ctx;
512     SHA256_Init(&ctx);
513     SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
514     SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
515     SHA256_Final((unsigned char*)&hash1, &ctx);
516     uint256 hash2;
517     SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
518     return hash2;
519 }
520
521 template<typename T1, typename T2, typename T3>
522 inline uint256 Hash(const T1 p1begin, const T1 p1end,
523                     const T2 p2begin, const T2 p2end,
524                     const T3 p3begin, const T3 p3end)
525 {
526     static unsigned char pblank[1];
527     uint256 hash1;
528     SHA256_CTX ctx;
529     SHA256_Init(&ctx);
530     SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
531     SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
532     SHA256_Update(&ctx, (p3begin == p3end ? pblank : (unsigned char*)&p3begin[0]), (p3end - p3begin) * sizeof(p3begin[0]));
533     SHA256_Final((unsigned char*)&hash1, &ctx);
534     uint256 hash2;
535     SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
536     return hash2;
537 }
538
539 template<typename T>
540 uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=PROTOCOL_VERSION)
541 {
542     // Most of the time is spent allocating and deallocating CDataStream's
543     // buffer.  If this ever needs to be optimized further, make a CStaticStream
544     // class with its buffer on the stack.
545     CDataStream ss(nType, nVersion);
546     ss.reserve(10000);
547     ss << obj;
548     return Hash(ss.begin(), ss.end());
549 }
550
551 inline uint160 Hash160(const std::vector<unsigned char>& vch)
552 {
553     uint256 hash1;
554     SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);
555     uint160 hash2;
556     RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
557     return hash2;
558 }
559
560
561 // Median filter over a stream of values
562 // Returns the median of the last N numbers
563 template <typename T> class CMedianFilter
564 {
565 private:
566     std::vector<T> vValues;
567     std::vector<T> vSorted;
568     int nSize;
569 public:
570     CMedianFilter(int size, T initial_value):
571         nSize(size)
572     {
573         vValues.reserve(size);
574         vValues.push_back(initial_value);
575         vSorted = vValues;
576     }
577     
578     void input(T value)
579     {
580         if(vValues.size() == nSize)
581         {
582             vValues.erase(vValues.begin());
583         }
584         vValues.push_back(value);
585
586         vSorted.resize(vValues.size());
587         std::copy(vValues.begin(), vValues.end(), vSorted.begin());
588         std::sort(vSorted.begin(), vSorted.end());
589     }
590
591     T median() const
592     {
593         int size = vSorted.size();
594         assert(size>0);
595         if(size & 1) // Odd number of elements
596         {
597             return vSorted[size/2];
598         }
599         else // Even number of elements
600         {
601             return (vSorted[size/2-1] + vSorted[size/2]) / 2;
602         }
603     }
604
605     int size() const
606     {
607         return vValues.size();
608     }
609
610     std::vector<T> sorted () const
611     {
612         return vSorted;
613     }
614 };
615
616
617
618
619
620
621
622
623
624
625 // Note: It turns out we might have been able to use boost::thread
626 // by using TerminateThread(boost::thread.native_handle(), 0);
627 #ifdef WIN32
628 typedef HANDLE pthread_t;
629
630 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
631 {
632     DWORD nUnused = 0;
633     HANDLE hthread =
634         CreateThread(
635             NULL,                        // default security
636             0,                           // inherit stack size from parent
637             (LPTHREAD_START_ROUTINE)pfn, // function pointer
638             parg,                        // argument
639             0,                           // creation option, start immediately
640             &nUnused);                   // thread identifier
641     if (hthread == NULL)
642     {
643         printf("Error: CreateThread() returned %d\n", GetLastError());
644         return (pthread_t)0;
645     }
646     if (!fWantHandle)
647     {
648         CloseHandle(hthread);
649         return (pthread_t)-1;
650     }
651     return hthread;
652 }
653
654 inline void SetThreadPriority(int nPriority)
655 {
656     SetThreadPriority(GetCurrentThread(), nPriority);
657 }
658 #else
659 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
660 {
661     pthread_t hthread = 0;
662     int ret = pthread_create(&hthread, NULL, (void*(*)(void*))pfn, parg);
663     if (ret != 0)
664     {
665         printf("Error: pthread_create() returned %d\n", ret);
666         return (pthread_t)0;
667     }
668     if (!fWantHandle)
669     {
670         pthread_detach(hthread);
671         return (pthread_t)-1;
672     }
673     return hthread;
674 }
675
676 #define THREAD_PRIORITY_LOWEST          PRIO_MAX
677 #define THREAD_PRIORITY_BELOW_NORMAL    2
678 #define THREAD_PRIORITY_NORMAL          0
679 #define THREAD_PRIORITY_ABOVE_NORMAL    0
680
681 inline void SetThreadPriority(int nPriority)
682 {
683     // It's unclear if it's even possible to change thread priorities on Linux,
684     // but we really and truly need it for the generation threads.
685 #ifdef PRIO_THREAD
686     setpriority(PRIO_THREAD, 0, nPriority);
687 #else
688     setpriority(PRIO_PROCESS, 0, nPriority);
689 #endif
690 }
691
692 inline bool TerminateThread(pthread_t hthread, unsigned int nExitCode)
693 {
694     return (pthread_cancel(hthread) == 0);
695 }
696
697 inline void ExitThread(size_t nExitCode)
698 {
699     pthread_exit((void*)nExitCode);
700 }
701 #endif
702
703
704
705
706
707 inline bool AffinityBugWorkaround(void(*pfn)(void*))
708 {
709 #ifdef WIN32
710     // Sometimes after a few hours affinity gets stuck on one processor
711     DWORD_PTR dwProcessAffinityMask = -1;
712     DWORD_PTR dwSystemAffinityMask = -1;
713     GetProcessAffinityMask(GetCurrentProcess(), &dwProcessAffinityMask, &dwSystemAffinityMask);
714     DWORD dwPrev1 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
715     DWORD dwPrev2 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
716     if (dwPrev2 != dwProcessAffinityMask)
717     {
718         printf("AffinityBugWorkaround() : SetThreadAffinityMask=%d, ProcessAffinityMask=%d, restarting thread\n", dwPrev2, dwProcessAffinityMask);
719         if (!CreateThread(pfn, NULL))
720             printf("Error: CreateThread() failed\n");
721         return true;
722     }
723 #endif
724     return false;
725 }
726
727 inline uint32_t ByteReverse(uint32_t value)
728 {
729     value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8);
730     return (value<<16) | (value>>16);
731 }
732
733 #endif
734