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