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>
27 #include <boost/foreach.hpp>
28 #include <boost/thread.hpp>
29 #include <openssl/crypto.h>
30 #include <openssl/rand.h>
35 #pragma warning(disable:4786)
36 #pragma warning(disable:4804)
37 #pragma warning(disable:4805)
38 #pragma warning(disable:4717)
43 #define _WIN32_WINNT 0x0501
47 #define _WIN32_IE 0x0501
48 #define WIN32_LEAN_AND_MEAN 1
52 #include <io.h> /* for _commit */
54 #elif defined(__linux__)
55 # include <sys/prctl.h>
65 map<string, string> mapArgs;
66 map<string, vector<string> > mapMultiArgs;
68 bool fDebugNet = false;
69 bool fPrintToConsole = false;
70 bool fPrintToDebugger = false;
71 bool fRequestShutdown = false;
72 bool fShutdown = false;
75 bool fCommandLine = false;
76 string strMiscWarning;
77 bool fTestNet = false;
78 bool fNoListen = false;
79 bool fLogTimestamps = false;
80 CMedianFilter<int64> vTimeOffsets(200,0);
81 bool fReopenDebugLog = false;
83 // Init OpenSSL library multithreading support
84 static CCriticalSection** ppmutexOpenSSL;
85 void locking_callback(int mode, int i, const char* file, int line)
87 if (mode & CRYPTO_LOCK) {
88 ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
90 LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
94 LockedPageManager LockedPageManager::instance;
102 // Init OpenSSL library multithreading support
103 ppmutexOpenSSL = (CCriticalSection**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(CCriticalSection*));
104 for (int i = 0; i < CRYPTO_num_locks(); i++)
105 ppmutexOpenSSL[i] = new CCriticalSection();
106 CRYPTO_set_locking_callback(locking_callback);
109 // Seed random number generator with screen scrape and other hardware sources
113 // Seed random number generator with performance counter
118 // Shutdown OpenSSL library multithreading support
119 CRYPTO_set_locking_callback(NULL);
120 for (int i = 0; i < CRYPTO_num_locks(); i++)
121 delete ppmutexOpenSSL[i];
122 OPENSSL_free(ppmutexOpenSSL);
136 // Seed with CPU performance counter
137 int64 nCounter = GetPerformanceCounter();
138 RAND_add(&nCounter, sizeof(nCounter), 1.5);
139 memset(&nCounter, 0, sizeof(nCounter));
142 void RandAddSeedPerfmon()
146 // This can take up to 2 seconds, so only do it every 10 minutes
147 static int64 nLastPerfmon;
148 if (GetTime() < nLastPerfmon + 10 * 60)
150 nLastPerfmon = GetTime();
153 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom
154 // Seed with the entire set of perfmon data
155 unsigned char pdata[250000];
156 memset(pdata, 0, sizeof(pdata));
157 unsigned long nSize = sizeof(pdata);
158 long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
159 RegCloseKey(HKEY_PERFORMANCE_DATA);
160 if (ret == ERROR_SUCCESS)
162 RAND_add(pdata, nSize, nSize/100.0);
163 memset(pdata, 0, nSize);
164 printf("RandAddSeed() %lu bytes\n", nSize);
169 uint64 GetRand(uint64 nMax)
174 // The range of the random source must be a multiple of the modulus
175 // to give every possible output value an equal possibility
176 uint64 nRange = (std::numeric_limits<uint64>::max() / nMax) * nMax;
179 RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
180 while (nRand >= nRange);
181 return (nRand % nMax);
184 int GetRandInt(int nMax)
186 return GetRand(nMax);
189 uint256 GetRandHash()
192 RAND_bytes((unsigned char*)&hash, sizeof(hash));
201 static FILE* fileout = NULL;
203 inline int OutputDebugStringF(const char* pszFormat, ...)
210 va_start(arg_ptr, pszFormat);
211 ret = vprintf(pszFormat, arg_ptr);
214 else if (!fPrintToDebugger)
216 // print to debug.log
220 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
221 fileout = fopen(pathDebug.string().c_str(), "a");
222 if (fileout) setbuf(fileout, NULL); // unbuffered
226 static bool fStartedNewLine = true;
228 // This routine may be called by global destructors during shutdown.
229 // Since the order of destruction of static/global objects is undefined,
230 // allocate mutexDebugLog on the heap the first time this routine
231 // is called to avoid crashes during shutdown.
232 static boost::mutex* mutexDebugLog = NULL;
233 if (mutexDebugLog == NULL) mutexDebugLog = new boost::mutex();
234 boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
236 // reopen the log file, if requested
237 if (fReopenDebugLog) {
238 fReopenDebugLog = false;
239 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
240 if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL)
241 setbuf(fileout, NULL); // unbuffered
244 // Debug print useful for profiling
245 if (fLogTimestamps && fStartedNewLine)
246 fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
247 if (pszFormat[strlen(pszFormat) - 1] == '\n')
248 fStartedNewLine = true;
250 fStartedNewLine = false;
253 va_start(arg_ptr, pszFormat);
254 ret = vfprintf(fileout, pszFormat, arg_ptr);
260 if (fPrintToDebugger)
262 static CCriticalSection cs_OutputDebugStringF;
264 // accumulate and output a line at a time
266 LOCK(cs_OutputDebugStringF);
267 static std::string buffer;
270 va_start(arg_ptr, pszFormat);
271 buffer += vstrprintf(pszFormat, arg_ptr);
274 int line_start = 0, line_end;
275 while((line_end = buffer.find('\n', line_start)) != -1)
277 OutputDebugStringA(buffer.substr(line_start, line_end - line_start).c_str());
278 line_start = line_end + 1;
280 buffer.erase(0, line_start);
287 string vstrprintf(const char *format, va_list ap)
291 int limit = sizeof(buffer);
296 va_copy(arg_ptr, ap);
298 ret = _vsnprintf(p, limit, format, arg_ptr);
300 ret = vsnprintf(p, limit, format, arg_ptr);
303 if (ret >= 0 && ret < limit)
310 throw std::bad_alloc();
312 string str(p, p+ret);
318 string real_strprintf(const char *format, int dummy, ...)
321 va_start(arg_ptr, dummy);
322 string str = vstrprintf(format, arg_ptr);
327 string real_strprintf(const std::string &format, int dummy, ...)
330 va_start(arg_ptr, dummy);
331 string str = vstrprintf(format.c_str(), arg_ptr);
336 bool error(const char *format, ...)
339 va_start(arg_ptr, format);
340 std::string str = vstrprintf(format, arg_ptr);
342 printf("ERROR: %s\n", str.c_str());
347 void ParseString(const string& str, char c, vector<string>& v)
351 string::size_type i1 = 0;
352 string::size_type i2;
355 i2 = str.find(c, i1);
358 v.push_back(str.substr(i1));
361 v.push_back(str.substr(i1, i2-i1));
367 string FormatMoney(int64 n, bool fPlus)
369 // Note: not using straight sprintf here because we do NOT want
370 // localized number formatting.
371 int64 n_abs = (n > 0 ? n : -n);
372 int64 quotient = n_abs/COIN;
373 int64 remainder = n_abs%COIN;
374 string str = strprintf("%"PRI64d".%08"PRI64d, quotient, remainder);
376 // Right-trim excess zeros before the decimal point:
378 for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
381 str.erase(str.size()-nTrim, nTrim);
384 str.insert((unsigned int)0, 1, '-');
385 else if (fPlus && n > 0)
386 str.insert((unsigned int)0, 1, '+');
391 bool ParseMoney(const string& str, int64& nRet)
393 return ParseMoney(str.c_str(), nRet);
396 bool ParseMoney(const char* pszIn, int64& nRet)
400 const char* p = pszIn;
408 int64 nMult = CENT*10;
409 while (isdigit(*p) && (nMult > 0))
411 nUnits += nMult * (*p++ - '0');
420 strWhole.insert(strWhole.end(), *p);
425 if (strWhole.size() > 10) // guard against 63 bit overflow
427 if (nUnits < 0 || nUnits > COIN)
429 int64 nWhole = atoi64(strWhole);
430 int64 nValue = nWhole*COIN + nUnits;
436 // safeChars chosen to allow simple messages/URLs/email addresses, but avoid anything
437 // even possibly remotely dangerous like & or >
438 static string safeChars("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890 .,;_/:?@");
439 string SanitizeString(const string& str)
442 for (std::string::size_type i = 0; i < str.size(); i++)
444 if (safeChars.find(str[i]) != std::string::npos)
445 strResult.push_back(str[i]);
450 static const signed char phexdigit[256] =
451 { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
452 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
453 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
454 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
455 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
456 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
457 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
458 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
459 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
460 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
461 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
462 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
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 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
468 bool IsHex(const string& str)
470 BOOST_FOREACH(unsigned char c, str)
472 if (phexdigit[c] < 0)
475 return (str.size() > 0) && (str.size()%2 == 0);
478 vector<unsigned char> ParseHex(const char* psz)
480 // convert hex dump to vector
481 vector<unsigned char> vch;
484 while (isspace(*psz))
486 signed char c = phexdigit[(unsigned char)*psz++];
487 if (c == (signed char)-1)
489 unsigned char n = (c << 4);
490 c = phexdigit[(unsigned char)*psz++];
491 if (c == (signed char)-1)
499 vector<unsigned char> ParseHex(const string& str)
501 return ParseHex(str.c_str());
504 static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
506 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
507 if (name.find("-no") == 0)
509 std::string positive("-");
510 positive.append(name.begin()+3, name.end());
511 if (mapSettingsRet.count(positive) == 0)
513 bool value = !GetBoolArg(name);
514 mapSettingsRet[positive] = (value ? "1" : "0");
519 void ParseParameters(int argc, const char* const argv[])
522 mapMultiArgs.clear();
523 for (int i = 1; i < argc; i++)
526 strlcpy(psz, argv[i], sizeof(psz));
527 char* pszValue = (char*)"";
528 if (strchr(psz, '='))
530 pszValue = strchr(psz, '=');
541 mapArgs[psz] = pszValue;
542 mapMultiArgs[psz].push_back(pszValue);
546 BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs)
548 string name = entry.first;
550 // interpret --foo as -foo (as long as both are not set)
551 if (name.find("--") == 0)
553 std::string singleDash(name.begin()+1, name.end());
554 if (mapArgs.count(singleDash) == 0)
555 mapArgs[singleDash] = entry.second;
559 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
560 InterpretNegativeSetting(name, mapArgs);
564 std::string GetArg(const std::string& strArg, const std::string& strDefault)
566 if (mapArgs.count(strArg))
567 return mapArgs[strArg];
571 int64 GetArg(const std::string& strArg, int64 nDefault)
573 if (mapArgs.count(strArg))
574 return atoi64(mapArgs[strArg]);
578 bool GetBoolArg(const std::string& strArg, bool fDefault)
580 if (mapArgs.count(strArg))
582 if (mapArgs[strArg].empty())
584 return (atoi(mapArgs[strArg]) != 0);
589 bool SoftSetArg(const std::string& strArg, const std::string& strValue)
591 if (mapArgs.count(strArg))
593 mapArgs[strArg] = strValue;
597 bool SoftSetBoolArg(const std::string& strArg, bool fValue)
600 return SoftSetArg(strArg, std::string("1"));
602 return SoftSetArg(strArg, std::string("0"));
606 string EncodeBase64(const unsigned char* pch, size_t len)
608 static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
611 strRet.reserve((len+2)/3*4);
614 const unsigned char *pchEnd = pch+len;
621 case 0: // we have no bits
622 strRet += pbase64[enc >> 2];
623 left = (enc & 3) << 4;
627 case 1: // we have two bits
628 strRet += pbase64[left | (enc >> 4)];
629 left = (enc & 15) << 2;
633 case 2: // we have four bits
634 strRet += pbase64[left | (enc >> 6)];
635 strRet += pbase64[enc & 63];
643 strRet += pbase64[left];
652 string EncodeBase64(const string& str)
654 return EncodeBase64((const unsigned char*)str.c_str(), str.size());
657 vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
659 static const int decode64_table[256] =
661 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
662 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
663 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
664 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
665 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
666 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
667 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
668 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
669 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
670 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
671 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
672 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
673 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
679 vector<unsigned char> vchRet;
680 vchRet.reserve(strlen(p)*3/4);
687 int dec = decode64_table[(unsigned char)*p];
688 if (dec == -1) break;
692 case 0: // we have no bits and get 6
697 case 1: // we have 6 bits and keep 4
698 vchRet.push_back((left<<2) | (dec>>4));
703 case 2: // we have 4 bits and get 6, we keep 2
704 vchRet.push_back((left<<4) | (dec>>2));
709 case 3: // we have 2 bits and get 6
710 vchRet.push_back((left<<6) | dec);
719 case 0: // 4n base64 characters processed: ok
722 case 1: // 4n+1 base64 character processed: impossible
726 case 2: // 4n+2 base64 characters processed: require '=='
727 if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1)
731 case 3: // 4n+3 base64 characters processed: require '='
732 if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1)
740 string DecodeBase64(const string& str)
742 vector<unsigned char> vchRet = DecodeBase64(str.c_str());
743 return string((const char*)&vchRet[0], vchRet.size());
746 string EncodeBase32(const unsigned char* pch, size_t len)
748 static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567";
751 strRet.reserve((len+4)/5*8);
754 const unsigned char *pchEnd = pch+len;
761 case 0: // we have no bits
762 strRet += pbase32[enc >> 3];
763 left = (enc & 7) << 2;
767 case 1: // we have three bits
768 strRet += pbase32[left | (enc >> 6)];
769 strRet += pbase32[(enc >> 1) & 31];
770 left = (enc & 1) << 4;
774 case 2: // we have one bit
775 strRet += pbase32[left | (enc >> 4)];
776 left = (enc & 15) << 1;
780 case 3: // we have four bits
781 strRet += pbase32[left | (enc >> 7)];
782 strRet += pbase32[(enc >> 2) & 31];
783 left = (enc & 3) << 3;
787 case 4: // we have two bits
788 strRet += pbase32[left | (enc >> 5)];
789 strRet += pbase32[enc & 31];
794 static const int nPadding[5] = {0, 6, 4, 3, 1};
797 strRet += pbase32[left];
798 for (int n=0; n<nPadding[mode]; n++)
805 string EncodeBase32(const string& str)
807 return EncodeBase32((const unsigned char*)str.c_str(), str.size());
810 vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid)
812 static const int decode32_table[256] =
814 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
815 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
816 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1,
817 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
818 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 0, 1, 2,
819 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
820 23, 24, 25, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
821 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
822 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
823 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
824 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
825 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
826 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
832 vector<unsigned char> vchRet;
833 vchRet.reserve((strlen(p))*5/8);
840 int dec = decode32_table[(unsigned char)*p];
841 if (dec == -1) break;
845 case 0: // we have no bits and get 5
850 case 1: // we have 5 bits and keep 2
851 vchRet.push_back((left<<3) | (dec>>2));
856 case 2: // we have 2 bits and keep 7
857 left = left << 5 | dec;
861 case 3: // we have 7 bits and keep 4
862 vchRet.push_back((left<<1) | (dec>>4));
867 case 4: // we have 4 bits, and keep 1
868 vchRet.push_back((left<<4) | (dec>>1));
873 case 5: // we have 1 bit, and keep 6
874 left = left << 5 | dec;
878 case 6: // we have 6 bits, and keep 3
879 vchRet.push_back((left<<2) | (dec>>3));
884 case 7: // we have 3 bits, and keep 0
885 vchRet.push_back((left<<5) | dec);
894 case 0: // 8n base32 characters processed: ok
897 case 1: // 8n+1 base32 characters processed: impossible
903 case 2: // 8n+2 base32 characters processed: require '======'
904 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || p[4] != '=' || p[5] != '=' || decode32_table[(unsigned char)p[6]] != -1)
908 case 4: // 8n+4 base32 characters processed: require '===='
909 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || decode32_table[(unsigned char)p[4]] != -1)
913 case 5: // 8n+5 base32 characters processed: require '==='
914 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || decode32_table[(unsigned char)p[3]] != -1)
918 case 7: // 8n+7 base32 characters processed: require '='
919 if (left || p[0] != '=' || decode32_table[(unsigned char)p[1]] != -1)
927 string DecodeBase32(const string& str)
929 vector<unsigned char> vchRet = DecodeBase32(str.c_str());
930 return string((const char*)&vchRet[0], vchRet.size());
934 bool WildcardMatch(const char* psz, const char* mask)
941 return (*psz == '\0');
943 return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
958 bool WildcardMatch(const string& str, const string& mask)
960 return WildcardMatch(str.c_str(), mask.c_str());
970 static std::string FormatException(std::exception* pex, const char* pszThread)
973 char pszModule[MAX_PATH] = "";
974 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
976 const char* pszModule = "novacoin";
980 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
983 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
986 void LogException(std::exception* pex, const char* pszThread)
988 std::string message = FormatException(pex, pszThread);
989 printf("\n%s", message.c_str());
992 void PrintException(std::exception* pex, const char* pszThread)
994 std::string message = FormatException(pex, pszThread);
995 printf("\n\n************************\n%s\n", message.c_str());
996 fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
997 strMiscWarning = message;
1001 void LogStackTrace() {
1002 printf("\n\n******* exception encountered *******\n");
1006 void* pszBuffer[32];
1008 size = backtrace(pszBuffer, 32);
1009 backtrace_symbols_fd(pszBuffer, size, fileno(fileout));
1014 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
1016 std::string message = FormatException(pex, pszThread);
1017 printf("\n\n************************\n%s\n", message.c_str());
1018 fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
1019 strMiscWarning = message;
1022 boost::filesystem::path GetDefaultDataDir()
1024 namespace fs = boost::filesystem;
1025 // Windows < Vista: C:\Documents and Settings\Username\Application Data\NovaCoin
1026 // Windows >= Vista: C:\Users\Username\AppData\Roaming\NovaCoin
1027 // Mac: ~/Library/Application Support/NovaCoin
1028 // Unix: ~/.novacoin
1031 return GetSpecialFolderPath(CSIDL_APPDATA) / "NovaCoin";
1034 char* pszHome = getenv("HOME");
1035 if (pszHome == NULL || strlen(pszHome) == 0)
1036 pathRet = fs::path("/");
1038 pathRet = fs::path(pszHome);
1041 pathRet /= "Library/Application Support";
1042 fs::create_directory(pathRet);
1043 return pathRet / "NovaCoin";
1046 return pathRet / ".novacoin";
1051 const boost::filesystem::path &GetDataDir(bool fNetSpecific)
1053 namespace fs = boost::filesystem;
1055 static fs::path pathCached[2];
1056 static CCriticalSection csPathCached;
1057 static bool cachedPath[2] = {false, false};
1059 fs::path &path = pathCached[fNetSpecific];
1061 // This can be called during exceptions by printf, so we cache the
1062 // value so we don't have to do memory allocations after that.
1063 if (cachedPath[fNetSpecific])
1068 if (mapArgs.count("-datadir")) {
1069 path = fs::system_complete(mapArgs["-datadir"]);
1070 if (!fs::is_directory(path)) {
1075 path = GetDefaultDataDir();
1077 if (fNetSpecific && GetBoolArg("-testnet", false))
1080 fs::create_directory(path);
1082 cachedPath[fNetSpecific]=true;
1086 boost::filesystem::path GetConfigFile()
1088 boost::filesystem::path pathConfigFile(GetArg("-conf", "novacoin.conf"));
1089 if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
1090 return pathConfigFile;
1093 void ReadConfigFile(map<string, string>& mapSettingsRet,
1094 map<string, vector<string> >& mapMultiSettingsRet)
1096 boost::filesystem::ifstream streamConfig(GetConfigFile());
1097 if (!streamConfig.good())
1098 return; // No bitcoin.conf file is OK
1100 set<string> setOptions;
1101 setOptions.insert("*");
1103 for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
1105 // Don't overwrite existing settings so command line settings override bitcoin.conf
1106 string strKey = string("-") + it->string_key;
1107 if (mapSettingsRet.count(strKey) == 0)
1109 mapSettingsRet[strKey] = it->value[0];
1110 // interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
1111 InterpretNegativeSetting(strKey, mapSettingsRet);
1113 mapMultiSettingsRet[strKey].push_back(it->value[0]);
1117 boost::filesystem::path GetPidFile()
1119 boost::filesystem::path pathPidFile(GetArg("-pid", "novacoind.pid"));
1120 if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
1125 void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
1127 FILE* file = fopen(path.string().c_str(), "w");
1130 fprintf(file, "%d\n", pid);
1136 bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
1139 return MoveFileExA(src.string().c_str(), dest.string().c_str(),
1140 MOVEFILE_REPLACE_EXISTING);
1142 int rc = std::rename(src.string().c_str(), dest.string().c_str());
1147 void FileCommit(FILE *fileout)
1149 fflush(fileout); // harmless if redundantly called
1151 _commit(_fileno(fileout));
1153 fsync(fileno(fileout));
1157 int GetFilesize(FILE* file)
1159 int nSavePos = ftell(file);
1161 if (fseek(file, 0, SEEK_END) == 0)
1162 nFilesize = ftell(file);
1163 fseek(file, nSavePos, SEEK_SET);
1167 // this function tries to make a particular range of a file allocated (corresponding to disk space)
1168 // it is advisory, and the range specified in the arguments will never contain live data
1169 void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length) {
1170 static const char buf[65536] = {};
1171 fseek(file, offset, SEEK_SET);
1172 while (length > 0) {
1173 unsigned int now = 65536;
1176 fwrite(buf, 1, now, file); // allowed to fail; this function is advisory anyway
1182 void ShrinkDebugFile()
1184 // Scroll debug.log if it's getting too big
1185 boost::filesystem::path pathLog = GetDataDir() / "debug.log";
1186 FILE* file = fopen(pathLog.string().c_str(), "r");
1187 if (file && GetFilesize(file) > 10 * 1000000)
1189 // Restart the file with some of the end
1191 fseek(file, -sizeof(pch), SEEK_END);
1192 int nBytes = fread(pch, 1, sizeof(pch), file);
1195 file = fopen(pathLog.string().c_str(), "w");
1198 fwrite(pch, 1, nBytes, file);
1212 // "Never go to sea with two chronometers; take one or three."
1213 // Our three time sources are:
1215 // - Median of other nodes clocks
1216 // - The user (asking the user to fix the system clock if the first two disagree)
1218 static int64 nMockTime = 0; // For unit testing
1222 if (nMockTime) return nMockTime;
1227 void SetMockTime(int64 nMockTimeIn)
1229 nMockTime = nMockTimeIn;
1232 static int64 nTimeOffset = 0;
1234 int64 GetTimeOffset()
1239 int64 GetAdjustedTime()
1241 return GetTime() + GetTimeOffset();
1244 void AddTimeData(const CNetAddr& ip, int64 nTime)
1246 int64 nOffsetSample = nTime - GetTime();
1248 // Ignore duplicates
1249 static set<CNetAddr> setKnown;
1250 if (!setKnown.insert(ip).second)
1254 vTimeOffsets.input(nOffsetSample);
1255 printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
1256 if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
1258 int64 nMedian = vTimeOffsets.median();
1259 std::vector<int64> vSorted = vTimeOffsets.sorted();
1260 // Only let other nodes change our time by so much
1261 if (abs64(nMedian) < 70 * 60)
1263 nTimeOffset = nMedian;
1272 // If nobody has a time different than ours but within 5 minutes of ours, give a warning
1273 bool fMatch = false;
1274 BOOST_FOREACH(int64 nOffset, vSorted)
1275 if (nOffset != 0 && abs64(nOffset) < 5 * 60)
1281 string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong NovaCoin will not work properly.");
1282 strMiscWarning = strMessage;
1283 printf("*** %s\n", strMessage.c_str());
1284 uiInterface.ThreadSafeMessageBox(strMessage+" ", string("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION);
1289 BOOST_FOREACH(int64 n, vSorted)
1290 printf("%+"PRI64d" ", n);
1293 printf("nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
1304 string FormatVersion(int nVersion)
1306 if (nVersion%100 == 0)
1307 return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
1309 return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
1312 string FormatFullVersion()
1314 return CLIENT_BUILD;
1317 // Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
1318 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
1320 std::ostringstream ss;
1322 ss << name << ":" << FormatVersion(nClientVersion);
1323 if (!comments.empty())
1324 ss << "(" << boost::algorithm::join(comments, "; ") << ")";
1330 boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate)
1332 namespace fs = boost::filesystem;
1334 char pszPath[MAX_PATH] = "";
1336 if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
1338 return fs::path(pszPath);
1341 printf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
1342 return fs::path("");
1346 void runCommand(std::string strCommand)
1348 int nErr = ::system(strCommand.c_str());
1350 printf("runCommand error: system(%s) returned %d\n", strCommand.c_str(), nErr);
1353 void RenameThread(const char* name)
1355 #if defined(PR_SET_NAME)
1356 // Only the first 15 characters are used (16 - NUL terminator)
1357 ::prctl(PR_SET_NAME, name, 0, 0, 0);
1358 #elif 0 && (defined(__FreeBSD__) || defined(__OpenBSD__))
1359 // TODO: This is currently disabled because it needs to be verified to work
1360 // on FreeBSD or OpenBSD first. When verified the '0 &&' part can be
1362 pthread_set_name_np(pthread_self(), name);
1364 // This is XCode 10.6-and-later; bring back if we drop 10.5 support:
1365 // #elif defined(MAC_OSX)
1366 // pthread_setname_np(name);
1369 // Prevent warnings for unused parameters...
1374 bool NewThread(void(*pfn)(void*), void* parg)
1378 boost::thread(pfn, parg); // thread detaches when out of scope
1379 } catch(boost::thread_resource_error &e) {
1380 printf("Error creating thread: %s\n", e.what());