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