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