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>
36 #pragma warning(disable:4786)
37 #pragma warning(disable:4804)
38 #pragma warning(disable:4805)
39 #pragma warning(disable:4717)
44 #define _WIN32_WINNT 0x0501
48 #define _WIN32_IE 0x0501
49 #define WIN32_LEAN_AND_MEAN 1
53 #include <io.h> /* for _commit */
55 #elif defined(__linux__)
56 # include <sys/prctl.h>
65 namespace bt = boost::posix_time;
67 map<string, string> mapArgs;
68 map<string, vector<string> > mapMultiArgs;
70 bool fDebugNet = false;
71 bool fPrintToConsole = false;
72 bool fPrintToDebugger = false;
73 bool fRequestShutdown = false;
74 bool fShutdown = false;
77 bool fCommandLine = false;
78 string strMiscWarning;
79 bool fTestNet = false;
80 bool fNoListen = false;
81 bool fLogTimestamps = false;
82 CMedianFilter<int64_t> vTimeOffsets(200,0);
83 bool fReopenDebugLog = false;
85 // Extended DecodeDumpTime implementation, see this page for details:
86 // http://stackoverflow.com/questions/3786201/parsing-of-date-time-from-string-boost
87 const std::locale formats[] = {
88 std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%dT%H:%M:%SZ")),
89 std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d %H:%M:%S")),
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("%d.%m.%Y %H:%M:%S")),
92 std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d"))
95 const size_t formats_n = sizeof(formats)/sizeof(formats[0]);
97 std::time_t pt_to_time_t(const bt::ptime& pt)
99 bt::ptime timet_start(boost::gregorian::date(1970,1,1));
100 bt::time_duration diff = pt - timet_start;
101 return diff.ticks()/bt::time_duration::rep_type::ticks_per_second;
104 // Init OpenSSL library multithreading support
105 static CCriticalSection** ppmutexOpenSSL;
106 void locking_callback(int mode, int i, const char* file, int line)
108 if (mode & CRYPTO_LOCK) {
109 ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
111 LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
115 LockedPageManager LockedPageManager::instance;
123 // Init OpenSSL library multithreading support
124 ppmutexOpenSSL = (CCriticalSection**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(CCriticalSection*));
125 for (int i = 0; i < CRYPTO_num_locks(); i++)
126 ppmutexOpenSSL[i] = new CCriticalSection();
127 CRYPTO_set_locking_callback(locking_callback);
130 // Seed random number generator with screen scrape and other hardware sources
134 // Seed random number generator with performance counter
139 // Shutdown OpenSSL library multithreading support
140 CRYPTO_set_locking_callback(NULL);
141 for (int i = 0; i < CRYPTO_num_locks(); i++)
142 delete ppmutexOpenSSL[i];
143 OPENSSL_free(ppmutexOpenSSL);
157 // Seed with CPU performance counter
158 int64_t nCounter = GetPerformanceCounter();
159 RAND_add(&nCounter, sizeof(nCounter), 1.5);
160 memset(&nCounter, 0, sizeof(nCounter));
163 void RandAddSeedPerfmon()
167 // This can take up to 2 seconds, so only do it every 10 minutes
168 static int64_t nLastPerfmon;
169 if (GetTime() < nLastPerfmon + 10 * 60)
171 nLastPerfmon = GetTime();
174 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom
175 // Seed with the entire set of perfmon data
176 unsigned char pdata[250000];
177 memset(pdata, 0, sizeof(pdata));
178 unsigned long nSize = sizeof(pdata);
179 long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
180 RegCloseKey(HKEY_PERFORMANCE_DATA);
181 if (ret == ERROR_SUCCESS)
183 RAND_add(pdata, nSize, nSize/100.0);
184 memset(pdata, 0, nSize);
185 printf("RandAddSeed() %lu bytes\n", nSize);
190 uint64_t GetRand(uint64_t nMax)
195 // The range of the random source must be a multiple of the modulus
196 // to give every possible output value an equal possibility
197 uint64_t nRange = (std::numeric_limits<uint64_t>::max() / nMax) * nMax;
200 RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
201 while (nRand >= nRange);
202 return (nRand % nMax);
205 int GetRandInt(int nMax)
207 return GetRand(nMax);
210 uint256 GetRandHash()
213 RAND_bytes((unsigned char*)&hash, sizeof(hash));
222 static FILE* fileout = NULL;
224 inline int OutputDebugStringF(const char* pszFormat, ...)
231 va_start(arg_ptr, pszFormat);
232 ret = vprintf(pszFormat, arg_ptr);
235 else if (!fPrintToDebugger)
237 // print to debug.log
241 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
242 fileout = fopen(pathDebug.string().c_str(), "a");
243 if (fileout) setbuf(fileout, NULL); // unbuffered
247 static bool fStartedNewLine = true;
249 // This routine may be called by global destructors during shutdown.
250 // Since the order of destruction of static/global objects is undefined,
251 // allocate mutexDebugLog on the heap the first time this routine
252 // is called to avoid crashes during shutdown.
253 static boost::mutex* mutexDebugLog = NULL;
254 if (mutexDebugLog == NULL) mutexDebugLog = new boost::mutex();
255 boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
257 // reopen the log file, if requested
258 if (fReopenDebugLog) {
259 fReopenDebugLog = false;
260 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
261 if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL)
262 setbuf(fileout, NULL); // unbuffered
265 // Debug print useful for profiling
266 if (fLogTimestamps && fStartedNewLine)
267 fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
268 if (pszFormat[strlen(pszFormat) - 1] == '\n')
269 fStartedNewLine = true;
271 fStartedNewLine = false;
274 va_start(arg_ptr, pszFormat);
275 ret = vfprintf(fileout, pszFormat, arg_ptr);
281 if (fPrintToDebugger)
283 static CCriticalSection cs_OutputDebugStringF;
285 // accumulate and output a line at a time
287 LOCK(cs_OutputDebugStringF);
288 static std::string buffer;
291 va_start(arg_ptr, pszFormat);
292 buffer += vstrprintf(pszFormat, arg_ptr);
295 int line_start = 0, line_end;
296 while((line_end = buffer.find('\n', line_start)) != -1)
298 OutputDebugStringA(buffer.substr(line_start, line_end - line_start).c_str());
299 line_start = line_end + 1;
301 buffer.erase(0, line_start);
308 string vstrprintf(const char *format, va_list ap)
312 int limit = sizeof(buffer);
318 va_copy(arg_ptr, ap);
320 va_list arg_ptr = ap;
323 ret = _vsnprintf(p, limit, format, arg_ptr);
325 ret = vsnprintf(p, limit, format, arg_ptr);
328 if (ret >= 0 && ret < limit)
335 throw std::bad_alloc();
337 string str(p, p+ret);
343 string real_strprintf(const char *format, int dummy, ...)
346 va_start(arg_ptr, dummy);
347 string str = vstrprintf(format, arg_ptr);
352 string real_strprintf(const std::string &format, int dummy, ...)
355 va_start(arg_ptr, dummy);
356 string str = vstrprintf(format.c_str(), arg_ptr);
361 bool error(const char *format, ...)
364 va_start(arg_ptr, format);
365 std::string str = vstrprintf(format, arg_ptr);
367 printf("ERROR: %s\n", str.c_str());
372 void ParseString(const string& str, char c, vector<string>& v)
376 string::size_type i1 = 0;
377 string::size_type i2;
380 i2 = str.find(c, i1);
383 v.push_back(str.substr(i1));
386 v.push_back(str.substr(i1, i2-i1));
392 string FormatMoney(int64_t n, bool fPlus)
394 // Note: not using straight sprintf here because we do NOT want
395 // localized number formatting.
396 int64_t n_abs = (n > 0 ? n : -n);
397 int64_t quotient = n_abs/COIN;
398 int64_t remainder = n_abs%COIN;
399 string str = strprintf("%" PRId64 ".%06" PRId64, quotient, remainder);
401 // Right-trim excess zeros before the decimal point:
403 for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
406 str.erase(str.size()-nTrim, nTrim);
409 str.insert((unsigned int)0, 1, '-');
410 else if (fPlus && n > 0)
411 str.insert((unsigned int)0, 1, '+');
416 bool ParseMoney(const string& str, int64_t& nRet)
418 return ParseMoney(str.c_str(), nRet);
421 bool ParseMoney(const char* pszIn, int64_t& nRet)
425 const char* p = pszIn;
433 int64_t nMult = CENT*10;
434 while (isdigit(*p) && (nMult > 0))
436 nUnits += nMult * (*p++ - '0');
445 strWhole.insert(strWhole.end(), *p);
450 if (strWhole.size() > 10) // guard against 63 bit overflow
452 if (nUnits < 0 || nUnits > COIN)
454 int64_t nWhole = atoi64(strWhole);
455 int64_t nValue = nWhole*COIN + nUnits;
462 static const signed char phexdigit[256] =
463 { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
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 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
467 -1,0xa,0xb,0xc,0xd,0xe,0xf,-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 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
470 -1,-1,-1,-1,-1,-1,-1,-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, };
480 bool IsHex(const string& str)
482 BOOST_FOREACH(unsigned char c, str)
484 if (phexdigit[c] < 0)
487 return (str.size() > 0) && (str.size()%2 == 0);
490 vector<unsigned char> ParseHex(const char* psz)
492 // convert hex dump to vector
493 vector<unsigned char> vch;
496 while (isspace(*psz))
498 signed char c = phexdigit[(unsigned char)*psz++];
499 if (c == (signed char)-1)
501 unsigned char n = (c << 4);
502 c = phexdigit[(unsigned char)*psz++];
503 if (c == (signed char)-1)
511 vector<unsigned char> ParseHex(const string& str)
513 return ParseHex(str.c_str());
516 static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
518 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
519 if (name.find("-no") == 0)
521 std::string positive("-");
522 positive.append(name.begin()+3, name.end());
523 if (mapSettingsRet.count(positive) == 0)
525 bool value = !GetBoolArg(name);
526 mapSettingsRet[positive] = (value ? "1" : "0");
531 void ParseParameters(int argc, const char* const argv[])
534 mapMultiArgs.clear();
535 for (int i = 1; i < argc; i++)
538 strlcpy(psz, argv[i], sizeof(psz));
539 char* pszValue = (char*)"";
540 if (strchr(psz, '='))
542 pszValue = strchr(psz, '=');
553 mapArgs[psz] = pszValue;
554 mapMultiArgs[psz].push_back(pszValue);
558 BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs)
560 string name = entry.first;
562 // interpret --foo as -foo (as long as both are not set)
563 if (name.find("--") == 0)
565 std::string singleDash(name.begin()+1, name.end());
566 if (mapArgs.count(singleDash) == 0)
567 mapArgs[singleDash] = entry.second;
571 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
572 InterpretNegativeSetting(name, mapArgs);
576 std::string GetArg(const std::string& strArg, const std::string& strDefault)
578 if (mapArgs.count(strArg))
579 return mapArgs[strArg];
583 int64_t GetArg(const std::string& strArg, int64_t nDefault)
585 if (mapArgs.count(strArg))
586 return atoi64(mapArgs[strArg]);
590 bool GetBoolArg(const std::string& strArg, bool fDefault)
592 if (mapArgs.count(strArg))
594 if (mapArgs[strArg].empty())
596 return (atoi(mapArgs[strArg]) != 0);
601 bool SoftSetArg(const std::string& strArg, const std::string& strValue)
603 if (mapArgs.count(strArg))
605 mapArgs[strArg] = strValue;
609 bool SoftSetBoolArg(const std::string& strArg, bool fValue)
612 return SoftSetArg(strArg, std::string("1"));
614 return SoftSetArg(strArg, std::string("0"));
618 string EncodeBase64(const unsigned char* pch, size_t len)
620 static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
623 strRet.reserve((len+2)/3*4);
626 const unsigned char *pchEnd = pch+len;
633 case 0: // we have no bits
634 strRet += pbase64[enc >> 2];
635 left = (enc & 3) << 4;
639 case 1: // we have two bits
640 strRet += pbase64[left | (enc >> 4)];
641 left = (enc & 15) << 2;
645 case 2: // we have four bits
646 strRet += pbase64[left | (enc >> 6)];
647 strRet += pbase64[enc & 63];
655 strRet += pbase64[left];
664 string EncodeBase64(const string& str)
666 return EncodeBase64((const unsigned char*)str.c_str(), str.size());
669 vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
671 static const int decode64_table[256] =
673 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
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, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
676 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
677 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
678 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
679 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
680 -1, -1, -1, -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
691 vector<unsigned char> vchRet;
692 vchRet.reserve(strlen(p)*3/4);
699 int dec = decode64_table[(unsigned char)*p];
700 if (dec == -1) break;
704 case 0: // we have no bits and get 6
709 case 1: // we have 6 bits and keep 4
710 vchRet.push_back((left<<2) | (dec>>4));
715 case 2: // we have 4 bits and get 6, we keep 2
716 vchRet.push_back((left<<4) | (dec>>2));
721 case 3: // we have 2 bits and get 6
722 vchRet.push_back((left<<6) | dec);
731 case 0: // 4n base64 characters processed: ok
734 case 1: // 4n+1 base64 character processed: impossible
738 case 2: // 4n+2 base64 characters processed: require '=='
739 if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1)
743 case 3: // 4n+3 base64 characters processed: require '='
744 if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1)
752 string DecodeBase64(const string& str)
754 vector<unsigned char> vchRet = DecodeBase64(str.c_str());
755 return string((const char*)&vchRet[0], vchRet.size());
758 string EncodeBase32(const unsigned char* pch, size_t len)
760 static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567";
763 strRet.reserve((len+4)/5*8);
766 const unsigned char *pchEnd = pch+len;
773 case 0: // we have no bits
774 strRet += pbase32[enc >> 3];
775 left = (enc & 7) << 2;
779 case 1: // we have three bits
780 strRet += pbase32[left | (enc >> 6)];
781 strRet += pbase32[(enc >> 1) & 31];
782 left = (enc & 1) << 4;
786 case 2: // we have one bit
787 strRet += pbase32[left | (enc >> 4)];
788 left = (enc & 15) << 1;
792 case 3: // we have four bits
793 strRet += pbase32[left | (enc >> 7)];
794 strRet += pbase32[(enc >> 2) & 31];
795 left = (enc & 3) << 3;
799 case 4: // we have two bits
800 strRet += pbase32[left | (enc >> 5)];
801 strRet += pbase32[enc & 31];
806 static const int nPadding[5] = {0, 6, 4, 3, 1};
809 strRet += pbase32[left];
810 for (int n=0; n<nPadding[mode]; n++)
817 string EncodeBase32(const string& str)
819 return EncodeBase32((const unsigned char*)str.c_str(), str.size());
822 vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid)
824 static const int decode32_table[256] =
826 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
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, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1,
829 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
830 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 0, 1, 2,
831 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
832 23, 24, 25, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
833 -1, -1, -1, -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
844 vector<unsigned char> vchRet;
845 vchRet.reserve((strlen(p))*5/8);
852 int dec = decode32_table[(unsigned char)*p];
853 if (dec == -1) break;
857 case 0: // we have no bits and get 5
862 case 1: // we have 5 bits and keep 2
863 vchRet.push_back((left<<3) | (dec>>2));
868 case 2: // we have 2 bits and keep 7
869 left = left << 5 | dec;
873 case 3: // we have 7 bits and keep 4
874 vchRet.push_back((left<<1) | (dec>>4));
879 case 4: // we have 4 bits, and keep 1
880 vchRet.push_back((left<<4) | (dec>>1));
885 case 5: // we have 1 bit, and keep 6
886 left = left << 5 | dec;
890 case 6: // we have 6 bits, and keep 3
891 vchRet.push_back((left<<2) | (dec>>3));
896 case 7: // we have 3 bits, and keep 0
897 vchRet.push_back((left<<5) | dec);
906 case 0: // 8n base32 characters processed: ok
909 case 1: // 8n+1 base32 characters processed: impossible
915 case 2: // 8n+2 base32 characters processed: require '======'
916 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || p[4] != '=' || p[5] != '=' || decode32_table[(unsigned char)p[6]] != -1)
920 case 4: // 8n+4 base32 characters processed: require '===='
921 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || decode32_table[(unsigned char)p[4]] != -1)
925 case 5: // 8n+5 base32 characters processed: require '==='
926 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || decode32_table[(unsigned char)p[3]] != -1)
930 case 7: // 8n+7 base32 characters processed: require '='
931 if (left || p[0] != '=' || decode32_table[(unsigned char)p[1]] != -1)
939 string DecodeBase32(const string& str)
941 vector<unsigned char> vchRet = DecodeBase32(str.c_str());
942 return string((const char*)&vchRet[0], vchRet.size());
946 int64_t DecodeDumpTime(const std::string& s)
950 for(size_t i=0; i<formats_n; ++i)
952 std::istringstream is(s);
953 is.imbue(formats[i]);
955 if(pt != bt::ptime()) break;
958 return pt_to_time_t(pt);
961 std::string EncodeDumpTime(int64_t nTime) {
962 return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime);
965 std::string EncodeDumpString(const std::string &str) {
966 std::stringstream ret;
967 BOOST_FOREACH(unsigned char c, str) {
968 if (c <= 32 || c >= 128 || c == '%') {
969 ret << '%' << HexStr(&c, &c + 1);
977 std::string DecodeDumpString(const std::string &str) {
978 std::stringstream ret;
979 for (unsigned int pos = 0; pos < str.length(); pos++) {
980 unsigned char c = str[pos];
981 if (c == '%' && pos+2 < str.length()) {
982 c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) |
983 ((str[pos+2]>>6)*9+((str[pos+2]-'0')&15));
991 bool WildcardMatch(const char* psz, const char* mask)
998 return (*psz == '\0');
1000 return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
1015 bool WildcardMatch(const string& str, const string& mask)
1017 return WildcardMatch(str.c_str(), mask.c_str());
1027 static std::string FormatException(std::exception* pex, const char* pszThread)
1030 char pszModule[MAX_PATH] = "";
1031 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
1033 const char* pszModule = "novacoin";
1037 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
1040 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
1043 void LogException(std::exception* pex, const char* pszThread)
1045 std::string message = FormatException(pex, pszThread);
1046 printf("\n%s", message.c_str());
1049 void PrintException(std::exception* pex, const char* pszThread)
1051 std::string message = FormatException(pex, pszThread);
1052 printf("\n\n************************\n%s\n", message.c_str());
1053 fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
1054 strMiscWarning = message;
1058 void LogStackTrace() {
1059 printf("\n\n******* exception encountered *******\n");
1063 void* pszBuffer[32];
1065 size = backtrace(pszBuffer, 32);
1066 backtrace_symbols_fd(pszBuffer, size, fileno(fileout));
1071 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
1073 std::string message = FormatException(pex, pszThread);
1074 printf("\n\n************************\n%s\n", message.c_str());
1075 fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
1076 strMiscWarning = message;
1079 boost::filesystem::path GetDefaultDataDir()
1081 namespace fs = boost::filesystem;
1082 // Windows < Vista: C:\Documents and Settings\Username\Application Data\NovaCoin
1083 // Windows >= Vista: C:\Users\Username\AppData\Roaming\NovaCoin
1084 // Mac: ~/Library/Application Support/NovaCoin
1085 // Unix: ~/.novacoin
1088 return GetSpecialFolderPath(CSIDL_APPDATA) / "NovaCoin";
1091 char* pszHome = getenv("HOME");
1092 if (pszHome == NULL || strlen(pszHome) == 0)
1093 pathRet = fs::path("/");
1095 pathRet = fs::path(pszHome);
1098 pathRet /= "Library/Application Support";
1099 fs::create_directory(pathRet);
1100 return pathRet / "NovaCoin";
1103 return pathRet / ".novacoin";
1108 const boost::filesystem::path &GetDataDir(bool fNetSpecific)
1110 namespace fs = boost::filesystem;
1112 static fs::path pathCached[2];
1113 static CCriticalSection csPathCached;
1114 static bool cachedPath[2] = {false, false};
1116 fs::path &path = pathCached[fNetSpecific];
1118 // This can be called during exceptions by printf, so we cache the
1119 // value so we don't have to do memory allocations after that.
1120 if (cachedPath[fNetSpecific])
1125 if (mapArgs.count("-datadir")) {
1126 path = fs::system_complete(mapArgs["-datadir"]);
1127 if (!fs::is_directory(path)) {
1132 path = GetDefaultDataDir();
1134 if (fNetSpecific && GetBoolArg("-testnet", false))
1137 fs::create_directory(path);
1139 cachedPath[fNetSpecific]=true;
1143 boost::filesystem::path GetConfigFile()
1145 boost::filesystem::path pathConfigFile(GetArg("-conf", "novacoin.conf"));
1146 if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
1147 return pathConfigFile;
1150 void ReadConfigFile(map<string, string>& mapSettingsRet,
1151 map<string, vector<string> >& mapMultiSettingsRet)
1153 boost::filesystem::ifstream streamConfig(GetConfigFile());
1154 if (!streamConfig.good())
1155 return; // No bitcoin.conf file is OK
1157 set<string> setOptions;
1158 setOptions.insert("*");
1160 for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
1162 // Don't overwrite existing settings so command line settings override bitcoin.conf
1163 string strKey = string("-") + it->string_key;
1164 if (mapSettingsRet.count(strKey) == 0)
1166 mapSettingsRet[strKey] = it->value[0];
1167 // interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
1168 InterpretNegativeSetting(strKey, mapSettingsRet);
1170 mapMultiSettingsRet[strKey].push_back(it->value[0]);
1174 boost::filesystem::path GetPidFile()
1176 boost::filesystem::path pathPidFile(GetArg("-pid", "novacoind.pid"));
1177 if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
1182 void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
1184 FILE* file = fopen(path.string().c_str(), "w");
1187 fprintf(file, "%d\n", pid);
1193 bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
1196 return MoveFileExA(src.string().c_str(), dest.string().c_str(),
1197 MOVEFILE_REPLACE_EXISTING);
1199 int rc = std::rename(src.string().c_str(), dest.string().c_str());
1204 void FileCommit(FILE *fileout)
1206 fflush(fileout); // harmless if redundantly called
1208 _commit(_fileno(fileout));
1210 fsync(fileno(fileout));
1214 int GetFilesize(FILE* file)
1216 int nSavePos = ftell(file);
1218 if (fseek(file, 0, SEEK_END) == 0)
1219 nFilesize = ftell(file);
1220 fseek(file, nSavePos, SEEK_SET);
1224 void ShrinkDebugFile()
1226 // Scroll debug.log if it's getting too big
1227 boost::filesystem::path pathLog = GetDataDir() / "debug.log";
1228 FILE* file = fopen(pathLog.string().c_str(), "r");
1229 if (file && GetFilesize(file) > 10 * 1000000)
1231 // Restart the file with some of the end
1233 fseek(file, -sizeof(pch), SEEK_END);
1234 int nBytes = fread(pch, 1, sizeof(pch), file);
1237 file = fopen(pathLog.string().c_str(), "w");
1240 fwrite(pch, 1, nBytes, file);
1254 // "Never go to sea with two chronometers; take one or three."
1255 // Our three time sources are:
1257 // - Median of other nodes clocks
1258 // - The user (asking the user to fix the system clock if the first two disagree)
1260 static int64_t nMockTime = 0; // For unit testing
1264 if (nMockTime) return nMockTime;
1269 void SetMockTime(int64_t nMockTimeIn)
1271 nMockTime = nMockTimeIn;
1274 static int64_t nTimeOffset = 0;
1276 int64_t GetTimeOffset()
1281 int64_t GetAdjustedTime()
1283 return GetTime() + GetTimeOffset();
1286 void AddTimeData(const CNetAddr& ip, int64_t nTime)
1288 int64_t nOffsetSample = nTime - GetTime();
1290 // Ignore duplicates
1291 static set<CNetAddr> setKnown;
1292 if (!setKnown.insert(ip).second)
1296 vTimeOffsets.input(nOffsetSample);
1297 printf("Added time data, samples %d, offset %+" PRId64 " (%+" PRId64 " minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
1298 if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
1300 int64_t nMedian = vTimeOffsets.median();
1301 std::vector<int64_t> vSorted = vTimeOffsets.sorted();
1302 // Only let other nodes change our time by so much
1303 if (abs64(nMedian) < 70 * 60)
1305 nTimeOffset = nMedian;
1314 // If nobody has a time different than ours but within 5 minutes of ours, give a warning
1315 bool fMatch = false;
1316 BOOST_FOREACH(int64_t nOffset, vSorted)
1317 if (nOffset != 0 && abs64(nOffset) < 5 * 60)
1323 string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong NovaCoin will not work properly.");
1324 strMiscWarning = strMessage;
1325 printf("*** %s\n", strMessage.c_str());
1326 uiInterface.ThreadSafeMessageBox(strMessage+" ", string("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION);
1331 BOOST_FOREACH(int64_t n, vSorted)
1332 printf("%+" PRId64 " ", n);
1335 printf("nTimeOffset = %+" PRId64 " (%+" PRId64 " minutes)\n", nTimeOffset, nTimeOffset/60);
1346 string FormatVersion(int nVersion)
1348 if (nVersion%100 == 0)
1349 return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
1351 return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
1354 string FormatFullVersion()
1356 return CLIENT_BUILD;
1359 // Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
1360 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
1362 std::ostringstream ss;
1364 ss << name << ":" << FormatVersion(nClientVersion);
1365 if (!comments.empty())
1366 ss << "(" << boost::algorithm::join(comments, "; ") << ")";
1372 boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate)
1374 namespace fs = boost::filesystem;
1376 char pszPath[MAX_PATH] = "";
1378 if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
1380 return fs::path(pszPath);
1383 printf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
1384 return fs::path("");
1388 void runCommand(std::string strCommand)
1390 int nErr = ::system(strCommand.c_str());
1392 printf("runCommand error: system(%s) returned %d\n", strCommand.c_str(), nErr);
1395 void RenameThread(const char* name)
1397 #if defined(PR_SET_NAME)
1398 // Only the first 15 characters are used (16 - NUL terminator)
1399 ::prctl(PR_SET_NAME, name, 0, 0, 0);
1400 #elif 0 && (defined(__FreeBSD__) || defined(__OpenBSD__))
1401 // TODO: This is currently disabled because it needs to be verified to work
1402 // on FreeBSD or OpenBSD first. When verified the '0 &&' part can be
1404 pthread_set_name_np(pthread_self(), name);
1406 // This is XCode 10.6-and-later; bring back if we drop 10.5 support:
1407 // #elif defined(MAC_OSX)
1408 // pthread_setname_np(name);
1411 // Prevent warnings for unused parameters...
1416 bool NewThread(void(*pfn)(void*), void* parg)
1420 boost::thread(pfn, parg); // thread detaches when out of scope
1421 } catch(boost::thread_resource_error &e) {
1422 printf("Error creating thread: %s\n", e.what());