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.
9 #include "ui_interface.h"
13 #include <boost/program_options/detail/config_file.hpp>
14 #include <boost/program_options/parsers.hpp>
15 #include <boost/filesystem.hpp>
16 #include <boost/filesystem/fstream.hpp>
17 #include <boost/date_time/posix_time/posix_time.hpp>
18 #include <boost/thread.hpp>
20 #include <openssl/crypto.h>
21 #include <openssl/rand.h>
27 #define _WIN32_WINNT 0x0501
31 #define _WIN32_IE 0x0501
32 #define WIN32_LEAN_AND_MEAN 1
36 #include <io.h> /* for _commit */
38 #elif defined(__linux__)
39 #include <sys/prctl.h>
42 #if !defined(WIN32) && !defined(ANDROID)
47 namespace bt = boost::posix_time;
49 map<string, string> mapArgs;
50 map<string, vector<string> > mapMultiArgs;
52 bool fDebugNet = false;
53 bool fPrintToConsole = false;
54 bool fPrintToDebugger = false;
55 bool fRequestShutdown = false;
56 bool fShutdown = false;
59 bool fCommandLine = false;
60 string strMiscWarning;
61 bool fTestNet = false;
62 bool fNoListen = false;
63 bool fLogTimestamps = false;
64 CMedianFilter<int64_t> vTimeOffsets(200,0);
65 bool fReopenDebugLog = false;
67 // Extended DecodeDumpTime implementation, see this page for details:
68 // http://stackoverflow.com/questions/3786201/parsing-of-date-time-from-string-boost
69 const locale formats[] = {
70 locale(locale::classic(),new bt::time_input_facet("%Y-%m-%dT%H:%M:%SZ")),
71 locale(locale::classic(),new bt::time_input_facet("%Y-%m-%d %H:%M:%S")),
72 locale(locale::classic(),new bt::time_input_facet("%Y/%m/%d %H:%M:%S")),
73 locale(locale::classic(),new bt::time_input_facet("%d.%m.%Y %H:%M:%S")),
74 locale(locale::classic(),new bt::time_input_facet("%Y-%m-%d"))
77 const size_t formats_n = sizeof(formats)/sizeof(formats[0]);
79 time_t pt_to_time_t(const bt::ptime& pt)
81 bt::ptime timet_start(boost::gregorian::date(1970,1,1));
82 bt::time_duration diff = pt - timet_start;
83 return diff.ticks()/bt::time_duration::rep_type::ticks_per_second;
86 // Init OpenSSL library multithreading support
87 static CCriticalSection** ppmutexOpenSSL;
88 void locking_callback(int mode, int i, const char* file, int line)
90 if (mode & CRYPTO_LOCK) {
91 ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
93 LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
97 LockedPageManager LockedPageManager::instance;
105 // Init OpenSSL library multithreading support
106 ppmutexOpenSSL = (CCriticalSection**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(CCriticalSection*));
107 for (int i = 0; i < CRYPTO_num_locks(); i++)
108 ppmutexOpenSSL[i] = new CCriticalSection();
109 CRYPTO_set_locking_callback(locking_callback);
112 // Seed random number generator with screen scrape and other hardware sources
116 // Seed random number generator with performance counter
121 // Shutdown OpenSSL library multithreading support
122 CRYPTO_set_locking_callback(NULL);
123 for (int i = 0; i < CRYPTO_num_locks(); i++)
124 delete ppmutexOpenSSL[i];
125 OPENSSL_free(ppmutexOpenSSL);
132 // Seed with CPU performance counter
133 int64_t nCounter = GetPerformanceCounter();
134 RAND_add(&nCounter, sizeof(nCounter), 1.5);
135 memset(&nCounter, 0, sizeof(nCounter));
138 void RandAddSeedPerfmon()
142 // This can take up to 2 seconds, so only do it every 10 minutes
143 static int64_t nLastPerfmon;
144 if (GetTime() < nLastPerfmon + 10 * 60)
146 nLastPerfmon = GetTime();
149 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom
150 // Seed with the entire set of perfmon data
151 unsigned char pdata[250000];
152 memset(pdata, 0, sizeof(pdata));
153 unsigned long nSize = sizeof(pdata);
154 long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
155 RegCloseKey(HKEY_PERFORMANCE_DATA);
156 if (ret == ERROR_SUCCESS)
158 RAND_add(pdata, nSize, nSize/100.0);
159 OPENSSL_cleanse(pdata, nSize);
160 printf("RandAddSeed() %lu bytes\n", nSize);
165 uint64_t GetRand(uint64_t nMax)
170 // The range of the random source must be a multiple of the modulus
171 // to give every possible output value an equal possibility
172 uint64_t nRange = (numeric_limits<uint64_t>::max() / nMax) * nMax;
175 RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
176 while (nRand >= nRange);
177 return (nRand % nMax);
180 int GetRandInt(int nMax)
182 return static_cast<int>(GetRand(nMax));
185 uint256 GetRandHash()
188 RAND_bytes(hash.begin(), hash.size());
192 void FillRand(uint8_t *buffer, size_t nCount)
194 RAND_bytes(buffer, nCount);
197 static FILE* fileout = NULL;
199 inline int OutputDebugStringF(const char* pszFormat, ...)
206 va_start(arg_ptr, pszFormat);
207 ret = vprintf(pszFormat, arg_ptr);
210 else if (!fPrintToDebugger)
212 // print to debug.log
216 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
217 fileout = fopen(pathDebug.string().c_str(), "a");
218 if (fileout) setbuf(fileout, NULL); // unbuffered
222 static bool fStartedNewLine = true;
224 // This routine may be called by global destructors during shutdown.
225 // Since the order of destruction of static/global objects is undefined,
226 // allocate mutexDebugLog on the heap the first time this routine
227 // is called to avoid crashes during shutdown.
228 static boost::mutex* mutexDebugLog = NULL;
229 if (mutexDebugLog == NULL) mutexDebugLog = new boost::mutex();
230 boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
232 // reopen the log file, if requested
233 if (fReopenDebugLog) {
234 fReopenDebugLog = false;
235 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
236 if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL)
237 setbuf(fileout, NULL); // unbuffered
240 // Debug print useful for profiling
241 if (fLogTimestamps && fStartedNewLine)
242 fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
243 if (pszFormat[strlen(pszFormat) - 1] == '\n')
244 fStartedNewLine = true;
246 fStartedNewLine = false;
249 va_start(arg_ptr, pszFormat);
250 ret = vfprintf(fileout, pszFormat, arg_ptr);
256 if (fPrintToDebugger)
258 static CCriticalSection cs_OutputDebugStringF;
260 // accumulate and output a line at a time
262 LOCK(cs_OutputDebugStringF);
263 static string buffer;
266 va_start(arg_ptr, pszFormat);
267 buffer += vstrprintf(pszFormat, arg_ptr);
270 size_t line_start = 0, line_end;
271 while((line_end = buffer.find('\n', line_start)) != string::npos)
273 OutputDebugStringA(buffer.substr(line_start, line_end - line_start).c_str());
274 line_start = line_end + 1;
276 buffer.erase(0, line_start);
283 string vstrprintf(const char *format, va_list ap)
287 int limit = sizeof(buffer);
293 va_copy(arg_ptr, ap);
295 va_list arg_ptr = ap;
298 ret = _vsnprintf(p, limit, format, arg_ptr);
300 ret = vsnprintf(p, limit, format, arg_ptr);
303 if (ret >= 0 && ret < limit)
308 p = new(nothrow) char[limit];
312 string str(p, p+ret);
318 string real_strprintf(const char *format, int dummy, ...)
321 va_start(arg_ptr, dummy);
322 string str = vstrprintf(format, arg_ptr);
327 string real_strprintf(const string &format, int dummy, ...)
330 va_start(arg_ptr, dummy);
331 string str = vstrprintf(format.c_str(), arg_ptr);
336 bool error(const char *format, ...)
339 va_start(arg_ptr, format);
340 string str = vstrprintf(format, arg_ptr);
342 printf("ERROR: %s\n", str.c_str());
347 void ParseString(const string& str, char c, vector<string>& v)
351 string::size_type i1 = 0;
352 string::size_type i2;
355 i2 = str.find(c, i1);
358 v.push_back(str.substr(i1));
361 v.push_back(str.substr(i1, i2-i1));
366 string FormatMoney(int64_t n, bool fPlus)
372 else if (fPlus && n > 0)
374 ss << abs(n/COIN) << '.' << setfill('0') << setw(6) << abs(n%COIN);
375 string str = ss.str();
376 // Right-trim excess zeros before the decimal point:
378 for (size_t i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
381 str.erase(str.size()-nTrim, nTrim);
386 bool ParseMoney(const string& str, int64_t& nRet)
388 return ParseMoney(str.c_str(), nRet);
391 bool ParseMoney(const char* pszIn, int64_t& nRet)
395 const char* p = pszIn;
403 int64_t nMult = CENT*10;
404 while (isdigit(*p) && (nMult > 0))
406 nUnits += nMult * (*p++ - '0');
415 strWhole.insert(strWhole.end(), *p);
420 if (strWhole.size() > 10) // guard against 63 bit overflow
422 if (nUnits < 0 || nUnits > COIN)
424 int64_t nWhole = strtoll(strWhole);
425 int64_t nValue = nWhole*COIN + nUnits;
431 static const int8_t phexdigit[256] =
433 -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
434 -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
435 -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
436 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1,
437 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
438 -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
439 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
440 -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
441 -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
442 -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
443 -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
444 -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
445 -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
446 -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
447 -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
448 -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
451 bool IsHex(const string& str)
453 for(unsigned char c : str)
455 if (phexdigit[c] < 0)
458 return (str.size() > 0) && (str.size()%2 == 0);
461 vector<unsigned char> ParseHex(const char* psz)
463 // convert hex dump to vector
464 vector<unsigned char> vch;
467 while (isspace(*psz))
469 auto c = phexdigit[(unsigned char)*psz++];
470 if (c == (signed char)-1)
473 c = phexdigit[(uint8_t)*psz++];
482 static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
484 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
485 if (name.find("-no") == 0)
487 string positive("-");
488 positive.append(name.begin()+3, name.end());
489 if (mapSettingsRet.count(positive) == 0)
491 bool value = !GetBoolArg(name);
492 mapSettingsRet[positive] = (value ? "1" : "0");
497 void ParseParameters(int argc, const char* const argv[])
500 mapMultiArgs.clear();
501 for (int i = 1; i < argc; i++)
505 size_t is_index = str.find('=');
506 if (is_index != string::npos)
508 strValue = str.substr(is_index+1);
509 str = str.substr(0, is_index);
512 transform(str.begin(), str.end(), str.begin(), ::tolower);
513 if (str.compare(0,1, "/") == 0)
514 str = "-" + str.substr(1);
519 mapArgs[str] = strValue;
520 mapMultiArgs[str].push_back(strValue);
524 for(const auto& entry : mapArgs)
526 string name = entry.first;
528 // interpret --foo as -foo (as long as both are not set)
529 if (name.find("--") == 0)
531 string singleDash(name.begin()+1, name.end());
532 if (mapArgs.count(singleDash) == 0)
533 mapArgs[singleDash] = entry.second;
537 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
538 InterpretNegativeSetting(name, mapArgs);
542 string GetArg(const string& strArg, const string& strDefault)
544 if (mapArgs.count(strArg))
545 return mapArgs[strArg];
549 int64_t GetArg(const string& strArg, int64_t nDefault)
551 if (mapArgs.count(strArg))
552 return strtoll(mapArgs[strArg]);
556 int32_t GetArgInt(const string& strArg, int32_t nDefault)
558 if (mapArgs.count(strArg))
559 return strtol(mapArgs[strArg]);
563 uint32_t GetArgUInt(const string& strArg, uint32_t nDefault)
565 if (mapArgs.count(strArg))
566 return strtoul(mapArgs[strArg]);
570 bool GetBoolArg(const string& strArg, bool fDefault)
572 if (mapArgs.count(strArg))
574 if (mapArgs[strArg].empty())
576 return (atoi(mapArgs[strArg]) != 0);
581 bool SoftSetArg(const string& strArg, const string& strValue)
583 if (mapArgs.count(strArg) || mapMultiArgs.count(strArg))
585 mapArgs[strArg] = strValue;
586 mapMultiArgs[strArg].push_back(strValue);
591 bool SoftSetBoolArg(const string& strArg, bool fValue)
594 return SoftSetArg(strArg, string("1"));
596 return SoftSetArg(strArg, string("0"));
600 string EncodeBase64(const unsigned char* pch, size_t len)
602 static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
605 strRet.reserve((len+2)/3*4);
608 const unsigned char *pchEnd = pch+len;
615 case 0: // we have no bits
616 strRet += pbase64[enc >> 2];
617 left = (enc & 3) << 4;
621 case 1: // we have two bits
622 strRet += pbase64[left | (enc >> 4)];
623 left = (enc & 15) << 2;
627 case 2: // we have four bits
628 strRet += pbase64[left | (enc >> 6)];
629 strRet += pbase64[enc & 63];
637 strRet += pbase64[left];
646 string EncodeBase64(const string& str)
648 return EncodeBase64((const unsigned char*)str.c_str(), str.size());
651 vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
653 static const int decode64_table[256] =
655 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
656 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
657 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
658 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
659 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
660 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
661 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
662 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
663 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
664 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
665 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
666 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
667 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
673 vector<unsigned char> vchRet;
674 vchRet.reserve(strlen(p)*3/4);
681 int dec = decode64_table[(unsigned char)*p];
682 if (dec == -1) break;
686 case 0: // we have no bits and get 6
691 case 1: // we have 6 bits and keep 4
692 vchRet.push_back((left<<2) | (dec>>4));
697 case 2: // we have 4 bits and get 6, we keep 2
698 vchRet.push_back((left<<4) | (dec>>2));
703 case 3: // we have 2 bits and get 6
704 vchRet.push_back((left<<6) | dec);
713 case 0: // 4n base64 characters processed: ok
716 case 1: // 4n+1 base64 character processed: impossible
720 case 2: // 4n+2 base64 characters processed: require '=='
721 if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1)
725 case 3: // 4n+3 base64 characters processed: require '='
726 if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1)
734 string DecodeBase64(const string& str)
736 vector<unsigned char> vchRet = DecodeBase64(str.c_str());
737 return string((const char*)&vchRet[0], vchRet.size());
740 string EncodeBase32(const unsigned char* pch, size_t len)
742 static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567";
745 strRet.reserve((len+4)/5*8);
748 const unsigned char *pchEnd = pch+len;
755 case 0: // we have no bits
756 strRet += pbase32[enc >> 3];
757 left = (enc & 7) << 2;
761 case 1: // we have three bits
762 strRet += pbase32[left | (enc >> 6)];
763 strRet += pbase32[(enc >> 1) & 31];
764 left = (enc & 1) << 4;
768 case 2: // we have one bit
769 strRet += pbase32[left | (enc >> 4)];
770 left = (enc & 15) << 1;
774 case 3: // we have four bits
775 strRet += pbase32[left | (enc >> 7)];
776 strRet += pbase32[(enc >> 2) & 31];
777 left = (enc & 3) << 3;
781 case 4: // we have two bits
782 strRet += pbase32[left | (enc >> 5)];
783 strRet += pbase32[enc & 31];
788 static const int nPadding[5] = {0, 6, 4, 3, 1};
791 strRet += pbase32[left];
792 for (int n=0; n<nPadding[mode]; n++)
799 string EncodeBase32(const string& str)
801 return EncodeBase32((const unsigned char*)str.c_str(), str.size());
804 vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid)
806 static const int decode32_table[256] =
808 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
809 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
810 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1,
811 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
812 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 0, 1, 2,
813 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
814 23, 24, 25, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
815 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
816 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
817 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
818 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
819 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
820 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
826 vector<unsigned char> vchRet;
827 vchRet.reserve((strlen(p))*5/8);
834 int dec = decode32_table[(unsigned char)*p];
835 if (dec == -1) break;
839 case 0: // we have no bits and get 5
844 case 1: // we have 5 bits and keep 2
845 vchRet.push_back((left<<3) | (dec>>2));
850 case 2: // we have 2 bits and keep 7
851 left = left << 5 | dec;
855 case 3: // we have 7 bits and keep 4
856 vchRet.push_back((left<<1) | (dec>>4));
861 case 4: // we have 4 bits, and keep 1
862 vchRet.push_back((left<<4) | (dec>>1));
867 case 5: // we have 1 bit, and keep 6
868 left = left << 5 | dec;
872 case 6: // we have 6 bits, and keep 3
873 vchRet.push_back((left<<2) | (dec>>3));
878 case 7: // we have 3 bits, and keep 0
879 vchRet.push_back((left<<5) | dec);
888 case 0: // 8n base32 characters processed: ok
891 case 1: // 8n+1 base32 characters processed: impossible
897 case 2: // 8n+2 base32 characters processed: require '======'
898 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || p[4] != '=' || p[5] != '=' || decode32_table[(unsigned char)p[6]] != -1)
902 case 4: // 8n+4 base32 characters processed: require '===='
903 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || decode32_table[(unsigned char)p[4]] != -1)
907 case 5: // 8n+5 base32 characters processed: require '==='
908 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || decode32_table[(unsigned char)p[3]] != -1)
912 case 7: // 8n+7 base32 characters processed: require '='
913 if (left || p[0] != '=' || decode32_table[(unsigned char)p[1]] != -1)
921 string DecodeBase32(const string& str)
923 vector<unsigned char> vchRet = DecodeBase32(str.c_str());
924 return string((const char*)&vchRet[0], vchRet.size());
928 int64_t DecodeDumpTime(const string& s)
932 for(size_t i=0; i<formats_n; ++i)
935 is.imbue(formats[i]);
937 if(pt != bt::ptime()) break;
940 return pt_to_time_t(pt);
943 string EncodeDumpTime(int64_t nTime) {
944 return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime);
947 string EncodeDumpString(const string &str) {
949 for(unsigned char c : str) {
950 if (c <= 32 || c >= 128 || c == '%') {
951 ret << '%' << HexStr(&c, &c + 1);
959 string DecodeDumpString(const string &str) {
961 for (unsigned int pos = 0; pos < str.length(); pos++) {
962 unsigned char c = str[pos];
963 if (c == '%' && pos+2 < str.length()) {
964 c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) |
965 ((str[pos+2]>>6)*9+((str[pos+2]-'0')&15));
973 bool WildcardMatch(const char* psz, const char* mask)
980 return (*psz == '\0');
982 return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
997 bool WildcardMatch(const string& str, const string& mask)
999 return WildcardMatch(str.c_str(), mask.c_str());
1003 static string FormatException(exception* pex, const char* pszThread)
1006 char pszModule[MAX_PATH] = "";
1007 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
1009 const char* pszModule = "novacoin";
1013 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
1016 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
1019 void LogException(exception* pex, const char* pszThread)
1021 string message = FormatException(pex, pszThread);
1022 printf("\n%s", message.c_str());
1025 void PrintException(exception* pex, const char* pszThread)
1027 string message = FormatException(pex, pszThread);
1028 printf("\n\n************************\n%s\n", message.c_str());
1029 fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
1030 strMiscWarning = message;
1034 void LogStackTrace() {
1035 printf("\n\n******* exception encountered *******\n");
1038 #if !defined(WIN32) && !defined(ANDROID)
1039 void* pszBuffer[32];
1041 size = backtrace(pszBuffer, 32);
1042 backtrace_symbols_fd(pszBuffer, size, fileno(fileout));
1047 void PrintExceptionContinue(exception* pex, const char* pszThread)
1049 string message = FormatException(pex, pszThread);
1050 printf("\n\n************************\n%s\n", message.c_str());
1051 fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
1052 strMiscWarning = message;
1055 boost::filesystem::path GetDefaultDataDir()
1057 namespace fs = boost::filesystem;
1058 // Windows < Vista: C:\Documents and Settings\Username\Application Data\NovaCoin
1059 // Windows >= Vista: C:\Users\Username\AppData\Roaming\NovaCoin
1060 // Mac: ~/Library/Application Support/NovaCoin
1061 // Unix: ~/.novacoin
1064 return GetSpecialFolderPath(CSIDL_APPDATA) / "NovaCoin";
1067 char* pszHome = getenv("HOME");
1068 if (pszHome == NULL || strlen(pszHome) == 0)
1069 pathRet = fs::path("/");
1071 pathRet = fs::path(pszHome);
1074 pathRet /= "Library/Application Support";
1075 fs::create_directory(pathRet);
1076 return pathRet / "NovaCoin";
1079 return pathRet / ".novacoin";
1084 const boost::filesystem::path &GetDataDir(bool fNetSpecific)
1086 namespace fs = boost::filesystem;
1088 static fs::path pathCached[2];
1089 static CCriticalSection csPathCached;
1090 static bool cachedPath[2] = {false, false};
1092 fs::path &path = pathCached[fNetSpecific];
1094 // This can be called during exceptions by printf, so we cache the
1095 // value so we don't have to do memory allocations after that.
1096 if (cachedPath[fNetSpecific])
1101 if (mapArgs.count("-datadir")) {
1102 path = fs::system_complete(mapArgs["-datadir"]);
1103 if (!fs::is_directory(path)) {
1108 path = GetDefaultDataDir();
1110 if (fNetSpecific && GetBoolArg("-testnet", false))
1113 fs::create_directory(path);
1115 cachedPath[fNetSpecific]=true;
1119 string randomStrGen(size_t length) {
1120 std::mt19937 mtrand;
1121 mtrand.seed(static_cast<unsigned int>(time(NULL)));
1122 static const string charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
1124 result.resize(length);
1125 for (size_t i = 0; i < length; ++i)
1126 result[i] = charset[mtrand() % charset.length()];
1133 #if BOOST_FILESYSTEM_VERSION >= 3
1134 pConf.open(GetConfigFile().generic_string().c_str());
1136 pConf.open(GetConfigFile().string().c_str());
1138 pConf << "rpcuser=user\nrpcpassword="
1141 + "\n#(0=off, 1=on) daemon - run in the background as a daemon and accept commands"
1143 + "\n#(0=off, 1=on) server - accept command line and JSON-RPC commands"
1145 + "\nrpcallowip=127.0.0.1";
1149 boost::filesystem::path GetConfigFile()
1151 boost::filesystem::path pathConfigFile(GetArg("-conf", "novacoin.conf"));
1152 if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
1153 return pathConfigFile;
1156 void ReadConfigFile(map<string, string>& mapSettingsRet,
1157 map<string, vector<string> >& mapMultiSettingsRet)
1159 boost::filesystem::ifstream streamConfig(GetConfigFile());
1160 if (!streamConfig.good())
1163 new(&streamConfig) boost::filesystem::ifstream(GetConfigFile());
1164 if(!streamConfig.good())
1168 set<string> setOptions;
1169 setOptions.insert("*");
1171 for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
1173 // Don't overwrite existing settings so command line settings override bitcoin.conf
1174 string strKey = string("-") + it->string_key;
1175 if (mapSettingsRet.count(strKey) == 0)
1177 mapSettingsRet[strKey] = it->value[0];
1178 // interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
1179 InterpretNegativeSetting(strKey, mapSettingsRet);
1181 mapMultiSettingsRet[strKey].push_back(it->value[0]);
1185 boost::filesystem::path GetPidFile()
1187 boost::filesystem::path pathPidFile(GetArg("-pid", "novacoind.pid"));
1188 if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
1193 void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
1195 FILE* file = fopen(path.string().c_str(), "w");
1198 fprintf(file, "%d\n", pid);
1204 bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
1207 return MoveFileExA(src.string().c_str(), dest.string().c_str(),
1208 MOVEFILE_REPLACE_EXISTING) != 0;
1210 int rc = rename(src.string().c_str(), dest.string().c_str());
1215 void FileCommit(FILE *fileout)
1217 fflush(fileout); // harmless if redundantly called
1219 _commit(_fileno(fileout));
1221 fsync(fileno(fileout));
1225 int GetFilesize(FILE* file)
1227 int nSavePos = ftell(file);
1229 if (fseek(file, 0, SEEK_END) == 0)
1230 nFilesize = ftell(file);
1231 fseek(file, nSavePos, SEEK_SET);
1235 void ShrinkDebugFile()
1237 // Scroll debug.log if it's getting too big
1238 boost::filesystem::path pathLog = GetDataDir() / "debug.log";
1239 FILE* file = fopen(pathLog.string().c_str(), "r");
1240 if (file && GetFilesize(file) > 10 * 1000000)
1242 // Restart the file with some of the end
1244 vector<char>* vBuf = new vector <char>(200000, 0);
1245 size_t nBytes = 1; //write one byte if fseek failed
1246 if (fseek(file, -((long)(vBuf->size())), SEEK_END) == 0)
1247 nBytes = fread(&vBuf->operator[](0), 1, vBuf->size(), file);
1249 file = fopen(pathLog.string().c_str(), "w");
1252 fwrite(&vBuf->operator[](0), 1, nBytes, file);
1257 catch (const bad_alloc& e) {
1258 // Bad things happen - no free memory in heap at program startup
1260 printf("Warning: %s in %s:%d\n ShrinkDebugFile failed - debug.log expands further", e.what(), __FILE__, __LINE__);
1266 // "Never go to sea with two chronometers; take one or three."
1267 // Our three time sources are:
1269 // - Median of other nodes clocks
1270 // - The user (asking the user to fix the system clock if the first two disagree)
1276 int64_t now = time(NULL);
1281 // Trusted NTP offset or median of NTP samples.
1282 extern int64_t nNtpOffset;
1284 // Median of time samples given by other nodes.
1285 static int64_t nNodesOffset = numeric_limits<int64_t>::max();
1287 // Select time offset:
1288 int64_t GetTimeOffset()
1290 // If NTP and system clock are in agreement within 40 minutes, then use NTP.
1291 if (abs(nNtpOffset) < 40 * 60)
1294 // If not, then choose between median peer time and system clock.
1295 if (abs(nNodesOffset) < 70 * 60)
1296 return nNodesOffset;
1301 int64_t GetNodesOffset()
1303 return nNodesOffset;
1306 int64_t GetAdjustedTime()
1308 return GetTime() + GetTimeOffset();
1311 void AddTimeData(const CNetAddr& ip, int64_t nTime)
1313 int64_t nOffsetSample = nTime - GetTime();
1315 // Ignore duplicates
1316 static set<CNetAddr> setKnown;
1317 if (!setKnown.insert(ip).second)
1321 vTimeOffsets.input(nOffsetSample);
1322 printf("Added time data, samples %d, offset %+" PRId64 " (%+" PRId64 " minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
1323 if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
1325 auto nMedian = vTimeOffsets.median();
1326 auto vSorted = vTimeOffsets.sorted();
1327 // Only let other nodes change our time by so much
1328 if (abs(nMedian) < 70 * 60)
1330 nNodesOffset = nMedian;
1334 nNodesOffset = numeric_limits<int64_t>::max();
1339 bool fMatch = false;
1341 // If nobody has a time different than ours but within 5 minutes of ours, give a warning
1342 for(auto nOffset : vSorted)
1343 if (nOffset != 0 && abs(nOffset) < 5 * 60)
1349 string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong NovaCoin will not work properly.");
1350 strMiscWarning = strMessage;
1351 printf("*** %s\n", strMessage.c_str());
1352 uiInterface.ThreadSafeMessageBox(strMessage+" ", string("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION);
1357 for(int64_t n : vSorted)
1358 printf("%+" PRId64 " ", n);
1361 if (nNodesOffset != numeric_limits<int64_t>::max())
1362 printf("nNodesOffset = %+" PRId64 " (%+" PRId64 " minutes)\n", nNodesOffset, nNodesOffset/60);
1366 string FormatVersion(int nVersion)
1368 if (nVersion%100 == 0)
1369 return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
1371 return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
1374 string FormatFullVersion()
1376 return CLIENT_BUILD;
1379 // Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
1380 string FormatSubVersion(const string& name, int nClientVersion, const vector<string>& comments)
1384 ss << name << ":" << FormatVersion(nClientVersion);
1385 if (!comments.empty())
1388 for (const auto& st : comments)
1391 if (st == comments.back()) break;
1401 boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate)
1403 namespace fs = boost::filesystem;
1405 char pszPath[MAX_PATH] = "";
1407 if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
1409 return fs::path(pszPath);
1412 printf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
1413 return fs::path("");
1417 void runCommand(string strCommand)
1419 int nErr = ::system(strCommand.c_str());
1421 printf("runCommand error: system(%s) returned %d\n", strCommand.c_str(), nErr);
1424 void RenameThread(const char* name)
1426 #if defined(PR_SET_NAME)
1427 // Only the first 15 characters are used (16 - NUL terminator)
1428 ::prctl(PR_SET_NAME, name, 0, 0, 0);
1429 #elif 0 && (defined(__FreeBSD__) || defined(__OpenBSD__))
1430 // TODO: This is currently disabled because it needs to be verified to work
1431 // on FreeBSD or OpenBSD first. When verified the '0 &&' part can be
1433 pthread_set_name_np(pthread_self(), name);
1435 // This is XCode 10.6-and-later; bring back if we drop 10.5 support:
1436 // #elif defined(MAC_OSX)
1437 // pthread_setname_np(name);
1440 // Prevent warnings for unused parameters...
1445 bool NewThread(void(*pfn)(void*), void* parg)
1449 boost::thread(pfn, parg); // thread detaches when out of scope
1450 } catch(boost::thread_resource_error &e) {
1451 printf("Error creating thread: %s\n", e.what());
1457 string DateTimeStrFormat(const char* pszFormat, int64_t nTime)
1459 // locale takes ownership of the pointer
1460 locale loc(locale::classic(), new boost::posix_time::time_facet(pszFormat));
1463 ss << boost::posix_time::from_time_t(nTime);