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