Network stack refactor
[novacoin.git] / src / util.h
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 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::thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(n));
92 }
93 #endif
94
95 #if !defined(QT_GUI)
96 inline const char* _(const char* psz)
97 {
98     return psz;
99 }
100 #endif
101
102
103
104
105
106
107
108
109
110 extern std::map<std::string, std::string> mapArgs;
111 extern std::map<std::string, std::vector<std::string> > mapMultiArgs;
112 extern bool fDebug;
113 extern bool fPrintToConsole;
114 extern bool fPrintToDebugger;
115 extern char pszSetDataDir[MAX_PATH];
116 extern bool fRequestShutdown;
117 extern bool fShutdown;
118 extern bool fDaemon;
119 extern bool fServer;
120 extern bool fCommandLine;
121 extern std::string strMiscWarning;
122 extern bool fTestNet;
123 extern bool fNoListen;
124 extern bool fLogTimestamps;
125
126 void RandAddSeed();
127 void RandAddSeedPerfmon();
128 int OutputDebugStringF(const char* pszFormat, ...);
129 int my_snprintf(char* buffer, size_t limit, const char* format, ...);
130 std::string strprintf(const std::string &format, ...);
131 bool error(const std::string &format, ...);
132 void LogException(std::exception* pex, const char* pszThread);
133 void PrintException(std::exception* pex, const char* pszThread);
134 void PrintExceptionContinue(std::exception* pex, const char* pszThread);
135 void ParseString(const std::string& str, char c, std::vector<std::string>& v);
136 std::string FormatMoney(int64 n, bool fPlus=false);
137 bool ParseMoney(const std::string& str, int64& nRet);
138 bool ParseMoney(const char* pszIn, int64& nRet);
139 std::vector<unsigned char> ParseHex(const char* psz);
140 std::vector<unsigned char> ParseHex(const std::string& str);
141 std::vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid = NULL);
142 std::string DecodeBase64(const std::string& str);
143 std::string EncodeBase64(const unsigned char* pch, size_t len);
144 std::string EncodeBase64(const std::string& str);
145 void ParseParameters(int argc, char* argv[]);
146 bool WildcardMatch(const char* psz, const char* mask);
147 bool WildcardMatch(const std::string& str, const std::string& mask);
148 int GetFilesize(FILE* file);
149 void GetDataDir(char* pszDirRet);
150 std::string GetConfigFile();
151 std::string GetPidFile();
152 void CreatePidFile(std::string pidFile, pid_t pid);
153 void ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet, std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet);
154 #ifdef WIN32
155 std::string MyGetSpecialFolderPath(int nFolder, bool fCreate);
156 #endif
157 std::string GetDefaultDataDir();
158 std::string GetDataDir();
159 void ShrinkDebugFile();
160 int GetRandInt(int nMax);
161 uint64 GetRand(uint64 nMax);
162 int64 GetTime();
163 void SetMockTime(int64 nMockTimeIn);
164 int64 GetAdjustedTime();
165 std::string FormatFullVersion();
166 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments);
167 void AddTimeData(const CNetAddr& ip, int64 nTime);
168
169
170
171
172
173
174
175
176
177
178
179
180 // Wrapper to automatically initialize mutex
181 class CCriticalSection
182 {
183 protected:
184     boost::interprocess::interprocess_recursive_mutex mutex;
185 public:
186     explicit CCriticalSection() { }
187     ~CCriticalSection() { }
188     void Enter(const char* pszName, const char* pszFile, int nLine);
189     void Leave();
190     bool TryEnter(const char* pszName, const char* pszFile, int nLine);
191 };
192
193 // Automatically leave critical section when leaving block, needed for exception safety
194 class CCriticalBlock
195 {
196 protected:
197     CCriticalSection* pcs;
198
199 public:
200     CCriticalBlock(CCriticalSection& csIn, const char* pszName, const char* pszFile, int nLine)
201     {
202         pcs = &csIn;
203         pcs->Enter(pszName, pszFile, nLine);
204     }
205
206     operator bool() const
207     {
208         return true;
209     }
210
211     ~CCriticalBlock()
212     {
213         pcs->Leave();
214     }
215 };
216
217 #define CRITICAL_BLOCK(cs)     \
218     if (CCriticalBlock criticalblock = CCriticalBlock(cs, #cs, __FILE__, __LINE__))
219
220 class CTryCriticalBlock
221 {
222 protected:
223     CCriticalSection* pcs;
224
225 public:
226     CTryCriticalBlock(CCriticalSection& csIn, const char* pszName, const char* pszFile, int nLine)
227     {
228         pcs = (csIn.TryEnter(pszName, pszFile, nLine) ? &csIn : NULL);
229     }
230
231     operator bool() const
232     {
233         return Entered();
234     }
235
236     ~CTryCriticalBlock()
237     {
238         if (pcs)
239         {
240             pcs->Leave();
241         }
242     }
243     bool Entered() const { return pcs != NULL; }
244 };
245
246 #define TRY_CRITICAL_BLOCK(cs)     \
247     if (CTryCriticalBlock criticalblock = CTryCriticalBlock(cs, #cs, __FILE__, __LINE__))
248
249
250
251
252
253
254 // This is exactly like std::string, but with a custom allocator.
255 // (secure_allocator<> is defined in serialize.h)
256 typedef std::basic_string<char, std::char_traits<char>, secure_allocator<char> > SecureString;
257
258
259
260
261
262 inline std::string i64tostr(int64 n)
263 {
264     return strprintf("%"PRI64d, n);
265 }
266
267 inline std::string itostr(int n)
268 {
269     return strprintf("%d", n);
270 }
271
272 inline int64 atoi64(const char* psz)
273 {
274 #ifdef _MSC_VER
275     return _atoi64(psz);
276 #else
277     return strtoll(psz, NULL, 10);
278 #endif
279 }
280
281 inline int64 atoi64(const std::string& str)
282 {
283 #ifdef _MSC_VER
284     return _atoi64(str.c_str());
285 #else
286     return strtoll(str.c_str(), NULL, 10);
287 #endif
288 }
289
290 inline int atoi(const std::string& str)
291 {
292     return atoi(str.c_str());
293 }
294
295 inline int roundint(double d)
296 {
297     return (int)(d > 0 ? d + 0.5 : d - 0.5);
298 }
299
300 inline int64 roundint64(double d)
301 {
302     return (int64)(d > 0 ? d + 0.5 : d - 0.5);
303 }
304
305 inline int64 abs64(int64 n)
306 {
307     return (n >= 0 ? n : -n);
308 }
309
310 template<typename T>
311 std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
312 {
313     if (itbegin == itend)
314         return "";
315     const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
316     const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
317     std::string str;
318     str.reserve((pend-pbegin) * (fSpaces ? 3 : 2));
319     for (const unsigned char* p = pbegin; p != pend; p++)
320         str += strprintf((fSpaces && p != pend-1 ? "%02x " : "%02x"), *p);
321     return str;
322 }
323
324 inline std::string HexStr(const std::vector<unsigned char>& vch, bool fSpaces=false)
325 {
326     return HexStr(vch.begin(), vch.end(), fSpaces);
327 }
328
329 template<typename T>
330 std::string HexNumStr(const T itbegin, const T itend, bool f0x=true)
331 {
332     if (itbegin == itend)
333         return "";
334     const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
335     const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
336     std::string str = (f0x ? "0x" : "");
337     str.reserve(str.size() + (pend-pbegin) * 2);
338     for (const unsigned char* p = pend-1; p >= pbegin; p--)
339         str += strprintf("%02x", *p);
340     return str;
341 }
342
343 inline std::string HexNumStr(const std::vector<unsigned char>& vch, bool f0x=true)
344 {
345     return HexNumStr(vch.begin(), vch.end(), f0x);
346 }
347
348 template<typename T>
349 void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)
350 {
351     printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());
352 }
353
354 inline void PrintHex(const std::vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true)
355 {
356     printf(pszFormat, HexStr(vch, fSpaces).c_str());
357 }
358
359 inline int64 GetPerformanceCounter()
360 {
361     int64 nCounter = 0;
362 #ifdef WIN32
363     QueryPerformanceCounter((LARGE_INTEGER*)&nCounter);
364 #else
365     timeval t;
366     gettimeofday(&t, NULL);
367     nCounter = t.tv_sec * 1000000 + t.tv_usec;
368 #endif
369     return nCounter;
370 }
371
372 inline int64 GetTimeMillis()
373 {
374     return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) -
375             boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
376 }
377
378 inline std::string DateTimeStrFormat(const char* pszFormat, int64 nTime)
379 {
380     time_t n = nTime;
381     struct tm* ptmTime = gmtime(&n);
382     char pszTime[200];
383     strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime);
384     return pszTime;
385 }
386
387 template<typename T>
388 void skipspaces(T& it)
389 {
390     while (isspace(*it))
391         ++it;
392 }
393
394 inline bool IsSwitchChar(char c)
395 {
396 #ifdef WIN32
397     return c == '-' || c == '/';
398 #else
399     return c == '-';
400 #endif
401 }
402
403 inline 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
410 inline int64 GetArg(const std::string& strArg, int64 nDefault)
411 {
412     if (mapArgs.count(strArg))
413         return atoi64(mapArgs[strArg]);
414     return nDefault;
415 }
416
417 inline 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  */
435 bool 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  */
444 bool SoftSetArg(const std::string& strArg, bool fValue);
445
446
447
448
449
450
451
452
453
454 // Randomize the stack to help protect against buffer overrun exploits
455 #define IMPLEMENT_RANDOMIZE_STACK(ThreadFn)     \
456     {                                           \
457         static char nLoops;                     \
458         if (nLoops <= 0)                        \
459             nLoops = GetRand(20) + 1;           \
460         if (nLoops-- > 1)                       \
461         {                                       \
462             ThreadFn;                           \
463             return;                             \
464         }                                       \
465     }
466
467 #define CATCH_PRINT_EXCEPTION(pszFn)     \
468     catch (std::exception& e) {          \
469         PrintException(&e, (pszFn));     \
470     } catch (...) {                      \
471         PrintException(NULL, (pszFn));   \
472     }
473
474
475
476
477
478
479
480
481
482
483 template<typename T1>
484 inline uint256 Hash(const T1 pbegin, const T1 pend)
485 {
486     static unsigned char pblank[1];
487     uint256 hash1;
488     SHA256((pbegin == pend ? pblank : (unsigned char*)&pbegin[0]), (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);
489     uint256 hash2;
490     SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
491     return hash2;
492 }
493
494 template<typename T1, typename T2>
495 inline uint256 Hash(const T1 p1begin, const T1 p1end,
496                     const T2 p2begin, const T2 p2end)
497 {
498     static unsigned char pblank[1];
499     uint256 hash1;
500     SHA256_CTX ctx;
501     SHA256_Init(&ctx);
502     SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
503     SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
504     SHA256_Final((unsigned char*)&hash1, &ctx);
505     uint256 hash2;
506     SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
507     return hash2;
508 }
509
510 template<typename T1, typename T2, typename T3>
511 inline uint256 Hash(const T1 p1begin, const T1 p1end,
512                     const T2 p2begin, const T2 p2end,
513                     const T3 p3begin, const T3 p3end)
514 {
515     static unsigned char pblank[1];
516     uint256 hash1;
517     SHA256_CTX ctx;
518     SHA256_Init(&ctx);
519     SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
520     SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
521     SHA256_Update(&ctx, (p3begin == p3end ? pblank : (unsigned char*)&p3begin[0]), (p3end - p3begin) * sizeof(p3begin[0]));
522     SHA256_Final((unsigned char*)&hash1, &ctx);
523     uint256 hash2;
524     SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
525     return hash2;
526 }
527
528 template<typename T>
529 uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=PROTOCOL_VERSION)
530 {
531     // Most of the time is spent allocating and deallocating CDataStream's
532     // buffer.  If this ever needs to be optimized further, make a CStaticStream
533     // class with its buffer on the stack.
534     CDataStream ss(nType, nVersion);
535     ss.reserve(10000);
536     ss << obj;
537     return Hash(ss.begin(), ss.end());
538 }
539
540 inline uint160 Hash160(const std::vector<unsigned char>& vch)
541 {
542     uint256 hash1;
543     SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);
544     uint160 hash2;
545     RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
546     return hash2;
547 }
548
549
550 // Median filter over a stream of values
551 // Returns the median of the last N numbers
552 template <typename T> class CMedianFilter
553 {
554 private:
555     std::vector<T> vValues;
556     std::vector<T> vSorted;
557     int nSize;
558 public:
559     CMedianFilter(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
606
607
608
609
610
611
612
613
614 // Note: It turns out we might have been able to use boost::thread
615 // by using TerminateThread(boost::thread.native_handle(), 0);
616 #ifdef WIN32
617 typedef HANDLE pthread_t;
618
619 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
620 {
621     DWORD nUnused = 0;
622     HANDLE hthread =
623         CreateThread(
624             NULL,                        // default security
625             0,                           // inherit stack size from parent
626             (LPTHREAD_START_ROUTINE)pfn, // function pointer
627             parg,                        // argument
628             0,                           // creation option, start immediately
629             &nUnused);                   // thread identifier
630     if (hthread == NULL)
631     {
632         printf("Error: CreateThread() returned %d\n", GetLastError());
633         return (pthread_t)0;
634     }
635     if (!fWantHandle)
636     {
637         CloseHandle(hthread);
638         return (pthread_t)-1;
639     }
640     return hthread;
641 }
642
643 inline void SetThreadPriority(int nPriority)
644 {
645     SetThreadPriority(GetCurrentThread(), nPriority);
646 }
647 #else
648 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
649 {
650     pthread_t hthread = 0;
651     int ret = pthread_create(&hthread, NULL, (void*(*)(void*))pfn, parg);
652     if (ret != 0)
653     {
654         printf("Error: pthread_create() returned %d\n", ret);
655         return (pthread_t)0;
656     }
657     if (!fWantHandle)
658     {
659         pthread_detach(hthread);
660         return (pthread_t)-1;
661     }
662     return hthread;
663 }
664
665 #define THREAD_PRIORITY_LOWEST          PRIO_MAX
666 #define THREAD_PRIORITY_BELOW_NORMAL    2
667 #define THREAD_PRIORITY_NORMAL          0
668 #define THREAD_PRIORITY_ABOVE_NORMAL    0
669
670 inline void SetThreadPriority(int nPriority)
671 {
672     // It's unclear if it's even possible to change thread priorities on Linux,
673     // but we really and truly need it for the generation threads.
674 #ifdef PRIO_THREAD
675     setpriority(PRIO_THREAD, 0, nPriority);
676 #else
677     setpriority(PRIO_PROCESS, 0, nPriority);
678 #endif
679 }
680
681 inline bool TerminateThread(pthread_t hthread, unsigned int nExitCode)
682 {
683     return (pthread_cancel(hthread) == 0);
684 }
685
686 inline void ExitThread(size_t nExitCode)
687 {
688     pthread_exit((void*)nExitCode);
689 }
690 #endif
691
692
693
694
695
696 inline bool AffinityBugWorkaround(void(*pfn)(void*))
697 {
698 #ifdef WIN32
699     // Sometimes after a few hours affinity gets stuck on one processor
700     DWORD_PTR dwProcessAffinityMask = -1;
701     DWORD_PTR dwSystemAffinityMask = -1;
702     GetProcessAffinityMask(GetCurrentProcess(), &dwProcessAffinityMask, &dwSystemAffinityMask);
703     DWORD dwPrev1 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
704     DWORD dwPrev2 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);
705     if (dwPrev2 != dwProcessAffinityMask)
706     {
707         printf("AffinityBugWorkaround() : SetThreadAffinityMask=%d, ProcessAffinityMask=%d, restarting thread\n", dwPrev2, dwProcessAffinityMask);
708         if (!CreateThread(pfn, NULL))
709             printf("Error: CreateThread() failed\n");
710         return true;
711     }
712 #endif
713     return false;
714 }
715
716 inline uint32_t ByteReverse(uint32_t value)
717 {
718         value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8);
719         return (value<<16) | (value>>16);
720 }
721
722 #endif
723