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;
437 static const signed char phexdigit[256] =
438 { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
439 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
440 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
441 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
442 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
443 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
444 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
445 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
446 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
447 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
448 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
449 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
450 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
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, };
455 bool IsHex(const string& str)
457 BOOST_FOREACH(unsigned char c, str)
459 if (phexdigit[c] < 0)
462 return (str.size() > 0) && (str.size()%2 == 0);
465 vector<unsigned char> ParseHex(const char* psz)
467 // convert hex dump to vector
468 vector<unsigned char> vch;
471 while (isspace(*psz))
473 signed char c = phexdigit[(unsigned char)*psz++];
474 if (c == (signed char)-1)
476 unsigned char n = (c << 4);
477 c = phexdigit[(unsigned char)*psz++];
478 if (c == (signed char)-1)
486 vector<unsigned char> ParseHex(const string& str)
488 return ParseHex(str.c_str());
491 static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
493 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
494 if (name.find("-no") == 0)
496 std::string positive("-");
497 positive.append(name.begin()+3, name.end());
498 if (mapSettingsRet.count(positive) == 0)
500 bool value = !GetBoolArg(name);
501 mapSettingsRet[positive] = (value ? "1" : "0");
506 void ParseParameters(int argc, const char* const argv[])
509 mapMultiArgs.clear();
510 for (int i = 1; i < argc; i++)
513 strlcpy(psz, argv[i], sizeof(psz));
514 char* pszValue = (char*)"";
515 if (strchr(psz, '='))
517 pszValue = strchr(psz, '=');
528 mapArgs[psz] = pszValue;
529 mapMultiArgs[psz].push_back(pszValue);
533 BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs)
535 string name = entry.first;
537 // interpret --foo as -foo (as long as both are not set)
538 if (name.find("--") == 0)
540 std::string singleDash(name.begin()+1, name.end());
541 if (mapArgs.count(singleDash) == 0)
542 mapArgs[singleDash] = entry.second;
546 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
547 InterpretNegativeSetting(name, mapArgs);
551 std::string GetArg(const std::string& strArg, const std::string& strDefault)
553 if (mapArgs.count(strArg))
554 return mapArgs[strArg];
558 int64 GetArg(const std::string& strArg, int64 nDefault)
560 if (mapArgs.count(strArg))
561 return atoi64(mapArgs[strArg]);
565 bool GetBoolArg(const std::string& strArg, bool fDefault)
567 if (mapArgs.count(strArg))
569 if (mapArgs[strArg].empty())
571 return (atoi(mapArgs[strArg]) != 0);
576 bool SoftSetArg(const std::string& strArg, const std::string& strValue)
578 if (mapArgs.count(strArg))
580 mapArgs[strArg] = strValue;
584 bool SoftSetBoolArg(const std::string& strArg, bool fValue)
587 return SoftSetArg(strArg, std::string("1"));
589 return SoftSetArg(strArg, std::string("0"));
593 string EncodeBase64(const unsigned char* pch, size_t len)
595 static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
598 strRet.reserve((len+2)/3*4);
601 const unsigned char *pchEnd = pch+len;
608 case 0: // we have no bits
609 strRet += pbase64[enc >> 2];
610 left = (enc & 3) << 4;
614 case 1: // we have two bits
615 strRet += pbase64[left | (enc >> 4)];
616 left = (enc & 15) << 2;
620 case 2: // we have four bits
621 strRet += pbase64[left | (enc >> 6)];
622 strRet += pbase64[enc & 63];
630 strRet += pbase64[left];
639 string EncodeBase64(const string& str)
641 return EncodeBase64((const unsigned char*)str.c_str(), str.size());
644 vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
646 static const int decode64_table[256] =
648 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
649 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
650 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
651 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
652 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
653 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
654 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
655 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
656 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
657 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
658 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
659 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
660 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
666 vector<unsigned char> vchRet;
667 vchRet.reserve(strlen(p)*3/4);
674 int dec = decode64_table[(unsigned char)*p];
675 if (dec == -1) break;
679 case 0: // we have no bits and get 6
684 case 1: // we have 6 bits and keep 4
685 vchRet.push_back((left<<2) | (dec>>4));
690 case 2: // we have 4 bits and get 6, we keep 2
691 vchRet.push_back((left<<4) | (dec>>2));
696 case 3: // we have 2 bits and get 6
697 vchRet.push_back((left<<6) | dec);
706 case 0: // 4n base64 characters processed: ok
709 case 1: // 4n+1 base64 character processed: impossible
713 case 2: // 4n+2 base64 characters processed: require '=='
714 if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1)
718 case 3: // 4n+3 base64 characters processed: require '='
719 if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1)
727 string DecodeBase64(const string& str)
729 vector<unsigned char> vchRet = DecodeBase64(str.c_str());
730 return string((const char*)&vchRet[0], vchRet.size());
733 string EncodeBase32(const unsigned char* pch, size_t len)
735 static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567";
738 strRet.reserve((len+4)/5*8);
741 const unsigned char *pchEnd = pch+len;
748 case 0: // we have no bits
749 strRet += pbase32[enc >> 3];
750 left = (enc & 7) << 2;
754 case 1: // we have three bits
755 strRet += pbase32[left | (enc >> 6)];
756 strRet += pbase32[(enc >> 1) & 31];
757 left = (enc & 1) << 4;
761 case 2: // we have one bit
762 strRet += pbase32[left | (enc >> 4)];
763 left = (enc & 15) << 1;
767 case 3: // we have four bits
768 strRet += pbase32[left | (enc >> 7)];
769 strRet += pbase32[(enc >> 2) & 31];
770 left = (enc & 3) << 3;
774 case 4: // we have two bits
775 strRet += pbase32[left | (enc >> 5)];
776 strRet += pbase32[enc & 31];
781 static const int nPadding[5] = {0, 6, 4, 3, 1};
784 strRet += pbase32[left];
785 for (int n=0; n<nPadding[mode]; n++)
792 string EncodeBase32(const string& str)
794 return EncodeBase32((const unsigned char*)str.c_str(), str.size());
797 vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid)
799 static const int decode32_table[256] =
801 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
802 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
803 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1,
804 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
805 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 0, 1, 2,
806 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
807 23, 24, 25, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
808 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
809 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
810 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
811 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
812 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
813 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
819 vector<unsigned char> vchRet;
820 vchRet.reserve((strlen(p))*5/8);
827 int dec = decode32_table[(unsigned char)*p];
828 if (dec == -1) break;
832 case 0: // we have no bits and get 5
837 case 1: // we have 5 bits and keep 2
838 vchRet.push_back((left<<3) | (dec>>2));
843 case 2: // we have 2 bits and keep 7
844 left = left << 5 | dec;
848 case 3: // we have 7 bits and keep 4
849 vchRet.push_back((left<<1) | (dec>>4));
854 case 4: // we have 4 bits, and keep 1
855 vchRet.push_back((left<<4) | (dec>>1));
860 case 5: // we have 1 bit, and keep 6
861 left = left << 5 | dec;
865 case 6: // we have 6 bits, and keep 3
866 vchRet.push_back((left<<2) | (dec>>3));
871 case 7: // we have 3 bits, and keep 0
872 vchRet.push_back((left<<5) | dec);
881 case 0: // 8n base32 characters processed: ok
884 case 1: // 8n+1 base32 characters processed: impossible
890 case 2: // 8n+2 base32 characters processed: require '======'
891 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || p[4] != '=' || p[5] != '=' || decode32_table[(unsigned char)p[6]] != -1)
895 case 4: // 8n+4 base32 characters processed: require '===='
896 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || decode32_table[(unsigned char)p[4]] != -1)
900 case 5: // 8n+5 base32 characters processed: require '==='
901 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || decode32_table[(unsigned char)p[3]] != -1)
905 case 7: // 8n+7 base32 characters processed: require '='
906 if (left || p[0] != '=' || decode32_table[(unsigned char)p[1]] != -1)
914 string DecodeBase32(const string& str)
916 vector<unsigned char> vchRet = DecodeBase32(str.c_str());
917 return string((const char*)&vchRet[0], vchRet.size());
921 bool WildcardMatch(const char* psz, const char* mask)
928 return (*psz == '\0');
930 return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
945 bool WildcardMatch(const string& str, const string& mask)
947 return WildcardMatch(str.c_str(), mask.c_str());
957 static std::string FormatException(std::exception* pex, const char* pszThread)
960 char pszModule[MAX_PATH] = "";
961 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
963 const char* pszModule = "novacoin";
967 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
970 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
973 void LogException(std::exception* pex, const char* pszThread)
975 std::string message = FormatException(pex, pszThread);
976 printf("\n%s", message.c_str());
979 void PrintException(std::exception* pex, const char* pszThread)
981 std::string message = FormatException(pex, pszThread);
982 printf("\n\n************************\n%s\n", message.c_str());
983 fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
984 strMiscWarning = message;
988 void LogStackTrace() {
989 printf("\n\n******* exception encountered *******\n");
995 size = backtrace(pszBuffer, 32);
996 backtrace_symbols_fd(pszBuffer, size, fileno(fileout));
1001 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
1003 std::string message = FormatException(pex, pszThread);
1004 printf("\n\n************************\n%s\n", message.c_str());
1005 fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
1006 strMiscWarning = message;
1009 boost::filesystem::path GetDefaultDataDir()
1011 namespace fs = boost::filesystem;
1012 // Windows < Vista: C:\Documents and Settings\Username\Application Data\NovaCoin
1013 // Windows >= Vista: C:\Users\Username\AppData\Roaming\NovaCoin
1014 // Mac: ~/Library/Application Support/NovaCoin
1015 // Unix: ~/.novacoin
1018 return GetSpecialFolderPath(CSIDL_APPDATA) / "NovaCoin";
1021 char* pszHome = getenv("HOME");
1022 if (pszHome == NULL || strlen(pszHome) == 0)
1023 pathRet = fs::path("/");
1025 pathRet = fs::path(pszHome);
1028 pathRet /= "Library/Application Support";
1029 fs::create_directory(pathRet);
1030 return pathRet / "NovaCoin";
1033 return pathRet / ".novacoin";
1038 const boost::filesystem::path &GetDataDir(bool fNetSpecific)
1040 namespace fs = boost::filesystem;
1042 static fs::path pathCached[2];
1043 static CCriticalSection csPathCached;
1044 static bool cachedPath[2] = {false, false};
1046 fs::path &path = pathCached[fNetSpecific];
1048 // This can be called during exceptions by printf, so we cache the
1049 // value so we don't have to do memory allocations after that.
1050 if (cachedPath[fNetSpecific])
1055 if (mapArgs.count("-datadir")) {
1056 path = fs::system_complete(mapArgs["-datadir"]);
1057 if (!fs::is_directory(path)) {
1062 path = GetDefaultDataDir();
1064 if (fNetSpecific && GetBoolArg("-testnet", false))
1067 fs::create_directory(path);
1069 cachedPath[fNetSpecific]=true;
1073 boost::filesystem::path GetConfigFile()
1075 boost::filesystem::path pathConfigFile(GetArg("-conf", "novacoin.conf"));
1076 if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
1077 return pathConfigFile;
1080 void ReadConfigFile(map<string, string>& mapSettingsRet,
1081 map<string, vector<string> >& mapMultiSettingsRet)
1083 boost::filesystem::ifstream streamConfig(GetConfigFile());
1084 if (!streamConfig.good())
1085 return; // No bitcoin.conf file is OK
1087 set<string> setOptions;
1088 setOptions.insert("*");
1090 for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
1092 // Don't overwrite existing settings so command line settings override bitcoin.conf
1093 string strKey = string("-") + it->string_key;
1094 if (mapSettingsRet.count(strKey) == 0)
1096 mapSettingsRet[strKey] = it->value[0];
1097 // interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
1098 InterpretNegativeSetting(strKey, mapSettingsRet);
1100 mapMultiSettingsRet[strKey].push_back(it->value[0]);
1104 boost::filesystem::path GetPidFile()
1106 boost::filesystem::path pathPidFile(GetArg("-pid", "novacoind.pid"));
1107 if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
1112 void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
1114 FILE* file = fopen(path.string().c_str(), "w");
1117 fprintf(file, "%d\n", pid);
1123 bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
1126 return MoveFileExA(src.string().c_str(), dest.string().c_str(),
1127 MOVEFILE_REPLACE_EXISTING);
1129 int rc = std::rename(src.string().c_str(), dest.string().c_str());
1134 void FileCommit(FILE *fileout)
1136 fflush(fileout); // harmless if redundantly called
1138 _commit(_fileno(fileout));
1140 fsync(fileno(fileout));
1144 int GetFilesize(FILE* file)
1146 int nSavePos = ftell(file);
1148 if (fseek(file, 0, SEEK_END) == 0)
1149 nFilesize = ftell(file);
1150 fseek(file, nSavePos, SEEK_SET);
1154 void ShrinkDebugFile()
1156 // Scroll debug.log if it's getting too big
1157 boost::filesystem::path pathLog = GetDataDir() / "debug.log";
1158 FILE* file = fopen(pathLog.string().c_str(), "r");
1159 if (file && GetFilesize(file) > 10 * 1000000)
1161 // Restart the file with some of the end
1163 fseek(file, -sizeof(pch), SEEK_END);
1164 int nBytes = fread(pch, 1, sizeof(pch), file);
1167 file = fopen(pathLog.string().c_str(), "w");
1170 fwrite(pch, 1, nBytes, file);
1184 // "Never go to sea with two chronometers; take one or three."
1185 // Our three time sources are:
1187 // - Median of other nodes clocks
1188 // - The user (asking the user to fix the system clock if the first two disagree)
1190 static int64 nMockTime = 0; // For unit testing
1194 if (nMockTime) return nMockTime;
1199 void SetMockTime(int64 nMockTimeIn)
1201 nMockTime = nMockTimeIn;
1204 static int64 nTimeOffset = 0;
1206 int64 GetTimeOffset()
1211 int64 GetAdjustedTime()
1213 return GetTime() + GetTimeOffset();
1216 void AddTimeData(const CNetAddr& ip, int64 nTime)
1218 int64 nOffsetSample = nTime - GetTime();
1220 // Ignore duplicates
1221 static set<CNetAddr> setKnown;
1222 if (!setKnown.insert(ip).second)
1226 vTimeOffsets.input(nOffsetSample);
1227 printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
1228 if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
1230 int64 nMedian = vTimeOffsets.median();
1231 std::vector<int64> vSorted = vTimeOffsets.sorted();
1232 // Only let other nodes change our time by so much
1233 if (abs64(nMedian) < 70 * 60)
1235 nTimeOffset = nMedian;
1244 // If nobody has a time different than ours but within 5 minutes of ours, give a warning
1245 bool fMatch = false;
1246 BOOST_FOREACH(int64 nOffset, vSorted)
1247 if (nOffset != 0 && abs64(nOffset) < 5 * 60)
1253 string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong NovaCoin will not work properly.");
1254 strMiscWarning = strMessage;
1255 printf("*** %s\n", strMessage.c_str());
1256 uiInterface.ThreadSafeMessageBox(strMessage+" ", string("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION);
1261 BOOST_FOREACH(int64 n, vSorted)
1262 printf("%+"PRI64d" ", n);
1265 printf("nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
1276 string FormatVersion(int nVersion)
1278 if (nVersion%100 == 0)
1279 return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
1281 return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
1284 string FormatFullVersion()
1286 return CLIENT_BUILD;
1289 // Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
1290 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
1292 std::ostringstream ss;
1294 ss << name << ":" << FormatVersion(nClientVersion);
1295 if (!comments.empty())
1296 ss << "(" << boost::algorithm::join(comments, "; ") << ")";
1302 boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate)
1304 namespace fs = boost::filesystem;
1306 char pszPath[MAX_PATH] = "";
1308 if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
1310 return fs::path(pszPath);
1313 printf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
1314 return fs::path("");
1318 void runCommand(std::string strCommand)
1320 int nErr = ::system(strCommand.c_str());
1322 printf("runCommand error: system(%s) returned %d\n", strCommand.c_str(), nErr);
1325 void RenameThread(const char* name)
1327 #if defined(PR_SET_NAME)
1328 // Only the first 15 characters are used (16 - NUL terminator)
1329 ::prctl(PR_SET_NAME, name, 0, 0, 0);
1330 #elif 0 && (defined(__FreeBSD__) || defined(__OpenBSD__))
1331 // TODO: This is currently disabled because it needs to be verified to work
1332 // on FreeBSD or OpenBSD first. When verified the '0 &&' part can be
1334 pthread_set_name_np(pthread_self(), name);
1336 // This is XCode 10.6-and-later; bring back if we drop 10.5 support:
1337 // #elif defined(MAC_OSX)
1338 // pthread_setname_np(name);
1341 // Prevent warnings for unused parameters...
1346 bool NewThread(void(*pfn)(void*), void* parg)
1350 boost::thread(pfn, parg); // thread detaches when out of scope
1351 } catch(boost::thread_resource_error &e) {
1352 printf("Error creating thread: %s\n", e.what());