Add -alertnotify=command option
[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     while (true)
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     while (true)
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 // safeChars chosen to allow simple messages/URLs/email addresses, but avoid anything
437 // even possibly remotely dangerous like & or >
438 static string safeChars("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890 .,;_/:?@");
439 string SanitizeString(const string& str)
440 {
441     string strResult;
442     for (std::string::size_type i = 0; i < str.size(); i++)
443     {
444         if (safeChars.find(str[i]) != std::string::npos)
445             strResult.push_back(str[i]);
446     }
447     return strResult;
448 }
449
450 static const signed char phexdigit[256] =
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   0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
455   -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
456   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
457   -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
458   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
459   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
460   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
461   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
462   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
463   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
464   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
465   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
466   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
467
468 bool IsHex(const string& str)
469 {
470     BOOST_FOREACH(unsigned char c, str)
471     {
472         if (phexdigit[c] < 0)
473             return false;
474     }
475     return (str.size() > 0) && (str.size()%2 == 0);
476 }
477
478 vector<unsigned char> ParseHex(const char* psz)
479 {
480     // convert hex dump to vector
481     vector<unsigned char> vch;
482     while (true)
483     {
484         while (isspace(*psz))
485             psz++;
486         signed char c = phexdigit[(unsigned char)*psz++];
487         if (c == (signed char)-1)
488             break;
489         unsigned char n = (c << 4);
490         c = phexdigit[(unsigned char)*psz++];
491         if (c == (signed char)-1)
492             break;
493         n |= c;
494         vch.push_back(n);
495     }
496     return vch;
497 }
498
499 vector<unsigned char> ParseHex(const string& str)
500 {
501     return ParseHex(str.c_str());
502 }
503
504 static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
505 {
506     // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
507     if (name.find("-no") == 0)
508     {
509         std::string positive("-");
510         positive.append(name.begin()+3, name.end());
511         if (mapSettingsRet.count(positive) == 0)
512         {
513             bool value = !GetBoolArg(name);
514             mapSettingsRet[positive] = (value ? "1" : "0");
515         }
516     }
517 }
518
519 void ParseParameters(int argc, const char* const argv[])
520 {
521     mapArgs.clear();
522     mapMultiArgs.clear();
523     for (int i = 1; i < argc; i++)
524     {
525         char psz[10000];
526         strlcpy(psz, argv[i], sizeof(psz));
527         char* pszValue = (char*)"";
528         if (strchr(psz, '='))
529         {
530             pszValue = strchr(psz, '=');
531             *pszValue++ = '\0';
532         }
533         #ifdef WIN32
534         _strlwr(psz);
535         if (psz[0] == '/')
536             psz[0] = '-';
537         #endif
538         if (psz[0] != '-')
539             break;
540
541         mapArgs[psz] = pszValue;
542         mapMultiArgs[psz].push_back(pszValue);
543     }
544
545     // New 0.6 features:
546     BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs)
547     {
548         string name = entry.first;
549
550         //  interpret --foo as -foo (as long as both are not set)
551         if (name.find("--") == 0)
552         {
553             std::string singleDash(name.begin()+1, name.end());
554             if (mapArgs.count(singleDash) == 0)
555                 mapArgs[singleDash] = entry.second;
556             name = singleDash;
557         }
558
559         // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
560         InterpretNegativeSetting(name, mapArgs);
561     }
562 }
563
564 std::string GetArg(const std::string& strArg, const std::string& strDefault)
565 {
566     if (mapArgs.count(strArg))
567         return mapArgs[strArg];
568     return strDefault;
569 }
570
571 int64 GetArg(const std::string& strArg, int64 nDefault)
572 {
573     if (mapArgs.count(strArg))
574         return atoi64(mapArgs[strArg]);
575     return nDefault;
576 }
577
578 bool GetBoolArg(const std::string& strArg, bool fDefault)
579 {
580     if (mapArgs.count(strArg))
581     {
582         if (mapArgs[strArg].empty())
583             return true;
584         return (atoi(mapArgs[strArg]) != 0);
585     }
586     return fDefault;
587 }
588
589 bool SoftSetArg(const std::string& strArg, const std::string& strValue)
590 {
591     if (mapArgs.count(strArg))
592         return false;
593     mapArgs[strArg] = strValue;
594     return true;
595 }
596
597 bool SoftSetBoolArg(const std::string& strArg, bool fValue)
598 {
599     if (fValue)
600         return SoftSetArg(strArg, std::string("1"));
601     else
602         return SoftSetArg(strArg, std::string("0"));
603 }
604
605
606 string EncodeBase64(const unsigned char* pch, size_t len)
607 {
608     static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
609
610     string strRet="";
611     strRet.reserve((len+2)/3*4);
612
613     int mode=0, left=0;
614     const unsigned char *pchEnd = pch+len;
615
616     while (pch<pchEnd)
617     {
618         int enc = *(pch++);
619         switch (mode)
620         {
621             case 0: // we have no bits
622                 strRet += pbase64[enc >> 2];
623                 left = (enc & 3) << 4;
624                 mode = 1;
625                 break;
626
627             case 1: // we have two bits
628                 strRet += pbase64[left | (enc >> 4)];
629                 left = (enc & 15) << 2;
630                 mode = 2;
631                 break;
632
633             case 2: // we have four bits
634                 strRet += pbase64[left | (enc >> 6)];
635                 strRet += pbase64[enc & 63];
636                 mode = 0;
637                 break;
638         }
639     }
640
641     if (mode)
642     {
643         strRet += pbase64[left];
644         strRet += '=';
645         if (mode == 1)
646             strRet += '=';
647     }
648
649     return strRet;
650 }
651
652 string EncodeBase64(const string& str)
653 {
654     return EncodeBase64((const unsigned char*)str.c_str(), str.size());
655 }
656
657 vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
658 {
659     static const int decode64_table[256] =
660     {
661         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
662         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
663         -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
664         -1, -1, -1, -1, -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
665         15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
666         29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
667         49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
668         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
669         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
670         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
671         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
672         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
673         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
674     };
675
676     if (pfInvalid)
677         *pfInvalid = false;
678
679     vector<unsigned char> vchRet;
680     vchRet.reserve(strlen(p)*3/4);
681
682     int mode = 0;
683     int left = 0;
684
685     while (1)
686     {
687          int dec = decode64_table[(unsigned char)*p];
688          if (dec == -1) break;
689          p++;
690          switch (mode)
691          {
692              case 0: // we have no bits and get 6
693                  left = dec;
694                  mode = 1;
695                  break;
696
697               case 1: // we have 6 bits and keep 4
698                   vchRet.push_back((left<<2) | (dec>>4));
699                   left = dec & 15;
700                   mode = 2;
701                   break;
702
703              case 2: // we have 4 bits and get 6, we keep 2
704                  vchRet.push_back((left<<4) | (dec>>2));
705                  left = dec & 3;
706                  mode = 3;
707                  break;
708
709              case 3: // we have 2 bits and get 6
710                  vchRet.push_back((left<<6) | dec);
711                  mode = 0;
712                  break;
713          }
714     }
715
716     if (pfInvalid)
717         switch (mode)
718         {
719             case 0: // 4n base64 characters processed: ok
720                 break;
721
722             case 1: // 4n+1 base64 character processed: impossible
723                 *pfInvalid = true;
724                 break;
725
726             case 2: // 4n+2 base64 characters processed: require '=='
727                 if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1)
728                     *pfInvalid = true;
729                 break;
730
731             case 3: // 4n+3 base64 characters processed: require '='
732                 if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1)
733                     *pfInvalid = true;
734                 break;
735         }
736
737     return vchRet;
738 }
739
740 string DecodeBase64(const string& str)
741 {
742     vector<unsigned char> vchRet = DecodeBase64(str.c_str());
743     return string((const char*)&vchRet[0], vchRet.size());
744 }
745
746 string EncodeBase32(const unsigned char* pch, size_t len)
747 {
748     static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567";
749
750     string strRet="";
751     strRet.reserve((len+4)/5*8);
752
753     int mode=0, left=0;
754     const unsigned char *pchEnd = pch+len;
755
756     while (pch<pchEnd)
757     {
758         int enc = *(pch++);
759         switch (mode)
760         {
761             case 0: // we have no bits
762                 strRet += pbase32[enc >> 3];
763                 left = (enc & 7) << 2;
764                 mode = 1;
765                 break;
766
767             case 1: // we have three bits
768                 strRet += pbase32[left | (enc >> 6)];
769                 strRet += pbase32[(enc >> 1) & 31];
770                 left = (enc & 1) << 4;
771                 mode = 2;
772                 break;
773
774             case 2: // we have one bit
775                 strRet += pbase32[left | (enc >> 4)];
776                 left = (enc & 15) << 1;
777                 mode = 3;
778                 break;
779
780             case 3: // we have four bits
781                 strRet += pbase32[left | (enc >> 7)];
782                 strRet += pbase32[(enc >> 2) & 31];
783                 left = (enc & 3) << 3;
784                 mode = 4;
785                 break;
786
787             case 4: // we have two bits
788                 strRet += pbase32[left | (enc >> 5)];
789                 strRet += pbase32[enc & 31];
790                 mode = 0;
791         }
792     }
793
794     static const int nPadding[5] = {0, 6, 4, 3, 1};
795     if (mode)
796     {
797         strRet += pbase32[left];
798         for (int n=0; n<nPadding[mode]; n++)
799              strRet += '=';
800     }
801
802     return strRet;
803 }
804
805 string EncodeBase32(const string& str)
806 {
807     return EncodeBase32((const unsigned char*)str.c_str(), str.size());
808 }
809
810 vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid)
811 {
812     static const int decode32_table[256] =
813     {
814         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
815         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
816         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1,
817         -1, -1, -1, -1, -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
818         15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1,  0,  1,  2,
819          3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
820         23, 24, 25, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
821         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
822         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
823         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
824         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
825         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
826         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
827     };
828
829     if (pfInvalid)
830         *pfInvalid = false;
831
832     vector<unsigned char> vchRet;
833     vchRet.reserve((strlen(p))*5/8);
834
835     int mode = 0;
836     int left = 0;
837
838     while (1)
839     {
840          int dec = decode32_table[(unsigned char)*p];
841          if (dec == -1) break;
842          p++;
843          switch (mode)
844          {
845              case 0: // we have no bits and get 5
846                  left = dec;
847                  mode = 1;
848                  break;
849
850               case 1: // we have 5 bits and keep 2
851                   vchRet.push_back((left<<3) | (dec>>2));
852                   left = dec & 3;
853                   mode = 2;
854                   break;
855
856              case 2: // we have 2 bits and keep 7
857                  left = left << 5 | dec;
858                  mode = 3;
859                  break;
860
861              case 3: // we have 7 bits and keep 4
862                  vchRet.push_back((left<<1) | (dec>>4));
863                  left = dec & 15;
864                  mode = 4;
865                  break;
866
867              case 4: // we have 4 bits, and keep 1
868                  vchRet.push_back((left<<4) | (dec>>1));
869                  left = dec & 1;
870                  mode = 5;
871                  break;
872
873              case 5: // we have 1 bit, and keep 6
874                  left = left << 5 | dec;
875                  mode = 6;
876                  break;
877
878              case 6: // we have 6 bits, and keep 3
879                  vchRet.push_back((left<<2) | (dec>>3));
880                  left = dec & 7;
881                  mode = 7;
882                  break;
883
884              case 7: // we have 3 bits, and keep 0
885                  vchRet.push_back((left<<5) | dec);
886                  mode = 0;
887                  break;
888          }
889     }
890
891     if (pfInvalid)
892         switch (mode)
893         {
894             case 0: // 8n base32 characters processed: ok
895                 break;
896
897             case 1: // 8n+1 base32 characters processed: impossible
898             case 3: //   +3
899             case 6: //   +6
900                 *pfInvalid = true;
901                 break;
902
903             case 2: // 8n+2 base32 characters processed: require '======'
904                 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || p[4] != '=' || p[5] != '=' || decode32_table[(unsigned char)p[6]] != -1)
905                     *pfInvalid = true;
906                 break;
907
908             case 4: // 8n+4 base32 characters processed: require '===='
909                 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || decode32_table[(unsigned char)p[4]] != -1)
910                     *pfInvalid = true;
911                 break;
912
913             case 5: // 8n+5 base32 characters processed: require '==='
914                 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || decode32_table[(unsigned char)p[3]] != -1)
915                     *pfInvalid = true;
916                 break;
917
918             case 7: // 8n+7 base32 characters processed: require '='
919                 if (left || p[0] != '=' || decode32_table[(unsigned char)p[1]] != -1)
920                     *pfInvalid = true;
921                 break;
922         }
923
924     return vchRet;
925 }
926
927 string DecodeBase32(const string& str)
928 {
929     vector<unsigned char> vchRet = DecodeBase32(str.c_str());
930     return string((const char*)&vchRet[0], vchRet.size());
931 }
932
933
934 bool WildcardMatch(const char* psz, const char* mask)
935 {
936     while (true)
937     {
938         switch (*mask)
939         {
940         case '\0':
941             return (*psz == '\0');
942         case '*':
943             return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
944         case '?':
945             if (*psz == '\0')
946                 return false;
947             break;
948         default:
949             if (*psz != *mask)
950                 return false;
951             break;
952         }
953         psz++;
954         mask++;
955     }
956 }
957
958 bool WildcardMatch(const string& str, const string& mask)
959 {
960     return WildcardMatch(str.c_str(), mask.c_str());
961 }
962
963
964
965
966
967
968
969
970 static std::string FormatException(std::exception* pex, const char* pszThread)
971 {
972 #ifdef WIN32
973     char pszModule[MAX_PATH] = "";
974     GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
975 #else
976     const char* pszModule = "novacoin";
977 #endif
978     if (pex)
979         return strprintf(
980             "EXCEPTION: %s       \n%s       \n%s in %s       \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
981     else
982         return strprintf(
983             "UNKNOWN EXCEPTION       \n%s in %s       \n", pszModule, pszThread);
984 }
985
986 void LogException(std::exception* pex, const char* pszThread)
987 {
988     std::string message = FormatException(pex, pszThread);
989     printf("\n%s", message.c_str());
990 }
991
992 void PrintException(std::exception* pex, const char* pszThread)
993 {
994     std::string message = FormatException(pex, pszThread);
995     printf("\n\n************************\n%s\n", message.c_str());
996     fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
997     strMiscWarning = message;
998     throw;
999 }
1000
1001 void LogStackTrace() {
1002     printf("\n\n******* exception encountered *******\n");
1003     if (fileout)
1004     {
1005 #ifndef WIN32
1006         void* pszBuffer[32];
1007         size_t size;
1008         size = backtrace(pszBuffer, 32);
1009         backtrace_symbols_fd(pszBuffer, size, fileno(fileout));
1010 #endif
1011     }
1012 }
1013
1014 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
1015 {
1016     std::string message = FormatException(pex, pszThread);
1017     printf("\n\n************************\n%s\n", message.c_str());
1018     fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
1019     strMiscWarning = message;
1020 }
1021
1022 boost::filesystem::path GetDefaultDataDir()
1023 {
1024     namespace fs = boost::filesystem;
1025     // Windows < Vista: C:\Documents and Settings\Username\Application Data\NovaCoin
1026     // Windows >= Vista: C:\Users\Username\AppData\Roaming\NovaCoin
1027     // Mac: ~/Library/Application Support/NovaCoin
1028     // Unix: ~/.novacoin
1029 #ifdef WIN32
1030     // Windows
1031     return GetSpecialFolderPath(CSIDL_APPDATA) / "NovaCoin";
1032 #else
1033     fs::path pathRet;
1034     char* pszHome = getenv("HOME");
1035     if (pszHome == NULL || strlen(pszHome) == 0)
1036         pathRet = fs::path("/");
1037     else
1038         pathRet = fs::path(pszHome);
1039 #ifdef MAC_OSX
1040     // Mac
1041     pathRet /= "Library/Application Support";
1042     fs::create_directory(pathRet);
1043     return pathRet / "NovaCoin";
1044 #else
1045     // Unix
1046     return pathRet / ".novacoin";
1047 #endif
1048 #endif
1049 }
1050
1051 const boost::filesystem::path &GetDataDir(bool fNetSpecific)
1052 {
1053     namespace fs = boost::filesystem;
1054
1055     static fs::path pathCached[2];
1056     static CCriticalSection csPathCached;
1057     static bool cachedPath[2] = {false, false};
1058
1059     fs::path &path = pathCached[fNetSpecific];
1060
1061     // This can be called during exceptions by printf, so we cache the
1062     // value so we don't have to do memory allocations after that.
1063     if (cachedPath[fNetSpecific])
1064         return path;
1065
1066     LOCK(csPathCached);
1067
1068     if (mapArgs.count("-datadir")) {
1069         path = fs::system_complete(mapArgs["-datadir"]);
1070         if (!fs::is_directory(path)) {
1071             path = "";
1072             return path;
1073         }
1074     } else {
1075         path = GetDefaultDataDir();
1076     }
1077     if (fNetSpecific && GetBoolArg("-testnet", false))
1078         path /= "testnet2";
1079
1080     fs::create_directory(path);
1081
1082     cachedPath[fNetSpecific]=true;
1083     return path;
1084 }
1085
1086 boost::filesystem::path GetConfigFile()
1087 {
1088     boost::filesystem::path pathConfigFile(GetArg("-conf", "novacoin.conf"));
1089     if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
1090     return pathConfigFile;
1091 }
1092
1093 void ReadConfigFile(map<string, string>& mapSettingsRet,
1094                     map<string, vector<string> >& mapMultiSettingsRet)
1095 {
1096     boost::filesystem::ifstream streamConfig(GetConfigFile());
1097     if (!streamConfig.good())
1098         return; // No bitcoin.conf file is OK
1099
1100     set<string> setOptions;
1101     setOptions.insert("*");
1102
1103     for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
1104     {
1105         // Don't overwrite existing settings so command line settings override bitcoin.conf
1106         string strKey = string("-") + it->string_key;
1107         if (mapSettingsRet.count(strKey) == 0)
1108         {
1109             mapSettingsRet[strKey] = it->value[0];
1110             // interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
1111             InterpretNegativeSetting(strKey, mapSettingsRet);
1112         }
1113         mapMultiSettingsRet[strKey].push_back(it->value[0]);
1114     }
1115 }
1116
1117 boost::filesystem::path GetPidFile()
1118 {
1119     boost::filesystem::path pathPidFile(GetArg("-pid", "novacoind.pid"));
1120     if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
1121     return pathPidFile;
1122 }
1123
1124 #ifndef WIN32
1125 void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
1126 {
1127     FILE* file = fopen(path.string().c_str(), "w");
1128     if (file)
1129     {
1130         fprintf(file, "%d\n", pid);
1131         fclose(file);
1132     }
1133 }
1134 #endif
1135
1136 bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
1137 {
1138 #ifdef WIN32
1139     return MoveFileExA(src.string().c_str(), dest.string().c_str(),
1140                       MOVEFILE_REPLACE_EXISTING);
1141 #else
1142     int rc = std::rename(src.string().c_str(), dest.string().c_str());
1143     return (rc == 0);
1144 #endif /* WIN32 */
1145 }
1146
1147 void FileCommit(FILE *fileout)
1148 {
1149     fflush(fileout);                // harmless if redundantly called
1150 #ifdef WIN32
1151     _commit(_fileno(fileout));
1152 #else
1153     fsync(fileno(fileout));
1154 #endif
1155 }
1156
1157 int GetFilesize(FILE* file)
1158 {
1159     int nSavePos = ftell(file);
1160     int nFilesize = -1;
1161     if (fseek(file, 0, SEEK_END) == 0)
1162         nFilesize = ftell(file);
1163     fseek(file, nSavePos, SEEK_SET);
1164     return nFilesize;
1165 }
1166
1167 // this function tries to make a particular range of a file allocated (corresponding to disk space)
1168 // it is advisory, and the range specified in the arguments will never contain live data
1169 void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length) {
1170     static const char buf[65536] = {};
1171     fseek(file, offset, SEEK_SET);
1172     while (length > 0) {
1173         unsigned int now = 65536;
1174         if (length < now)
1175             now = length;
1176         fwrite(buf, 1, now, file); // allowed to fail; this function is advisory anyway
1177         length -= now;
1178     }
1179 }
1180
1181
1182 void ShrinkDebugFile()
1183 {
1184     // Scroll debug.log if it's getting too big
1185     boost::filesystem::path pathLog = GetDataDir() / "debug.log";
1186     FILE* file = fopen(pathLog.string().c_str(), "r");
1187     if (file && GetFilesize(file) > 10 * 1000000)
1188     {
1189         // Restart the file with some of the end
1190         char pch[200000];
1191         fseek(file, -sizeof(pch), SEEK_END);
1192         int nBytes = fread(pch, 1, sizeof(pch), file);
1193         fclose(file);
1194
1195         file = fopen(pathLog.string().c_str(), "w");
1196         if (file)
1197         {
1198             fwrite(pch, 1, nBytes, file);
1199             fclose(file);
1200         }
1201     }
1202 }
1203
1204
1205
1206
1207
1208
1209
1210
1211 //
1212 // "Never go to sea with two chronometers; take one or three."
1213 // Our three time sources are:
1214 //  - System clock
1215 //  - Median of other nodes clocks
1216 //  - The user (asking the user to fix the system clock if the first two disagree)
1217 //
1218 static int64 nMockTime = 0;  // For unit testing
1219
1220 int64 GetTime()
1221 {
1222     if (nMockTime) return nMockTime;
1223
1224     return time(NULL);
1225 }
1226
1227 void SetMockTime(int64 nMockTimeIn)
1228 {
1229     nMockTime = nMockTimeIn;
1230 }
1231
1232 static int64 nTimeOffset = 0;
1233
1234 int64 GetTimeOffset()
1235 {
1236     return nTimeOffset;
1237 }
1238
1239 int64 GetAdjustedTime()
1240 {
1241     return GetTime() + GetTimeOffset();
1242 }
1243
1244 void AddTimeData(const CNetAddr& ip, int64 nTime)
1245 {
1246     int64 nOffsetSample = nTime - GetTime();
1247
1248     // Ignore duplicates
1249     static set<CNetAddr> setKnown;
1250     if (!setKnown.insert(ip).second)
1251         return;
1252
1253     // Add data
1254     vTimeOffsets.input(nOffsetSample);
1255     printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
1256     if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
1257     {
1258         int64 nMedian = vTimeOffsets.median();
1259         std::vector<int64> vSorted = vTimeOffsets.sorted();
1260         // Only let other nodes change our time by so much
1261         if (abs64(nMedian) < 70 * 60)
1262         {
1263             nTimeOffset = nMedian;
1264         }
1265         else
1266         {
1267             nTimeOffset = 0;
1268
1269             static bool fDone;
1270             if (!fDone)
1271             {
1272                 // If nobody has a time different than ours but within 5 minutes of ours, give a warning
1273                 bool fMatch = false;
1274                 BOOST_FOREACH(int64 nOffset, vSorted)
1275                     if (nOffset != 0 && abs64(nOffset) < 5 * 60)
1276                         fMatch = true;
1277
1278                 if (!fMatch)
1279                 {
1280                     fDone = true;
1281                     string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong NovaCoin will not work properly.");
1282                     strMiscWarning = strMessage;
1283                     printf("*** %s\n", strMessage.c_str());
1284                     uiInterface.ThreadSafeMessageBox(strMessage+" ", string("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION);
1285                 }
1286             }
1287         }
1288         if (fDebug) {
1289             BOOST_FOREACH(int64 n, vSorted)
1290                 printf("%+"PRI64d"  ", n);
1291             printf("|  ");
1292         }
1293         printf("nTimeOffset = %+"PRI64d"  (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
1294     }
1295 }
1296
1297
1298
1299
1300
1301
1302
1303
1304 string FormatVersion(int nVersion)
1305 {
1306     if (nVersion%100 == 0)
1307         return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
1308     else
1309         return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
1310 }
1311
1312 string FormatFullVersion()
1313 {
1314     return CLIENT_BUILD;
1315 }
1316
1317 // Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
1318 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
1319 {
1320     std::ostringstream ss;
1321     ss << "/";
1322     ss << name << ":" << FormatVersion(nClientVersion);
1323     if (!comments.empty())
1324         ss << "(" << boost::algorithm::join(comments, "; ") << ")";
1325     ss << "/";
1326     return ss.str();
1327 }
1328
1329 #ifdef WIN32
1330 boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate)
1331 {
1332     namespace fs = boost::filesystem;
1333
1334     char pszPath[MAX_PATH] = "";
1335
1336     if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
1337     {
1338         return fs::path(pszPath);
1339     }
1340
1341     printf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
1342     return fs::path("");
1343 }
1344 #endif
1345
1346 void runCommand(std::string strCommand)
1347 {
1348     int nErr = ::system(strCommand.c_str());
1349     if (nErr)
1350         printf("runCommand error: system(%s) returned %d\n", strCommand.c_str(), nErr);
1351 }
1352
1353 void RenameThread(const char* name)
1354 {
1355 #if defined(PR_SET_NAME)
1356     // Only the first 15 characters are used (16 - NUL terminator)
1357     ::prctl(PR_SET_NAME, name, 0, 0, 0);
1358 #elif 0 && (defined(__FreeBSD__) || defined(__OpenBSD__))
1359     // TODO: This is currently disabled because it needs to be verified to work
1360     //       on FreeBSD or OpenBSD first. When verified the '0 &&' part can be
1361     //       removed.
1362     pthread_set_name_np(pthread_self(), name);
1363
1364 // This is XCode 10.6-and-later; bring back if we drop 10.5 support:
1365 // #elif defined(MAC_OSX)
1366 //    pthread_setname_np(name);
1367
1368 #else
1369     // Prevent warnings for unused parameters...
1370     (void)name;
1371 #endif
1372 }
1373
1374 bool NewThread(void(*pfn)(void*), void* parg)
1375 {
1376     try
1377     {
1378         boost::thread(pfn, parg); // thread detaches when out of scope
1379     } catch(boost::thread_resource_error &e) {
1380         printf("Error creating thread: %s\n", e.what());
1381         return false;
1382     }
1383     return true;
1384 }