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