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 license.txt 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 <openssl/crypto.h>
30 #include <openssl/rand.h>
34 #pragma warning(disable:4786)
35 #pragma warning(disable:4804)
36 #pragma warning(disable:4805)
37 #pragma warning(disable:4717)
42 #define _WIN32_WINNT 0x0501
46 #define _WIN32_IE 0x0400
47 #define WIN32_LEAN_AND_MEAN 1
56 using namespace boost;
58 map<string, string> mapArgs;
59 map<string, vector<string> > mapMultiArgs;
61 bool fPrintToConsole = false;
62 bool fPrintToDebugger = false;
63 bool fRequestShutdown = false;
64 bool fShutdown = false;
67 bool fCommandLine = false;
68 string strMiscWarning;
69 bool fTestNet = false;
70 bool fNoListen = false;
71 bool fLogTimestamps = false;
72 CMedianFilter<int64> vTimeOffsets(200,0);
74 // Init openssl library multithreading support
75 static boost::interprocess::interprocess_mutex** ppmutexOpenSSL;
76 void locking_callback(int mode, int i, const char* file, int line)
78 if (mode & CRYPTO_LOCK)
79 ppmutexOpenSSL[i]->lock();
81 ppmutexOpenSSL[i]->unlock();
90 // Init openssl library multithreading support
91 ppmutexOpenSSL = (boost::interprocess::interprocess_mutex**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(boost::interprocess::interprocess_mutex*));
92 for (int i = 0; i < CRYPTO_num_locks(); i++)
93 ppmutexOpenSSL[i] = new boost::interprocess::interprocess_mutex();
94 CRYPTO_set_locking_callback(locking_callback);
97 // Seed random number generator with screen scrape and other hardware sources
101 // Seed random number generator with performance counter
106 // Shutdown openssl library multithreading support
107 CRYPTO_set_locking_callback(NULL);
108 for (int i = 0; i < CRYPTO_num_locks(); i++)
109 delete ppmutexOpenSSL[i];
110 OPENSSL_free(ppmutexOpenSSL);
124 // Seed with CPU performance counter
125 int64 nCounter = GetPerformanceCounter();
126 RAND_add(&nCounter, sizeof(nCounter), 1.5);
127 memset(&nCounter, 0, sizeof(nCounter));
130 void RandAddSeedPerfmon()
134 // This can take up to 2 seconds, so only do it every 10 minutes
135 static int64 nLastPerfmon;
136 if (GetTime() < nLastPerfmon + 10 * 60)
138 nLastPerfmon = GetTime();
141 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom
142 // Seed with the entire set of perfmon data
143 unsigned char pdata[250000];
144 memset(pdata, 0, sizeof(pdata));
145 unsigned long nSize = sizeof(pdata);
146 long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
147 RegCloseKey(HKEY_PERFORMANCE_DATA);
148 if (ret == ERROR_SUCCESS)
150 RAND_add(pdata, nSize, nSize/100.0);
151 memset(pdata, 0, nSize);
152 printf("%s RandAddSeed() %d bytes\n", DateTimeStrFormat("%x %H:%M", GetTime()).c_str(), nSize);
157 uint64 GetRand(uint64 nMax)
162 // The range of the random source must be a multiple of the modulus
163 // to give every possible output value an equal possibility
164 uint64 nRange = (std::numeric_limits<uint64>::max() / nMax) * nMax;
167 RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
168 while (nRand >= nRange);
169 return (nRand % nMax);
172 int GetRandInt(int nMax)
174 return GetRand(nMax);
187 inline int OutputDebugStringF(const char* pszFormat, ...)
194 va_start(arg_ptr, pszFormat);
195 ret = vprintf(pszFormat, arg_ptr);
200 // print to debug.log
201 static FILE* fileout = NULL;
205 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
206 fileout = fopen(pathDebug.string().c_str(), "a");
207 if (fileout) setbuf(fileout, NULL); // unbuffered
211 static bool fStartedNewLine = true;
213 // Debug print useful for profiling
214 if (fLogTimestamps && fStartedNewLine)
215 fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
216 if (pszFormat[strlen(pszFormat) - 1] == '\n')
217 fStartedNewLine = true;
219 fStartedNewLine = false;
222 va_start(arg_ptr, pszFormat);
223 ret = vfprintf(fileout, pszFormat, arg_ptr);
229 if (fPrintToDebugger)
231 static CCriticalSection cs_OutputDebugStringF;
233 // accumulate a line at a time
235 LOCK(cs_OutputDebugStringF);
236 static char pszBuffer[50000];
241 va_start(arg_ptr, pszFormat);
242 int limit = END(pszBuffer) - pend - 2;
243 int ret = _vsnprintf(pend, limit, pszFormat, arg_ptr);
245 if (ret < 0 || ret >= limit)
247 pend = END(pszBuffer) - 2;
253 char* p1 = pszBuffer;
255 while ((p2 = strchr(p1, '\n')))
260 OutputDebugStringA(p1);
265 memmove(pszBuffer, p1, pend - p1 + 1);
266 pend -= (p1 - pszBuffer);
275 // - prints up to limit-1 characters
276 // - output string is always null terminated even if limit reached
277 // - return value is the number of characters actually printed
278 int my_snprintf(char* buffer, size_t limit, const char* format, ...)
283 va_start(arg_ptr, format);
284 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
286 if (ret < 0 || ret >= (int)limit)
294 string real_strprintf(const std::string &format, int dummy, ...)
298 int limit = sizeof(buffer);
303 va_start(arg_ptr, dummy);
304 ret = _vsnprintf(p, limit, format.c_str(), arg_ptr);
306 if (ret >= 0 && ret < limit)
313 throw std::bad_alloc();
315 string str(p, p+ret);
321 bool error(const char *format, ...)
324 int limit = sizeof(buffer);
326 va_start(arg_ptr, format);
327 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
329 if (ret < 0 || ret >= limit)
333 printf("ERROR: %s\n", buffer);
338 void ParseString(const string& str, char c, vector<string>& v)
342 string::size_type i1 = 0;
343 string::size_type i2;
346 i2 = str.find(c, i1);
349 v.push_back(str.substr(i1));
352 v.push_back(str.substr(i1, i2-i1));
358 string FormatMoney(int64 n, bool fPlus)
360 // Note: not using straight sprintf here because we do NOT want
361 // localized number formatting.
362 int64 n_abs = (n > 0 ? n : -n);
363 int64 quotient = n_abs/COIN;
364 int64 remainder = n_abs%COIN;
365 string str = strprintf("%"PRI64d".%08"PRI64d, quotient, remainder);
367 // Right-trim excess 0's before the decimal point:
369 for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
372 str.erase(str.size()-nTrim, nTrim);
375 str.insert((unsigned int)0, 1, '-');
376 else if (fPlus && n > 0)
377 str.insert((unsigned int)0, 1, '+');
382 bool ParseMoney(const string& str, int64& nRet)
384 return ParseMoney(str.c_str(), nRet);
387 bool ParseMoney(const char* pszIn, int64& nRet)
391 const char* p = pszIn;
399 int64 nMult = CENT*10;
400 while (isdigit(*p) && (nMult > 0))
402 nUnits += nMult * (*p++ - '0');
411 strWhole.insert(strWhole.end(), *p);
416 if (strWhole.size() > 10) // guard against 63 bit overflow
418 if (nUnits < 0 || nUnits > COIN)
420 int64 nWhole = atoi64(strWhole);
421 int64 nValue = nWhole*COIN + nUnits;
428 static signed char phexdigit[256] =
429 { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
430 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
431 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
432 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
433 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
434 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
435 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
436 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
437 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
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 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
442 -1,-1,-1,-1,-1,-1,-1,-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,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
446 bool IsHex(const string& str)
448 BOOST_FOREACH(unsigned char c, str)
450 if (phexdigit[c] < 0)
453 return (str.size() > 0) && (str.size()%2 == 0);
456 vector<unsigned char> ParseHex(const char* psz)
458 // convert hex dump to vector
459 vector<unsigned char> vch;
462 while (isspace(*psz))
464 signed char c = phexdigit[(unsigned char)*psz++];
465 if (c == (signed char)-1)
467 unsigned char n = (c << 4);
468 c = phexdigit[(unsigned char)*psz++];
469 if (c == (signed char)-1)
477 vector<unsigned char> ParseHex(const string& str)
479 return ParseHex(str.c_str());
482 static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
484 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
485 if (name.find("-no") == 0)
487 std::string positive("-");
488 positive.append(name.begin()+3, name.end());
489 if (mapSettingsRet.count(positive) == 0)
491 bool value = !GetBoolArg(name);
492 mapSettingsRet[positive] = (value ? "1" : "0");
497 void ParseParameters(int argc, const char*const argv[])
500 mapMultiArgs.clear();
501 for (int i = 1; i < argc; i++)
504 strlcpy(psz, argv[i], sizeof(psz));
505 char* pszValue = (char*)"";
506 if (strchr(psz, '='))
508 pszValue = strchr(psz, '=');
519 mapArgs[psz] = pszValue;
520 mapMultiArgs[psz].push_back(pszValue);
524 BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs)
526 string name = entry.first;
528 // interpret --foo as -foo (as long as both are not set)
529 if (name.find("--") == 0)
531 std::string singleDash(name.begin()+1, name.end());
532 if (mapArgs.count(singleDash) == 0)
533 mapArgs[singleDash] = entry.second;
537 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
538 InterpretNegativeSetting(name, mapArgs);
542 std::string GetArg(const std::string& strArg, const std::string& strDefault)
544 if (mapArgs.count(strArg))
545 return mapArgs[strArg];
549 int64 GetArg(const std::string& strArg, int64 nDefault)
551 if (mapArgs.count(strArg))
552 return atoi64(mapArgs[strArg]);
556 bool GetBoolArg(const std::string& strArg, bool fDefault)
558 if (mapArgs.count(strArg))
560 if (mapArgs[strArg].empty())
562 return (atoi(mapArgs[strArg]) != 0);
567 bool SoftSetArg(const std::string& strArg, const std::string& strValue)
569 if (mapArgs.count(strArg))
571 mapArgs[strArg] = strValue;
575 bool SoftSetBoolArg(const std::string& strArg, bool fValue)
578 return SoftSetArg(strArg, std::string("1"));
580 return SoftSetArg(strArg, std::string("0"));
584 string EncodeBase64(const unsigned char* pch, size_t len)
586 static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
589 strRet.reserve((len+2)/3*4);
592 const unsigned char *pchEnd = pch+len;
599 case 0: // we have no bits
600 strRet += pbase64[enc >> 2];
601 left = (enc & 3) << 4;
605 case 1: // we have two bits
606 strRet += pbase64[left | (enc >> 4)];
607 left = (enc & 15) << 2;
611 case 2: // we have four bits
612 strRet += pbase64[left | (enc >> 6)];
613 strRet += pbase64[enc & 63];
621 strRet += pbase64[left];
630 string EncodeBase64(const string& str)
632 return EncodeBase64((const unsigned char*)str.c_str(), str.size());
635 vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
637 static const int decode64_table[256] =
639 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
640 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
641 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
642 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
643 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
644 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
645 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
646 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
647 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
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, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
651 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
657 vector<unsigned char> vchRet;
658 vchRet.reserve(strlen(p)*3/4);
665 int dec = decode64_table[(unsigned char)*p];
666 if (dec == -1) break;
670 case 0: // we have no bits and get 6
675 case 1: // we have 6 bits and keep 4
676 vchRet.push_back((left<<2) | (dec>>4));
681 case 2: // we have 4 bits and get 6, we keep 2
682 vchRet.push_back((left<<4) | (dec>>2));
687 case 3: // we have 2 bits and get 6
688 vchRet.push_back((left<<6) | dec);
697 case 0: // 4n base64 characters processed: ok
700 case 1: // 4n+1 base64 character processed: impossible
704 case 2: // 4n+2 base64 characters processed: require '=='
705 if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1)
709 case 3: // 4n+3 base64 characters processed: require '='
710 if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1)
718 string DecodeBase64(const string& str)
720 vector<unsigned char> vchRet = DecodeBase64(str.c_str());
721 return string((const char*)&vchRet[0], vchRet.size());
725 bool WildcardMatch(const char* psz, const char* mask)
732 return (*psz == '\0');
734 return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
749 bool WildcardMatch(const string& str, const string& mask)
751 return WildcardMatch(str.c_str(), mask.c_str());
761 void FormatException(char* pszMessage, std::exception* pex, const char* pszThread)
764 char pszModule[MAX_PATH];
766 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
768 const char* pszModule = "bitcoin";
771 snprintf(pszMessage, 1000,
772 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
774 snprintf(pszMessage, 1000,
775 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
778 void LogException(std::exception* pex, const char* pszThread)
780 char pszMessage[10000];
781 FormatException(pszMessage, pex, pszThread);
782 printf("\n%s", pszMessage);
785 void PrintException(std::exception* pex, const char* pszThread)
787 char pszMessage[10000];
788 FormatException(pszMessage, pex, pszThread);
789 printf("\n\n************************\n%s\n", pszMessage);
790 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
791 strMiscWarning = pszMessage;
795 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
797 char pszMessage[10000];
798 FormatException(pszMessage, pex, pszThread);
799 printf("\n\n************************\n%s\n", pszMessage);
800 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
801 strMiscWarning = pszMessage;
805 boost::filesystem::path MyGetSpecialFolderPath(int nFolder, bool fCreate)
807 namespace fs = boost::filesystem;
809 char pszPath[MAX_PATH] = "";
810 if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
812 return fs::path(pszPath);
814 else if (nFolder == CSIDL_STARTUP)
816 return fs::path(getenv("USERPROFILE")) / "Start Menu" / "Programs" / "Startup";
818 else if (nFolder == CSIDL_APPDATA)
820 return fs::path(getenv("APPDATA"));
826 boost::filesystem::path GetDefaultDataDir()
828 namespace fs = boost::filesystem;
830 // Windows: C:\Documents and Settings\username\Application Data\Bitcoin
831 // Mac: ~/Library/Application Support/Bitcoin
835 return MyGetSpecialFolderPath(CSIDL_APPDATA, true) / "Bitcoin";
838 char* pszHome = getenv("HOME");
839 if (pszHome == NULL || strlen(pszHome) == 0)
840 pathRet = fs::path("/");
842 pathRet = fs::path(pszHome);
845 pathRet /= "Library/Application Support";
846 filesystem::create_directory(pathRet);
847 return pathRet / "Bitcoin";
850 return pathRet / ".bitcoin";
855 const boost::filesystem::path &GetDataDir(bool fNetSpecific)
857 namespace fs = boost::filesystem;
859 static fs::path pathCached[2];
860 static CCriticalSection csPathCached;
861 static bool cachedPath[2] = {false, false};
863 fs::path &path = pathCached[fNetSpecific];
865 // This can be called during exceptions by printf, so we cache the
866 // value so we don't have to do memory allocations after that.
867 if (cachedPath[fNetSpecific])
872 if (mapArgs.count("-datadir")) {
873 path = fs::system_complete(mapArgs["-datadir"]);
874 if (!fs::is_directory(path)) {
879 path = GetDefaultDataDir();
881 if (fNetSpecific && GetBoolArg("-testnet", false))
884 fs::create_directory(path);
886 cachedPath[fNetSpecific]=true;
890 boost::filesystem::path GetConfigFile()
892 namespace fs = boost::filesystem;
894 fs::path pathConfigFile(GetArg("-conf", "bitcoin.conf"));
895 if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
896 return pathConfigFile;
899 void ReadConfigFile(map<string, string>& mapSettingsRet,
900 map<string, vector<string> >& mapMultiSettingsRet)
902 namespace fs = boost::filesystem;
903 namespace pod = boost::program_options::detail;
905 fs::ifstream streamConfig(GetConfigFile());
906 if (!streamConfig.good())
907 return; // No bitcoin.conf file is OK
909 set<string> setOptions;
910 setOptions.insert("*");
912 for (pod::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
914 // Don't overwrite existing settings so command line settings override bitcoin.conf
915 string strKey = string("-") + it->string_key;
916 if (mapSettingsRet.count(strKey) == 0)
918 mapSettingsRet[strKey] = it->value[0];
919 // interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
920 InterpretNegativeSetting(strKey, mapSettingsRet);
922 mapMultiSettingsRet[strKey].push_back(it->value[0]);
926 boost::filesystem::path GetPidFile()
928 namespace fs = boost::filesystem;
930 fs::path pathPidFile(GetArg("-pid", "bitcoind.pid"));
931 if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
935 void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
937 FILE* file = fopen(path.string().c_str(), "w");
940 fprintf(file, "%d\n", pid);
945 int GetFilesize(FILE* file)
947 int nSavePos = ftell(file);
949 if (fseek(file, 0, SEEK_END) == 0)
950 nFilesize = ftell(file);
951 fseek(file, nSavePos, SEEK_SET);
955 void ShrinkDebugFile()
957 // Scroll debug.log if it's getting too big
958 boost::filesystem::path pathLog = GetDataDir() / "debug.log";
959 FILE* file = fopen(pathLog.string().c_str(), "r");
960 if (file && GetFilesize(file) > 10 * 1000000)
962 // Restart the file with some of the end
964 fseek(file, -sizeof(pch), SEEK_END);
965 int nBytes = fread(pch, 1, sizeof(pch), file);
968 file = fopen(pathLog.string().c_str(), "w");
971 fwrite(pch, 1, nBytes, file);
985 // "Never go to sea with two chronometers; take one or three."
986 // Our three time sources are:
988 // - Median of other nodes's clocks
989 // - The user (asking the user to fix the system clock if the first two disagree)
991 static int64 nMockTime = 0; // For unit testing
995 if (nMockTime) return nMockTime;
1000 void SetMockTime(int64 nMockTimeIn)
1002 nMockTime = nMockTimeIn;
1005 static int64 nTimeOffset = 0;
1007 int64 GetAdjustedTime()
1009 return GetTime() + nTimeOffset;
1012 void AddTimeData(const CNetAddr& ip, int64 nTime)
1014 int64 nOffsetSample = nTime - GetTime();
1016 // Ignore duplicates
1017 static set<CNetAddr> setKnown;
1018 if (!setKnown.insert(ip).second)
1022 vTimeOffsets.input(nOffsetSample);
1023 printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
1024 if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
1026 int64 nMedian = vTimeOffsets.median();
1027 std::vector<int64> vSorted = vTimeOffsets.sorted();
1028 // Only let other nodes change our time by so much
1029 if (abs64(nMedian) < 70 * 60)
1031 nTimeOffset = nMedian;
1040 // If nobody has a time different than ours but within 5 minutes of ours, give a warning
1041 bool fMatch = false;
1042 BOOST_FOREACH(int64 nOffset, vSorted)
1043 if (nOffset != 0 && abs64(nOffset) < 5 * 60)
1049 string strMessage = _("Warning: Please check that your computer's date and time are correct. If your clock is wrong Bitcoin will not work properly.");
1050 strMiscWarning = strMessage;
1051 printf("*** %s\n", strMessage.c_str());
1052 ThreadSafeMessageBox(strMessage+" ", string("Bitcoin"), wxOK | wxICON_EXCLAMATION);
1057 BOOST_FOREACH(int64 n, vSorted)
1058 printf("%+"PRI64d" ", n);
1061 printf("nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
1072 string FormatVersion(int nVersion)
1074 if (nVersion%100 == 0)
1075 return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
1077 return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
1080 string FormatFullVersion()
1082 return CLIENT_BUILD;
1085 // Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
1086 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
1088 std::ostringstream ss;
1090 ss << name << ":" << FormatVersion(nClientVersion);
1091 if (!comments.empty())
1092 ss << "(" << boost::algorithm::join(comments, "; ") << ")";
1098 boost::filesystem::path static StartupShortcutPath()
1100 return MyGetSpecialFolderPath(CSIDL_STARTUP, true) / "Bitcoin.lnk";
1103 bool GetStartOnSystemStartup()
1105 return filesystem::exists(StartupShortcutPath());
1108 bool SetStartOnSystemStartup(bool fAutoStart)
1110 // If the shortcut exists already, remove it for updating
1111 boost::filesystem::remove(StartupShortcutPath());
1117 // Get a pointer to the IShellLink interface.
1118 IShellLink* psl = NULL;
1119 HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
1120 CLSCTX_INPROC_SERVER, IID_IShellLink,
1121 reinterpret_cast<void**>(&psl));
1123 if (SUCCEEDED(hres))
1125 // Get the current executable path
1126 TCHAR pszExePath[MAX_PATH];
1127 GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
1129 TCHAR pszArgs[5] = TEXT("-min");
1131 // Set the path to the shortcut target
1132 psl->SetPath(pszExePath);
1133 PathRemoveFileSpec(pszExePath);
1134 psl->SetWorkingDirectory(pszExePath);
1135 psl->SetShowCmd(SW_SHOWMINNOACTIVE);
1136 psl->SetArguments(pszArgs);
1138 // Query IShellLink for the IPersistFile interface for
1139 // saving the shortcut in persistent storage.
1140 IPersistFile* ppf = NULL;
1141 hres = psl->QueryInterface(IID_IPersistFile,
1142 reinterpret_cast<void**>(&ppf));
1143 if (SUCCEEDED(hres))
1145 WCHAR pwsz[MAX_PATH];
1146 // Ensure that the string is ANSI.
1147 MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH);
1148 // Save the link by calling IPersistFile::Save.
1149 hres = ppf->Save(pwsz, TRUE);
1163 #elif defined(LINUX)
1165 // Follow the Desktop Application Autostart Spec:
1166 // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
1168 boost::filesystem::path static GetAutostartDir()
1170 namespace fs = boost::filesystem;
1172 char* pszConfigHome = getenv("XDG_CONFIG_HOME");
1173 if (pszConfigHome) return fs::path(pszConfigHome) / "autostart";
1174 char* pszHome = getenv("HOME");
1175 if (pszHome) return fs::path(pszHome) / ".config" / "autostart";
1179 boost::filesystem::path static GetAutostartFilePath()
1181 return GetAutostartDir() / "bitcoin.desktop";
1184 bool GetStartOnSystemStartup()
1186 boost::filesystem::ifstream optionFile(GetAutostartFilePath());
1187 if (!optionFile.good())
1189 // Scan through file for "Hidden=true":
1191 while (!optionFile.eof())
1193 getline(optionFile, line);
1194 if (line.find("Hidden") != string::npos &&
1195 line.find("true") != string::npos)
1203 bool SetStartOnSystemStartup(bool fAutoStart)
1206 boost::filesystem::remove(GetAutostartFilePath());
1209 char pszExePath[MAX_PATH+1];
1210 memset(pszExePath, 0, sizeof(pszExePath));
1211 if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
1214 boost::filesystem::create_directories(GetAutostartDir());
1216 boost::filesystem::ofstream optionFile(GetAutostartFilePath(), ios_base::out|ios_base::trunc);
1217 if (!optionFile.good())
1219 // Write a bitcoin.desktop file to the autostart directory:
1220 optionFile << "[Desktop Entry]\n";
1221 optionFile << "Type=Application\n";
1222 optionFile << "Name=Bitcoin\n";
1223 optionFile << "Exec=" << pszExePath << " -min\n";
1224 optionFile << "Terminal=false\n";
1225 optionFile << "Hidden=false\n";
1232 // TODO: OSX startup stuff; see:
1233 // http://developer.apple.com/mac/library/documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html
1235 bool GetStartOnSystemStartup() { return false; }
1236 bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
1242 #ifdef DEBUG_LOCKORDER
1244 // Early deadlock detection.
1245 // Problem being solved:
1246 // Thread 1 locks A, then B, then C
1247 // Thread 2 locks D, then C, then A
1248 // --> may result in deadlock between the two threads, depending on when they run.
1249 // Solution implemented here:
1250 // Keep track of pairs of locks: (A before B), (A before C), etc.
1251 // Complain if any thread trys to lock in a different order.
1254 struct CLockLocation
1256 CLockLocation(const char* pszName, const char* pszFile, int nLine)
1258 mutexName = pszName;
1259 sourceFile = pszFile;
1263 std::string ToString() const
1265 return mutexName+" "+sourceFile+":"+itostr(sourceLine);
1269 std::string mutexName;
1270 std::string sourceFile;
1274 typedef std::vector< std::pair<void*, CLockLocation> > LockStack;
1276 static boost::interprocess::interprocess_mutex dd_mutex;
1277 static std::map<std::pair<void*, void*>, LockStack> lockorders;
1278 static boost::thread_specific_ptr<LockStack> lockstack;
1281 static void potential_deadlock_detected(const std::pair<void*, void*>& mismatch, const LockStack& s1, const LockStack& s2)
1283 printf("POTENTIAL DEADLOCK DETECTED\n");
1284 printf("Previous lock order was:\n");
1285 BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, s2)
1287 if (i.first == mismatch.first) printf(" (1)");
1288 if (i.first == mismatch.second) printf(" (2)");
1289 printf(" %s\n", i.second.ToString().c_str());
1291 printf("Current lock order is:\n");
1292 BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, s1)
1294 if (i.first == mismatch.first) printf(" (1)");
1295 if (i.first == mismatch.second) printf(" (2)");
1296 printf(" %s\n", i.second.ToString().c_str());
1300 static void push_lock(void* c, const CLockLocation& locklocation, bool fTry)
1302 bool fOrderOK = true;
1303 if (lockstack.get() == NULL)
1304 lockstack.reset(new LockStack);
1306 if (fDebug) printf("Locking: %s\n", locklocation.ToString().c_str());
1309 (*lockstack).push_back(std::make_pair(c, locklocation));
1311 if (!fTry) BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, (*lockstack))
1313 if (i.first == c) break;
1315 std::pair<void*, void*> p1 = std::make_pair(i.first, c);
1316 if (lockorders.count(p1))
1318 lockorders[p1] = (*lockstack);
1320 std::pair<void*, void*> p2 = std::make_pair(c, i.first);
1321 if (lockorders.count(p2))
1323 potential_deadlock_detected(p1, lockorders[p2], lockorders[p1]);
1330 static void pop_lock()
1334 const CLockLocation& locklocation = (*lockstack).rbegin()->second;
1335 printf("Unlocked: %s\n", locklocation.ToString().c_str());
1338 (*lockstack).pop_back();
1342 void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry)
1344 push_lock(cs, CLockLocation(pszName, pszFile, nLine), fTry);
1347 void LeaveCritical()
1352 #endif /* DEBUG_LOCKORDER */