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.
10 #include "ui_interface.h"
11 #include <boost/algorithm/string/join.hpp>
13 // Work around clang compilation problem in Boost 1.46:
14 // /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
15 // See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options
16 // http://clang.debian.net/status.php?version=3.0&key=CANNOT_FIND_FUNCTION
18 namespace program_options {
19 std::string to_internal(const std::string&);
23 #include <boost/program_options/detail/config_file.hpp>
24 #include <boost/program_options/parsers.hpp>
25 #include <boost/filesystem.hpp>
26 #include <boost/filesystem/fstream.hpp>
28 #include <boost/date_time/posix_time/posix_time.hpp>
29 #include <boost/foreach.hpp>
30 #include <boost/thread.hpp>
31 #include <openssl/crypto.h>
32 #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>
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> 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 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 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 memset(pdata, 0, nSize);
186 printf("RandAddSeed() %lu bytes\n", nSize);
191 uint64 GetRand(uint64 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 nRange = (std::numeric_limits<uint64>::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 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 n, bool fPlus)
395 // Note: not using straight sprintf here because we do NOT want
396 // localized number formatting.
397 int64 n_abs = (n > 0 ? n : -n);
398 int64 quotient = n_abs/COIN;
399 int64 remainder = n_abs%COIN;
400 string str = strprintf("%"PRI64d".%06"PRI64d, 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& nRet)
419 return ParseMoney(str.c_str(), nRet);
422 bool ParseMoney(const char* pszIn, int64& nRet)
426 const char* p = pszIn;
434 int64 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 nWhole = atoi64(strWhole);
456 int64 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++)
539 strlcpy(psz, argv[i], sizeof(psz));
540 char* pszValue = (char*)"";
541 if (strchr(psz, '='))
543 pszValue = strchr(psz, '=');
554 mapArgs[psz] = pszValue;
555 mapMultiArgs[psz].push_back(pszValue);
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 GetArg(const std::string& strArg, int64 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))
606 mapArgs[strArg] = strValue;
610 bool SoftSetBoolArg(const std::string& strArg, bool fValue)
613 return SoftSetArg(strArg, std::string("1"));
615 return SoftSetArg(strArg, std::string("0"));
619 string EncodeBase64(const unsigned char* pch, size_t len)
621 static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
624 strRet.reserve((len+2)/3*4);
627 const unsigned char *pchEnd = pch+len;
634 case 0: // we have no bits
635 strRet += pbase64[enc >> 2];
636 left = (enc & 3) << 4;
640 case 1: // we have two bits
641 strRet += pbase64[left | (enc >> 4)];
642 left = (enc & 15) << 2;
646 case 2: // we have four bits
647 strRet += pbase64[left | (enc >> 6)];
648 strRet += pbase64[enc & 63];
656 strRet += pbase64[left];
665 string EncodeBase64(const string& str)
667 return EncodeBase64((const unsigned char*)str.c_str(), str.size());
670 vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
672 static const int decode64_table[256] =
674 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
675 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
676 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
677 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
678 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
679 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
680 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
681 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
682 -1, -1, -1, -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
692 vector<unsigned char> vchRet;
693 vchRet.reserve(strlen(p)*3/4);
700 int dec = decode64_table[(unsigned char)*p];
701 if (dec == -1) break;
705 case 0: // we have no bits and get 6
710 case 1: // we have 6 bits and keep 4
711 vchRet.push_back((left<<2) | (dec>>4));
716 case 2: // we have 4 bits and get 6, we keep 2
717 vchRet.push_back((left<<4) | (dec>>2));
722 case 3: // we have 2 bits and get 6
723 vchRet.push_back((left<<6) | dec);
732 case 0: // 4n base64 characters processed: ok
735 case 1: // 4n+1 base64 character processed: impossible
739 case 2: // 4n+2 base64 characters processed: require '=='
740 if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1)
744 case 3: // 4n+3 base64 characters processed: require '='
745 if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1)
753 string DecodeBase64(const string& str)
755 vector<unsigned char> vchRet = DecodeBase64(str.c_str());
756 return string((const char*)&vchRet[0], vchRet.size());
759 string EncodeBase32(const unsigned char* pch, size_t len)
761 static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567";
764 strRet.reserve((len+4)/5*8);
767 const unsigned char *pchEnd = pch+len;
774 case 0: // we have no bits
775 strRet += pbase32[enc >> 3];
776 left = (enc & 7) << 2;
780 case 1: // we have three bits
781 strRet += pbase32[left | (enc >> 6)];
782 strRet += pbase32[(enc >> 1) & 31];
783 left = (enc & 1) << 4;
787 case 2: // we have one bit
788 strRet += pbase32[left | (enc >> 4)];
789 left = (enc & 15) << 1;
793 case 3: // we have four bits
794 strRet += pbase32[left | (enc >> 7)];
795 strRet += pbase32[(enc >> 2) & 31];
796 left = (enc & 3) << 3;
800 case 4: // we have two bits
801 strRet += pbase32[left | (enc >> 5)];
802 strRet += pbase32[enc & 31];
807 static const int nPadding[5] = {0, 6, 4, 3, 1};
810 strRet += pbase32[left];
811 for (int n=0; n<nPadding[mode]; n++)
818 string EncodeBase32(const string& str)
820 return EncodeBase32((const unsigned char*)str.c_str(), str.size());
823 vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid)
825 static const int decode32_table[256] =
827 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
828 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
829 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1,
830 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
831 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 0, 1, 2,
832 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
833 23, 24, 25, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
834 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
835 -1, -1, -1, -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
845 vector<unsigned char> vchRet;
846 vchRet.reserve((strlen(p))*5/8);
853 int dec = decode32_table[(unsigned char)*p];
854 if (dec == -1) break;
858 case 0: // we have no bits and get 5
863 case 1: // we have 5 bits and keep 2
864 vchRet.push_back((left<<3) | (dec>>2));
869 case 2: // we have 2 bits and keep 7
870 left = left << 5 | dec;
874 case 3: // we have 7 bits and keep 4
875 vchRet.push_back((left<<1) | (dec>>4));
880 case 4: // we have 4 bits, and keep 1
881 vchRet.push_back((left<<4) | (dec>>1));
886 case 5: // we have 1 bit, and keep 6
887 left = left << 5 | dec;
891 case 6: // we have 6 bits, and keep 3
892 vchRet.push_back((left<<2) | (dec>>3));
897 case 7: // we have 3 bits, and keep 0
898 vchRet.push_back((left<<5) | dec);
907 case 0: // 8n base32 characters processed: ok
910 case 1: // 8n+1 base32 characters processed: impossible
916 case 2: // 8n+2 base32 characters processed: require '======'
917 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || p[4] != '=' || p[5] != '=' || decode32_table[(unsigned char)p[6]] != -1)
921 case 4: // 8n+4 base32 characters processed: require '===='
922 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || decode32_table[(unsigned char)p[4]] != -1)
926 case 5: // 8n+5 base32 characters processed: require '==='
927 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || decode32_table[(unsigned char)p[3]] != -1)
931 case 7: // 8n+7 base32 characters processed: require '='
932 if (left || p[0] != '=' || decode32_table[(unsigned char)p[1]] != -1)
940 string DecodeBase32(const string& str)
942 vector<unsigned char> vchRet = DecodeBase32(str.c_str());
943 return string((const char*)&vchRet[0], vchRet.size());
947 int64 DecodeDumpTime(const std::string& s)
951 for(size_t i=0; i<formats_n; ++i)
953 std::istringstream is(s);
954 is.imbue(formats[i]);
956 if(pt != bt::ptime()) break;
959 return pt_to_time_t(pt);
962 std::string EncodeDumpTime(int64 nTime) {
963 return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime);
966 std::string EncodeDumpString(const std::string &str) {
967 std::stringstream ret;
968 BOOST_FOREACH(unsigned char c, str) {
969 if (c <= 32 || c >= 128 || c == '%') {
970 ret << '%' << HexStr(&c, &c + 1);
978 std::string DecodeDumpString(const std::string &str) {
979 std::stringstream ret;
980 for (unsigned int pos = 0; pos < str.length(); pos++) {
981 unsigned char c = str[pos];
982 if (c == '%' && pos+2 < str.length()) {
983 c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) |
984 ((str[pos+2]>>6)*9+((str[pos+2]-'0')&15));
992 bool WildcardMatch(const char* psz, const char* mask)
999 return (*psz == '\0');
1001 return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
1016 bool WildcardMatch(const string& str, const string& mask)
1018 return WildcardMatch(str.c_str(), mask.c_str());
1028 static std::string FormatException(std::exception* pex, const char* pszThread)
1031 char pszModule[MAX_PATH] = "";
1032 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
1034 const char* pszModule = "novacoin";
1038 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
1041 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
1044 void LogException(std::exception* pex, const char* pszThread)
1046 std::string message = FormatException(pex, pszThread);
1047 printf("\n%s", message.c_str());
1050 void PrintException(std::exception* pex, const char* pszThread)
1052 std::string message = FormatException(pex, pszThread);
1053 printf("\n\n************************\n%s\n", message.c_str());
1054 fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
1055 strMiscWarning = message;
1059 void LogStackTrace() {
1060 printf("\n\n******* exception encountered *******\n");
1064 void* pszBuffer[32];
1066 size = backtrace(pszBuffer, 32);
1067 backtrace_symbols_fd(pszBuffer, size, fileno(fileout));
1072 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
1074 std::string message = FormatException(pex, pszThread);
1075 printf("\n\n************************\n%s\n", message.c_str());
1076 fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
1077 strMiscWarning = message;
1080 boost::filesystem::path GetDefaultDataDir()
1082 namespace fs = boost::filesystem;
1083 // Windows < Vista: C:\Documents and Settings\Username\Application Data\NovaCoin
1084 // Windows >= Vista: C:\Users\Username\AppData\Roaming\NovaCoin
1085 // Mac: ~/Library/Application Support/NovaCoin
1086 // Unix: ~/.novacoin
1089 return GetSpecialFolderPath(CSIDL_APPDATA) / "NovaCoin";
1092 char* pszHome = getenv("HOME");
1093 if (pszHome == NULL || strlen(pszHome) == 0)
1094 pathRet = fs::path("/");
1096 pathRet = fs::path(pszHome);
1099 pathRet /= "Library/Application Support";
1100 fs::create_directory(pathRet);
1101 return pathRet / "NovaCoin";
1104 return pathRet / ".novacoin";
1109 const boost::filesystem::path &GetDataDir(bool fNetSpecific)
1111 namespace fs = boost::filesystem;
1113 static fs::path pathCached[2];
1114 static CCriticalSection csPathCached;
1115 static bool cachedPath[2] = {false, false};
1117 fs::path &path = pathCached[fNetSpecific];
1119 // This can be called during exceptions by printf, so we cache the
1120 // value so we don't have to do memory allocations after that.
1121 if (cachedPath[fNetSpecific])
1126 if (mapArgs.count("-datadir")) {
1127 path = fs::system_complete(mapArgs["-datadir"]);
1128 if (!fs::is_directory(path)) {
1133 path = GetDefaultDataDir();
1135 if (fNetSpecific && GetBoolArg("-testnet", false))
1138 fs::create_directory(path);
1140 cachedPath[fNetSpecific]=true;
1144 boost::filesystem::path GetConfigFile()
1146 boost::filesystem::path pathConfigFile(GetArg("-conf", "novacoin.conf"));
1147 if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
1148 return pathConfigFile;
1151 void ReadConfigFile(map<string, string>& mapSettingsRet,
1152 map<string, vector<string> >& mapMultiSettingsRet)
1154 boost::filesystem::ifstream streamConfig(GetConfigFile());
1155 if (!streamConfig.good())
1156 return; // No bitcoin.conf file is OK
1158 set<string> setOptions;
1159 setOptions.insert("*");
1161 for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
1163 // Don't overwrite existing settings so command line settings override bitcoin.conf
1164 string strKey = string("-") + it->string_key;
1165 if (mapSettingsRet.count(strKey) == 0)
1167 mapSettingsRet[strKey] = it->value[0];
1168 // interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
1169 InterpretNegativeSetting(strKey, mapSettingsRet);
1171 mapMultiSettingsRet[strKey].push_back(it->value[0]);
1175 boost::filesystem::path GetPidFile()
1177 boost::filesystem::path pathPidFile(GetArg("-pid", "novacoind.pid"));
1178 if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
1183 void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
1185 FILE* file = fopen(path.string().c_str(), "w");
1188 fprintf(file, "%d\n", pid);
1194 bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
1197 return MoveFileExA(src.string().c_str(), dest.string().c_str(),
1198 MOVEFILE_REPLACE_EXISTING);
1200 int rc = std::rename(src.string().c_str(), dest.string().c_str());
1205 void FileCommit(FILE *fileout)
1207 fflush(fileout); // harmless if redundantly called
1209 _commit(_fileno(fileout));
1211 fsync(fileno(fileout));
1215 int GetFilesize(FILE* file)
1217 int nSavePos = ftell(file);
1219 if (fseek(file, 0, SEEK_END) == 0)
1220 nFilesize = ftell(file);
1221 fseek(file, nSavePos, SEEK_SET);
1225 void ShrinkDebugFile()
1227 // Scroll debug.log if it's getting too big
1228 boost::filesystem::path pathLog = GetDataDir() / "debug.log";
1229 FILE* file = fopen(pathLog.string().c_str(), "r");
1230 if (file && GetFilesize(file) > 10 * 1000000)
1232 // Restart the file with some of the end
1234 fseek(file, -sizeof(pch), SEEK_END);
1235 int nBytes = fread(pch, 1, sizeof(pch), file);
1238 file = fopen(pathLog.string().c_str(), "w");
1241 fwrite(pch, 1, nBytes, file);
1255 // "Never go to sea with two chronometers; take one or three."
1256 // Our three time sources are:
1258 // - Median of other nodes clocks
1259 // - The user (asking the user to fix the system clock if the first two disagree)
1261 static int64 nMockTime = 0; // For unit testing
1265 if (nMockTime) return nMockTime;
1270 void SetMockTime(int64 nMockTimeIn)
1272 nMockTime = nMockTimeIn;
1275 static int64 nTimeOffset = 0;
1277 int64 GetTimeOffset()
1282 int64 GetAdjustedTime()
1284 return GetTime() + GetTimeOffset();
1287 void AddTimeData(const CNetAddr& ip, int64 nTime)
1289 int64 nOffsetSample = nTime - GetTime();
1291 // Ignore duplicates
1292 static set<CNetAddr> setKnown;
1293 if (!setKnown.insert(ip).second)
1297 vTimeOffsets.input(nOffsetSample);
1298 printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
1299 if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
1301 int64 nMedian = vTimeOffsets.median();
1302 std::vector<int64> vSorted = vTimeOffsets.sorted();
1303 // Only let other nodes change our time by so much
1304 if (abs64(nMedian) < 70 * 60)
1306 nTimeOffset = nMedian;
1315 // If nobody has a time different than ours but within 5 minutes of ours, give a warning
1316 bool fMatch = false;
1317 BOOST_FOREACH(int64 nOffset, vSorted)
1318 if (nOffset != 0 && abs64(nOffset) < 5 * 60)
1324 string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong NovaCoin will not work properly.");
1325 strMiscWarning = strMessage;
1326 printf("*** %s\n", strMessage.c_str());
1327 uiInterface.ThreadSafeMessageBox(strMessage+" ", string("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION);
1332 BOOST_FOREACH(int64 n, vSorted)
1333 printf("%+"PRI64d" ", n);
1336 printf("nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
1347 string FormatVersion(int nVersion)
1349 if (nVersion%100 == 0)
1350 return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
1352 return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
1355 string FormatFullVersion()
1357 return CLIENT_BUILD;
1360 // Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
1361 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
1363 std::ostringstream ss;
1365 ss << name << ":" << FormatVersion(nClientVersion);
1366 if (!comments.empty())
1367 ss << "(" << boost::algorithm::join(comments, "; ") << ")";
1373 boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate)
1375 namespace fs = boost::filesystem;
1377 char pszPath[MAX_PATH] = "";
1379 if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
1381 return fs::path(pszPath);
1384 printf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
1385 return fs::path("");
1389 void runCommand(std::string strCommand)
1391 int nErr = ::system(strCommand.c_str());
1393 printf("runCommand error: system(%s) returned %d\n", strCommand.c_str(), nErr);
1396 void RenameThread(const char* name)
1398 #if defined(PR_SET_NAME)
1399 // Only the first 15 characters are used (16 - NUL terminator)
1400 ::prctl(PR_SET_NAME, name, 0, 0, 0);
1401 #elif 0 && (defined(__FreeBSD__) || defined(__OpenBSD__))
1402 // TODO: This is currently disabled because it needs to be verified to work
1403 // on FreeBSD or OpenBSD first. When verified the '0 &&' part can be
1405 pthread_set_name_np(pthread_self(), name);
1407 // This is XCode 10.6-and-later; bring back if we drop 10.5 support:
1408 // #elif defined(MAC_OSX)
1409 // pthread_setname_np(name);
1412 // Prevent warnings for unused parameters...
1417 bool NewThread(void(*pfn)(void*), void* parg)
1421 boost::thread(pfn, parg); // thread detaches when out of scope
1422 } catch(boost::thread_resource_error &e) {
1423 printf("Error creating thread: %s\n", e.what());