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