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