55a3645ce9e81bafe49d80e29a261ada4dc769b0
[novacoin.git] / src / util.cpp
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
6 #include "util.h"
7 #include "sync.h"
8 #include "strlcpy.h"
9 #include "version.h"
10 #include "ui_interface.h"
11 #include <boost/algorithm/string/join.hpp>
12
13 // Work around clang compilation problem in Boost 1.46:
14 // /usr/include/boost/program_options/detail/config_file.hpp:163:17: error: call to function 'to_internal' that is neither visible in the template definition nor found by argument-dependent lookup
15 // See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options
16 //           http://clang.debian.net/status.php?version=3.0&key=CANNOT_FIND_FUNCTION
17 namespace boost {
18     namespace program_options {
19         std::string to_internal(const std::string&);
20     }
21 }
22
23 #include <boost/program_options/detail/config_file.hpp>
24 #include <boost/program_options/parsers.hpp>
25 #include <boost/filesystem.hpp>
26 #include <boost/filesystem/fstream.hpp>
27 #include <boost/foreach.hpp>
28 #include <boost/thread.hpp>
29 #include <openssl/crypto.h>
30 #include <openssl/rand.h>
31 #include <stdarg.h>
32
33 #ifdef WIN32
34 #ifdef _MSC_VER
35 #pragma warning(disable:4786)
36 #pragma warning(disable:4804)
37 #pragma warning(disable:4805)
38 #pragma warning(disable:4717)
39 #endif
40 #ifdef _WIN32_WINNT
41 #undef _WIN32_WINNT
42 #endif
43 #define _WIN32_WINNT 0x0501
44 #ifdef _WIN32_IE
45 #undef _WIN32_IE
46 #endif
47 #define _WIN32_IE 0x0501
48 #define WIN32_LEAN_AND_MEAN 1
49 #ifndef NOMINMAX
50 #define NOMINMAX
51 #endif
52 #include <io.h> /* for _commit */
53 #include "shlobj.h"
54 #elif defined(__linux__)
55 # include <sys/prctl.h>
56 #endif
57
58 #ifndef WIN32
59 #include <execinfo.h>
60 #endif
61
62
63 using namespace std;
64
65 map<string, string> mapArgs;
66 map<string, vector<string> > mapMultiArgs;
67 bool fDebug = false;
68 bool fDebugNet = false;
69 bool fPrintToConsole = false;
70 bool fPrintToDebugger = false;
71 bool fRequestShutdown = false;
72 bool fShutdown = false;
73 bool fDaemon = false;
74 bool fServer = false;
75 bool fCommandLine = false;
76 string strMiscWarning;
77 bool fTestNet = false;
78 bool fNoListen = false;
79 bool fLogTimestamps = false;
80 CMedianFilter<int64> vTimeOffsets(200,0);
81 bool fReopenDebugLog = false;
82
83 // Init OpenSSL library multithreading support
84 static CCriticalSection** ppmutexOpenSSL;
85 void locking_callback(int mode, int i, const char* file, int line)
86 {
87     if (mode & CRYPTO_LOCK) {
88         ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
89     } else {
90         LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
91     }
92 }
93
94 LockedPageManager LockedPageManager::instance;
95
96 // Init
97 class CInit
98 {
99 public:
100     CInit()
101     {
102         // Init OpenSSL library multithreading support
103         ppmutexOpenSSL = (CCriticalSection**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(CCriticalSection*));
104         for (int i = 0; i < CRYPTO_num_locks(); i++)
105             ppmutexOpenSSL[i] = new CCriticalSection();
106         CRYPTO_set_locking_callback(locking_callback);
107
108 #ifdef WIN32
109         // Seed random number generator with screen scrape and other hardware sources
110         RAND_screen();
111 #endif
112
113         // Seed random number generator with performance counter
114         RandAddSeed();
115     }
116     ~CInit()
117     {
118         // Shutdown OpenSSL library multithreading support
119         CRYPTO_set_locking_callback(NULL);
120         for (int i = 0; i < CRYPTO_num_locks(); i++)
121             delete ppmutexOpenSSL[i];
122         OPENSSL_free(ppmutexOpenSSL);
123     }
124 }
125 instance_of_cinit;
126
127
128
129
130
131
132
133
134 void RandAddSeed()
135 {
136     // Seed with CPU performance counter
137     int64 nCounter = GetPerformanceCounter();
138     RAND_add(&nCounter, sizeof(nCounter), 1.5);
139     memset(&nCounter, 0, sizeof(nCounter));
140 }
141
142 void RandAddSeedPerfmon()
143 {
144     RandAddSeed();
145
146     // This can take up to 2 seconds, so only do it every 10 minutes
147     static int64 nLastPerfmon;
148     if (GetTime() < nLastPerfmon + 10 * 60)
149         return;
150     nLastPerfmon = GetTime();
151
152 #ifdef WIN32
153     // Don't need this on Linux, OpenSSL automatically uses /dev/urandom
154     // Seed with the entire set of perfmon data
155     unsigned char pdata[250000];
156     memset(pdata, 0, sizeof(pdata));
157     unsigned long nSize = sizeof(pdata);
158     long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
159     RegCloseKey(HKEY_PERFORMANCE_DATA);
160     if (ret == ERROR_SUCCESS)
161     {
162         RAND_add(pdata, nSize, nSize/100.0);
163         memset(pdata, 0, nSize);
164         printf("RandAddSeed() %lu bytes\n", nSize);
165     }
166 #endif
167 }
168
169 uint64 GetRand(uint64 nMax)
170 {
171     if (nMax == 0)
172         return 0;
173
174     // The range of the random source must be a multiple of the modulus
175     // to give every possible output value an equal possibility
176     uint64 nRange = (std::numeric_limits<uint64>::max() / nMax) * nMax;
177     uint64 nRand = 0;
178     do
179         RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
180     while (nRand >= nRange);
181     return (nRand % nMax);
182 }
183
184 int GetRandInt(int nMax)
185 {
186     return GetRand(nMax);
187 }
188
189 uint256 GetRandHash()
190 {
191     uint256 hash;
192     RAND_bytes((unsigned char*)&hash, sizeof(hash));
193     return hash;
194 }
195
196
197
198
199
200
201 static FILE* fileout = NULL;
202
203 inline int OutputDebugStringF(const char* pszFormat, ...)
204 {
205     int ret = 0;
206     if (fPrintToConsole)
207     {
208         // print to console
209         va_list arg_ptr;
210         va_start(arg_ptr, pszFormat);
211         ret = vprintf(pszFormat, arg_ptr);
212         va_end(arg_ptr);
213     }
214     else if (!fPrintToDebugger)
215     {
216         // print to debug.log
217
218         if (!fileout)
219         {
220             boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
221             fileout = fopen(pathDebug.string().c_str(), "a");
222             if (fileout) setbuf(fileout, NULL); // unbuffered
223         }
224         if (fileout)
225         {
226             static bool fStartedNewLine = true;
227
228             // This routine may be called by global destructors during shutdown.
229             // Since the order of destruction of static/global objects is undefined,
230             // allocate mutexDebugLog on the heap the first time this routine
231             // is called to avoid crashes during shutdown.
232             static boost::mutex* mutexDebugLog = NULL;
233             if (mutexDebugLog == NULL) mutexDebugLog = new boost::mutex();
234             boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
235
236             // reopen the log file, if requested
237             if (fReopenDebugLog) {
238                 fReopenDebugLog = false;
239                 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
240                 if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL)
241                     setbuf(fileout, NULL); // unbuffered
242             }
243
244             // Debug print useful for profiling
245             if (fLogTimestamps && fStartedNewLine)
246                 fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
247             if (pszFormat[strlen(pszFormat) - 1] == '\n')
248                 fStartedNewLine = true;
249             else
250                 fStartedNewLine = false;
251
252             va_list arg_ptr;
253             va_start(arg_ptr, pszFormat);
254             ret = vfprintf(fileout, pszFormat, arg_ptr);
255             va_end(arg_ptr);
256         }
257     }
258
259 #ifdef WIN32
260     if (fPrintToDebugger)
261     {
262         static CCriticalSection cs_OutputDebugStringF;
263
264         // accumulate and output a line at a time
265         {
266             LOCK(cs_OutputDebugStringF);
267             static std::string buffer;
268
269             va_list arg_ptr;
270             va_start(arg_ptr, pszFormat);
271             buffer += vstrprintf(pszFormat, arg_ptr);
272             va_end(arg_ptr);
273
274             int line_start = 0, line_end;
275             while((line_end = buffer.find('\n', line_start)) != -1)
276             {
277                 OutputDebugStringA(buffer.substr(line_start, line_end - line_start).c_str());
278                 line_start = line_end + 1;
279             }
280             buffer.erase(0, line_start);
281         }
282     }
283 #endif
284     return ret;
285 }
286
287 string vstrprintf(const char *format, va_list ap)
288 {
289     char buffer[50000];
290     char* p = buffer;
291     int limit = sizeof(buffer);
292     int ret;
293     loop
294     {
295         va_list arg_ptr;
296         va_copy(arg_ptr, ap);
297 #ifdef WIN32
298         ret = _vsnprintf(p, limit, format, arg_ptr);
299 #else
300         ret = vsnprintf(p, limit, format, arg_ptr);
301 #endif
302         va_end(arg_ptr);
303         if (ret >= 0 && ret < limit)
304             break;
305         if (p != buffer)
306             delete[] p;
307         limit *= 2;
308         p = new char[limit];
309         if (p == NULL)
310             throw std::bad_alloc();
311     }
312     string str(p, p+ret);
313     if (p != buffer)
314         delete[] p;
315     return str;
316 }
317
318 string real_strprintf(const char *format, int dummy, ...)
319 {
320     va_list arg_ptr;
321     va_start(arg_ptr, dummy);
322     string str = vstrprintf(format, arg_ptr);
323     va_end(arg_ptr);
324     return str;
325 }
326
327 string real_strprintf(const std::string &format, int dummy, ...)
328 {
329     va_list arg_ptr;
330     va_start(arg_ptr, dummy);
331     string str = vstrprintf(format.c_str(), arg_ptr);
332     va_end(arg_ptr);
333     return str;
334 }
335
336 bool error(const char *format, ...)
337 {
338     va_list arg_ptr;
339     va_start(arg_ptr, format);
340     std::string str = vstrprintf(format, arg_ptr);
341     va_end(arg_ptr);
342     printf("ERROR: %s\n", str.c_str());
343     return false;
344 }
345
346
347 void ParseString(const string& str, char c, vector<string>& v)
348 {
349     if (str.empty())
350         return;
351     string::size_type i1 = 0;
352     string::size_type i2;
353     loop
354     {
355         i2 = str.find(c, i1);
356         if (i2 == str.npos)
357         {
358             v.push_back(str.substr(i1));
359             return;
360         }
361         v.push_back(str.substr(i1, i2-i1));
362         i1 = i2+1;
363     }
364 }
365
366
367 string FormatMoney(int64 n, bool fPlus)
368 {
369     // Note: not using straight sprintf here because we do NOT want
370     // localized number formatting.
371     int64 n_abs = (n > 0 ? n : -n);
372     int64 quotient = n_abs/COIN;
373     int64 remainder = n_abs%COIN;
374     string str = strprintf("%"PRI64d".%08"PRI64d, quotient, remainder);
375
376     // Right-trim excess zeros before the decimal point:
377     int nTrim = 0;
378     for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
379         ++nTrim;
380     if (nTrim)
381         str.erase(str.size()-nTrim, nTrim);
382
383     if (n < 0)
384         str.insert((unsigned int)0, 1, '-');
385     else if (fPlus && n > 0)
386         str.insert((unsigned int)0, 1, '+');
387     return str;
388 }
389
390
391 bool ParseMoney(const string& str, int64& nRet)
392 {
393     return ParseMoney(str.c_str(), nRet);
394 }
395
396 bool ParseMoney(const char* pszIn, int64& nRet)
397 {
398     string strWhole;
399     int64 nUnits = 0;
400     const char* p = pszIn;
401     while (isspace(*p))
402         p++;
403     for (; *p; p++)
404     {
405         if (*p == '.')
406         {
407             p++;
408             int64 nMult = CENT*10;
409             while (isdigit(*p) && (nMult > 0))
410             {
411                 nUnits += nMult * (*p++ - '0');
412                 nMult /= 10;
413             }
414             break;
415         }
416         if (isspace(*p))
417             break;
418         if (!isdigit(*p))
419             return false;
420         strWhole.insert(strWhole.end(), *p);
421     }
422     for (; *p; p++)
423         if (!isspace(*p))
424             return false;
425     if (strWhole.size() > 10) // guard against 63 bit overflow
426         return false;
427     if (nUnits < 0 || nUnits > COIN)
428         return false;
429     int64 nWhole = atoi64(strWhole);
430     int64 nValue = nWhole*COIN + nUnits;
431
432     nRet = nValue;
433     return true;
434 }
435
436
437 static const signed char phexdigit[256] =
438 { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
439   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
440   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
441   0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
442   -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
443   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
444   -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
445   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
446   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
447   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
448   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
449   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
450   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
451   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
452   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
453   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
454
455 bool IsHex(const string& str)
456 {
457     BOOST_FOREACH(unsigned char c, str)
458     {
459         if (phexdigit[c] < 0)
460             return false;
461     }
462     return (str.size() > 0) && (str.size()%2 == 0);
463 }
464
465 vector<unsigned char> ParseHex(const char* psz)
466 {
467     // convert hex dump to vector
468     vector<unsigned char> vch;
469     loop
470     {
471         while (isspace(*psz))
472             psz++;
473         signed char c = phexdigit[(unsigned char)*psz++];
474         if (c == (signed char)-1)
475             break;
476         unsigned char n = (c << 4);
477         c = phexdigit[(unsigned char)*psz++];
478         if (c == (signed char)-1)
479             break;
480         n |= c;
481         vch.push_back(n);
482     }
483     return vch;
484 }
485
486 vector<unsigned char> ParseHex(const string& str)
487 {
488     return ParseHex(str.c_str());
489 }
490
491 static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
492 {
493     // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
494     if (name.find("-no") == 0)
495     {
496         std::string positive("-");
497         positive.append(name.begin()+3, name.end());
498         if (mapSettingsRet.count(positive) == 0)
499         {
500             bool value = !GetBoolArg(name);
501             mapSettingsRet[positive] = (value ? "1" : "0");
502         }
503     }
504 }
505
506 void ParseParameters(int argc, const char* const argv[])
507 {
508     mapArgs.clear();
509     mapMultiArgs.clear();
510     for (int i = 1; i < argc; i++)
511     {
512         char psz[10000];
513         strlcpy(psz, argv[i], sizeof(psz));
514         char* pszValue = (char*)"";
515         if (strchr(psz, '='))
516         {
517             pszValue = strchr(psz, '=');
518             *pszValue++ = '\0';
519         }
520         #ifdef WIN32
521         _strlwr(psz);
522         if (psz[0] == '/')
523             psz[0] = '-';
524         #endif
525         if (psz[0] != '-')
526             break;
527
528         mapArgs[psz] = pszValue;
529         mapMultiArgs[psz].push_back(pszValue);
530     }
531
532     // New 0.6 features:
533     BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs)
534     {
535         string name = entry.first;
536
537         //  interpret --foo as -foo (as long as both are not set)
538         if (name.find("--") == 0)
539         {
540             std::string singleDash(name.begin()+1, name.end());
541             if (mapArgs.count(singleDash) == 0)
542                 mapArgs[singleDash] = entry.second;
543             name = singleDash;
544         }
545
546         // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
547         InterpretNegativeSetting(name, mapArgs);
548     }
549 }
550
551 std::string GetArg(const std::string& strArg, const std::string& strDefault)
552 {
553     if (mapArgs.count(strArg))
554         return mapArgs[strArg];
555     return strDefault;
556 }
557
558 int64 GetArg(const std::string& strArg, int64 nDefault)
559 {
560     if (mapArgs.count(strArg))
561         return atoi64(mapArgs[strArg]);
562     return nDefault;
563 }
564
565 bool GetBoolArg(const std::string& strArg, bool fDefault)
566 {
567     if (mapArgs.count(strArg))
568     {
569         if (mapArgs[strArg].empty())
570             return true;
571         return (atoi(mapArgs[strArg]) != 0);
572     }
573     return fDefault;
574 }
575
576 bool SoftSetArg(const std::string& strArg, const std::string& strValue)
577 {
578     if (mapArgs.count(strArg))
579         return false;
580     mapArgs[strArg] = strValue;
581     return true;
582 }
583
584 bool SoftSetBoolArg(const std::string& strArg, bool fValue)
585 {
586     if (fValue)
587         return SoftSetArg(strArg, std::string("1"));
588     else
589         return SoftSetArg(strArg, std::string("0"));
590 }
591
592
593 string EncodeBase64(const unsigned char* pch, size_t len)
594 {
595     static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
596
597     string strRet="";
598     strRet.reserve((len+2)/3*4);
599
600     int mode=0, left=0;
601     const unsigned char *pchEnd = pch+len;
602
603     while (pch<pchEnd)
604     {
605         int enc = *(pch++);
606         switch (mode)
607         {
608             case 0: // we have no bits
609                 strRet += pbase64[enc >> 2];
610                 left = (enc & 3) << 4;
611                 mode = 1;
612                 break;
613
614             case 1: // we have two bits
615                 strRet += pbase64[left | (enc >> 4)];
616                 left = (enc & 15) << 2;
617                 mode = 2;
618                 break;
619
620             case 2: // we have four bits
621                 strRet += pbase64[left | (enc >> 6)];
622                 strRet += pbase64[enc & 63];
623                 mode = 0;
624                 break;
625         }
626     }
627
628     if (mode)
629     {
630         strRet += pbase64[left];
631         strRet += '=';
632         if (mode == 1)
633             strRet += '=';
634     }
635
636     return strRet;
637 }
638
639 string EncodeBase64(const string& str)
640 {
641     return EncodeBase64((const unsigned char*)str.c_str(), str.size());
642 }
643
644 vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
645 {
646     static const int decode64_table[256] =
647     {
648         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
649         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
650         -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
651         -1, -1, -1, -1, -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
652         15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
653         29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
654         49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
655         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
656         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
657         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
658         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
659         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
660         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
661     };
662
663     if (pfInvalid)
664         *pfInvalid = false;
665
666     vector<unsigned char> vchRet;
667     vchRet.reserve(strlen(p)*3/4);
668
669     int mode = 0;
670     int left = 0;
671
672     while (1)
673     {
674          int dec = decode64_table[(unsigned char)*p];
675          if (dec == -1) break;
676          p++;
677          switch (mode)
678          {
679              case 0: // we have no bits and get 6
680                  left = dec;
681                  mode = 1;
682                  break;
683
684               case 1: // we have 6 bits and keep 4
685                   vchRet.push_back((left<<2) | (dec>>4));
686                   left = dec & 15;
687                   mode = 2;
688                   break;
689
690              case 2: // we have 4 bits and get 6, we keep 2
691                  vchRet.push_back((left<<4) | (dec>>2));
692                  left = dec & 3;
693                  mode = 3;
694                  break;
695
696              case 3: // we have 2 bits and get 6
697                  vchRet.push_back((left<<6) | dec);
698                  mode = 0;
699                  break;
700          }
701     }
702
703     if (pfInvalid)
704         switch (mode)
705         {
706             case 0: // 4n base64 characters processed: ok
707                 break;
708
709             case 1: // 4n+1 base64 character processed: impossible
710                 *pfInvalid = true;
711                 break;
712
713             case 2: // 4n+2 base64 characters processed: require '=='
714                 if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1)
715                     *pfInvalid = true;
716                 break;
717
718             case 3: // 4n+3 base64 characters processed: require '='
719                 if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1)
720                     *pfInvalid = true;
721                 break;
722         }
723
724     return vchRet;
725 }
726
727 string DecodeBase64(const string& str)
728 {
729     vector<unsigned char> vchRet = DecodeBase64(str.c_str());
730     return string((const char*)&vchRet[0], vchRet.size());
731 }
732
733 string EncodeBase32(const unsigned char* pch, size_t len)
734 {
735     static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567";
736
737     string strRet="";
738     strRet.reserve((len+4)/5*8);
739
740     int mode=0, left=0;
741     const unsigned char *pchEnd = pch+len;
742
743     while (pch<pchEnd)
744     {
745         int enc = *(pch++);
746         switch (mode)
747         {
748             case 0: // we have no bits
749                 strRet += pbase32[enc >> 3];
750                 left = (enc & 7) << 2;
751                 mode = 1;
752                 break;
753
754             case 1: // we have three bits
755                 strRet += pbase32[left | (enc >> 6)];
756                 strRet += pbase32[(enc >> 1) & 31];
757                 left = (enc & 1) << 4;
758                 mode = 2;
759                 break;
760
761             case 2: // we have one bit
762                 strRet += pbase32[left | (enc >> 4)];
763                 left = (enc & 15) << 1;
764                 mode = 3;
765                 break;
766
767             case 3: // we have four bits
768                 strRet += pbase32[left | (enc >> 7)];
769                 strRet += pbase32[(enc >> 2) & 31];
770                 left = (enc & 3) << 3;
771                 mode = 4;
772                 break;
773
774             case 4: // we have two bits
775                 strRet += pbase32[left | (enc >> 5)];
776                 strRet += pbase32[enc & 31];
777                 mode = 0;
778         }
779     }
780
781     static const int nPadding[5] = {0, 6, 4, 3, 1};
782     if (mode)
783     {
784         strRet += pbase32[left];
785         for (int n=0; n<nPadding[mode]; n++)
786              strRet += '=';
787     }
788
789     return strRet;
790 }
791
792 string EncodeBase32(const string& str)
793 {
794     return EncodeBase32((const unsigned char*)str.c_str(), str.size());
795 }
796
797 vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid)
798 {
799     static const int decode32_table[256] =
800     {
801         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
802         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
803         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1,
804         -1, -1, -1, -1, -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
805         15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1,  0,  1,  2,
806          3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
807         23, 24, 25, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
808         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
809         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
810         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
811         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
812         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
813         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
814     };
815
816     if (pfInvalid)
817         *pfInvalid = false;
818
819     vector<unsigned char> vchRet;
820     vchRet.reserve((strlen(p))*5/8);
821
822     int mode = 0;
823     int left = 0;
824
825     while (1)
826     {
827          int dec = decode32_table[(unsigned char)*p];
828          if (dec == -1) break;
829          p++;
830          switch (mode)
831          {
832              case 0: // we have no bits and get 5
833                  left = dec;
834                  mode = 1;
835                  break;
836
837               case 1: // we have 5 bits and keep 2
838                   vchRet.push_back((left<<3) | (dec>>2));
839                   left = dec & 3;
840                   mode = 2;
841                   break;
842
843              case 2: // we have 2 bits and keep 7
844                  left = left << 5 | dec;
845                  mode = 3;
846                  break;
847
848              case 3: // we have 7 bits and keep 4
849                  vchRet.push_back((left<<1) | (dec>>4));
850                  left = dec & 15;
851                  mode = 4;
852                  break;
853
854              case 4: // we have 4 bits, and keep 1
855                  vchRet.push_back((left<<4) | (dec>>1));
856                  left = dec & 1;
857                  mode = 5;
858                  break;
859
860              case 5: // we have 1 bit, and keep 6
861                  left = left << 5 | dec;
862                  mode = 6;
863                  break;
864
865              case 6: // we have 6 bits, and keep 3
866                  vchRet.push_back((left<<2) | (dec>>3));
867                  left = dec & 7;
868                  mode = 7;
869                  break;
870
871              case 7: // we have 3 bits, and keep 0
872                  vchRet.push_back((left<<5) | dec);
873                  mode = 0;
874                  break;
875          }
876     }
877
878     if (pfInvalid)
879         switch (mode)
880         {
881             case 0: // 8n base32 characters processed: ok
882                 break;
883
884             case 1: // 8n+1 base32 characters processed: impossible
885             case 3: //   +3
886             case 6: //   +6
887                 *pfInvalid = true;
888                 break;
889
890             case 2: // 8n+2 base32 characters processed: require '======'
891                 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || p[4] != '=' || p[5] != '=' || decode32_table[(unsigned char)p[6]] != -1)
892                     *pfInvalid = true;
893                 break;
894
895             case 4: // 8n+4 base32 characters processed: require '===='
896                 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || decode32_table[(unsigned char)p[4]] != -1)
897                     *pfInvalid = true;
898                 break;
899
900             case 5: // 8n+5 base32 characters processed: require '==='
901                 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || decode32_table[(unsigned char)p[3]] != -1)
902                     *pfInvalid = true;
903                 break;
904
905             case 7: // 8n+7 base32 characters processed: require '='
906                 if (left || p[0] != '=' || decode32_table[(unsigned char)p[1]] != -1)
907                     *pfInvalid = true;
908                 break;
909         }
910
911     return vchRet;
912 }
913
914 string DecodeBase32(const string& str)
915 {
916     vector<unsigned char> vchRet = DecodeBase32(str.c_str());
917     return string((const char*)&vchRet[0], vchRet.size());
918 }
919
920
921 bool WildcardMatch(const char* psz, const char* mask)
922 {
923     loop
924     {
925         switch (*mask)
926         {
927         case '\0':
928             return (*psz == '\0');
929         case '*':
930             return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
931         case '?':
932             if (*psz == '\0')
933                 return false;
934             break;
935         default:
936             if (*psz != *mask)
937                 return false;
938             break;
939         }
940         psz++;
941         mask++;
942     }
943 }
944
945 bool WildcardMatch(const string& str, const string& mask)
946 {
947     return WildcardMatch(str.c_str(), mask.c_str());
948 }
949
950
951
952
953
954
955
956
957 static std::string FormatException(std::exception* pex, const char* pszThread)
958 {
959 #ifdef WIN32
960     char pszModule[MAX_PATH] = "";
961     GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
962 #else
963     const char* pszModule = "novacoin";
964 #endif
965     if (pex)
966         return strprintf(
967             "EXCEPTION: %s       \n%s       \n%s in %s       \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
968     else
969         return strprintf(
970             "UNKNOWN EXCEPTION       \n%s in %s       \n", pszModule, pszThread);
971 }
972
973 void LogException(std::exception* pex, const char* pszThread)
974 {
975     std::string message = FormatException(pex, pszThread);
976     printf("\n%s", message.c_str());
977 }
978
979 void PrintException(std::exception* pex, const char* pszThread)
980 {
981     std::string message = FormatException(pex, pszThread);
982     printf("\n\n************************\n%s\n", message.c_str());
983     fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
984     strMiscWarning = message;
985     throw;
986 }
987
988 void LogStackTrace() {
989     printf("\n\n******* exception encountered *******\n");
990     if (fileout)
991     {
992 #ifndef WIN32
993         void* pszBuffer[32];
994         size_t size;
995         size = backtrace(pszBuffer, 32);
996         backtrace_symbols_fd(pszBuffer, size, fileno(fileout));
997 #endif
998     }
999 }
1000
1001 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
1002 {
1003     std::string message = FormatException(pex, pszThread);
1004     printf("\n\n************************\n%s\n", message.c_str());
1005     fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
1006     strMiscWarning = message;
1007 }
1008
1009 boost::filesystem::path GetDefaultDataDir()
1010 {
1011     namespace fs = boost::filesystem;
1012     // Windows < Vista: C:\Documents and Settings\Username\Application Data\NovaCoin
1013     // Windows >= Vista: C:\Users\Username\AppData\Roaming\NovaCoin
1014     // Mac: ~/Library/Application Support/NovaCoin
1015     // Unix: ~/.novacoin
1016 #ifdef WIN32
1017     // Windows
1018     return GetSpecialFolderPath(CSIDL_APPDATA) / "NovaCoin";
1019 #else
1020     fs::path pathRet;
1021     char* pszHome = getenv("HOME");
1022     if (pszHome == NULL || strlen(pszHome) == 0)
1023         pathRet = fs::path("/");
1024     else
1025         pathRet = fs::path(pszHome);
1026 #ifdef MAC_OSX
1027     // Mac
1028     pathRet /= "Library/Application Support";
1029     fs::create_directory(pathRet);
1030     return pathRet / "NovaCoin";
1031 #else
1032     // Unix
1033     return pathRet / ".novacoin";
1034 #endif
1035 #endif
1036 }
1037
1038 const boost::filesystem::path &GetDataDir(bool fNetSpecific)
1039 {
1040     namespace fs = boost::filesystem;
1041
1042     static fs::path pathCached[2];
1043     static CCriticalSection csPathCached;
1044     static bool cachedPath[2] = {false, false};
1045
1046     fs::path &path = pathCached[fNetSpecific];
1047
1048     // This can be called during exceptions by printf, so we cache the
1049     // value so we don't have to do memory allocations after that.
1050     if (cachedPath[fNetSpecific])
1051         return path;
1052
1053     LOCK(csPathCached);
1054
1055     if (mapArgs.count("-datadir")) {
1056         path = fs::system_complete(mapArgs["-datadir"]);
1057         if (!fs::is_directory(path)) {
1058             path = "";
1059             return path;
1060         }
1061     } else {
1062         path = GetDefaultDataDir();
1063     }
1064     if (fNetSpecific && GetBoolArg("-testnet", false))
1065         path /= "testnet2";
1066
1067     fs::create_directory(path);
1068
1069     cachedPath[fNetSpecific]=true;
1070     return path;
1071 }
1072
1073 boost::filesystem::path GetConfigFile()
1074 {
1075     boost::filesystem::path pathConfigFile(GetArg("-conf", "novacoin.conf"));
1076     if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
1077     return pathConfigFile;
1078 }
1079
1080 void ReadConfigFile(map<string, string>& mapSettingsRet,
1081                     map<string, vector<string> >& mapMultiSettingsRet)
1082 {
1083     boost::filesystem::ifstream streamConfig(GetConfigFile());
1084     if (!streamConfig.good())
1085         return; // No bitcoin.conf file is OK
1086
1087     set<string> setOptions;
1088     setOptions.insert("*");
1089
1090     for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
1091     {
1092         // Don't overwrite existing settings so command line settings override bitcoin.conf
1093         string strKey = string("-") + it->string_key;
1094         if (mapSettingsRet.count(strKey) == 0)
1095         {
1096             mapSettingsRet[strKey] = it->value[0];
1097             // interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
1098             InterpretNegativeSetting(strKey, mapSettingsRet);
1099         }
1100         mapMultiSettingsRet[strKey].push_back(it->value[0]);
1101     }
1102 }
1103
1104 boost::filesystem::path GetPidFile()
1105 {
1106     boost::filesystem::path pathPidFile(GetArg("-pid", "novacoind.pid"));
1107     if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
1108     return pathPidFile;
1109 }
1110
1111 void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
1112 {
1113     FILE* file = fopen(path.string().c_str(), "w");
1114     if (file)
1115     {
1116         fprintf(file, "%d\n", pid);
1117         fclose(file);
1118     }
1119 }
1120
1121 bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
1122 {
1123 #ifdef WIN32
1124     return MoveFileExA(src.string().c_str(), dest.string().c_str(),
1125                       MOVEFILE_REPLACE_EXISTING);
1126 #else
1127     int rc = std::rename(src.string().c_str(), dest.string().c_str());
1128     return (rc == 0);
1129 #endif /* WIN32 */
1130 }
1131
1132 void FileCommit(FILE *fileout)
1133 {
1134     fflush(fileout);                // harmless if redundantly called
1135 #ifdef WIN32
1136     _commit(_fileno(fileout));
1137 #else
1138     fsync(fileno(fileout));
1139 #endif
1140 }
1141
1142 int GetFilesize(FILE* file)
1143 {
1144     int nSavePos = ftell(file);
1145     int nFilesize = -1;
1146     if (fseek(file, 0, SEEK_END) == 0)
1147         nFilesize = ftell(file);
1148     fseek(file, nSavePos, SEEK_SET);
1149     return nFilesize;
1150 }
1151
1152 void ShrinkDebugFile()
1153 {
1154     // Scroll debug.log if it's getting too big
1155     boost::filesystem::path pathLog = GetDataDir() / "debug.log";
1156     FILE* file = fopen(pathLog.string().c_str(), "r");
1157     if (file && GetFilesize(file) > 10 * 1000000)
1158     {
1159         // Restart the file with some of the end
1160         char pch[200000];
1161         fseek(file, -sizeof(pch), SEEK_END);
1162         int nBytes = fread(pch, 1, sizeof(pch), file);
1163         fclose(file);
1164
1165         file = fopen(pathLog.string().c_str(), "w");
1166         if (file)
1167         {
1168             fwrite(pch, 1, nBytes, file);
1169             fclose(file);
1170         }
1171     }
1172 }
1173
1174
1175
1176
1177
1178
1179
1180
1181 //
1182 // "Never go to sea with two chronometers; take one or three."
1183 // Our three time sources are:
1184 //  - System clock
1185 //  - Median of other nodes clocks
1186 //  - The user (asking the user to fix the system clock if the first two disagree)
1187 //
1188 static int64 nMockTime = 0;  // For unit testing
1189
1190 int64 GetTime()
1191 {
1192     if (nMockTime) return nMockTime;
1193
1194     return time(NULL);
1195 }
1196
1197 void SetMockTime(int64 nMockTimeIn)
1198 {
1199     nMockTime = nMockTimeIn;
1200 }
1201
1202 static int64 nTimeOffset = 0;
1203
1204 int64 GetTimeOffset()
1205 {
1206     return nTimeOffset;
1207 }
1208
1209 int64 GetAdjustedTime()
1210 {
1211     return GetTime() + GetTimeOffset();
1212 }
1213
1214 void AddTimeData(const CNetAddr& ip, int64 nTime)
1215 {
1216     int64 nOffsetSample = nTime - GetTime();
1217
1218     // Ignore duplicates
1219     static set<CNetAddr> setKnown;
1220     if (!setKnown.insert(ip).second)
1221         return;
1222
1223     // Add data
1224     vTimeOffsets.input(nOffsetSample);
1225     printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
1226     if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
1227     {
1228         int64 nMedian = vTimeOffsets.median();
1229         std::vector<int64> vSorted = vTimeOffsets.sorted();
1230         // Only let other nodes change our time by so much
1231         if (abs64(nMedian) < 70 * 60)
1232         {
1233             nTimeOffset = nMedian;
1234         }
1235         else
1236         {
1237             nTimeOffset = 0;
1238
1239             static bool fDone;
1240             if (!fDone)
1241             {
1242                 // If nobody has a time different than ours but within 5 minutes of ours, give a warning
1243                 bool fMatch = false;
1244                 BOOST_FOREACH(int64 nOffset, vSorted)
1245                     if (nOffset != 0 && abs64(nOffset) < 5 * 60)
1246                         fMatch = true;
1247
1248                 if (!fMatch)
1249                 {
1250                     fDone = true;
1251                     string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong NovaCoin will not work properly.");
1252                     strMiscWarning = strMessage;
1253                     printf("*** %s\n", strMessage.c_str());
1254                     uiInterface.ThreadSafeMessageBox(strMessage+" ", string("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION);
1255                 }
1256             }
1257         }
1258         if (fDebug) {
1259             BOOST_FOREACH(int64 n, vSorted)
1260                 printf("%+"PRI64d"  ", n);
1261             printf("|  ");
1262         }
1263         printf("nTimeOffset = %+"PRI64d"  (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
1264     }
1265 }
1266
1267
1268
1269
1270
1271
1272
1273
1274 string FormatVersion(int nVersion)
1275 {
1276     if (nVersion%100 == 0)
1277         return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
1278     else
1279         return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
1280 }
1281
1282 string FormatFullVersion()
1283 {
1284     return CLIENT_BUILD;
1285 }
1286
1287 // Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
1288 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
1289 {
1290     std::ostringstream ss;
1291     ss << "/";
1292     ss << name << ":" << FormatVersion(nClientVersion);
1293     if (!comments.empty())
1294         ss << "(" << boost::algorithm::join(comments, "; ") << ")";
1295     ss << "/";
1296     return ss.str();
1297 }
1298
1299 #ifdef WIN32
1300 boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate)
1301 {
1302     namespace fs = boost::filesystem;
1303
1304     char pszPath[MAX_PATH] = "";
1305
1306     if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
1307     {
1308         return fs::path(pszPath);
1309     }
1310
1311     printf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
1312     return fs::path("");
1313 }
1314 #endif
1315
1316 void runCommand(std::string strCommand)
1317 {
1318     int nErr = ::system(strCommand.c_str());
1319     if (nErr)
1320         printf("runCommand error: system(%s) returned %d\n", strCommand.c_str(), nErr);
1321 }
1322
1323 void RenameThread(const char* name)
1324 {
1325 #if defined(PR_SET_NAME)
1326     // Only the first 15 characters are used (16 - NUL terminator)
1327     ::prctl(PR_SET_NAME, name, 0, 0, 0);
1328 #elif 0 && (defined(__FreeBSD__) || defined(__OpenBSD__))
1329     // TODO: This is currently disabled because it needs to be verified to work
1330     //       on FreeBSD or OpenBSD first. When verified the '0 &&' part can be
1331     //       removed.
1332     pthread_set_name_np(pthread_self(), name);
1333
1334 // This is XCode 10.6-and-later; bring back if we drop 10.5 support:
1335 // #elif defined(MAC_OSX)
1336 //    pthread_setname_np(name);
1337
1338 #else
1339     // Prevent warnings for unused parameters...
1340     (void)name;
1341 #endif
1342 }
1343
1344 bool NewThread(void(*pfn)(void*), void* parg)
1345 {
1346     try
1347     {
1348         boost::thread(pfn, parg); // thread detaches when out of scope
1349     } catch(boost::thread_resource_error &e) {
1350         printf("Error creating thread: %s\n", e.what());
1351         return false;
1352     }
1353     return true;
1354 }