Back to home page

Bitcoin sources

 
 

    


0001 // Copyright (c) 2009-2010 Satoshi Nakamoto
0002 // Copyright (c) 2009-2012 The Bitcoin developers
0003 // Distributed under the MIT/X11 software license, see the accompanying
0004 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
0005 #include "headers.h"
0006 #include "strlcpy.h"
0007 #include <boost/program_options/detail/config_file.hpp>
0008 #include <boost/program_options/parsers.hpp>
0009 #include <boost/filesystem.hpp>
0010 #include <boost/filesystem/fstream.hpp>
0011 #include <boost/interprocess/sync/interprocess_mutex.hpp>
0012 #include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>
0013 #include <boost/foreach.hpp>
0014 
0015 using namespace std;
0016 using namespace boost;
0017 
0018 map<string, string> mapArgs;
0019 map<string, vector<string> > mapMultiArgs;
0020 bool fDebug = false;
0021 bool fPrintToConsole = false;
0022 bool fPrintToDebugger = false;
0023 char pszSetDataDir[MAX_PATH] = "";
0024 bool fRequestShutdown = false;
0025 bool fShutdown = false;
0026 bool fDaemon = false;
0027 bool fServer = false;
0028 bool fCommandLine = false;
0029 string strMiscWarning;
0030 bool fTestNet = false;
0031 bool fNoListen = false;
0032 bool fLogTimestamps = false;
0033 
0034 
0035 
0036 
0037 // Workaround for "multiple definition of `_tls_used'"
0038 // http://svn.boost.org/trac/boost/ticket/4258
0039 extern "C" void tss_cleanup_implemented() { }
0040 
0041 
0042 
0043 
0044 
0045 // Init openssl library multithreading support
0046 static boost::interprocess::interprocess_mutex** ppmutexOpenSSL;
0047 void locking_callback(int mode, int i, const char* file, int line)
0048 {
0049     if (mode & CRYPTO_LOCK)
0050         ppmutexOpenSSL[i]->lock();
0051     else
0052         ppmutexOpenSSL[i]->unlock();
0053 }
0054 
0055 // Init
0056 class CInit
0057 {
0058 public:
0059     CInit()
0060     {
0061         // Init openssl library multithreading support
0062         ppmutexOpenSSL = (boost::interprocess::interprocess_mutex**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(boost::interprocess::interprocess_mutex*));
0063         for (int i = 0; i < CRYPTO_num_locks(); i++)
0064             ppmutexOpenSSL[i] = new boost::interprocess::interprocess_mutex();
0065         CRYPTO_set_locking_callback(locking_callback);
0066 
0067         // Seed random number generator with performance counter
0068         RandAddSeed();
0069     }
0070     ~CInit()
0071     {
0072         // Shutdown openssl library multithreading support
0073         CRYPTO_set_locking_callback(NULL);
0074         for (int i = 0; i < CRYPTO_num_locks(); i++)
0075             delete ppmutexOpenSSL[i];
0076         OPENSSL_free(ppmutexOpenSSL);
0077     }
0078 }
0079 instance_of_cinit;
0080 
0081 
0082 
0083 
0084 
0085 
0086 
0087 
0088 void RandAddSeed()
0089 {
0090     // Seed with CPU performance counter
0091     int64 nCounter = GetPerformanceCounter();
0092     RAND_add(&nCounter, sizeof(nCounter), 1.5);
0093     memset(&nCounter, 0, sizeof(nCounter));
0094 }
0095 
0096 void RandAddSeedPerfmon()
0097 {
0098     RandAddSeed();
0099 
0100     // This can take up to 2 seconds, so only do it every 10 minutes
0101     static int64 nLastPerfmon;
0102     if (GetTime() < nLastPerfmon + 10 * 60)
0103         return;
0104     nLastPerfmon = GetTime();
0105 
0106 }
0107 
0108 uint64 GetRand(uint64 nMax)
0109 {
0110     if (nMax == 0)
0111         return 0;
0112 
0113     // The range of the random source must be a multiple of the modulus
0114     // to give every possible output value an equal possibility
0115     uint64 nRange = (UINT64_MAX / nMax) * nMax;
0116     uint64 nRand = 0;
0117     do
0118         RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
0119     while (nRand >= nRange);
0120     return (nRand % nMax);
0121 }
0122 
0123 int GetRandInt(int nMax)
0124 {
0125     return GetRand(nMax);
0126 }
0127 
0128 
0129 
0130 
0131 
0132 
0133 
0134 
0135 
0136 
0137 
0138 inline int OutputDebugStringF(const char* pszFormat, ...)
0139 {
0140     int ret = 0;
0141     if (fPrintToConsole)
0142     {
0143         // print to console
0144         va_list arg_ptr;
0145         va_start(arg_ptr, pszFormat);
0146         ret = vprintf(pszFormat, arg_ptr);
0147         va_end(arg_ptr);
0148     }
0149     else
0150     {
0151         // print to debug.log
0152         static FILE* fileout = NULL;
0153 
0154         if (!fileout)
0155         {
0156             char pszFile[MAX_PATH+100];
0157             GetDataDir(pszFile);
0158             strlcat(pszFile, "/debug.log", sizeof(pszFile));
0159             fileout = fopen(pszFile, "a");
0160             if (fileout) setbuf(fileout, NULL); // unbuffered
0161         }
0162         if (fileout)
0163         {
0164             static bool fStartedNewLine = true;
0165 
0166             // Debug print useful for profiling
0167             if (fLogTimestamps && fStartedNewLine)
0168                 fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
0169             if (pszFormat[strlen(pszFormat) - 1] == '\n')
0170                 fStartedNewLine = true;
0171             else
0172                 fStartedNewLine = false;
0173 
0174             va_list arg_ptr;
0175             va_start(arg_ptr, pszFormat);
0176             ret = vfprintf(fileout, pszFormat, arg_ptr);
0177             va_end(arg_ptr);
0178         }
0179     }
0180 
0181     return ret;
0182 }
0183 
0184 
0185 // Safer snprintf
0186 //  - prints up to limit-1 characters
0187 //  - output string is always null terminated even if limit reached
0188 //  - return value is the number of characters actually printed
0189 int my_snprintf(char* buffer, size_t limit, const char* format, ...)
0190 {
0191     if (limit == 0)
0192         return 0;
0193     va_list arg_ptr;
0194     va_start(arg_ptr, format);
0195     int ret = _vsnprintf(buffer, limit, format, arg_ptr);
0196     va_end(arg_ptr);
0197     if (ret < 0 || ret >= limit)
0198     {
0199         ret = limit - 1;
0200         buffer[limit-1] = 0;
0201     }
0202     return ret;
0203 }
0204 
0205 string strprintf(const std::string &format, ...)
0206 {
0207     char buffer[50000];
0208     char* p = buffer;
0209     int limit = sizeof(buffer);
0210     int ret;
0211     loop
0212     {
0213         va_list arg_ptr;
0214         va_start(arg_ptr, format);
0215         ret = _vsnprintf(p, limit, format.c_str(), arg_ptr);
0216         va_end(arg_ptr);
0217         if (ret >= 0 && ret < limit)
0218             break;
0219         if (p != buffer)
0220             delete[] p;
0221         limit *= 2;
0222         p = new char[limit];
0223         if (p == NULL)
0224             throw std::bad_alloc();
0225     }
0226     string str(p, p+ret);
0227     if (p != buffer)
0228         delete[] p;
0229     return str;
0230 }
0231 
0232 bool error(const std::string &format, ...)
0233 {
0234     char buffer[50000];
0235     int limit = sizeof(buffer);
0236     va_list arg_ptr;
0237     va_start(arg_ptr, format);
0238     int ret = _vsnprintf(buffer, limit, format.c_str(), arg_ptr);
0239     va_end(arg_ptr);
0240     if (ret < 0 || ret >= limit)
0241     {
0242         ret = limit - 1;
0243         buffer[limit-1] = 0;
0244     }
0245     printf("ERROR: %s\n", buffer);
0246     return false;
0247 }
0248 
0249 
0250 void ParseString(const string& str, char c, vector<string>& v)
0251 {
0252     if (str.empty())
0253         return;
0254     string::size_type i1 = 0;
0255     string::size_type i2;
0256     loop
0257     {
0258         i2 = str.find(c, i1);
0259         if (i2 == str.npos)
0260         {
0261             v.push_back(str.substr(i1));
0262             return;
0263         }
0264         v.push_back(str.substr(i1, i2-i1));
0265         i1 = i2+1;
0266     }
0267 }
0268 
0269 
0270 string FormatMoney(int64 n, bool fPlus)
0271 {
0272     // Note: not using straight sprintf here because we do NOT want
0273     // localized number formatting.
0274     int64 n_abs = (n > 0 ? n : -n);
0275     int64 quotient = n_abs/COIN;
0276     int64 remainder = n_abs%COIN;
0277     string str = strprintf("%"PRI64d".%08"PRI64d, quotient, remainder);
0278 
0279     // Right-trim excess 0's before the decimal point:
0280     int nTrim = 0;
0281     for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
0282         ++nTrim;
0283     if (nTrim)
0284         str.erase(str.size()-nTrim, nTrim);
0285 
0286     if (n < 0)
0287         str.insert((unsigned int)0, 1, '-');
0288     else if (fPlus && n > 0)
0289         str.insert((unsigned int)0, 1, '+');
0290     return str;
0291 }
0292 
0293 
0294 bool ParseMoney(const string& str, int64& nRet)
0295 {
0296     return ParseMoney(str.c_str(), nRet);
0297 }
0298 
0299 bool ParseMoney(const char* pszIn, int64& nRet)
0300 {
0301     string strWhole;
0302     int64 nUnits = 0;
0303     const char* p = pszIn;
0304     while (isspace(*p))
0305         p++;
0306     for (; *p; p++)
0307     {
0308         if (*p == '.')
0309         {
0310             p++;
0311             int64 nMult = CENT*10;
0312             while (isdigit(*p) && (nMult > 0))
0313             {
0314                 nUnits += nMult * (*p++ - '0');
0315                 nMult /= 10;
0316             }
0317             break;
0318         }
0319         if (isspace(*p))
0320             break;
0321         if (!isdigit(*p))
0322             return false;
0323         strWhole.insert(strWhole.end(), *p);
0324     }
0325     for (; *p; p++)
0326         if (!isspace(*p))
0327             return false;
0328     if (strWhole.size() > 10) // guard against 63 bit overflow
0329         return false;
0330     if (nUnits < 0 || nUnits > COIN)
0331         return false;
0332     int64 nWhole = atoi64(strWhole);
0333     int64 nValue = nWhole*COIN + nUnits;
0334 
0335     nRet = nValue;
0336     return true;
0337 }
0338 
0339 
0340 vector<unsigned char> ParseHex(const char* psz)
0341 {
0342     static char phexdigit[256] =
0343     { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
0344       -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
0345       -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
0346       0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
0347       -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
0348       -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
0349       -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1
0350       -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
0351       -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
0352       -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
0353       -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
0354       -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
0355       -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
0356       -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
0357       -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
0358       -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
0359 
0360     // convert hex dump to vector
0361     vector<unsigned char> vch;
0362     loop
0363     {
0364         while (isspace(*psz))
0365             psz++;
0366         char c = phexdigit[(unsigned char)*psz++];
0367         if (c == (char)-1)
0368             break;
0369         unsigned char n = (c << 4);
0370         c = phexdigit[(unsigned char)*psz++];
0371         if (c == (char)-1)
0372             break;
0373         n |= c;
0374         vch.push_back(n);
0375     }
0376     return vch;
0377 }
0378 
0379 vector<unsigned char> ParseHex(const string& str)
0380 {
0381     return ParseHex(str.c_str());
0382 }
0383 
0384 void ParseParameters(int argc, char* argv[])
0385 {
0386     mapArgs.clear();
0387     mapMultiArgs.clear();
0388     for (int i = 1; i < argc; i++)
0389     {
0390         char psz[10000];
0391         strlcpy(psz, argv[i], sizeof(psz));
0392         char* pszValue = (char*)"";
0393         if (strchr(psz, '='))
0394         {
0395             pszValue = strchr(psz, '=');
0396             *pszValue++ = '\0';
0397         }
0398         if (psz[0] != '-')
0399             break;
0400         mapArgs[psz] = pszValue;
0401         mapMultiArgs[psz].push_back(pszValue);
0402     }
0403 }
0404 
0405 bool SoftSetArg(const std::string& strArg, const std::string& strValue)
0406 {
0407     if (mapArgs.count(strArg))
0408         return false;
0409     mapArgs[strArg] = strValue;
0410     return true;
0411 }
0412 
0413 bool SoftSetArg(const std::string& strArg, bool fValue)
0414 {
0415     if (fValue)
0416         return SoftSetArg(strArg, std::string("1"));
0417     else
0418         return SoftSetArg(strArg, std::string("0"));
0419 }
0420 
0421 
0422 string EncodeBase64(const unsigned char* pch, size_t len)
0423 {
0424     static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
0425 
0426     string strRet="";
0427     strRet.reserve((len+2)/3*4);
0428 
0429     int mode=0, left=0;
0430     const unsigned char *pchEnd = pch+len;
0431 
0432     while (pch<pchEnd)
0433     {
0434         int enc = *(pch++);
0435         switch (mode)
0436         {
0437             case 0: // we have no bits
0438                 strRet += pbase64[enc >> 2];
0439                 left = (enc & 3) << 4;
0440                 mode = 1;
0441                 break;
0442 
0443             case 1: // we have two bits
0444                 strRet += pbase64[left | (enc >> 4)];
0445                 left = (enc & 15) << 2;
0446                 mode = 2;
0447                 break;
0448 
0449             case 2: // we have four bits
0450                 strRet += pbase64[left | (enc >> 6)];
0451                 strRet += pbase64[enc & 63];
0452                 mode = 0;
0453                 break;
0454         }
0455     }
0456 
0457     if (mode)
0458     {
0459         strRet += pbase64[left];
0460         strRet += '=';
0461         if (mode == 1)
0462             strRet += '=';
0463     }
0464 
0465     return strRet;
0466 }
0467 
0468 string EncodeBase64(const string& str)
0469 {
0470     return EncodeBase64((const unsigned char*)str.c_str(), str.size());
0471 }
0472 
0473 vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
0474 {
0475     static const int decode64_table[256] =
0476     {
0477         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
0478         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
0479         -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
0480         -1, -1, -1, -1, -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
0481         15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
0482         29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
0483         49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
0484         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
0485         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
0486         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
0487         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
0488         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
0489         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
0490     };
0491 
0492     if (pfInvalid)
0493         *pfInvalid = false;
0494 
0495     vector<unsigned char> vchRet;
0496     vchRet.reserve(strlen(p)*3/4);
0497 
0498     int mode = 0;
0499     int left = 0;
0500 
0501     while (1)
0502     {
0503          int dec = decode64_table[*p];
0504          if (dec == -1) break;
0505          p++;
0506          switch (mode)
0507          {
0508              case 0: // we have no bits and get 6
0509                  left = dec;
0510                  mode = 1;
0511                  break;
0512 
0513               case 1: // we have 6 bits and keep 4
0514                   vchRet.push_back((left<<2) | (dec>>4));
0515                   left = dec & 15;
0516                   mode = 2;
0517                   break;
0518 
0519              case 2: // we have 4 bits and get 6, we keep 2
0520                  vchRet.push_back((left<<4) | (dec>>2));
0521                  left = dec & 3;
0522                  mode = 3;
0523                  break;
0524 
0525              case 3: // we have 2 bits and get 6
0526                  vchRet.push_back((left<<6) | dec);
0527                  mode = 0;
0528                  break;
0529          }
0530     }
0531 
0532     if (pfInvalid)
0533         switch (mode)
0534         {
0535             case 0: // 4n base64 characters processed: ok
0536                 break;
0537 
0538             case 1: // 4n+1 base64 character processed: impossible
0539                 *pfInvalid = true;
0540                 break;
0541 
0542             case 2: // 4n+2 base64 characters processed: require '=='
0543                 if (left || p[0] != '=' || p[1] != '=' || decode64_table[p[2]] != -1)
0544                     *pfInvalid = true;
0545                 break;
0546 
0547             case 3: // 4n+3 base64 characters processed: require '='
0548                 if (left || p[0] != '=' || decode64_table[p[1]] != -1)
0549                     *pfInvalid = true;
0550                 break;
0551         }
0552 
0553     return vchRet;
0554 }
0555 
0556 string DecodeBase64(const string& str)
0557 {
0558     vector<unsigned char> vchRet = DecodeBase64(str.c_str());
0559     return string((const char*)&vchRet[0], vchRet.size());
0560 }
0561 
0562 
0563 bool WildcardMatch(const char* psz, const char* mask)
0564 {
0565     loop
0566     {
0567         switch (*mask)
0568         {
0569         case '\0':
0570             return (*psz == '\0');
0571         case '*':
0572             return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
0573         case '?':
0574             if (*psz == '\0')
0575                 return false;
0576             break;
0577         default:
0578             if (*psz != *mask)
0579                 return false;
0580             break;
0581         }
0582         psz++;
0583         mask++;
0584     }
0585 }
0586 
0587 bool WildcardMatch(const string& str, const string& mask)
0588 {
0589     return WildcardMatch(str.c_str(), mask.c_str());
0590 }
0591 
0592 
0593 
0594 
0595 
0596 
0597 
0598 
0599 void FormatException(char* pszMessage, std::exception* pex, const char* pszThread)
0600 {
0601     const char* pszModule = "bitcoin";
0602     if (pex)
0603         snprintf(pszMessage, 1000,
0604             "EXCEPTION: %s       \n%s       \n%s in %s       \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
0605     else
0606         snprintf(pszMessage, 1000,
0607             "UNKNOWN EXCEPTION       \n%s in %s       \n", pszModule, pszThread);
0608 }
0609 
0610 void LogException(std::exception* pex, const char* pszThread)
0611 {
0612     char pszMessage[10000];
0613     FormatException(pszMessage, pex, pszThread);
0614     printf("\n%s", pszMessage);
0615 }
0616 
0617 void PrintException(std::exception* pex, const char* pszThread)
0618 {
0619     char pszMessage[10000];
0620     FormatException(pszMessage, pex, pszThread);
0621     printf("\n\n************************\n%s\n", pszMessage);
0622     fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
0623     strMiscWarning = pszMessage;
0624     throw;
0625 }
0626 
0627 void ThreadOneMessageBox(string strMessage)
0628 {
0629     // Skip message boxes if one is already open
0630     static bool fMessageBoxOpen;
0631     if (fMessageBoxOpen)
0632         return;
0633     fMessageBoxOpen = true;
0634     ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
0635     fMessageBoxOpen = false;
0636 }
0637 
0638 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
0639 {
0640     char pszMessage[10000];
0641     FormatException(pszMessage, pex, pszThread);
0642     printf("\n\n************************\n%s\n", pszMessage);
0643     fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
0644     strMiscWarning = pszMessage;
0645 }
0646 
0647 string GetDefaultDataDir()
0648 {
0649     // Mac: ~/Library/Application Support/Bitcoin
0650     // Unix: ~/.bitcoin
0651     char* pszHome = getenv("HOME");
0652     if (pszHome == NULL || strlen(pszHome) == 0)
0653         pszHome = (char*)"/";
0654     string strHome = pszHome;
0655     if (strHome[strHome.size()-1] != '/')
0656         strHome += '/';
0657 #ifdef MAC_OSX
0658     // Mac
0659     strHome += "Library/Application Support/";
0660     filesystem::create_directory(strHome.c_str());
0661     return strHome + "Bitcoin";
0662 #else
0663     // Unix
0664     return strHome + ".bitcoin";
0665 #endif
0666 }
0667 
0668 void GetDataDir(char* pszDir)
0669 {
0670     // pszDir must be at least MAX_PATH length.
0671     int nVariation;
0672     if (pszSetDataDir[0] != 0)
0673     {
0674         strlcpy(pszDir, pszSetDataDir, MAX_PATH);
0675         nVariation = 0;
0676     }
0677     else
0678     {
0679         // This can be called during exceptions by printf, so we cache the
0680         // value so we don't have to do memory allocations after that.
0681         static char pszCachedDir[MAX_PATH];
0682         if (pszCachedDir[0] == 0)
0683             strlcpy(pszCachedDir, GetDefaultDataDir().c_str(), sizeof(pszCachedDir));
0684         strlcpy(pszDir, pszCachedDir, MAX_PATH);
0685         nVariation = 1;
0686     }
0687     if (fTestNet)
0688     {
0689         char* p = pszDir + strlen(pszDir);
0690         if (p > pszDir && p[-1] != '/' && p[-1] != '\\')
0691             *p++ = '/';
0692         strcpy(p, "testnet");
0693         nVariation += 2;
0694     }
0695     static bool pfMkdir[4];
0696     if (!pfMkdir[nVariation])
0697     {
0698         pfMkdir[nVariation] = true;
0699         boost::filesystem::create_directory(pszDir);
0700     }
0701 }
0702 
0703 string GetDataDir()
0704 {
0705     char pszDir[MAX_PATH];
0706     GetDataDir(pszDir);
0707     return pszDir;
0708 }
0709 
0710 string GetConfigFile()
0711 {
0712     namespace fs = boost::filesystem;
0713     fs::path pathConfig(GetArg("-conf", "bitcoin.conf"));
0714     if (!pathConfig.is_complete())
0715         pathConfig = fs::path(GetDataDir()) / pathConfig;
0716     return pathConfig.string();
0717 }
0718 
0719 void ReadConfigFile(map<string, string>& mapSettingsRet,
0720                     map<string, vector<string> >& mapMultiSettingsRet)
0721 {
0722     namespace fs = boost::filesystem;
0723     namespace pod = boost::program_options::detail;
0724 
0725     fs::ifstream streamConfig(GetConfigFile());
0726     if (!streamConfig.good())
0727         return;
0728 
0729     set<string> setOptions;
0730     setOptions.insert("*");
0731     
0732     for (pod::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
0733     {
0734         // Don't overwrite existing settings so command line settings override bitcoin.conf
0735         string strKey = string("-") + it->string_key;
0736         if (mapSettingsRet.count(strKey) == 0)
0737             mapSettingsRet[strKey] = it->value[0];
0738         mapMultiSettingsRet[strKey].push_back(it->value[0]);
0739     }
0740 }
0741 
0742 string GetPidFile()
0743 {
0744     namespace fs = boost::filesystem;
0745     fs::path pathConfig(GetArg("-pid", "bitcoind.pid"));
0746     if (!pathConfig.is_complete())
0747         pathConfig = fs::path(GetDataDir()) / pathConfig;
0748     return pathConfig.string();
0749 }
0750 
0751 void CreatePidFile(string pidFile, pid_t pid)
0752 {
0753     FILE* file = fopen(pidFile.c_str(), "w");
0754     if (file)
0755     {
0756         fprintf(file, "%d\n", pid);
0757         fclose(file);
0758     }
0759 }
0760 
0761 int GetFilesize(FILE* file)
0762 {
0763     int nSavePos = ftell(file);
0764     int nFilesize = -1;
0765     if (fseek(file, 0, SEEK_END) == 0)
0766         nFilesize = ftell(file);
0767     fseek(file, nSavePos, SEEK_SET);
0768     return nFilesize;
0769 }
0770 
0771 void ShrinkDebugFile()
0772 {
0773     // Scroll debug.log if it's getting too big
0774     string strFile = GetDataDir() + "/debug.log";
0775     FILE* file = fopen(strFile.c_str(), "r");
0776     if (file && GetFilesize(file) > 10 * 1000000)
0777     {
0778         // Restart the file with some of the end
0779         char pch[200000];
0780         fseek(file, -sizeof(pch), SEEK_END);
0781         int nBytes = fread(pch, 1, sizeof(pch), file);
0782         fclose(file);
0783 
0784         file = fopen(strFile.c_str(), "w");
0785         if (file)
0786         {
0787             fwrite(pch, 1, nBytes, file);
0788             fclose(file);
0789         }
0790     }
0791 }
0792 
0793 
0794 
0795 
0796 
0797 
0798 
0799 
0800 //
0801 // "Never go to sea with two chronometers; take one or three."
0802 // Our three time sources are:
0803 //  - System clock
0804 //  - Median of other nodes's clocks
0805 //  - The user (asking the user to fix the system clock if the first two disagree)
0806 //
0807 static int64 nMockTime = 0;  // For unit testing
0808 
0809 int64 GetTime()
0810 {
0811     if (nMockTime) return nMockTime;
0812 
0813     return time(NULL);
0814 }
0815 
0816 void SetMockTime(int64 nMockTimeIn)
0817 {
0818     nMockTime = nMockTimeIn;
0819 }
0820 
0821 static int64 nTimeOffset = 0;
0822 
0823 int64 GetAdjustedTime()
0824 {
0825     return GetTime() + nTimeOffset;
0826 }
0827 
0828 void AddTimeData(unsigned int ip, int64 nTime)
0829 {
0830     int64 nOffsetSample = nTime - GetTime();
0831 
0832     // Ignore duplicates
0833     static set<unsigned int> setKnown;
0834     if (!setKnown.insert(ip).second)
0835         return;
0836 
0837     // Add data
0838     static vector<int64> vTimeOffsets;
0839     if (vTimeOffsets.empty())
0840         vTimeOffsets.push_back(0);
0841     vTimeOffsets.push_back(nOffsetSample);
0842     printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), vTimeOffsets.back(), vTimeOffsets.back()/60);
0843     if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
0844     {
0845         sort(vTimeOffsets.begin(), vTimeOffsets.end());
0846         int64 nMedian = vTimeOffsets[vTimeOffsets.size()/2];
0847         // Only let other nodes change our time by so much
0848         if (abs64(nMedian) < 70 * 60)
0849         {
0850             nTimeOffset = nMedian;
0851         }
0852         else
0853         {
0854             nTimeOffset = 0;
0855 
0856             static bool fDone;
0857             if (!fDone)
0858             {
0859                 // If nobody has a time different than ours but within 5 minutes of ours, give a warning
0860                 bool fMatch = false;
0861                 BOOST_FOREACH(int64 nOffset, vTimeOffsets)
0862                     if (nOffset != 0 && abs64(nOffset) < 5 * 60)
0863                         fMatch = true;
0864 
0865                 if (!fMatch)
0866                 {
0867                     fDone = true;
0868                     string strMessage = _("Warning: Please check that your computer's date and time are correct.  If your clock is wrong Bitcoin will not work properly.");
0869                     strMiscWarning = strMessage;
0870                     printf("*** %s\n", strMessage.c_str());
0871                     boost::thread(boost::bind(ThreadSafeMessageBox, strMessage+" ", string("Bitcoin"), wxOK | wxICON_EXCLAMATION, (wxWindow*)NULL, -1, -1));
0872                 }
0873             }
0874         }
0875         BOOST_FOREACH(int64 n, vTimeOffsets)
0876             printf("%+"PRI64d"  ", n);
0877         printf("|  nTimeOffset = %+"PRI64d"  (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
0878     }
0879 }
0880 
0881 
0882 
0883 
0884 
0885 
0886 
0887 
0888 
0889 string FormatVersion(int nVersion)
0890 {
0891     if (nVersion%100 == 0)
0892         return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
0893     else
0894         return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
0895 }
0896 
0897 string FormatFullVersion()
0898 {
0899     string s = FormatVersion(VERSION) + pszSubVer;
0900     if (VERSION_IS_BETA) {
0901         s += "-";
0902         s += _("beta");
0903     }
0904     return s;
0905 }
0906 
0907 
0908 
0909 
0910 #ifdef DEBUG_LOCKORDER
0911 //
0912 // Early deadlock detection.
0913 // Problem being solved:
0914 //    Thread 1 locks  A, then B, then C
0915 //    Thread 2 locks  D, then C, then A
0916 //     --> may result in deadlock between the two threads, depending on when they run.
0917 // Solution implemented here:
0918 // Keep track of pairs of locks: (A before B), (A before C), etc.
0919 // Complain if any thread trys to lock in a different order.
0920 //
0921 
0922 struct CLockLocation
0923 {
0924     CLockLocation(const char* pszName, const char* pszFile, int nLine)
0925     {
0926         mutexName = pszName;
0927         sourceFile = pszFile;
0928         sourceLine = nLine;
0929     }
0930 
0931     std::string ToString() const
0932     {
0933         return mutexName+"  "+sourceFile+":"+itostr(sourceLine);
0934     }
0935 
0936 private:
0937     std::string mutexName;
0938     std::string sourceFile;
0939     int sourceLine;
0940 };
0941 
0942 typedef std::vector< std::pair<CCriticalSection*, CLockLocation> > LockStack;
0943 
0944 static boost::interprocess::interprocess_mutex dd_mutex;
0945 static std::map<std::pair<CCriticalSection*, CCriticalSection*>, LockStack> lockorders;
0946 static boost::thread_specific_ptr<LockStack> lockstack;
0947 
0948 
0949 static void potential_deadlock_detected(const std::pair<CCriticalSection*, CCriticalSection*>& mismatch, const LockStack& s1, const LockStack& s2)
0950 {
0951     printf("POTENTIAL DEADLOCK DETECTED\n");
0952     printf("Previous lock order was:\n");
0953     BOOST_FOREACH(const PAIRTYPE(CCriticalSection*, CLockLocation)& i, s2)
0954     {
0955         if (i.first == mismatch.first) printf(" (1)");
0956         if (i.first == mismatch.second) printf(" (2)");
0957         printf(" %s\n", i.second.ToString().c_str());
0958     }
0959     printf("Current lock order is:\n");
0960     BOOST_FOREACH(const PAIRTYPE(CCriticalSection*, CLockLocation)& i, s1)
0961     {
0962         if (i.first == mismatch.first) printf(" (1)");
0963         if (i.first == mismatch.second) printf(" (2)");
0964         printf(" %s\n", i.second.ToString().c_str());
0965     }
0966 }
0967 
0968 static void push_lock(CCriticalSection* c, const CLockLocation& locklocation)
0969 {
0970     bool fOrderOK = true;
0971     if (lockstack.get() == NULL)
0972         lockstack.reset(new LockStack);
0973 
0974     if (fDebug) printf("Locking: %s\n", locklocation.ToString().c_str());
0975     dd_mutex.lock();
0976 
0977     (*lockstack).push_back(std::make_pair(c, locklocation));
0978 
0979     BOOST_FOREACH(const PAIRTYPE(CCriticalSection*, CLockLocation)& i, (*lockstack))
0980     {
0981         if (i.first == c) break;
0982 
0983         std::pair<CCriticalSection*, CCriticalSection*> p1 = std::make_pair(i.first, c);
0984         if (lockorders.count(p1))
0985             continue;
0986         lockorders[p1] = (*lockstack);
0987 
0988         std::pair<CCriticalSection*, CCriticalSection*> p2 = std::make_pair(c, i.first);
0989         if (lockorders.count(p2))
0990         {
0991             potential_deadlock_detected(p1, lockorders[p2], lockorders[p1]);
0992             break;
0993         }
0994     }
0995     dd_mutex.unlock();
0996 }
0997 
0998 static void pop_lock()
0999 {
1000     if (fDebug) 
1001     {
1002         const CLockLocation& locklocation = (*lockstack).rbegin()->second;
1003         printf("Unlocked: %s\n", locklocation.ToString().c_str());
1004     }
1005     dd_mutex.lock();
1006     (*lockstack).pop_back();
1007     dd_mutex.unlock();
1008 }
1009 
1010 void CCriticalSection::Enter(const char* pszName, const char* pszFile, int nLine)
1011 {
1012     push_lock(this, CLockLocation(pszName, pszFile, nLine));
1013     mutex.lock();
1014 }
1015 void CCriticalSection::Leave()
1016 {
1017     mutex.unlock();
1018     pop_lock();
1019 }
1020 bool CCriticalSection::TryEnter(const char* pszName, const char* pszFile, int nLine)
1021 {
1022     push_lock(this, CLockLocation(pszName, pszFile, nLine));
1023     bool result = mutex.try_lock();
1024     if (!result) pop_lock();
1025     return result;
1026 }
1027 
1028 #else
1029 
1030 void CCriticalSection::Enter(const char*, const char*, int)
1031 {
1032     mutex.lock();
1033 }
1034 
1035 void CCriticalSection::Leave()
1036 {
1037     mutex.unlock();
1038 }
1039 
1040 bool CCriticalSection::TryEnter(const char*, const char*, int)
1041 {
1042     bool result = mutex.try_lock();
1043     return result;
1044 }
1045 
1046 #endif /* DEBUG_LOCKORDER */