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