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>
37 #pragma warning(disable:4786)
38 #pragma warning(disable:4804)
39 #pragma warning(disable:4805)
40 #pragma warning(disable:4717)
45 #define _WIN32_WINNT 0x0501
49 #define _WIN32_IE 0x0501
50 #define WIN32_LEAN_AND_MEAN 1
54 #include <io.h> /* for _commit */
56 #elif defined(__linux__)
57 # include <sys/prctl.h>
60 #if !defined(WIN32) && !defined(ANDROID)
66 namespace bt = boost::posix_time;
68 map<string, string> mapArgs;
69 map<string, vector<string> > mapMultiArgs;
71 bool fDebugNet = false;
72 bool fPrintToConsole = false;
73 bool fPrintToDebugger = false;
74 bool fRequestShutdown = false;
75 bool fShutdown = false;
78 bool fCommandLine = false;
79 string strMiscWarning;
80 bool fTestNet = false;
81 bool fNoListen = false;
82 bool fLogTimestamps = false;
83 CMedianFilter<int64_t> vTimeOffsets(200,0);
84 bool fReopenDebugLog = false;
86 // Extended DecodeDumpTime implementation, see this page for details:
87 // http://stackoverflow.com/questions/3786201/parsing-of-date-time-from-string-boost
88 const std::locale formats[] = {
89 std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%dT%H:%M:%SZ")),
90 std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d %H:%M:%S")),
91 std::locale(std::locale::classic(),new bt::time_input_facet("%Y/%m/%d %H:%M:%S")),
92 std::locale(std::locale::classic(),new bt::time_input_facet("%d.%m.%Y %H:%M:%S")),
93 std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d"))
96 const size_t formats_n = sizeof(formats)/sizeof(formats[0]);
98 std::time_t pt_to_time_t(const bt::ptime& pt)
100 bt::ptime timet_start(boost::gregorian::date(1970,1,1));
101 bt::time_duration diff = pt - timet_start;
102 return diff.ticks()/bt::time_duration::rep_type::ticks_per_second;
105 // Init OpenSSL library multithreading support
106 static CCriticalSection** ppmutexOpenSSL;
107 void locking_callback(int mode, int i, const char* file, int line)
109 if (mode & CRYPTO_LOCK) {
110 ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
112 LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
116 LockedPageManager LockedPageManager::instance;
124 // Init OpenSSL library multithreading support
125 ppmutexOpenSSL = (CCriticalSection**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(CCriticalSection*));
126 for (int i = 0; i < CRYPTO_num_locks(); i++)
127 ppmutexOpenSSL[i] = new CCriticalSection();
128 CRYPTO_set_locking_callback(locking_callback);
131 // Seed random number generator with screen scrape and other hardware sources
135 // Seed random number generator with performance counter
140 // Shutdown OpenSSL library multithreading support
141 CRYPTO_set_locking_callback(NULL);
142 for (int i = 0; i < CRYPTO_num_locks(); i++)
143 delete ppmutexOpenSSL[i];
144 OPENSSL_free(ppmutexOpenSSL);
158 // Seed with CPU performance counter
159 int64_t nCounter = GetPerformanceCounter();
160 RAND_add(&nCounter, sizeof(nCounter), 1.5);
161 memset(&nCounter, 0, sizeof(nCounter));
164 void RandAddSeedPerfmon()
168 // This can take up to 2 seconds, so only do it every 10 minutes
169 static int64_t nLastPerfmon;
170 if (GetTime() < nLastPerfmon + 10 * 60)
172 nLastPerfmon = GetTime();
175 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom
176 // Seed with the entire set of perfmon data
177 unsigned char pdata[250000];
178 memset(pdata, 0, sizeof(pdata));
179 unsigned long nSize = sizeof(pdata);
180 long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
181 RegCloseKey(HKEY_PERFORMANCE_DATA);
182 if (ret == ERROR_SUCCESS)
184 RAND_add(pdata, nSize, nSize/100.0);
185 OPENSSL_cleanse(pdata, nSize);
186 printf("RandAddSeed() %lu bytes\n", nSize);
191 uint64_t GetRand(uint64_t nMax)
196 // The range of the random source must be a multiple of the modulus
197 // to give every possible output value an equal possibility
198 uint64_t nRange = (std::numeric_limits<uint64_t>::max() / nMax) * nMax;
201 RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
202 while (nRand >= nRange);
203 return (nRand % nMax);
206 int GetRandInt(int nMax)
208 return static_cast<int>(GetRand(nMax));
211 uint256 GetRandHash()
214 RAND_bytes((unsigned char*)&hash, sizeof(hash));
223 static FILE* fileout = NULL;
225 inline int OutputDebugStringF(const char* pszFormat, ...)
232 va_start(arg_ptr, pszFormat);
233 ret = vprintf(pszFormat, arg_ptr);
236 else if (!fPrintToDebugger)
238 // print to debug.log
242 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
243 fileout = fopen(pathDebug.string().c_str(), "a");
244 if (fileout) setbuf(fileout, NULL); // unbuffered
248 static bool fStartedNewLine = true;
250 // This routine may be called by global destructors during shutdown.
251 // Since the order of destruction of static/global objects is undefined,
252 // allocate mutexDebugLog on the heap the first time this routine
253 // is called to avoid crashes during shutdown.
254 static boost::mutex* mutexDebugLog = NULL;
255 if (mutexDebugLog == NULL) mutexDebugLog = new boost::mutex();
256 boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
258 // reopen the log file, if requested
259 if (fReopenDebugLog) {
260 fReopenDebugLog = false;
261 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
262 if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL)
263 setbuf(fileout, NULL); // unbuffered
266 // Debug print useful for profiling
267 if (fLogTimestamps && fStartedNewLine)
268 fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
269 if (pszFormat[strlen(pszFormat) - 1] == '\n')
270 fStartedNewLine = true;
272 fStartedNewLine = false;
275 va_start(arg_ptr, pszFormat);
276 ret = vfprintf(fileout, pszFormat, arg_ptr);
282 if (fPrintToDebugger)
284 static CCriticalSection cs_OutputDebugStringF;
286 // accumulate and output a line at a time
288 LOCK(cs_OutputDebugStringF);
289 static std::string buffer;
292 va_start(arg_ptr, pszFormat);
293 buffer += vstrprintf(pszFormat, arg_ptr);
296 int line_start = 0, line_end;
297 while((line_end = buffer.find('\n', line_start)) != -1)
299 OutputDebugStringA(buffer.substr(line_start, line_end - line_start).c_str());
300 line_start = line_end + 1;
302 buffer.erase(0, line_start);
309 string vstrprintf(const char *format, va_list ap)
313 int limit = sizeof(buffer);
319 va_copy(arg_ptr, ap);
321 va_list arg_ptr = ap;
324 ret = _vsnprintf(p, limit, format, arg_ptr);
326 ret = vsnprintf(p, limit, format, arg_ptr);
329 if (ret >= 0 && ret < limit)
336 throw std::bad_alloc();
338 string str(p, p+ret);
344 string real_strprintf(const char *format, int dummy, ...)
347 va_start(arg_ptr, dummy);
348 string str = vstrprintf(format, arg_ptr);
353 string real_strprintf(const std::string &format, int dummy, ...)
356 va_start(arg_ptr, dummy);
357 string str = vstrprintf(format.c_str(), arg_ptr);
362 bool error(const char *format, ...)
365 va_start(arg_ptr, format);
366 std::string str = vstrprintf(format, arg_ptr);
368 printf("ERROR: %s\n", str.c_str());
373 void ParseString(const string& str, char c, vector<string>& v)
377 string::size_type i1 = 0;
378 string::size_type i2;
381 i2 = str.find(c, i1);
384 v.push_back(str.substr(i1));
387 v.push_back(str.substr(i1, i2-i1));
393 string FormatMoney(int64_t n, bool fPlus)
395 // Note: not using straight sprintf here because we do NOT want
396 // localized number formatting.
397 int64_t n_abs = (n > 0 ? n : -n);
398 int64_t quotient = n_abs/COIN;
399 int64_t remainder = n_abs%COIN;
400 string str = strprintf("%" PRId64 ".%06" PRId64, quotient, remainder);
402 // Right-trim excess zeros before the decimal point:
404 for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
407 str.erase(str.size()-nTrim, nTrim);
410 str.insert((unsigned int)0, 1, '-');
411 else if (fPlus && n > 0)
412 str.insert((unsigned int)0, 1, '+');
417 bool ParseMoney(const string& str, int64_t& nRet)
419 return ParseMoney(str.c_str(), nRet);
422 bool ParseMoney(const char* pszIn, int64_t& nRet)
426 const char* p = pszIn;
434 int64_t nMult = CENT*10;
435 while (isdigit(*p) && (nMult > 0))
437 nUnits += nMult * (*p++ - '0');
446 strWhole.insert(strWhole.end(), *p);
451 if (strWhole.size() > 10) // guard against 63 bit overflow
453 if (nUnits < 0 || nUnits > COIN)
455 int64_t nWhole = atoi64(strWhole);
456 int64_t nValue = nWhole*COIN + nUnits;
463 static const signed char phexdigit[256] =
464 { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
465 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
466 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
467 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
468 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
469 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-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,-1,-1,-1,-1,-1,-1,-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, };
481 bool IsHex(const string& str)
483 BOOST_FOREACH(unsigned char c, str)
485 if (phexdigit[c] < 0)
488 return (str.size() > 0) && (str.size()%2 == 0);
491 vector<unsigned char> ParseHex(const char* psz)
493 // convert hex dump to vector
494 vector<unsigned char> vch;
497 while (isspace(*psz))
499 signed char c = phexdigit[(unsigned char)*psz++];
500 if (c == (signed char)-1)
502 unsigned char n = (c << 4);
503 c = phexdigit[(unsigned char)*psz++];
504 if (c == (signed char)-1)
512 vector<unsigned char> ParseHex(const string& str)
514 return ParseHex(str.c_str());
517 static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
519 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
520 if (name.find("-no") == 0)
522 std::string positive("-");
523 positive.append(name.begin()+3, name.end());
524 if (mapSettingsRet.count(positive) == 0)
526 bool value = !GetBoolArg(name);
527 mapSettingsRet[positive] = (value ? "1" : "0");
532 void ParseParameters(int argc, const char* const argv[])
535 mapMultiArgs.clear();
536 for (int i = 1; i < argc; i++)
538 std::string str(argv[i]);
539 std::string strValue;
540 size_t is_index = str.find('=');
541 if (is_index != std::string::npos)
543 strValue = str.substr(is_index+1);
544 str = str.substr(0, is_index);
547 boost::to_lower(str);
548 if (boost::algorithm::starts_with(str, "/"))
549 str = "-" + str.substr(1);
554 mapArgs[str] = strValue;
555 mapMultiArgs[str].push_back(strValue);
559 BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs)
561 string name = entry.first;
563 // interpret --foo as -foo (as long as both are not set)
564 if (name.find("--") == 0)
566 std::string singleDash(name.begin()+1, name.end());
567 if (mapArgs.count(singleDash) == 0)
568 mapArgs[singleDash] = entry.second;
572 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
573 InterpretNegativeSetting(name, mapArgs);
577 std::string GetArg(const std::string& strArg, const std::string& strDefault)
579 if (mapArgs.count(strArg))
580 return mapArgs[strArg];
584 int64_t GetArg(const std::string& strArg, int64_t nDefault)
586 if (mapArgs.count(strArg))
587 return atoi64(mapArgs[strArg]);
591 bool GetBoolArg(const std::string& strArg, bool fDefault)
593 if (mapArgs.count(strArg))
595 if (mapArgs[strArg].empty())
597 return (atoi(mapArgs[strArg]) != 0);
602 bool SoftSetArg(const std::string& strArg, const std::string& strValue)
604 if (mapArgs.count(strArg) || mapMultiArgs.count(strArg))
606 mapArgs[strArg] = strValue;
607 mapMultiArgs[strArg].push_back(strValue);
612 bool SoftSetBoolArg(const std::string& strArg, bool fValue)
615 return SoftSetArg(strArg, std::string("1"));
617 return SoftSetArg(strArg, std::string("0"));
621 string EncodeBase64(const unsigned char* pch, size_t len)
623 static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
626 strRet.reserve((len+2)/3*4);
629 const unsigned char *pchEnd = pch+len;
636 case 0: // we have no bits
637 strRet += pbase64[enc >> 2];
638 left = (enc & 3) << 4;
642 case 1: // we have two bits
643 strRet += pbase64[left | (enc >> 4)];
644 left = (enc & 15) << 2;
648 case 2: // we have four bits
649 strRet += pbase64[left | (enc >> 6)];
650 strRet += pbase64[enc & 63];
658 strRet += pbase64[left];
667 string EncodeBase64(const string& str)
669 return EncodeBase64((const unsigned char*)str.c_str(), str.size());
672 vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
674 static const int decode64_table[256] =
676 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
677 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
678 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
679 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
680 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
681 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
682 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
683 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
684 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
685 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
686 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
687 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
688 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
694 vector<unsigned char> vchRet;
695 vchRet.reserve(strlen(p)*3/4);
702 int dec = decode64_table[(unsigned char)*p];
703 if (dec == -1) break;
707 case 0: // we have no bits and get 6
712 case 1: // we have 6 bits and keep 4
713 vchRet.push_back((left<<2) | (dec>>4));
718 case 2: // we have 4 bits and get 6, we keep 2
719 vchRet.push_back((left<<4) | (dec>>2));
724 case 3: // we have 2 bits and get 6
725 vchRet.push_back((left<<6) | dec);
734 case 0: // 4n base64 characters processed: ok
737 case 1: // 4n+1 base64 character processed: impossible
741 case 2: // 4n+2 base64 characters processed: require '=='
742 if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1)
746 case 3: // 4n+3 base64 characters processed: require '='
747 if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1)
755 string DecodeBase64(const string& str)
757 vector<unsigned char> vchRet = DecodeBase64(str.c_str());
758 return string((const char*)&vchRet[0], vchRet.size());
761 string EncodeBase32(const unsigned char* pch, size_t len)
763 static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567";
766 strRet.reserve((len+4)/5*8);
769 const unsigned char *pchEnd = pch+len;
776 case 0: // we have no bits
777 strRet += pbase32[enc >> 3];
778 left = (enc & 7) << 2;
782 case 1: // we have three bits
783 strRet += pbase32[left | (enc >> 6)];
784 strRet += pbase32[(enc >> 1) & 31];
785 left = (enc & 1) << 4;
789 case 2: // we have one bit
790 strRet += pbase32[left | (enc >> 4)];
791 left = (enc & 15) << 1;
795 case 3: // we have four bits
796 strRet += pbase32[left | (enc >> 7)];
797 strRet += pbase32[(enc >> 2) & 31];
798 left = (enc & 3) << 3;
802 case 4: // we have two bits
803 strRet += pbase32[left | (enc >> 5)];
804 strRet += pbase32[enc & 31];
809 static const int nPadding[5] = {0, 6, 4, 3, 1};
812 strRet += pbase32[left];
813 for (int n=0; n<nPadding[mode]; n++)
820 string EncodeBase32(const string& str)
822 return EncodeBase32((const unsigned char*)str.c_str(), str.size());
825 vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid)
827 static const int decode32_table[256] =
829 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
830 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
831 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1,
832 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
833 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 0, 1, 2,
834 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
835 23, 24, 25, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
836 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
837 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
838 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
839 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
840 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
841 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
847 vector<unsigned char> vchRet;
848 vchRet.reserve((strlen(p))*5/8);
855 int dec = decode32_table[(unsigned char)*p];
856 if (dec == -1) break;
860 case 0: // we have no bits and get 5
865 case 1: // we have 5 bits and keep 2
866 vchRet.push_back((left<<3) | (dec>>2));
871 case 2: // we have 2 bits and keep 7
872 left = left << 5 | dec;
876 case 3: // we have 7 bits and keep 4
877 vchRet.push_back((left<<1) | (dec>>4));
882 case 4: // we have 4 bits, and keep 1
883 vchRet.push_back((left<<4) | (dec>>1));
888 case 5: // we have 1 bit, and keep 6
889 left = left << 5 | dec;
893 case 6: // we have 6 bits, and keep 3
894 vchRet.push_back((left<<2) | (dec>>3));
899 case 7: // we have 3 bits, and keep 0
900 vchRet.push_back((left<<5) | dec);
909 case 0: // 8n base32 characters processed: ok
912 case 1: // 8n+1 base32 characters processed: impossible
918 case 2: // 8n+2 base32 characters processed: require '======'
919 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || p[4] != '=' || p[5] != '=' || decode32_table[(unsigned char)p[6]] != -1)
923 case 4: // 8n+4 base32 characters processed: require '===='
924 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || decode32_table[(unsigned char)p[4]] != -1)
928 case 5: // 8n+5 base32 characters processed: require '==='
929 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || decode32_table[(unsigned char)p[3]] != -1)
933 case 7: // 8n+7 base32 characters processed: require '='
934 if (left || p[0] != '=' || decode32_table[(unsigned char)p[1]] != -1)
942 string DecodeBase32(const string& str)
944 vector<unsigned char> vchRet = DecodeBase32(str.c_str());
945 return string((const char*)&vchRet[0], vchRet.size());
949 int64_t DecodeDumpTime(const std::string& s)
953 for(size_t i=0; i<formats_n; ++i)
955 std::istringstream is(s);
956 is.imbue(formats[i]);
958 if(pt != bt::ptime()) break;
961 return pt_to_time_t(pt);
964 std::string EncodeDumpTime(int64_t nTime) {
965 return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime);
968 std::string EncodeDumpString(const std::string &str) {
969 std::stringstream ret;
970 BOOST_FOREACH(unsigned char c, str) {
971 if (c <= 32 || c >= 128 || c == '%') {
972 ret << '%' << HexStr(&c, &c + 1);
980 std::string DecodeDumpString(const std::string &str) {
981 std::stringstream ret;
982 for (unsigned int pos = 0; pos < str.length(); pos++) {
983 unsigned char c = str[pos];
984 if (c == '%' && pos+2 < str.length()) {
985 c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) |
986 ((str[pos+2]>>6)*9+((str[pos+2]-'0')&15));
994 bool WildcardMatch(const char* psz, const char* mask)
1001 return (*psz == '\0');
1003 return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
1018 bool WildcardMatch(const string& str, const string& mask)
1020 return WildcardMatch(str.c_str(), mask.c_str());
1030 static std::string FormatException(std::exception* pex, const char* pszThread)
1033 char pszModule[MAX_PATH] = "";
1034 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
1036 const char* pszModule = "novacoin";
1040 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
1043 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
1046 void LogException(std::exception* pex, const char* pszThread)
1048 std::string message = FormatException(pex, pszThread);
1049 printf("\n%s", message.c_str());
1052 void PrintException(std::exception* pex, const char* pszThread)
1054 std::string message = FormatException(pex, pszThread);
1055 printf("\n\n************************\n%s\n", message.c_str());
1056 fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
1057 strMiscWarning = message;
1061 void LogStackTrace() {
1062 printf("\n\n******* exception encountered *******\n");
1065 #if !defined(WIN32) && !defined(ANDROID)
1066 void* pszBuffer[32];
1068 size = backtrace(pszBuffer, 32);
1069 backtrace_symbols_fd(pszBuffer, size, fileno(fileout));
1074 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
1076 std::string message = FormatException(pex, pszThread);
1077 printf("\n\n************************\n%s\n", message.c_str());
1078 fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
1079 strMiscWarning = message;
1082 boost::filesystem::path GetDefaultDataDir()
1084 namespace fs = boost::filesystem;
1085 // Windows < Vista: C:\Documents and Settings\Username\Application Data\NovaCoin
1086 // Windows >= Vista: C:\Users\Username\AppData\Roaming\NovaCoin
1087 // Mac: ~/Library/Application Support/NovaCoin
1088 // Unix: ~/.novacoin
1091 return GetSpecialFolderPath(CSIDL_APPDATA) / "NovaCoin";
1094 char* pszHome = getenv("HOME");
1095 if (pszHome == NULL || strlen(pszHome) == 0)
1096 pathRet = fs::path("/");
1098 pathRet = fs::path(pszHome);
1101 pathRet /= "Library/Application Support";
1102 fs::create_directory(pathRet);
1103 return pathRet / "NovaCoin";
1106 return pathRet / ".novacoin";
1111 const boost::filesystem::path &GetDataDir(bool fNetSpecific)
1113 namespace fs = boost::filesystem;
1115 static fs::path pathCached[2];
1116 static CCriticalSection csPathCached;
1117 static bool cachedPath[2] = {false, false};
1119 fs::path &path = pathCached[fNetSpecific];
1121 // This can be called during exceptions by printf, so we cache the
1122 // value so we don't have to do memory allocations after that.
1123 if (cachedPath[fNetSpecific])
1128 if (mapArgs.count("-datadir")) {
1129 path = fs::system_complete(mapArgs["-datadir"]);
1130 if (!fs::is_directory(path)) {
1135 path = GetDefaultDataDir();
1137 if (fNetSpecific && GetBoolArg("-testnet", false))
1140 fs::create_directory(path);
1142 cachedPath[fNetSpecific]=true;
1146 string randomStrGen(int length) {
1147 static string charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
1149 result.resize(length);
1150 for (int32_t i = 0; i < length; i++)
1151 result[i] = charset[rand() % charset.length()];
1158 srand(static_cast<unsigned int>(time(NULL)));
1161 #if BOOST_FILESYSTEM_VERSION >= 3
1162 pConf.open(GetConfigFile().generic_string().c_str());
1164 pConf.open(GetConfigFile().string().c_str());
1166 pConf << "rpcuser=user\nrpcpassword="
1170 + "\n#(0=off, 1=on) daemon - run in the background as a daemon and accept commands"
1172 + "\n#(0=off, 1=on) server - accept command line and JSON-RPC commands"
1174 + "\nrpcallowip=127.0.0.1"
1179 boost::filesystem::path GetConfigFile()
1181 boost::filesystem::path pathConfigFile(GetArg("-conf", "novacoin.conf"));
1182 if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
1183 return pathConfigFile;
1186 void ReadConfigFile(map<string, string>& mapSettingsRet,
1187 map<string, vector<string> >& mapMultiSettingsRet)
1189 boost::filesystem::ifstream streamConfig(GetConfigFile());
1190 if (!streamConfig.good())
1193 new(&streamConfig) boost::filesystem::ifstream(GetConfigFile());
1194 if(!streamConfig.good())
1198 set<string> setOptions;
1199 setOptions.insert("*");
1201 for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
1203 // Don't overwrite existing settings so command line settings override bitcoin.conf
1204 string strKey = string("-") + it->string_key;
1205 if (mapSettingsRet.count(strKey) == 0)
1207 mapSettingsRet[strKey] = it->value[0];
1208 // interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
1209 InterpretNegativeSetting(strKey, mapSettingsRet);
1211 mapMultiSettingsRet[strKey].push_back(it->value[0]);
1215 boost::filesystem::path GetPidFile()
1217 boost::filesystem::path pathPidFile(GetArg("-pid", "novacoind.pid"));
1218 if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
1223 void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
1225 FILE* file = fopen(path.string().c_str(), "w");
1228 fprintf(file, "%d\n", pid);
1234 bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
1237 return MoveFileExA(src.string().c_str(), dest.string().c_str(),
1238 MOVEFILE_REPLACE_EXISTING) != 0;
1240 int rc = std::rename(src.string().c_str(), dest.string().c_str());
1245 void FileCommit(FILE *fileout)
1247 fflush(fileout); // harmless if redundantly called
1249 _commit(_fileno(fileout));
1251 fsync(fileno(fileout));
1255 int GetFilesize(FILE* file)
1257 int nSavePos = ftell(file);
1259 if (fseek(file, 0, SEEK_END) == 0)
1260 nFilesize = ftell(file);
1261 fseek(file, nSavePos, SEEK_SET);
1265 void ShrinkDebugFile()
1267 // Scroll debug.log if it's getting too big
1268 boost::filesystem::path pathLog = GetDataDir() / "debug.log";
1269 FILE* file = fopen(pathLog.string().c_str(), "r");
1270 if (file && GetFilesize(file) > 10 * 1000000)
1272 // Restart the file with some of the end
1274 fseek(file, -((long long)sizeof(pch)), SEEK_END);
1275 int nBytes = fread(pch, 1, sizeof(pch), file);
1278 file = fopen(pathLog.string().c_str(), "w");
1281 fwrite(pch, 1, nBytes, file);
1295 // "Never go to sea with two chronometers; take one or three."
1296 // Our three time sources are:
1298 // - Median of other nodes clocks
1299 // - The user (asking the user to fix the system clock if the first two disagree)
1308 // Trusted NTP offset or median of NTP samples.
1309 extern int64_t nNtpOffset;
1311 // Median of time samples given by other nodes.
1312 static int64_t nNodesOffset = INT64_MAX;
1314 // Select time offset:
1315 int64_t GetTimeOffset()
1317 // If NTP and system clock are in agreement within 40 minutes, then use NTP.
1318 if (abs64(nNtpOffset) < 40 * 60)
1321 // If not, then choose between median peer time and system clock.
1322 if (abs64(nNodesOffset) < 70 * 60)
1323 return nNodesOffset;
1328 int64_t GetNodesOffset()
1330 return nNodesOffset;
1333 int64_t GetAdjustedTime()
1335 return GetTime() + GetTimeOffset();
1338 void AddTimeData(const CNetAddr& ip, int64_t nTime)
1340 int64_t nOffsetSample = nTime - GetTime();
1342 // Ignore duplicates
1343 static set<CNetAddr> setKnown;
1344 if (!setKnown.insert(ip).second)
1348 vTimeOffsets.input(nOffsetSample);
1349 printf("Added time data, samples %d, offset %+" PRId64 " (%+" PRId64 " minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
1350 if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
1352 int64_t nMedian = vTimeOffsets.median();
1353 std::vector<int64_t> vSorted = vTimeOffsets.sorted();
1354 // Only let other nodes change our time by so much
1355 if (abs64(nMedian) < 70 * 60)
1357 nNodesOffset = nMedian;
1361 nNodesOffset = INT64_MAX;
1366 bool fMatch = false;
1368 // If nobody has a time different than ours but within 5 minutes of ours, give a warning
1369 BOOST_FOREACH(int64_t nOffset, vSorted)
1370 if (nOffset != 0 && abs64(nOffset) < 5 * 60)
1376 string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong NovaCoin will not work properly.");
1377 strMiscWarning = strMessage;
1378 printf("*** %s\n", strMessage.c_str());
1379 uiInterface.ThreadSafeMessageBox(strMessage+" ", string("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION);
1384 BOOST_FOREACH(int64_t n, vSorted)
1385 printf("%+" PRId64 " ", n);
1388 if (nNodesOffset != INT64_MAX)
1389 printf("nNodesOffset = %+" PRId64 " (%+" PRId64 " minutes)\n", nNodesOffset, nNodesOffset/60);
1393 string FormatVersion(int nVersion)
1395 if (nVersion%100 == 0)
1396 return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
1398 return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
1401 string FormatFullVersion()
1403 return CLIENT_BUILD;
1406 // Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
1407 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
1409 std::ostringstream ss;
1411 ss << name << ":" << FormatVersion(nClientVersion);
1412 if (!comments.empty())
1413 ss << "(" << boost::algorithm::join(comments, "; ") << ")";
1419 boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate)
1421 namespace fs = boost::filesystem;
1423 char pszPath[MAX_PATH] = "";
1425 if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
1427 return fs::path(pszPath);
1430 printf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
1431 return fs::path("");
1435 void runCommand(std::string strCommand)
1437 int nErr = ::system(strCommand.c_str());
1439 printf("runCommand error: system(%s) returned %d\n", strCommand.c_str(), nErr);
1442 void RenameThread(const char* name)
1444 #if defined(PR_SET_NAME)
1445 // Only the first 15 characters are used (16 - NUL terminator)
1446 ::prctl(PR_SET_NAME, name, 0, 0, 0);
1447 #elif 0 && (defined(__FreeBSD__) || defined(__OpenBSD__))
1448 // TODO: This is currently disabled because it needs to be verified to work
1449 // on FreeBSD or OpenBSD first. When verified the '0 &&' part can be
1451 pthread_set_name_np(pthread_self(), name);
1453 // This is XCode 10.6-and-later; bring back if we drop 10.5 support:
1454 // #elif defined(MAC_OSX)
1455 // pthread_setname_np(name);
1458 // Prevent warnings for unused parameters...
1463 bool NewThread(void(*pfn)(void*), void* parg)
1467 boost::thread(pfn, parg); // thread detaches when out of scope
1468 } catch(boost::thread_resource_error &e) {
1469 printf("Error creating thread: %s\n", e.what());
1475 std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime)
1477 // std::locale takes ownership of the pointer
1478 std::locale loc(std::locale::classic(), new boost::posix_time::time_facet(pszFormat));
1479 std::stringstream ss;
1481 ss << boost::posix_time::from_time_t(nTime);