1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Copyright (c) 2011-2012 The PPCoin developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // 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/interprocess/sync/interprocess_mutex.hpp>
28 #include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>
29 #include <boost/foreach.hpp>
30 #include <boost/thread.hpp>
31 #include <openssl/crypto.h>
32 #include <openssl/rand.h>
36 #pragma warning(disable:4786)
37 #pragma warning(disable:4804)
38 #pragma warning(disable:4805)
39 #pragma warning(disable:4717)
44 #define _WIN32_WINNT 0x0501
48 #define _WIN32_IE 0x0400
49 #define WIN32_LEAN_AND_MEAN 1
62 using namespace boost;
64 map<string, string> mapArgs;
65 map<string, vector<string> > mapMultiArgs;
67 bool fPrintToConsole = false;
68 bool fPrintToDebugger = false;
69 bool fRequestShutdown = false;
70 bool fShutdown = false;
73 bool fCommandLine = false;
74 string strMiscWarning;
75 bool fTestNet = false;
76 bool fNoListen = false;
77 bool fLogTimestamps = false;
78 CMedianFilter<int64> vTimeOffsets(200,0);
80 // Init openssl library multithreading support
81 static boost::interprocess::interprocess_mutex** ppmutexOpenSSL;
82 void locking_callback(int mode, int i, const char* file, int line)
84 if (mode & CRYPTO_LOCK)
85 ppmutexOpenSSL[i]->lock();
87 ppmutexOpenSSL[i]->unlock();
96 // Init openssl library multithreading support
97 ppmutexOpenSSL = (boost::interprocess::interprocess_mutex**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(boost::interprocess::interprocess_mutex*));
98 for (int i = 0; i < CRYPTO_num_locks(); i++)
99 ppmutexOpenSSL[i] = new boost::interprocess::interprocess_mutex();
100 CRYPTO_set_locking_callback(locking_callback);
103 // Seed random number generator with screen scrape and other hardware sources
107 // Seed random number generator with performance counter
112 // Shutdown openssl library multithreading support
113 CRYPTO_set_locking_callback(NULL);
114 for (int i = 0; i < CRYPTO_num_locks(); i++)
115 delete ppmutexOpenSSL[i];
116 OPENSSL_free(ppmutexOpenSSL);
130 // Seed with CPU performance counter
131 int64 nCounter = GetPerformanceCounter();
132 RAND_add(&nCounter, sizeof(nCounter), 1.5);
133 memset(&nCounter, 0, sizeof(nCounter));
136 void RandAddSeedPerfmon()
140 // This can take up to 2 seconds, so only do it every 10 minutes
141 static int64 nLastPerfmon;
142 if (GetTime() < nLastPerfmon + 10 * 60)
144 nLastPerfmon = GetTime();
147 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom
148 // Seed with the entire set of perfmon data
149 unsigned char pdata[250000];
150 memset(pdata, 0, sizeof(pdata));
151 unsigned long nSize = sizeof(pdata);
152 long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
153 RegCloseKey(HKEY_PERFORMANCE_DATA);
154 if (ret == ERROR_SUCCESS)
156 RAND_add(pdata, nSize, nSize/100.0);
157 memset(pdata, 0, nSize);
158 printf("%s RandAddSeed() %d bytes\n", DateTimeStrFormat(GetTime()).c_str(), nSize);
163 uint64 GetRand(uint64 nMax)
168 // The range of the random source must be a multiple of the modulus
169 // to give every possible output value an equal possibility
170 uint64 nRange = (std::numeric_limits<uint64>::max() / nMax) * nMax;
173 RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
174 while (nRand >= nRange);
175 return (nRand % nMax);
178 int GetRandInt(int nMax)
180 return GetRand(nMax);
183 uint256 GetRandHash()
186 RAND_bytes((unsigned char*)&hash, sizeof(hash));
197 static FILE* fileout = NULL;
199 inline int OutputDebugStringF(const char* pszFormat, ...)
206 va_start(arg_ptr, pszFormat);
207 ret = vprintf(pszFormat, arg_ptr);
212 // print to debug.log
215 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
216 fileout = fopen(pathDebug.string().c_str(), "a");
217 if (fileout) setbuf(fileout, NULL); // unbuffered
221 static bool fStartedNewLine = true;
222 static boost::mutex mutexDebugLog;
223 boost::mutex::scoped_lock scoped_lock(mutexDebugLog);
225 // Debug print useful for profiling
226 if (fLogTimestamps && fStartedNewLine)
227 fprintf(fileout, "%s ", DateTimeStrFormat(GetTime()).c_str());
228 if (pszFormat[strlen(pszFormat) - 1] == '\n')
229 fStartedNewLine = true;
231 fStartedNewLine = false;
234 va_start(arg_ptr, pszFormat);
235 ret = vfprintf(fileout, pszFormat, arg_ptr);
241 if (fPrintToDebugger)
243 static CCriticalSection cs_OutputDebugStringF;
245 // accumulate a line at a time
247 LOCK(cs_OutputDebugStringF);
248 static char pszBuffer[50000];
253 va_start(arg_ptr, pszFormat);
254 int limit = END(pszBuffer) - pend - 2;
255 int ret = _vsnprintf(pend, limit, pszFormat, arg_ptr);
257 if (ret < 0 || ret >= limit)
259 pend = END(pszBuffer) - 2;
265 char* p1 = pszBuffer;
267 while ((p2 = strchr(p1, '\n')))
272 OutputDebugStringA(p1);
277 memmove(pszBuffer, p1, pend - p1 + 1);
278 pend -= (p1 - pszBuffer);
287 // - prints up to limit-1 characters
288 // - output string is always null terminated even if limit reached
289 // - return value is the number of characters actually printed
290 int my_snprintf(char* buffer, size_t limit, const char* format, ...)
295 va_start(arg_ptr, format);
296 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
298 if (ret < 0 || ret >= (int)limit)
306 string real_strprintf(const std::string &format, int dummy, ...)
310 int limit = sizeof(buffer);
315 va_start(arg_ptr, dummy);
316 ret = _vsnprintf(p, limit, format.c_str(), arg_ptr);
318 if (ret >= 0 && ret < limit)
325 throw std::bad_alloc();
327 string str(p, p+ret);
333 bool error(const char *format, ...)
336 int limit = sizeof(buffer);
338 va_start(arg_ptr, format);
339 int ret = _vsnprintf(buffer, limit, format, arg_ptr);
341 if (ret < 0 || ret >= limit)
345 printf("ERROR: %s\n", buffer);
350 void ParseString(const string& str, char c, vector<string>& v)
354 string::size_type i1 = 0;
355 string::size_type i2;
358 i2 = str.find(c, i1);
361 v.push_back(str.substr(i1));
364 v.push_back(str.substr(i1, i2-i1));
370 string FormatMoney(int64 n, bool fPlus)
372 // Note: not using straight sprintf here because we do NOT want
373 // localized number formatting.
374 int64 n_abs = (n > 0 ? n : -n);
375 int64 quotient = n_abs/COIN;
376 int64 remainder = n_abs%COIN;
377 string str = strprintf("%"PRI64d".%06"PRI64d, quotient, remainder);
379 // Right-trim excess 0's before the decimal point:
381 for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
384 str.erase(str.size()-nTrim, nTrim);
387 str.insert((unsigned int)0, 1, '-');
388 else if (fPlus && n > 0)
389 str.insert((unsigned int)0, 1, '+');
394 bool ParseMoney(const string& str, int64& nRet)
396 return ParseMoney(str.c_str(), nRet);
399 bool ParseMoney(const char* pszIn, int64& nRet)
403 const char* p = pszIn;
411 int64 nMult = CENT*10;
412 while (isdigit(*p) && (nMult > 0))
414 nUnits += nMult * (*p++ - '0');
423 strWhole.insert(strWhole.end(), *p);
428 if (strWhole.size() > 10) // guard against 63 bit overflow
430 if (nUnits < 0 || nUnits > COIN)
432 int64 nWhole = atoi64(strWhole);
433 int64 nValue = nWhole*COIN + nUnits;
440 static signed char phexdigit[256] =
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 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
445 -1,0xa,0xb,0xc,0xd,0xe,0xf,-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,0xa,0xb,0xc,0xd,0xe,0xf,-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,
454 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
455 -1,-1,-1,-1,-1,-1,-1,-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, };
458 bool IsHex(const string& str)
460 BOOST_FOREACH(unsigned char c, str)
462 if (phexdigit[c] < 0)
465 return (str.size() > 0) && (str.size()%2 == 0);
468 vector<unsigned char> ParseHex(const char* psz)
470 // convert hex dump to vector
471 vector<unsigned char> vch;
474 while (isspace(*psz))
476 signed char c = phexdigit[(unsigned char)*psz++];
477 if (c == (signed char)-1)
479 unsigned char n = (c << 4);
480 c = phexdigit[(unsigned char)*psz++];
481 if (c == (signed char)-1)
489 vector<unsigned char> ParseHex(const string& str)
491 return ParseHex(str.c_str());
494 static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
496 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
497 if (name.find("-no") == 0)
499 std::string positive("-");
500 positive.append(name.begin()+3, name.end());
501 if (mapSettingsRet.count(positive) == 0)
503 bool value = !GetBoolArg(name);
504 mapSettingsRet[positive] = (value ? "1" : "0");
509 void ParseParameters(int argc, const char*const argv[])
512 mapMultiArgs.clear();
513 for (int i = 1; i < argc; i++)
516 strlcpy(psz, argv[i], sizeof(psz));
517 char* pszValue = (char*)"";
518 if (strchr(psz, '='))
520 pszValue = strchr(psz, '=');
531 mapArgs[psz] = pszValue;
532 mapMultiArgs[psz].push_back(pszValue);
536 BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs)
538 string name = entry.first;
540 // interpret --foo as -foo (as long as both are not set)
541 if (name.find("--") == 0)
543 std::string singleDash(name.begin()+1, name.end());
544 if (mapArgs.count(singleDash) == 0)
545 mapArgs[singleDash] = entry.second;
549 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
550 InterpretNegativeSetting(name, mapArgs);
554 std::string GetArg(const std::string& strArg, const std::string& strDefault)
556 if (mapArgs.count(strArg))
557 return mapArgs[strArg];
561 int64 GetArg(const std::string& strArg, int64 nDefault)
563 if (mapArgs.count(strArg))
564 return atoi64(mapArgs[strArg]);
568 bool GetBoolArg(const std::string& strArg, bool fDefault)
570 if (mapArgs.count(strArg))
572 if (mapArgs[strArg].empty())
574 return (atoi(mapArgs[strArg]) != 0);
579 bool SoftSetArg(const std::string& strArg, const std::string& strValue)
581 if (mapArgs.count(strArg))
583 mapArgs[strArg] = strValue;
587 bool SoftSetBoolArg(const std::string& strArg, bool fValue)
590 return SoftSetArg(strArg, std::string("1"));
592 return SoftSetArg(strArg, std::string("0"));
596 string EncodeBase64(const unsigned char* pch, size_t len)
598 static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
601 strRet.reserve((len+2)/3*4);
604 const unsigned char *pchEnd = pch+len;
611 case 0: // we have no bits
612 strRet += pbase64[enc >> 2];
613 left = (enc & 3) << 4;
617 case 1: // we have two bits
618 strRet += pbase64[left | (enc >> 4)];
619 left = (enc & 15) << 2;
623 case 2: // we have four bits
624 strRet += pbase64[left | (enc >> 6)];
625 strRet += pbase64[enc & 63];
633 strRet += pbase64[left];
642 string EncodeBase64(const string& str)
644 return EncodeBase64((const unsigned char*)str.c_str(), str.size());
647 vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
649 static const int decode64_table[256] =
651 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
652 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
653 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
654 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
655 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
656 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
657 49, 50, 51, -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, -1, -1, -1, -1,
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, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
669 vector<unsigned char> vchRet;
670 vchRet.reserve(strlen(p)*3/4);
677 int dec = decode64_table[(unsigned char)*p];
678 if (dec == -1) break;
682 case 0: // we have no bits and get 6
687 case 1: // we have 6 bits and keep 4
688 vchRet.push_back((left<<2) | (dec>>4));
693 case 2: // we have 4 bits and get 6, we keep 2
694 vchRet.push_back((left<<4) | (dec>>2));
699 case 3: // we have 2 bits and get 6
700 vchRet.push_back((left<<6) | dec);
709 case 0: // 4n base64 characters processed: ok
712 case 1: // 4n+1 base64 character processed: impossible
716 case 2: // 4n+2 base64 characters processed: require '=='
717 if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1)
721 case 3: // 4n+3 base64 characters processed: require '='
722 if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1)
730 string DecodeBase64(const string& str)
732 vector<unsigned char> vchRet = DecodeBase64(str.c_str());
733 return string((const char*)&vchRet[0], vchRet.size());
737 bool WildcardMatch(const char* psz, const char* mask)
744 return (*psz == '\0');
746 return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
761 bool WildcardMatch(const string& str, const string& mask)
763 return WildcardMatch(str.c_str(), mask.c_str());
773 void FormatException(char* pszMessage, std::exception* pex, const char* pszThread)
776 char pszModule[MAX_PATH];
778 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
780 const char* pszModule = "ppcoin";
783 snprintf(pszMessage, 1000,
784 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
786 snprintf(pszMessage, 1000,
787 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
790 void LogException(std::exception* pex, const char* pszThread)
792 char pszMessage[10000];
793 FormatException(pszMessage, pex, pszThread);
794 printf("\n%s", pszMessage);
797 void PrintException(std::exception* pex, const char* pszThread)
799 char pszMessage[10000];
800 FormatException(pszMessage, pex, pszThread);
801 printf("\n\n************************\n%s\n", pszMessage);
802 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
803 strMiscWarning = pszMessage;
807 void LogStackTrace() {
808 printf("\n\n******* exception encountered *******\n");
814 size = backtrace(pszBuffer, 32);
815 backtrace_symbols_fd(pszBuffer, size, fileno(fileout));
820 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
822 char pszMessage[10000];
823 FormatException(pszMessage, pex, pszThread);
824 printf("\n\n************************\n%s\n", pszMessage);
825 fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
826 strMiscWarning = pszMessage;
830 boost::filesystem::path MyGetSpecialFolderPath(int nFolder, bool fCreate)
832 namespace fs = boost::filesystem;
834 char pszPath[MAX_PATH] = "";
835 if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
837 return fs::path(pszPath);
839 else if (nFolder == CSIDL_STARTUP)
841 return fs::path(getenv("USERPROFILE")) / "Start Menu" / "Programs" / "Startup";
843 else if (nFolder == CSIDL_APPDATA)
845 return fs::path(getenv("APPDATA"));
851 boost::filesystem::path GetDefaultDataDir()
853 namespace fs = boost::filesystem;
855 // Windows: C:\Documents and Settings\username\Application Data\PPCoin
856 // Mac: ~/Library/Application Support/PPCoin
860 return MyGetSpecialFolderPath(CSIDL_APPDATA, true) / "PPCoin";
863 char* pszHome = getenv("HOME");
864 if (pszHome == NULL || strlen(pszHome) == 0)
865 pathRet = fs::path("/");
867 pathRet = fs::path(pszHome);
870 pathRet /= "Library/Application Support";
871 fs::create_directory(pathRet);
872 return pathRet / "PPCoin";
875 return pathRet / ".ppcoin";
880 const boost::filesystem::path &GetDataDir(bool fNetSpecific)
882 namespace fs = boost::filesystem;
884 static fs::path pathCached[2];
885 static CCriticalSection csPathCached;
886 static bool cachedPath[2] = {false, false};
888 fs::path &path = pathCached[fNetSpecific];
890 // This can be called during exceptions by printf, so we cache the
891 // value so we don't have to do memory allocations after that.
892 if (cachedPath[fNetSpecific])
897 if (mapArgs.count("-datadir")) {
898 path = fs::system_complete(mapArgs["-datadir"]);
899 if (!fs::is_directory(path)) {
904 path = GetDefaultDataDir();
906 if (fNetSpecific && GetBoolArg("-testnet", false))
909 fs::create_directory(path);
911 cachedPath[fNetSpecific]=true;
915 boost::filesystem::path GetConfigFile()
917 namespace fs = boost::filesystem;
919 fs::path pathConfigFile(GetArg("-conf", "ppcoin.conf"));
920 if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
921 return pathConfigFile;
924 void ReadConfigFile(map<string, string>& mapSettingsRet,
925 map<string, vector<string> >& mapMultiSettingsRet)
927 namespace fs = boost::filesystem;
928 namespace pod = boost::program_options::detail;
930 fs::ifstream streamConfig(GetConfigFile());
931 if (!streamConfig.good())
932 return; // No bitcoin.conf file is OK
934 set<string> setOptions;
935 setOptions.insert("*");
937 for (pod::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
939 // Don't overwrite existing settings so command line settings override bitcoin.conf
940 string strKey = string("-") + it->string_key;
941 if (mapSettingsRet.count(strKey) == 0)
943 mapSettingsRet[strKey] = it->value[0];
944 // interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
945 InterpretNegativeSetting(strKey, mapSettingsRet);
947 mapMultiSettingsRet[strKey].push_back(it->value[0]);
951 boost::filesystem::path GetPidFile()
953 namespace fs = boost::filesystem;
955 fs::path pathPidFile(GetArg("-pid", "ppcoind.pid"));
956 if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
960 void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
962 FILE* file = fopen(path.string().c_str(), "w");
965 fprintf(file, "%d\n", pid);
970 int GetFilesize(FILE* file)
972 int nSavePos = ftell(file);
974 if (fseek(file, 0, SEEK_END) == 0)
975 nFilesize = ftell(file);
976 fseek(file, nSavePos, SEEK_SET);
980 void ShrinkDebugFile()
982 // Scroll debug.log if it's getting too big
983 boost::filesystem::path pathLog = GetDataDir() / "debug.log";
984 FILE* file = fopen(pathLog.string().c_str(), "r");
985 if (file && GetFilesize(file) > 10 * 1000000)
987 // Restart the file with some of the end
989 fseek(file, -sizeof(pch), SEEK_END);
990 int nBytes = fread(pch, 1, sizeof(pch), file);
993 file = fopen(pathLog.string().c_str(), "w");
996 fwrite(pch, 1, nBytes, file);
1010 // "Never go to sea with two chronometers; take one or three."
1011 // Our three time sources are:
1013 // - Median of other nodes's clocks
1014 // - The user (asking the user to fix the system clock if the first two disagree)
1016 static int64 nMockTime = 0; // For unit testing
1020 if (nMockTime) return nMockTime;
1025 void SetMockTime(int64 nMockTimeIn)
1027 nMockTime = nMockTimeIn;
1030 static int64 nTimeOffset = 0;
1032 int64 GetAdjustedTime()
1034 return GetTime() + nTimeOffset;
1037 void AddTimeData(const CNetAddr& ip, int64 nTime)
1039 int64 nOffsetSample = nTime - GetTime();
1041 // Ignore duplicates
1042 static set<CNetAddr> setKnown;
1043 if (!setKnown.insert(ip).second)
1047 vTimeOffsets.input(nOffsetSample);
1048 printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
1049 if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
1051 int64 nMedian = vTimeOffsets.median();
1052 std::vector<int64> vSorted = vTimeOffsets.sorted();
1053 // Only let other nodes change our time by so much
1054 if (abs64(nMedian) < 70 * 60)
1056 nTimeOffset = nMedian;
1065 // If nobody has a time different than ours but within 5 minutes of ours, give a warning
1066 bool fMatch = false;
1067 BOOST_FOREACH(int64 nOffset, vSorted)
1068 if (nOffset != 0 && abs64(nOffset) < 5 * 60)
1074 string strMessage = _("Warning: Please check that your computer's date and time are correct. If your clock is wrong PPCoin will not work properly.");
1075 strMiscWarning = strMessage;
1076 printf("*** %s\n", strMessage.c_str());
1077 ThreadSafeMessageBox(strMessage+" ", string("PPCoin"), wxOK | wxICON_EXCLAMATION);
1082 BOOST_FOREACH(int64 n, vSorted)
1083 printf("%+"PRI64d" ", n);
1086 printf("nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
1097 string FormatVersion(int nVersion)
1099 if (nVersion%100 == 0)
1100 return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
1102 return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
1105 string FormatFullVersion()
1107 return CLIENT_BUILD;
1110 // Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
1111 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
1113 std::ostringstream ss;
1115 ss << name << ":" << FormatVersion(nClientVersion);
1116 if (!comments.empty())
1117 ss << "(" << boost::algorithm::join(comments, "; ") << ")";
1123 boost::filesystem::path static StartupShortcutPath()
1125 return MyGetSpecialFolderPath(CSIDL_STARTUP, true) / "PPCoin.lnk";
1128 bool GetStartOnSystemStartup()
1130 return filesystem::exists(StartupShortcutPath());
1133 bool SetStartOnSystemStartup(bool fAutoStart)
1135 // If the shortcut exists already, remove it for updating
1136 boost::filesystem::remove(StartupShortcutPath());
1142 // Get a pointer to the IShellLink interface.
1143 IShellLink* psl = NULL;
1144 HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
1145 CLSCTX_INPROC_SERVER, IID_IShellLink,
1146 reinterpret_cast<void**>(&psl));
1148 if (SUCCEEDED(hres))
1150 // Get the current executable path
1151 TCHAR pszExePath[MAX_PATH];
1152 GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
1154 TCHAR pszArgs[5] = TEXT("-min");
1156 // Set the path to the shortcut target
1157 psl->SetPath(pszExePath);
1158 PathRemoveFileSpec(pszExePath);
1159 psl->SetWorkingDirectory(pszExePath);
1160 psl->SetShowCmd(SW_SHOWMINNOACTIVE);
1161 psl->SetArguments(pszArgs);
1163 // Query IShellLink for the IPersistFile interface for
1164 // saving the shortcut in persistent storage.
1165 IPersistFile* ppf = NULL;
1166 hres = psl->QueryInterface(IID_IPersistFile,
1167 reinterpret_cast<void**>(&ppf));
1168 if (SUCCEEDED(hres))
1170 WCHAR pwsz[MAX_PATH];
1171 // Ensure that the string is ANSI.
1172 MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH);
1173 // Save the link by calling IPersistFile::Save.
1174 hres = ppf->Save(pwsz, TRUE);
1188 #elif defined(LINUX)
1190 // Follow the Desktop Application Autostart Spec:
1191 // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
1193 boost::filesystem::path static GetAutostartDir()
1195 namespace fs = boost::filesystem;
1197 char* pszConfigHome = getenv("XDG_CONFIG_HOME");
1198 if (pszConfigHome) return fs::path(pszConfigHome) / "autostart";
1199 char* pszHome = getenv("HOME");
1200 if (pszHome) return fs::path(pszHome) / ".config" / "autostart";
1204 boost::filesystem::path static GetAutostartFilePath()
1206 return GetAutostartDir() / "ppcoin.desktop";
1209 bool GetStartOnSystemStartup()
1211 boost::filesystem::ifstream optionFile(GetAutostartFilePath());
1212 if (!optionFile.good())
1214 // Scan through file for "Hidden=true":
1216 while (!optionFile.eof())
1218 getline(optionFile, line);
1219 if (line.find("Hidden") != string::npos &&
1220 line.find("true") != string::npos)
1228 bool SetStartOnSystemStartup(bool fAutoStart)
1231 boost::filesystem::remove(GetAutostartFilePath());
1234 char pszExePath[MAX_PATH+1];
1235 memset(pszExePath, 0, sizeof(pszExePath));
1236 if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
1239 boost::filesystem::create_directories(GetAutostartDir());
1241 boost::filesystem::ofstream optionFile(GetAutostartFilePath(), ios_base::out|ios_base::trunc);
1242 if (!optionFile.good())
1244 // Write a bitcoin.desktop file to the autostart directory:
1245 optionFile << "[Desktop Entry]\n";
1246 optionFile << "Type=Application\n";
1247 optionFile << "Name=PPCoin\n";
1248 optionFile << "Exec=" << pszExePath << " -min\n";
1249 optionFile << "Terminal=false\n";
1250 optionFile << "Hidden=false\n";
1257 // TODO: OSX startup stuff; see:
1258 // http://developer.apple.com/mac/library/documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html
1260 bool GetStartOnSystemStartup() { return false; }
1261 bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
1267 #ifdef DEBUG_LOCKORDER
1269 // Early deadlock detection.
1270 // Problem being solved:
1271 // Thread 1 locks A, then B, then C
1272 // Thread 2 locks D, then C, then A
1273 // --> may result in deadlock between the two threads, depending on when they run.
1274 // Solution implemented here:
1275 // Keep track of pairs of locks: (A before B), (A before C), etc.
1276 // Complain if any thread trys to lock in a different order.
1279 struct CLockLocation
1281 CLockLocation(const char* pszName, const char* pszFile, int nLine)
1283 mutexName = pszName;
1284 sourceFile = pszFile;
1288 std::string ToString() const
1290 return mutexName+" "+sourceFile+":"+itostr(sourceLine);
1294 std::string mutexName;
1295 std::string sourceFile;
1299 typedef std::vector< std::pair<void*, CLockLocation> > LockStack;
1301 static boost::interprocess::interprocess_mutex dd_mutex;
1302 static std::map<std::pair<void*, void*>, LockStack> lockorders;
1303 static boost::thread_specific_ptr<LockStack> lockstack;
1306 static void potential_deadlock_detected(const std::pair<void*, void*>& mismatch, const LockStack& s1, const LockStack& s2)
1308 printf("POTENTIAL DEADLOCK DETECTED\n");
1309 printf("Previous lock order was:\n");
1310 BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, s2)
1312 if (i.first == mismatch.first) printf(" (1)");
1313 if (i.first == mismatch.second) printf(" (2)");
1314 printf(" %s\n", i.second.ToString().c_str());
1316 printf("Current lock order is:\n");
1317 BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, s1)
1319 if (i.first == mismatch.first) printf(" (1)");
1320 if (i.first == mismatch.second) printf(" (2)");
1321 printf(" %s\n", i.second.ToString().c_str());
1325 static void push_lock(void* c, const CLockLocation& locklocation, bool fTry)
1327 bool fOrderOK = true;
1328 if (lockstack.get() == NULL)
1329 lockstack.reset(new LockStack);
1331 if (fDebug) printf("Locking: %s\n", locklocation.ToString().c_str());
1334 (*lockstack).push_back(std::make_pair(c, locklocation));
1336 if (!fTry) BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, (*lockstack))
1338 if (i.first == c) break;
1340 std::pair<void*, void*> p1 = std::make_pair(i.first, c);
1341 if (lockorders.count(p1))
1343 lockorders[p1] = (*lockstack);
1345 std::pair<void*, void*> p2 = std::make_pair(c, i.first);
1346 if (lockorders.count(p2))
1348 potential_deadlock_detected(p1, lockorders[p2], lockorders[p1]);
1355 static void pop_lock()
1359 const CLockLocation& locklocation = (*lockstack).rbegin()->second;
1360 printf("Unlocked: %s\n", locklocation.ToString().c_str());
1363 (*lockstack).pop_back();
1367 void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry)
1369 push_lock(cs, CLockLocation(pszName, pszFile, nLine), fTry);
1372 void LeaveCritical()
1377 #endif /* DEBUG_LOCKORDER */