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"
10 #include <boost/algorithm/string/join.hpp>
11 #include <boost/algorithm/string/case_conv.hpp> // for to_lower()
12 #include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
14 // Work around clang compilation problem in Boost 1.46:
15 // /usr/include/boost/program_options/detail/config_file.hpp:163:17: error: call to function 'to_internal' that is neither visible in the template definition nor found by argument-dependent lookup
16 // See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options
17 // http://clang.debian.net/status.php?version=3.0&key=CANNOT_FIND_FUNCTION
19 namespace program_options {
20 std::string to_internal(const std::string&);
24 #include <boost/program_options/detail/config_file.hpp>
25 #include <boost/program_options/parsers.hpp>
26 #include <boost/filesystem.hpp>
27 #include <boost/filesystem/fstream.hpp>
29 #include <boost/date_time/posix_time/posix_time.hpp>
30 #include <boost/foreach.hpp>
31 #include <boost/thread.hpp>
32 #include <openssl/crypto.h>
33 #include <openssl/rand.h>
34 #include <openssl/conf.h>
40 #define _WIN32_WINNT 0x0501
44 #define _WIN32_IE 0x0501
45 #define WIN32_LEAN_AND_MEAN 1
49 #include <io.h> /* for _commit */
51 #elif defined(__linux__)
52 # include <sys/prctl.h>
55 #if !defined(WIN32) && !defined(ANDROID)
61 namespace bt = boost::posix_time;
63 map<string, string> mapArgs;
64 map<string, vector<string> > mapMultiArgs;
66 bool fDebugNet = false;
67 bool fPrintToConsole = false;
68 bool fPrintToDebugger = false;
69 bool fRequestShutdown = false;
70 bool fShutdown = false;
73 bool fCommandLine = false;
74 string strMiscWarning;
75 bool fTestNet = false;
76 bool fNoListen = false;
77 bool fLogTimestamps = false;
78 CMedianFilter<int64_t> vTimeOffsets(200,0);
79 bool fReopenDebugLog = false;
81 // Extended DecodeDumpTime implementation, see this page for details:
82 // http://stackoverflow.com/questions/3786201/parsing-of-date-time-from-string-boost
83 const std::locale formats[] = {
84 std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%dT%H:%M:%SZ")),
85 std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d %H:%M:%S")),
86 std::locale(std::locale::classic(),new bt::time_input_facet("%Y/%m/%d %H:%M:%S")),
87 std::locale(std::locale::classic(),new bt::time_input_facet("%d.%m.%Y %H:%M:%S")),
88 std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d"))
91 const size_t formats_n = sizeof(formats)/sizeof(formats[0]);
93 std::time_t pt_to_time_t(const bt::ptime& pt)
95 bt::ptime timet_start(boost::gregorian::date(1970,1,1));
96 bt::time_duration diff = pt - timet_start;
97 return diff.ticks()/bt::time_duration::rep_type::ticks_per_second;
100 // Init OpenSSL library multithreading support
101 static CCriticalSection** ppmutexOpenSSL;
102 void locking_callback(int mode, int i, const char* file, int line)
104 if (mode & CRYPTO_LOCK) {
105 ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
107 LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
111 LockedPageManager LockedPageManager::instance;
119 // Init OpenSSL library multithreading support
120 ppmutexOpenSSL = (CCriticalSection**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(CCriticalSection*));
121 for (int i = 0; i < CRYPTO_num_locks(); i++)
122 ppmutexOpenSSL[i] = new CCriticalSection();
123 CRYPTO_set_locking_callback(locking_callback);
125 // OpenSSL can optionally load a config file which lists optional loadable modules and engines.
126 // We don't use them so we don't require the config. However some of our libs may call functions
127 // which attempt to load the config file, possibly resulting in an exit() or crash if it is missing
128 // or corrupt. Explicitly tell OpenSSL not to try to load the file. The result for our libs will be
129 // that the config appears to have been loaded and there are no modules/engines available.
133 // Seed random number generator with screen scrape and other hardware sources
137 // Seed random number generator with performance counter
142 // Shutdown OpenSSL library multithreading support
143 CRYPTO_set_locking_callback(NULL);
144 for (int i = 0; i < CRYPTO_num_locks(); i++)
145 delete ppmutexOpenSSL[i];
146 OPENSSL_free(ppmutexOpenSSL);
160 // Seed with CPU performance counter
161 int64_t nCounter = GetPerformanceCounter();
162 RAND_add(&nCounter, sizeof(nCounter), 1.5);
163 memset(&nCounter, 0, sizeof(nCounter));
166 void RandAddSeedPerfmon()
170 // This can take up to 2 seconds, so only do it every 10 minutes
171 static int64_t nLastPerfmon;
172 if (GetTime() < nLastPerfmon + 10 * 60)
174 nLastPerfmon = GetTime();
177 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom
178 // Seed with the entire set of perfmon data
179 unsigned char pdata[250000];
180 memset(pdata, 0, sizeof(pdata));
181 unsigned long nSize = sizeof(pdata);
182 long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
183 RegCloseKey(HKEY_PERFORMANCE_DATA);
184 if (ret == ERROR_SUCCESS)
186 RAND_add(pdata, nSize, nSize/100.0);
187 OPENSSL_cleanse(pdata, nSize);
188 printf("RandAddSeed() %lu bytes\n", nSize);
193 uint64_t GetRand(uint64_t nMax)
198 // The range of the random source must be a multiple of the modulus
199 // to give every possible output value an equal possibility
200 uint64_t nRange = (std::numeric_limits<uint64_t>::max() / nMax) * nMax;
203 RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
204 while (nRand >= nRange);
205 return (nRand % nMax);
208 int GetRandInt(int nMax)
210 return static_cast<int>(GetRand(nMax));
213 uint256 GetRandHash()
216 RAND_bytes((unsigned char*)&hash, sizeof(hash));
225 static FILE* fileout = NULL;
227 inline int OutputDebugStringF(const char* pszFormat, ...)
234 va_start(arg_ptr, pszFormat);
235 ret = vprintf(pszFormat, arg_ptr);
238 else if (!fPrintToDebugger)
240 // print to debug.log
244 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
245 fileout = fopen(pathDebug.string().c_str(), "a");
246 if (fileout) setbuf(fileout, NULL); // unbuffered
250 static bool fStartedNewLine = true;
252 // This routine may be called by global destructors during shutdown.
253 // Since the order of destruction of static/global objects is undefined,
254 // allocate mutexDebugLog on the heap the first time this routine
255 // is called to avoid crashes during shutdown.
256 static boost::mutex* mutexDebugLog = NULL;
257 if (mutexDebugLog == NULL) mutexDebugLog = new boost::mutex();
258 boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
260 // reopen the log file, if requested
261 if (fReopenDebugLog) {
262 fReopenDebugLog = false;
263 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
264 if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL)
265 setbuf(fileout, NULL); // unbuffered
268 // Debug print useful for profiling
269 if (fLogTimestamps && fStartedNewLine)
270 fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
271 if (pszFormat[strlen(pszFormat) - 1] == '\n')
272 fStartedNewLine = true;
274 fStartedNewLine = false;
277 va_start(arg_ptr, pszFormat);
278 ret = vfprintf(fileout, pszFormat, arg_ptr);
284 if (fPrintToDebugger)
286 static CCriticalSection cs_OutputDebugStringF;
288 // accumulate and output a line at a time
290 LOCK(cs_OutputDebugStringF);
291 static std::string buffer;
294 va_start(arg_ptr, pszFormat);
295 buffer += vstrprintf(pszFormat, arg_ptr);
298 size_t line_start = 0, line_end;
299 while((line_end = buffer.find('\n', line_start)) != -1)
301 OutputDebugStringA(buffer.substr(line_start, line_end - line_start).c_str());
302 line_start = line_end + 1;
304 buffer.erase(0, line_start);
311 string vstrprintf(const char *format, va_list ap)
315 int limit = sizeof(buffer);
321 va_copy(arg_ptr, ap);
323 va_list arg_ptr = ap;
326 ret = _vsnprintf(p, limit, format, arg_ptr);
328 ret = vsnprintf(p, limit, format, arg_ptr);
331 if (ret >= 0 && ret < limit)
336 p = new(nothrow) char[limit];
338 throw std::bad_alloc();
340 string str(p, p+ret);
346 string real_strprintf(const char *format, int dummy, ...)
349 va_start(arg_ptr, dummy);
350 string str = vstrprintf(format, arg_ptr);
355 string real_strprintf(const std::string &format, int dummy, ...)
358 va_start(arg_ptr, dummy);
359 string str = vstrprintf(format.c_str(), arg_ptr);
364 bool error(const char *format, ...)
367 va_start(arg_ptr, format);
368 std::string str = vstrprintf(format, arg_ptr);
370 printf("ERROR: %s\n", str.c_str());
375 void ParseString(const string& str, char c, vector<string>& v)
379 string::size_type i1 = 0;
380 string::size_type i2;
383 i2 = str.find(c, i1);
386 v.push_back(str.substr(i1));
389 v.push_back(str.substr(i1, i2-i1));
395 string FormatMoney(int64_t n, bool fPlus)
397 // Note: not using straight sprintf here because we do NOT want
398 // localized number formatting.
399 int64_t n_abs = (n > 0 ? n : -n);
400 int64_t quotient = n_abs/COIN;
401 int64_t remainder = n_abs%COIN;
402 string str = strprintf("%" PRId64 ".%06" PRId64, quotient, remainder);
404 // Right-trim excess zeros before the decimal point:
406 for (size_t i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
409 str.erase(str.size()-nTrim, nTrim);
412 str.insert(0u, 1, '-');
413 else if (fPlus && n > 0)
414 str.insert(0u, 1, '+');
419 bool ParseMoney(const string& str, int64_t& nRet)
421 return ParseMoney(str.c_str(), nRet);
424 bool ParseMoney(const char* pszIn, int64_t& nRet)
428 const char* p = pszIn;
436 int64_t nMult = CENT*10;
437 while (isdigit(*p) && (nMult > 0))
439 nUnits += nMult * (*p++ - '0');
448 strWhole.insert(strWhole.end(), *p);
453 if (strWhole.size() > 10) // guard against 63 bit overflow
455 if (nUnits < 0 || nUnits > COIN)
457 int64_t nWhole = atoi64(strWhole);
458 int64_t nValue = nWhole*COIN + nUnits;
465 static const signed char phexdigit[256] =
466 { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
467 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
468 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
469 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
470 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
471 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
472 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
473 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
474 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
475 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
476 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
477 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
478 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
479 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
480 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
481 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
483 bool IsHex(const string& str)
485 BOOST_FOREACH(unsigned char c, str)
487 if (phexdigit[c] < 0)
490 return (str.size() > 0) && (str.size()%2 == 0);
493 vector<unsigned char> ParseHex(const char* psz)
495 // convert hex dump to vector
496 vector<unsigned char> vch;
499 while (isspace(*psz))
501 signed char c = phexdigit[(unsigned char)*psz++];
502 if (c == (signed char)-1)
504 unsigned char n = (c << 4);
505 c = phexdigit[(unsigned char)*psz++];
506 if (c == (signed char)-1)
514 vector<unsigned char> ParseHex(const string& str)
516 return ParseHex(str.c_str());
519 static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
521 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
522 if (name.find("-no") == 0)
524 std::string positive("-");
525 positive.append(name.begin()+3, name.end());
526 if (mapSettingsRet.count(positive) == 0)
528 bool value = !GetBoolArg(name);
529 mapSettingsRet[positive] = (value ? "1" : "0");
534 void ParseParameters(int argc, const char* const argv[])
537 mapMultiArgs.clear();
538 for (int i = 1; i < argc; i++)
540 std::string str(argv[i]);
541 std::string strValue;
542 size_t is_index = str.find('=');
543 if (is_index != std::string::npos)
545 strValue = str.substr(is_index+1);
546 str = str.substr(0, is_index);
549 boost::to_lower(str);
550 if (boost::algorithm::starts_with(str, "/"))
551 str = "-" + str.substr(1);
556 mapArgs[str] = strValue;
557 mapMultiArgs[str].push_back(strValue);
561 BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs)
563 string name = entry.first;
565 // interpret --foo as -foo (as long as both are not set)
566 if (name.find("--") == 0)
568 std::string singleDash(name.begin()+1, name.end());
569 if (mapArgs.count(singleDash) == 0)
570 mapArgs[singleDash] = entry.second;
574 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
575 InterpretNegativeSetting(name, mapArgs);
579 std::string GetArg(const std::string& strArg, const std::string& strDefault)
581 if (mapArgs.count(strArg))
582 return mapArgs[strArg];
586 int64_t GetArg(const std::string& strArg, int64_t nDefault)
588 if (mapArgs.count(strArg))
589 return atoi64(mapArgs[strArg]);
593 int32_t GetArgInt(const std::string& strArg, int32_t nDefault)
595 if (mapArgs.count(strArg))
596 return strtol(mapArgs[strArg]);
600 uint32_t GetArgUInt(const std::string& strArg, uint32_t nDefault)
602 if (mapArgs.count(strArg))
603 return strtoul(mapArgs[strArg]);
607 bool GetBoolArg(const std::string& strArg, bool fDefault)
609 if (mapArgs.count(strArg))
611 if (mapArgs[strArg].empty())
613 return (atoi(mapArgs[strArg]) != 0);
618 bool SoftSetArg(const std::string& strArg, const std::string& strValue)
620 if (mapArgs.count(strArg) || mapMultiArgs.count(strArg))
622 mapArgs[strArg] = strValue;
623 mapMultiArgs[strArg].push_back(strValue);
628 bool SoftSetBoolArg(const std::string& strArg, bool fValue)
631 return SoftSetArg(strArg, std::string("1"));
633 return SoftSetArg(strArg, std::string("0"));
637 string EncodeBase64(const unsigned char* pch, size_t len)
639 static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
642 strRet.reserve((len+2)/3*4);
645 const unsigned char *pchEnd = pch+len;
652 case 0: // we have no bits
653 strRet += pbase64[enc >> 2];
654 left = (enc & 3) << 4;
658 case 1: // we have two bits
659 strRet += pbase64[left | (enc >> 4)];
660 left = (enc & 15) << 2;
664 case 2: // we have four bits
665 strRet += pbase64[left | (enc >> 6)];
666 strRet += pbase64[enc & 63];
674 strRet += pbase64[left];
683 string EncodeBase64(const string& str)
685 return EncodeBase64((const unsigned char*)str.c_str(), str.size());
688 vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
690 static const int decode64_table[256] =
692 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
693 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
694 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
695 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
696 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
697 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
698 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
699 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
700 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
701 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
702 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
703 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
704 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
710 vector<unsigned char> vchRet;
711 vchRet.reserve(strlen(p)*3/4);
718 int dec = decode64_table[(unsigned char)*p];
719 if (dec == -1) break;
723 case 0: // we have no bits and get 6
728 case 1: // we have 6 bits and keep 4
729 vchRet.push_back((left<<2) | (dec>>4));
734 case 2: // we have 4 bits and get 6, we keep 2
735 vchRet.push_back((left<<4) | (dec>>2));
740 case 3: // we have 2 bits and get 6
741 vchRet.push_back((left<<6) | dec);
750 case 0: // 4n base64 characters processed: ok
753 case 1: // 4n+1 base64 character processed: impossible
757 case 2: // 4n+2 base64 characters processed: require '=='
758 if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1)
762 case 3: // 4n+3 base64 characters processed: require '='
763 if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1)
771 string DecodeBase64(const string& str)
773 vector<unsigned char> vchRet = DecodeBase64(str.c_str());
774 return string((const char*)&vchRet[0], vchRet.size());
777 string EncodeBase32(const unsigned char* pch, size_t len)
779 static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567";
782 strRet.reserve((len+4)/5*8);
785 const unsigned char *pchEnd = pch+len;
792 case 0: // we have no bits
793 strRet += pbase32[enc >> 3];
794 left = (enc & 7) << 2;
798 case 1: // we have three bits
799 strRet += pbase32[left | (enc >> 6)];
800 strRet += pbase32[(enc >> 1) & 31];
801 left = (enc & 1) << 4;
805 case 2: // we have one bit
806 strRet += pbase32[left | (enc >> 4)];
807 left = (enc & 15) << 1;
811 case 3: // we have four bits
812 strRet += pbase32[left | (enc >> 7)];
813 strRet += pbase32[(enc >> 2) & 31];
814 left = (enc & 3) << 3;
818 case 4: // we have two bits
819 strRet += pbase32[left | (enc >> 5)];
820 strRet += pbase32[enc & 31];
825 static const int nPadding[5] = {0, 6, 4, 3, 1};
828 strRet += pbase32[left];
829 for (int n=0; n<nPadding[mode]; n++)
836 string EncodeBase32(const string& str)
838 return EncodeBase32((const unsigned char*)str.c_str(), str.size());
841 vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid)
843 static const int decode32_table[256] =
845 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
846 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
847 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1,
848 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
849 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 0, 1, 2,
850 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
851 23, 24, 25, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
852 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
853 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
854 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
855 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
856 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
857 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
863 vector<unsigned char> vchRet;
864 vchRet.reserve((strlen(p))*5/8);
871 int dec = decode32_table[(unsigned char)*p];
872 if (dec == -1) break;
876 case 0: // we have no bits and get 5
881 case 1: // we have 5 bits and keep 2
882 vchRet.push_back((left<<3) | (dec>>2));
887 case 2: // we have 2 bits and keep 7
888 left = left << 5 | dec;
892 case 3: // we have 7 bits and keep 4
893 vchRet.push_back((left<<1) | (dec>>4));
898 case 4: // we have 4 bits, and keep 1
899 vchRet.push_back((left<<4) | (dec>>1));
904 case 5: // we have 1 bit, and keep 6
905 left = left << 5 | dec;
909 case 6: // we have 6 bits, and keep 3
910 vchRet.push_back((left<<2) | (dec>>3));
915 case 7: // we have 3 bits, and keep 0
916 vchRet.push_back((left<<5) | dec);
925 case 0: // 8n base32 characters processed: ok
928 case 1: // 8n+1 base32 characters processed: impossible
934 case 2: // 8n+2 base32 characters processed: require '======'
935 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || p[4] != '=' || p[5] != '=' || decode32_table[(unsigned char)p[6]] != -1)
939 case 4: // 8n+4 base32 characters processed: require '===='
940 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || decode32_table[(unsigned char)p[4]] != -1)
944 case 5: // 8n+5 base32 characters processed: require '==='
945 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || decode32_table[(unsigned char)p[3]] != -1)
949 case 7: // 8n+7 base32 characters processed: require '='
950 if (left || p[0] != '=' || decode32_table[(unsigned char)p[1]] != -1)
958 string DecodeBase32(const string& str)
960 vector<unsigned char> vchRet = DecodeBase32(str.c_str());
961 return string((const char*)&vchRet[0], vchRet.size());
965 int64_t DecodeDumpTime(const std::string& s)
969 for(size_t i=0; i<formats_n; ++i)
971 std::istringstream is(s);
972 is.imbue(formats[i]);
974 if(pt != bt::ptime()) break;
977 return pt_to_time_t(pt);
980 std::string EncodeDumpTime(int64_t nTime) {
981 return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime);
984 std::string EncodeDumpString(const std::string &str) {
985 std::stringstream ret;
986 BOOST_FOREACH(unsigned char c, str) {
987 if (c <= 32 || c >= 128 || c == '%') {
988 ret << '%' << HexStr(&c, &c + 1);
996 std::string DecodeDumpString(const std::string &str) {
997 std::stringstream ret;
998 for (unsigned int pos = 0; pos < str.length(); pos++) {
999 unsigned char c = str[pos];
1000 if (c == '%' && pos+2 < str.length()) {
1001 c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) |
1002 ((str[pos+2]>>6)*9+((str[pos+2]-'0')&15));
1010 bool WildcardMatch(const char* psz, const char* mask)
1017 return (*psz == '\0');
1019 return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
1034 bool WildcardMatch(const string& str, const string& mask)
1036 return WildcardMatch(str.c_str(), mask.c_str());
1046 static std::string FormatException(std::exception* pex, const char* pszThread)
1049 char pszModule[MAX_PATH] = "";
1050 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
1052 const char* pszModule = "novacoin";
1056 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
1059 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
1062 void LogException(std::exception* pex, const char* pszThread)
1064 std::string message = FormatException(pex, pszThread);
1065 printf("\n%s", message.c_str());
1068 void PrintException(std::exception* pex, const char* pszThread)
1070 std::string message = FormatException(pex, pszThread);
1071 printf("\n\n************************\n%s\n", message.c_str());
1072 fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
1073 strMiscWarning = message;
1077 void LogStackTrace() {
1078 printf("\n\n******* exception encountered *******\n");
1081 #if !defined(WIN32) && !defined(ANDROID)
1082 void* pszBuffer[32];
1084 size = backtrace(pszBuffer, 32);
1085 backtrace_symbols_fd(pszBuffer, size, fileno(fileout));
1090 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
1092 std::string message = FormatException(pex, pszThread);
1093 printf("\n\n************************\n%s\n", message.c_str());
1094 fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
1095 strMiscWarning = message;
1098 boost::filesystem::path GetDefaultDataDir()
1100 namespace fs = boost::filesystem;
1101 // Windows < Vista: C:\Documents and Settings\Username\Application Data\NovaCoin
1102 // Windows >= Vista: C:\Users\Username\AppData\Roaming\NovaCoin
1103 // Mac: ~/Library/Application Support/NovaCoin
1104 // Unix: ~/.novacoin
1107 return GetSpecialFolderPath(CSIDL_APPDATA) / "NovaCoin";
1110 char* pszHome = getenv("HOME");
1111 if (pszHome == NULL || strlen(pszHome) == 0)
1112 pathRet = fs::path("/");
1114 pathRet = fs::path(pszHome);
1117 pathRet /= "Library/Application Support";
1118 fs::create_directory(pathRet);
1119 return pathRet / "NovaCoin";
1122 return pathRet / ".novacoin";
1127 const boost::filesystem::path &GetDataDir(bool fNetSpecific)
1129 namespace fs = boost::filesystem;
1131 static fs::path pathCached[2];
1132 static CCriticalSection csPathCached;
1133 static bool cachedPath[2] = {false, false};
1135 fs::path &path = pathCached[fNetSpecific];
1137 // This can be called during exceptions by printf, so we cache the
1138 // value so we don't have to do memory allocations after that.
1139 if (cachedPath[fNetSpecific])
1144 if (mapArgs.count("-datadir")) {
1145 path = fs::system_complete(mapArgs["-datadir"]);
1146 if (!fs::is_directory(path)) {
1151 path = GetDefaultDataDir();
1153 if (fNetSpecific && GetBoolArg("-testnet", false))
1156 fs::create_directory(path);
1158 cachedPath[fNetSpecific]=true;
1162 string randomStrGen(int length) {
1163 static string charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
1165 result.resize(length);
1166 for (int32_t i = 0; i < length; i++)
1167 result[i] = charset[rand() % charset.length()];
1174 srand(static_cast<unsigned int>(time(NULL)));
1177 #if BOOST_FILESYSTEM_VERSION >= 3
1178 pConf.open(GetConfigFile().generic_string().c_str());
1180 pConf.open(GetConfigFile().string().c_str());
1182 pConf << "rpcuser=user\nrpcpassword="
1185 + "\n#(0=off, 1=on) daemon - run in the background as a daemon and accept commands"
1187 + "\n#(0=off, 1=on) server - accept command line and JSON-RPC commands"
1189 + "\nrpcallowip=127.0.0.1";
1193 boost::filesystem::path GetConfigFile()
1195 boost::filesystem::path pathConfigFile(GetArg("-conf", "novacoin.conf"));
1196 if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
1197 return pathConfigFile;
1200 void ReadConfigFile(map<string, string>& mapSettingsRet,
1201 map<string, vector<string> >& mapMultiSettingsRet)
1203 boost::filesystem::ifstream streamConfig(GetConfigFile());
1204 if (!streamConfig.good())
1207 new(&streamConfig) boost::filesystem::ifstream(GetConfigFile());
1208 if(!streamConfig.good())
1212 set<string> setOptions;
1213 setOptions.insert("*");
1215 for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
1217 // Don't overwrite existing settings so command line settings override bitcoin.conf
1218 string strKey = string("-") + it->string_key;
1219 if (mapSettingsRet.count(strKey) == 0)
1221 mapSettingsRet[strKey] = it->value[0];
1222 // interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
1223 InterpretNegativeSetting(strKey, mapSettingsRet);
1225 mapMultiSettingsRet[strKey].push_back(it->value[0]);
1229 boost::filesystem::path GetPidFile()
1231 boost::filesystem::path pathPidFile(GetArg("-pid", "novacoind.pid"));
1232 if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
1237 void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
1239 FILE* file = fopen(path.string().c_str(), "w");
1242 fprintf(file, "%d\n", pid);
1248 bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
1251 return MoveFileExA(src.string().c_str(), dest.string().c_str(),
1252 MOVEFILE_REPLACE_EXISTING) != 0;
1254 int rc = std::rename(src.string().c_str(), dest.string().c_str());
1259 void FileCommit(FILE *fileout)
1261 fflush(fileout); // harmless if redundantly called
1263 _commit(_fileno(fileout));
1265 fsync(fileno(fileout));
1269 int GetFilesize(FILE* file)
1271 int nSavePos = ftell(file);
1273 if (fseek(file, 0, SEEK_END) == 0)
1274 nFilesize = ftell(file);
1275 fseek(file, nSavePos, SEEK_SET);
1279 void ShrinkDebugFile()
1281 // Scroll debug.log if it's getting too big
1282 boost::filesystem::path pathLog = GetDataDir() / "debug.log";
1283 FILE* file = fopen(pathLog.string().c_str(), "r");
1284 if (file && GetFilesize(file) > 10 * 1000000)
1286 // Restart the file with some of the end
1288 fseek(file, -((long long)sizeof(pch)), SEEK_END);
1289 size_t nBytes = fread(pch, 1, sizeof(pch), file);
1292 file = fopen(pathLog.string().c_str(), "w");
1295 fwrite(pch, 1, nBytes, file);
1309 // "Never go to sea with two chronometers; take one or three."
1310 // Our three time sources are:
1312 // - Median of other nodes clocks
1313 // - The user (asking the user to fix the system clock if the first two disagree)
1322 // Trusted NTP offset or median of NTP samples.
1323 extern int64_t nNtpOffset;
1325 // Median of time samples given by other nodes.
1326 static int64_t nNodesOffset = INT64_MAX;
1328 // Select time offset:
1329 int64_t GetTimeOffset()
1331 // If NTP and system clock are in agreement within 40 minutes, then use NTP.
1332 if (abs64(nNtpOffset) < 40 * 60)
1335 // If not, then choose between median peer time and system clock.
1336 if (abs64(nNodesOffset) < 70 * 60)
1337 return nNodesOffset;
1342 int64_t GetNodesOffset()
1344 return nNodesOffset;
1347 int64_t GetAdjustedTime()
1349 return GetTime() + GetTimeOffset();
1352 void AddTimeData(const CNetAddr& ip, int64_t nTime)
1354 int64_t nOffsetSample = nTime - GetTime();
1356 // Ignore duplicates
1357 static set<CNetAddr> setKnown;
1358 if (!setKnown.insert(ip).second)
1362 vTimeOffsets.input(nOffsetSample);
1363 printf("Added time data, samples %d, offset %+" PRId64 " (%+" PRId64 " minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
1364 if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
1366 int64_t nMedian = vTimeOffsets.median();
1367 std::vector<int64_t> vSorted = vTimeOffsets.sorted();
1368 // Only let other nodes change our time by so much
1369 if (abs64(nMedian) < 70 * 60)
1371 nNodesOffset = nMedian;
1375 nNodesOffset = INT64_MAX;
1380 bool fMatch = false;
1382 // If nobody has a time different than ours but within 5 minutes of ours, give a warning
1383 BOOST_FOREACH(int64_t nOffset, vSorted)
1384 if (nOffset != 0 && abs64(nOffset) < 5 * 60)
1390 string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong NovaCoin will not work properly.");
1391 strMiscWarning = strMessage;
1392 printf("*** %s\n", strMessage.c_str());
1393 uiInterface.ThreadSafeMessageBox(strMessage+" ", string("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION);
1398 BOOST_FOREACH(int64_t n, vSorted)
1399 printf("%+" PRId64 " ", n);
1402 if (nNodesOffset != INT64_MAX)
1403 printf("nNodesOffset = %+" PRId64 " (%+" PRId64 " minutes)\n", nNodesOffset, nNodesOffset/60);
1407 string FormatVersion(int nVersion)
1409 if (nVersion%100 == 0)
1410 return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
1412 return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
1415 string FormatFullVersion()
1417 return CLIENT_BUILD;
1420 // Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
1421 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
1423 std::ostringstream ss;
1425 ss << name << ":" << FormatVersion(nClientVersion);
1426 if (!comments.empty())
1427 ss << "(" << boost::algorithm::join(comments, "; ") << ")";
1433 boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate)
1435 namespace fs = boost::filesystem;
1437 char pszPath[MAX_PATH] = "";
1439 if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
1441 return fs::path(pszPath);
1444 printf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
1445 return fs::path("");
1449 void runCommand(std::string strCommand)
1451 int nErr = ::system(strCommand.c_str());
1453 printf("runCommand error: system(%s) returned %d\n", strCommand.c_str(), nErr);
1456 void RenameThread(const char* name)
1458 #if defined(PR_SET_NAME)
1459 // Only the first 15 characters are used (16 - NUL terminator)
1460 ::prctl(PR_SET_NAME, name, 0, 0, 0);
1461 #elif 0 && (defined(__FreeBSD__) || defined(__OpenBSD__))
1462 // TODO: This is currently disabled because it needs to be verified to work
1463 // on FreeBSD or OpenBSD first. When verified the '0 &&' part can be
1465 pthread_set_name_np(pthread_self(), name);
1467 // This is XCode 10.6-and-later; bring back if we drop 10.5 support:
1468 // #elif defined(MAC_OSX)
1469 // pthread_setname_np(name);
1472 // Prevent warnings for unused parameters...
1477 bool NewThread(void(*pfn)(void*), void* parg)
1481 boost::thread(pfn, parg); // thread detaches when out of scope
1482 } catch(boost::thread_resource_error &e) {
1483 printf("Error creating thread: %s\n", e.what());
1489 std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime)
1491 // std::locale takes ownership of the pointer
1492 std::locale loc(std::locale::classic(), new boost::posix_time::time_facet(pszFormat));
1493 std::stringstream ss;
1495 ss << boost::posix_time::from_time_t(nTime);