1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
9 #include "ui_interface.h"
10 #include <boost/algorithm/string/join.hpp>
12 // Work around clang compilation problem in Boost 1.46:
13 // /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
14 // See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options
15 // http://clang.debian.net/status.php?version=3.0&key=CANNOT_FIND_FUNCTION
17 namespace program_options {
18 std::string to_internal(const std::string&);
22 #include <boost/program_options/detail/config_file.hpp>
23 #include <boost/program_options/parsers.hpp>
24 #include <boost/filesystem.hpp>
25 #include <boost/filesystem/fstream.hpp>
26 #include <boost/interprocess/sync/interprocess_mutex.hpp>
27 #include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>
28 #include <boost/foreach.hpp>
29 #include <boost/thread.hpp>
30 #include <openssl/crypto.h>
31 #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 0x0400
48 #define WIN32_LEAN_AND_MEAN 1
57 using namespace boost;
59 map<string, string> mapArgs;
60 map<string, vector<string> > mapMultiArgs;
62 bool fPrintToConsole = false;
63 bool fPrintToDebugger = false;
64 bool fRequestShutdown = false;
65 bool fShutdown = false;
68 bool fCommandLine = false;
69 string strMiscWarning;
70 bool fTestNet = false;
71 bool fNoListen = false;
72 bool fLogTimestamps = false;
73 CMedianFilter<int64> vTimeOffsets(200,0);
75 // Init openssl library multithreading support
76 static boost::interprocess::interprocess_mutex** ppmutexOpenSSL;
77 void locking_callback(int mode, int i, const char* file, int line)
79 if (mode & CRYPTO_LOCK)
80 ppmutexOpenSSL[i]->lock();
82 ppmutexOpenSSL[i]->unlock();
91 // Init openssl library multithreading support
92 ppmutexOpenSSL = (boost::interprocess::interprocess_mutex**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(boost::interprocess::interprocess_mutex*));
93 for (int i = 0; i < CRYPTO_num_locks(); i++)
94 ppmutexOpenSSL[i] = new boost::interprocess::interprocess_mutex();
95 CRYPTO_set_locking_callback(locking_callback);
98 // Seed random number generator with screen scrape and other hardware sources
102 // Seed random number generator with performance counter
107 // Shutdown openssl library multithreading support
108 CRYPTO_set_locking_callback(NULL);
109 for (int i = 0; i < CRYPTO_num_locks(); i++)
110 delete ppmutexOpenSSL[i];
111 OPENSSL_free(ppmutexOpenSSL);
125 // Seed with CPU performance counter
126 int64 nCounter = GetPerformanceCounter();
127 RAND_add(&nCounter, sizeof(nCounter), 1.5);
128 memset(&nCounter, 0, sizeof(nCounter));
131 void RandAddSeedPerfmon()
135 // This can take up to 2 seconds, so only do it every 10 minutes
136 static int64 nLastPerfmon;
137 if (GetTime() < nLastPerfmon + 10 * 60)
139 nLastPerfmon = GetTime();
142 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom
143 // Seed with the entire set of perfmon data
144 unsigned char pdata[250000];
145 memset(pdata, 0, sizeof(pdata));
146 unsigned long nSize = sizeof(pdata);
147 long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
148 RegCloseKey(HKEY_PERFORMANCE_DATA);
149 if (ret == ERROR_SUCCESS)
151 RAND_add(pdata, nSize, nSize/100.0);
152 memset(pdata, 0, nSize);
153 printf("%s RandAddSeed() %d bytes\n", DateTimeStrFormat("%x %H:%M", GetTime()).c_str(), nSize);
158 uint64 GetRand(uint64 nMax)
163 // The range of the random source must be a multiple of the modulus
164 // to give every possible output value an equal possibility
165 uint64 nRange = (std::numeric_limits<uint64>::max() / nMax) * nMax;
168 RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
169 while (nRand >= nRange);
170 return (nRand % nMax);
173 int GetRandInt(int nMax)
175 return GetRand(nMax);
178 uint256 GetRandHash()
181 RAND_bytes((unsigned char*)&hash, sizeof(hash));
194 inline int OutputDebugStringF(const char* pszFormat, ...)
201 va_start(arg_ptr, pszFormat);
202 ret = vprintf(pszFormat, arg_ptr);
207 // print to debug.log
208 static FILE* fileout = NULL;
212 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
213 fileout = fopen(pathDebug.string().c_str(), "a");
214 if (fileout) setbuf(fileout, NULL); // unbuffered
218 static bool fStartedNewLine = true;
219 static boost::mutex mutexDebugLog;
220 boost::mutex::scoped_lock scoped_lock(mutexDebugLog);
222 // Debug print useful for profiling
223 if (fLogTimestamps && fStartedNewLine)
224 fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
225 if (pszFormat[strlen(pszFormat) - 1] == '\n')
226 fStartedNewLine = true;
228 fStartedNewLine = false;
231 va_start(arg_ptr, pszFormat);
232 ret = vfprintf(fileout, pszFormat, arg_ptr);
238 if (fPrintToDebugger)
240 static CCriticalSection cs_OutputDebugStringF;
242 // accumulate a line at a time
244 LOCK(cs_OutputDebugStringF);
245 static char pszBuffer[50000];
250 va_start(arg_ptr, pszFormat);
251 int limit = END(pszBuffer) - pend - 2;
252 int ret = _vsnprintf(pend, limit, pszFormat, arg_ptr);
254 if (ret < 0 || ret >= limit)
256 pend = END(pszBuffer) - 2;
262 char* p1 = pszBuffer;
264 while ((p2 = strchr(p1, '\n')))
269 OutputDebugStringA(p1);
274 memmove(pszBuffer, p1, pend - p1 + 1);
275 pend -= (p1 - pszBuffer);
284 // - prints up to limit-1 characters
285 // - output string is always null terminated even if limit reached
286 // - return value is the number of characters actually printed
287 int my_snprintf(char* buffer, size_t limit, const char* format, ...)
292 va_start(arg_ptr, format);
293 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
295 if (ret < 0 || ret >= (int)limit)
303 string real_strprintf(const std::string &format, int dummy, ...)
307 int limit = sizeof(buffer);
312 va_start(arg_ptr, dummy);
313 ret = _vsnprintf(p, limit, format.c_str(), arg_ptr);
315 if (ret >= 0 && ret < limit)
322 throw std::bad_alloc();
324 string str(p, p+ret);
330 bool error(const char *format, ...)
333 int limit = sizeof(buffer);
335 va_start(arg_ptr, format);
336 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
338 if (ret < 0 || ret >= limit)
342 printf("ERROR: %s\n", buffer);
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 0's 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 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());
734 bool WildcardMatch(const char* psz, const char* mask)
741 return (*psz == '\0');
743 return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
758 bool WildcardMatch(const string& str, const string& mask)
760 return WildcardMatch(str.c_str(), mask.c_str());
770 void FormatException(char* pszMessage, std::exception* pex, const char* pszThread)
773 char pszModule[MAX_PATH];
775 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
777 const char* pszModule = "bitcoin";
780 snprintf(pszMessage, 1000,
781 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
783 snprintf(pszMessage, 1000,
784 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
787 void LogException(std::exception* pex, const char* pszThread)
789 char pszMessage[10000];
790 FormatException(pszMessage, pex, pszThread);
791 printf("\n%s", pszMessage);
794 void PrintException(std::exception* pex, const char* pszThread)
796 char pszMessage[10000];
797 FormatException(pszMessage, pex, pszThread);
798 printf("\n\n************************\n%s\n", pszMessage);
799 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
800 strMiscWarning = pszMessage;
804 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
806 char pszMessage[10000];
807 FormatException(pszMessage, pex, pszThread);
808 printf("\n\n************************\n%s\n", pszMessage);
809 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
810 strMiscWarning = pszMessage;
814 boost::filesystem::path MyGetSpecialFolderPath(int nFolder, bool fCreate)
816 namespace fs = boost::filesystem;
818 char pszPath[MAX_PATH] = "";
819 if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
821 return fs::path(pszPath);
823 else if (nFolder == CSIDL_STARTUP)
825 return fs::path(getenv("USERPROFILE")) / "Start Menu" / "Programs" / "Startup";
827 else if (nFolder == CSIDL_APPDATA)
829 return fs::path(getenv("APPDATA"));
835 boost::filesystem::path GetDefaultDataDir()
837 namespace fs = boost::filesystem;
839 // Windows: C:\Documents and Settings\username\Application Data\Bitcoin
840 // Mac: ~/Library/Application Support/Bitcoin
844 return MyGetSpecialFolderPath(CSIDL_APPDATA, true) / "Bitcoin";
847 char* pszHome = getenv("HOME");
848 if (pszHome == NULL || strlen(pszHome) == 0)
849 pathRet = fs::path("/");
851 pathRet = fs::path(pszHome);
854 pathRet /= "Library/Application Support";
855 fs::create_directory(pathRet);
856 return pathRet / "Bitcoin";
859 return pathRet / ".bitcoin";
864 const boost::filesystem::path &GetDataDir(bool fNetSpecific)
866 namespace fs = boost::filesystem;
868 static fs::path pathCached[2];
869 static CCriticalSection csPathCached;
870 static bool cachedPath[2] = {false, false};
872 fs::path &path = pathCached[fNetSpecific];
874 // This can be called during exceptions by printf, so we cache the
875 // value so we don't have to do memory allocations after that.
876 if (cachedPath[fNetSpecific])
881 if (mapArgs.count("-datadir")) {
882 path = fs::system_complete(mapArgs["-datadir"]);
883 if (!fs::is_directory(path)) {
888 path = GetDefaultDataDir();
890 if (fNetSpecific && GetBoolArg("-testnet", false))
893 fs::create_directory(path);
895 cachedPath[fNetSpecific]=true;
899 boost::filesystem::path GetConfigFile()
901 namespace fs = boost::filesystem;
903 fs::path pathConfigFile(GetArg("-conf", "bitcoin.conf"));
904 if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
905 return pathConfigFile;
908 void ReadConfigFile(map<string, string>& mapSettingsRet,
909 map<string, vector<string> >& mapMultiSettingsRet)
911 namespace fs = boost::filesystem;
912 namespace pod = boost::program_options::detail;
914 fs::ifstream streamConfig(GetConfigFile());
915 if (!streamConfig.good())
916 return; // No bitcoin.conf file is OK
918 set<string> setOptions;
919 setOptions.insert("*");
921 for (pod::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
923 // Don't overwrite existing settings so command line settings override bitcoin.conf
924 string strKey = string("-") + it->string_key;
925 if (mapSettingsRet.count(strKey) == 0)
927 mapSettingsRet[strKey] = it->value[0];
928 // interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
929 InterpretNegativeSetting(strKey, mapSettingsRet);
931 mapMultiSettingsRet[strKey].push_back(it->value[0]);
935 boost::filesystem::path GetPidFile()
937 namespace fs = boost::filesystem;
939 fs::path pathPidFile(GetArg("-pid", "bitcoind.pid"));
940 if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
944 void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
946 FILE* file = fopen(path.string().c_str(), "w");
949 fprintf(file, "%d\n", pid);
954 int GetFilesize(FILE* file)
956 int nSavePos = ftell(file);
958 if (fseek(file, 0, SEEK_END) == 0)
959 nFilesize = ftell(file);
960 fseek(file, nSavePos, SEEK_SET);
964 void ShrinkDebugFile()
966 // Scroll debug.log if it's getting too big
967 boost::filesystem::path pathLog = GetDataDir() / "debug.log";
968 FILE* file = fopen(pathLog.string().c_str(), "r");
969 if (file && GetFilesize(file) > 10 * 1000000)
971 // Restart the file with some of the end
973 fseek(file, -sizeof(pch), SEEK_END);
974 int nBytes = fread(pch, 1, sizeof(pch), file);
977 file = fopen(pathLog.string().c_str(), "w");
980 fwrite(pch, 1, nBytes, file);
994 // "Never go to sea with two chronometers; take one or three."
995 // Our three time sources are:
997 // - Median of other nodes's clocks
998 // - The user (asking the user to fix the system clock if the first two disagree)
1000 static int64 nMockTime = 0; // For unit testing
1004 if (nMockTime) return nMockTime;
1009 void SetMockTime(int64 nMockTimeIn)
1011 nMockTime = nMockTimeIn;
1014 static int64 nTimeOffset = 0;
1016 int64 GetAdjustedTime()
1018 return GetTime() + nTimeOffset;
1021 void AddTimeData(const CNetAddr& ip, int64 nTime)
1023 int64 nOffsetSample = nTime - GetTime();
1025 // Ignore duplicates
1026 static set<CNetAddr> setKnown;
1027 if (!setKnown.insert(ip).second)
1031 vTimeOffsets.input(nOffsetSample);
1032 printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
1033 if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
1035 int64 nMedian = vTimeOffsets.median();
1036 std::vector<int64> vSorted = vTimeOffsets.sorted();
1037 // Only let other nodes change our time by so much
1038 if (abs64(nMedian) < 70 * 60)
1040 nTimeOffset = nMedian;
1049 // If nobody has a time different than ours but within 5 minutes of ours, give a warning
1050 bool fMatch = false;
1051 BOOST_FOREACH(int64 nOffset, vSorted)
1052 if (nOffset != 0 && abs64(nOffset) < 5 * 60)
1058 string strMessage = _("Warning: Please check that your computer's date and time are correct. If your clock is wrong Bitcoin will not work properly.");
1059 strMiscWarning = strMessage;
1060 printf("*** %s\n", strMessage.c_str());
1061 ThreadSafeMessageBox(strMessage+" ", string("Bitcoin"), wxOK | wxICON_EXCLAMATION);
1066 BOOST_FOREACH(int64 n, vSorted)
1067 printf("%+"PRI64d" ", n);
1070 printf("nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
1081 string FormatVersion(int nVersion)
1083 if (nVersion%100 == 0)
1084 return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
1086 return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
1089 string FormatFullVersion()
1091 return CLIENT_BUILD;
1094 // Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
1095 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
1097 std::ostringstream ss;
1099 ss << name << ":" << FormatVersion(nClientVersion);
1100 if (!comments.empty())
1101 ss << "(" << boost::algorithm::join(comments, "; ") << ")";
1107 boost::filesystem::path static StartupShortcutPath()
1109 return MyGetSpecialFolderPath(CSIDL_STARTUP, true) / "Bitcoin.lnk";
1112 bool GetStartOnSystemStartup()
1114 return filesystem::exists(StartupShortcutPath());
1117 bool SetStartOnSystemStartup(bool fAutoStart)
1119 // If the shortcut exists already, remove it for updating
1120 boost::filesystem::remove(StartupShortcutPath());
1126 // Get a pointer to the IShellLink interface.
1127 IShellLink* psl = NULL;
1128 HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
1129 CLSCTX_INPROC_SERVER, IID_IShellLink,
1130 reinterpret_cast<void**>(&psl));
1132 if (SUCCEEDED(hres))
1134 // Get the current executable path
1135 TCHAR pszExePath[MAX_PATH];
1136 GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
1138 TCHAR pszArgs[5] = TEXT("-min");
1140 // Set the path to the shortcut target
1141 psl->SetPath(pszExePath);
1142 PathRemoveFileSpec(pszExePath);
1143 psl->SetWorkingDirectory(pszExePath);
1144 psl->SetShowCmd(SW_SHOWMINNOACTIVE);
1145 psl->SetArguments(pszArgs);
1147 // Query IShellLink for the IPersistFile interface for
1148 // saving the shortcut in persistent storage.
1149 IPersistFile* ppf = NULL;
1150 hres = psl->QueryInterface(IID_IPersistFile,
1151 reinterpret_cast<void**>(&ppf));
1152 if (SUCCEEDED(hres))
1154 WCHAR pwsz[MAX_PATH];
1155 // Ensure that the string is ANSI.
1156 MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH);
1157 // Save the link by calling IPersistFile::Save.
1158 hres = ppf->Save(pwsz, TRUE);
1172 #elif defined(LINUX)
1174 // Follow the Desktop Application Autostart Spec:
1175 // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
1177 boost::filesystem::path static GetAutostartDir()
1179 namespace fs = boost::filesystem;
1181 char* pszConfigHome = getenv("XDG_CONFIG_HOME");
1182 if (pszConfigHome) return fs::path(pszConfigHome) / "autostart";
1183 char* pszHome = getenv("HOME");
1184 if (pszHome) return fs::path(pszHome) / ".config" / "autostart";
1188 boost::filesystem::path static GetAutostartFilePath()
1190 return GetAutostartDir() / "bitcoin.desktop";
1193 bool GetStartOnSystemStartup()
1195 boost::filesystem::ifstream optionFile(GetAutostartFilePath());
1196 if (!optionFile.good())
1198 // Scan through file for "Hidden=true":
1200 while (!optionFile.eof())
1202 getline(optionFile, line);
1203 if (line.find("Hidden") != string::npos &&
1204 line.find("true") != string::npos)
1212 bool SetStartOnSystemStartup(bool fAutoStart)
1215 boost::filesystem::remove(GetAutostartFilePath());
1218 char pszExePath[MAX_PATH+1];
1219 memset(pszExePath, 0, sizeof(pszExePath));
1220 if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
1223 boost::filesystem::create_directories(GetAutostartDir());
1225 boost::filesystem::ofstream optionFile(GetAutostartFilePath(), ios_base::out|ios_base::trunc);
1226 if (!optionFile.good())
1228 // Write a bitcoin.desktop file to the autostart directory:
1229 optionFile << "[Desktop Entry]\n";
1230 optionFile << "Type=Application\n";
1231 optionFile << "Name=Bitcoin\n";
1232 optionFile << "Exec=" << pszExePath << " -min\n";
1233 optionFile << "Terminal=false\n";
1234 optionFile << "Hidden=false\n";
1241 // TODO: OSX startup stuff; see:
1242 // http://developer.apple.com/mac/library/documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html
1244 bool GetStartOnSystemStartup() { return false; }
1245 bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
1251 #ifdef DEBUG_LOCKORDER
1253 // Early deadlock detection.
1254 // Problem being solved:
1255 // Thread 1 locks A, then B, then C
1256 // Thread 2 locks D, then C, then A
1257 // --> may result in deadlock between the two threads, depending on when they run.
1258 // Solution implemented here:
1259 // Keep track of pairs of locks: (A before B), (A before C), etc.
1260 // Complain if any thread trys to lock in a different order.
1263 struct CLockLocation
1265 CLockLocation(const char* pszName, const char* pszFile, int nLine)
1267 mutexName = pszName;
1268 sourceFile = pszFile;
1272 std::string ToString() const
1274 return mutexName+" "+sourceFile+":"+itostr(sourceLine);
1278 std::string mutexName;
1279 std::string sourceFile;
1283 typedef std::vector< std::pair<void*, CLockLocation> > LockStack;
1285 static boost::interprocess::interprocess_mutex dd_mutex;
1286 static std::map<std::pair<void*, void*>, LockStack> lockorders;
1287 static boost::thread_specific_ptr<LockStack> lockstack;
1290 static void potential_deadlock_detected(const std::pair<void*, void*>& mismatch, const LockStack& s1, const LockStack& s2)
1292 printf("POTENTIAL DEADLOCK DETECTED\n");
1293 printf("Previous lock order was:\n");
1294 BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, s2)
1296 if (i.first == mismatch.first) printf(" (1)");
1297 if (i.first == mismatch.second) printf(" (2)");
1298 printf(" %s\n", i.second.ToString().c_str());
1300 printf("Current lock order is:\n");
1301 BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, s1)
1303 if (i.first == mismatch.first) printf(" (1)");
1304 if (i.first == mismatch.second) printf(" (2)");
1305 printf(" %s\n", i.second.ToString().c_str());
1309 static void push_lock(void* c, const CLockLocation& locklocation, bool fTry)
1311 bool fOrderOK = true;
1312 if (lockstack.get() == NULL)
1313 lockstack.reset(new LockStack);
1315 if (fDebug) printf("Locking: %s\n", locklocation.ToString().c_str());
1318 (*lockstack).push_back(std::make_pair(c, locklocation));
1320 if (!fTry) BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, (*lockstack))
1322 if (i.first == c) break;
1324 std::pair<void*, void*> p1 = std::make_pair(i.first, c);
1325 if (lockorders.count(p1))
1327 lockorders[p1] = (*lockstack);
1329 std::pair<void*, void*> p2 = std::make_pair(c, i.first);
1330 if (lockorders.count(p2))
1332 potential_deadlock_detected(p1, lockorders[p2], lockorders[p1]);
1339 static void pop_lock()
1343 const CLockLocation& locklocation = (*lockstack).rbegin()->second;
1344 printf("Unlocked: %s\n", locklocation.ToString().c_str());
1347 (*lockstack).pop_back();
1351 void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry)
1353 push_lock(cs, CLockLocation(pszName, pszFile, nLine), fTry);
1356 void LeaveCritical()
1361 #endif /* DEBUG_LOCKORDER */