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