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