0f496bc455afcf4a288361b28f7462a850d92219
[novacoin.git] / src / util.cpp
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.
5 #include "headers.h"
6 #include "strlcpy.h"
7 #include <boost/program_options/detail/config_file.hpp>
8 #include <boost/program_options/parsers.hpp>
9 #include <boost/filesystem.hpp>
10 #include <boost/filesystem/fstream.hpp>
11 #include <boost/interprocess/sync/interprocess_mutex.hpp>
12 #include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>
13 #include <boost/foreach.hpp>
14
15 using namespace std;
16 using namespace boost;
17
18 map<string, string> mapArgs;
19 map<string, vector<string> > mapMultiArgs;
20 bool fDebug = false;
21 bool fPrintToConsole = false;
22 bool fPrintToDebugger = false;
23 char pszSetDataDir[MAX_PATH] = "";
24 bool fRequestShutdown = false;
25 bool fShutdown = false;
26 bool fDaemon = false;
27 bool fServer = false;
28 bool fCommandLine = false;
29 string strMiscWarning;
30 bool fTestNet = false;
31 bool fNoListen = false;
32 bool fLogTimestamps = false;
33
34
35
36
37 // Workaround for "multiple definition of `_tls_used'"
38 // http://svn.boost.org/trac/boost/ticket/4258
39 extern "C" void tss_cleanup_implemented() { }
40
41
42
43
44
45 // Init openssl library multithreading support
46 static boost::interprocess::interprocess_mutex** ppmutexOpenSSL;
47 void locking_callback(int mode, int i, const char* file, int line)
48 {
49     if (mode & CRYPTO_LOCK)
50         ppmutexOpenSSL[i]->lock();
51     else
52         ppmutexOpenSSL[i]->unlock();
53 }
54
55 // Init
56 class CInit
57 {
58 public:
59     CInit()
60     {
61         // Init openssl library multithreading support
62         ppmutexOpenSSL = (boost::interprocess::interprocess_mutex**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(boost::interprocess::interprocess_mutex*));
63         for (int i = 0; i < CRYPTO_num_locks(); i++)
64             ppmutexOpenSSL[i] = new boost::interprocess::interprocess_mutex();
65         CRYPTO_set_locking_callback(locking_callback);
66
67 #ifdef __WXMSW__
68         // Seed random number generator with screen scrape and other hardware sources
69         RAND_screen();
70 #endif
71
72         // Seed random number generator with performance counter
73         RandAddSeed();
74     }
75     ~CInit()
76     {
77         // Shutdown openssl library multithreading support
78         CRYPTO_set_locking_callback(NULL);
79         for (int i = 0; i < CRYPTO_num_locks(); i++)
80             delete ppmutexOpenSSL[i];
81         OPENSSL_free(ppmutexOpenSSL);
82     }
83 }
84 instance_of_cinit;
85
86
87
88
89
90
91
92
93 void RandAddSeed()
94 {
95     // Seed with CPU performance counter
96     int64 nCounter = GetPerformanceCounter();
97     RAND_add(&nCounter, sizeof(nCounter), 1.5);
98     memset(&nCounter, 0, sizeof(nCounter));
99 }
100
101 void RandAddSeedPerfmon()
102 {
103     RandAddSeed();
104
105     // This can take up to 2 seconds, so only do it every 10 minutes
106     static int64 nLastPerfmon;
107     if (GetTime() < nLastPerfmon + 10 * 60)
108         return;
109     nLastPerfmon = GetTime();
110
111 #ifdef __WXMSW__
112     // Don't need this on Linux, OpenSSL automatically uses /dev/urandom
113     // Seed with the entire set of perfmon data
114     unsigned char pdata[250000];
115     memset(pdata, 0, sizeof(pdata));
116     unsigned long nSize = sizeof(pdata);
117     long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
118     RegCloseKey(HKEY_PERFORMANCE_DATA);
119     if (ret == ERROR_SUCCESS)
120     {
121         RAND_add(pdata, nSize, nSize/100.0);
122         memset(pdata, 0, nSize);
123         printf("%s RandAddSeed() %d bytes\n", DateTimeStrFormat("%x %H:%M", GetTime()).c_str(), nSize);
124     }
125 #endif
126 }
127
128 uint64 GetRand(uint64 nMax)
129 {
130     if (nMax == 0)
131         return 0;
132
133     // The range of the random source must be a multiple of the modulus
134     // to give every possible output value an equal possibility
135     uint64 nRange = (UINT64_MAX / nMax) * nMax;
136     uint64 nRand = 0;
137     do
138         RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
139     while (nRand >= nRange);
140     return (nRand % nMax);
141 }
142
143 int GetRandInt(int nMax)
144 {
145     return GetRand(nMax);
146 }
147
148
149
150
151
152
153
154
155
156
157
158 inline int OutputDebugStringF(const char* pszFormat, ...)
159 {
160     int ret = 0;
161     if (fPrintToConsole)
162     {
163         // print to console
164         va_list arg_ptr;
165         va_start(arg_ptr, pszFormat);
166         ret = vprintf(pszFormat, arg_ptr);
167         va_end(arg_ptr);
168     }
169     else
170     {
171         // print to debug.log
172         static FILE* fileout = NULL;
173
174         if (!fileout)
175         {
176             char pszFile[MAX_PATH+100];
177             GetDataDir(pszFile);
178             strlcat(pszFile, "/debug.log", sizeof(pszFile));
179             fileout = fopen(pszFile, "a");
180             if (fileout) setbuf(fileout, NULL); // unbuffered
181         }
182         if (fileout)
183         {
184             static bool fStartedNewLine = true;
185
186             // Debug print useful for profiling
187             if (fLogTimestamps && fStartedNewLine)
188                 fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
189             if (pszFormat[strlen(pszFormat) - 1] == '\n')
190                 fStartedNewLine = true;
191             else
192                 fStartedNewLine = false;
193
194             va_list arg_ptr;
195             va_start(arg_ptr, pszFormat);
196             ret = vfprintf(fileout, pszFormat, arg_ptr);
197             va_end(arg_ptr);
198         }
199     }
200
201 #ifdef __WXMSW__
202     if (fPrintToDebugger)
203     {
204         static CCriticalSection cs_OutputDebugStringF;
205
206         // accumulate a line at a time
207         CRITICAL_BLOCK(cs_OutputDebugStringF)
208         {
209             static char pszBuffer[50000];
210             static char* pend;
211             if (pend == NULL)
212                 pend = pszBuffer;
213             va_list arg_ptr;
214             va_start(arg_ptr, pszFormat);
215             int limit = END(pszBuffer) - pend - 2;
216             int ret = _vsnprintf(pend, limit, pszFormat, arg_ptr);
217             va_end(arg_ptr);
218             if (ret < 0 || ret >= limit)
219             {
220                 pend = END(pszBuffer) - 2;
221                 *pend++ = '\n';
222             }
223             else
224                 pend += ret;
225             *pend = '\0';
226             char* p1 = pszBuffer;
227             char* p2;
228             while (p2 = strchr(p1, '\n'))
229             {
230                 p2++;
231                 char c = *p2;
232                 *p2 = '\0';
233                 OutputDebugStringA(p1);
234                 *p2 = c;
235                 p1 = p2;
236             }
237             if (p1 != pszBuffer)
238                 memmove(pszBuffer, p1, pend - p1 + 1);
239             pend -= (p1 - pszBuffer);
240         }
241     }
242 #endif
243     return ret;
244 }
245
246
247 // Safer snprintf
248 //  - prints up to limit-1 characters
249 //  - output string is always null terminated even if limit reached
250 //  - return value is the number of characters actually printed
251 int my_snprintf(char* buffer, size_t limit, const char* format, ...)
252 {
253     if (limit == 0)
254         return 0;
255     va_list arg_ptr;
256     va_start(arg_ptr, format);
257     int ret = _vsnprintf(buffer, limit, format, arg_ptr);
258     va_end(arg_ptr);
259     if (ret < 0 || ret >= limit)
260     {
261         ret = limit - 1;
262         buffer[limit-1] = 0;
263     }
264     return ret;
265 }
266
267
268 string strprintf(const char* format, ...)
269 {
270     char buffer[50000];
271     char* p = buffer;
272     int limit = sizeof(buffer);
273     int ret;
274     loop
275     {
276         va_list arg_ptr;
277         va_start(arg_ptr, format);
278         ret = _vsnprintf(p, limit, format, arg_ptr);
279         va_end(arg_ptr);
280         if (ret >= 0 && ret < limit)
281             break;
282         if (p != buffer)
283             delete[] p;
284         limit *= 2;
285         p = new char[limit];
286         if (p == NULL)
287             throw std::bad_alloc();
288     }
289     string str(p, p+ret);
290     if (p != buffer)
291         delete[] p;
292     return str;
293 }
294
295
296 bool error(const char* format, ...)
297 {
298     char buffer[50000];
299     int limit = sizeof(buffer);
300     va_list arg_ptr;
301     va_start(arg_ptr, format);
302     int ret = _vsnprintf(buffer, limit, format, arg_ptr);
303     va_end(arg_ptr);
304     if (ret < 0 || ret >= limit)
305     {
306         ret = limit - 1;
307         buffer[limit-1] = 0;
308     }
309     printf("ERROR: %s\n", buffer);
310     return false;
311 }
312
313
314 void ParseString(const string& str, char c, vector<string>& v)
315 {
316     if (str.empty())
317         return;
318     string::size_type i1 = 0;
319     string::size_type i2;
320     loop
321     {
322         i2 = str.find(c, i1);
323         if (i2 == str.npos)
324         {
325             v.push_back(str.substr(i1));
326             return;
327         }
328         v.push_back(str.substr(i1, i2-i1));
329         i1 = i2+1;
330     }
331 }
332
333
334 string FormatMoney(int64 n, bool fPlus)
335 {
336     // Note: not using straight sprintf here because we do NOT want
337     // localized number formatting.
338     int64 n_abs = (n > 0 ? n : -n);
339     int64 quotient = n_abs/COIN;
340     int64 remainder = n_abs%COIN;
341     string str = strprintf("%"PRI64d".%08"PRI64d, quotient, remainder);
342
343     // Right-trim excess 0's before the decimal point:
344     int nTrim = 0;
345     for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
346         ++nTrim;
347     if (nTrim)
348         str.erase(str.size()-nTrim, nTrim);
349
350     if (n < 0)
351         str.insert((unsigned int)0, 1, '-');
352     else if (fPlus && n > 0)
353         str.insert((unsigned int)0, 1, '+');
354     return str;
355 }
356
357
358 bool ParseMoney(const string& str, int64& nRet)
359 {
360     return ParseMoney(str.c_str(), nRet);
361 }
362
363 bool ParseMoney(const char* pszIn, int64& nRet)
364 {
365     string strWhole;
366     int64 nUnits = 0;
367     const char* p = pszIn;
368     while (isspace(*p))
369         p++;
370     for (; *p; p++)
371     {
372         if (*p == '.')
373         {
374             p++;
375             int64 nMult = CENT*10;
376             while (isdigit(*p) && (nMult > 0))
377             {
378                 nUnits += nMult * (*p++ - '0');
379                 nMult /= 10;
380             }
381             break;
382         }
383         if (isspace(*p))
384             break;
385         if (!isdigit(*p))
386             return false;
387         strWhole.insert(strWhole.end(), *p);
388     }
389     for (; *p; p++)
390         if (!isspace(*p))
391             return false;
392     if (strWhole.size() > 10) // guard against 63 bit overflow
393         return false;
394     if (nUnits < 0 || nUnits > COIN)
395         return false;
396     int64 nWhole = atoi64(strWhole);
397     int64 nValue = nWhole*COIN + nUnits;
398
399     nRet = nValue;
400     return true;
401 }
402
403
404 vector<unsigned char> ParseHex(const char* psz)
405 {
406     static char phexdigit[256] =
407     { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
408       -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
409       -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
410       0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
411       -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
412       -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
413       -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1
414       -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
415       -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
416       -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
417       -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
418       -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
419       -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
420       -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
421       -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
422       -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
423
424     // convert hex dump to vector
425     vector<unsigned char> vch;
426     loop
427     {
428         while (isspace(*psz))
429             psz++;
430         char c = phexdigit[(unsigned char)*psz++];
431         if (c == (char)-1)
432             break;
433         unsigned char n = (c << 4);
434         c = phexdigit[(unsigned char)*psz++];
435         if (c == (char)-1)
436             break;
437         n |= c;
438         vch.push_back(n);
439     }
440     return vch;
441 }
442
443 vector<unsigned char> ParseHex(const string& str)
444 {
445     return ParseHex(str.c_str());
446 }
447
448
449 void ParseParameters(int argc, char* argv[])
450 {
451     mapArgs.clear();
452     mapMultiArgs.clear();
453     for (int i = 1; i < argc; i++)
454     {
455         char psz[10000];
456         strlcpy(psz, argv[i], sizeof(psz));
457         char* pszValue = (char*)"";
458         if (strchr(psz, '='))
459         {
460             pszValue = strchr(psz, '=');
461             *pszValue++ = '\0';
462         }
463         #ifdef __WXMSW__
464         _strlwr(psz);
465         if (psz[0] == '/')
466             psz[0] = '-';
467         #endif
468         if (psz[0] != '-')
469             break;
470         mapArgs[psz] = pszValue;
471         mapMultiArgs[psz].push_back(pszValue);
472     }
473 }
474
475 bool SoftSetArg(const std::string& strArg, const std::string& strValue)
476 {
477     if (mapArgs.count(strArg))
478         return false;
479     mapArgs[strArg] = strValue;
480     return true;
481 }
482
483 bool SoftSetArg(const std::string& strArg, bool fValue)
484 {
485     if (fValue)
486         return SoftSetArg(strArg, std::string("1"));
487     else
488         return SoftSetArg(strArg, std::string("0"));
489 }
490
491
492
493 const char* wxGetTranslation(const char* pszEnglish)
494 {
495 #ifdef GUI
496     // Wrapper of wxGetTranslation returning the same const char* type as was passed in
497     static CCriticalSection cs;
498     CRITICAL_BLOCK(cs)
499     {
500         // Look in cache
501         static map<string, char*> mapCache;
502         map<string, char*>::iterator mi = mapCache.find(pszEnglish);
503         if (mi != mapCache.end())
504             return (*mi).second;
505
506         // wxWidgets translation
507         wxString strTranslated = wxGetTranslation(wxString(pszEnglish, wxConvUTF8));
508
509         // We don't cache unknown strings because caller might be passing in a
510         // dynamic string and we would keep allocating memory for each variation.
511         if (strcmp(pszEnglish, strTranslated.utf8_str()) == 0)
512             return pszEnglish;
513
514         // Add to cache, memory doesn't need to be freed.  We only cache because
515         // we must pass back a pointer to permanently allocated memory.
516         char* pszCached = new char[strlen(strTranslated.utf8_str())+1];
517         strcpy(pszCached, strTranslated.utf8_str());
518         mapCache[pszEnglish] = pszCached;
519         return pszCached;
520     }
521     return NULL;
522 #else
523     return pszEnglish;
524 #endif
525 }
526
527
528 bool WildcardMatch(const char* psz, const char* mask)
529 {
530     loop
531     {
532         switch (*mask)
533         {
534         case '\0':
535             return (*psz == '\0');
536         case '*':
537             return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
538         case '?':
539             if (*psz == '\0')
540                 return false;
541             break;
542         default:
543             if (*psz != *mask)
544                 return false;
545             break;
546         }
547         psz++;
548         mask++;
549     }
550 }
551
552 bool WildcardMatch(const string& str, const string& mask)
553 {
554     return WildcardMatch(str.c_str(), mask.c_str());
555 }
556
557
558
559
560
561
562
563
564 void FormatException(char* pszMessage, std::exception* pex, const char* pszThread)
565 {
566 #ifdef __WXMSW__
567     char pszModule[MAX_PATH];
568     pszModule[0] = '\0';
569     GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
570 #else
571     const char* pszModule = "bitcoin";
572 #endif
573     if (pex)
574         snprintf(pszMessage, 1000,
575             "EXCEPTION: %s       \n%s       \n%s in %s       \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
576     else
577         snprintf(pszMessage, 1000,
578             "UNKNOWN EXCEPTION       \n%s in %s       \n", pszModule, pszThread);
579 }
580
581 void LogException(std::exception* pex, const char* pszThread)
582 {
583     char pszMessage[10000];
584     FormatException(pszMessage, pex, pszThread);
585     printf("\n%s", pszMessage);
586 }
587
588 void PrintException(std::exception* pex, const char* pszThread)
589 {
590     char pszMessage[10000];
591     FormatException(pszMessage, pex, pszThread);
592     printf("\n\n************************\n%s\n", pszMessage);
593     fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
594     strMiscWarning = pszMessage;
595 #ifdef GUI
596     if (wxTheApp && !fDaemon)
597         MyMessageBox(pszMessage, "Bitcoin", wxOK | wxICON_ERROR);
598 #endif
599     throw;
600 }
601
602 void ThreadOneMessageBox(string strMessage)
603 {
604     // Skip message boxes if one is already open
605     static bool fMessageBoxOpen;
606     if (fMessageBoxOpen)
607         return;
608     fMessageBoxOpen = true;
609     ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
610     fMessageBoxOpen = false;
611 }
612
613 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
614 {
615     char pszMessage[10000];
616     FormatException(pszMessage, pex, pszThread);
617     printf("\n\n************************\n%s\n", pszMessage);
618     fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
619     strMiscWarning = pszMessage;
620 #ifdef GUI
621     if (wxTheApp && !fDaemon)
622         boost::thread(boost::bind(ThreadOneMessageBox, string(pszMessage)));
623 #endif
624 }
625
626
627
628
629
630
631
632
633 #ifdef __WXMSW__
634 typedef WINSHELLAPI BOOL (WINAPI *PSHGETSPECIALFOLDERPATHA)(HWND hwndOwner, LPSTR lpszPath, int nFolder, BOOL fCreate);
635
636 string MyGetSpecialFolderPath(int nFolder, bool fCreate)
637 {
638     char pszPath[MAX_PATH+100] = "";
639
640     // SHGetSpecialFolderPath isn't always available on old Windows versions
641     HMODULE hShell32 = LoadLibraryA("shell32.dll");
642     if (hShell32)
643     {
644         PSHGETSPECIALFOLDERPATHA pSHGetSpecialFolderPath =
645             (PSHGETSPECIALFOLDERPATHA)GetProcAddress(hShell32, "SHGetSpecialFolderPathA");
646         bool fSuccess = false;
647         if (pSHGetSpecialFolderPath)
648             fSuccess =
649             (*pSHGetSpecialFolderPath)(NULL, pszPath, nFolder, fCreate);
650         FreeModule(hShell32);
651         if (fSuccess)
652             return pszPath;
653     }
654
655     // Backup option
656     std::string strPath;
657     {
658         const char *pszEnv;
659         if (nFolder == CSIDL_STARTUP)
660         {
661             pszEnv = getenv("USERPROFILE");
662             if (pszEnv)
663                 strPath = pszEnv;
664             strPath += "\\Start Menu\\Programs\\Startup";
665         }
666         else if (nFolder == CSIDL_APPDATA)
667         {
668             pszEnv = getenv("APPDATA");
669             if (pszEnv)
670                 strPath = pszEnv;
671         }
672     }
673
674     return strPath;
675 }
676 #endif
677
678 string GetDefaultDataDir()
679 {
680     // Windows: C:\Documents and Settings\username\Application Data\Bitcoin
681     // Mac: ~/Library/Application Support/Bitcoin
682     // Unix: ~/.bitcoin
683 #ifdef __WXMSW__
684     // Windows
685     return MyGetSpecialFolderPath(CSIDL_APPDATA, true) + "\\Bitcoin";
686 #else
687     char* pszHome = getenv("HOME");
688     if (pszHome == NULL || strlen(pszHome) == 0)
689         pszHome = (char*)"/";
690     string strHome = pszHome;
691     if (strHome[strHome.size()-1] != '/')
692         strHome += '/';
693 #ifdef __WXMAC_OSX__
694     // Mac
695     strHome += "Library/Application Support/";
696     filesystem::create_directory(strHome.c_str());
697     return strHome + "Bitcoin";
698 #else
699     // Unix
700     return strHome + ".bitcoin";
701 #endif
702 #endif
703 }
704
705 void GetDataDir(char* pszDir)
706 {
707     // pszDir must be at least MAX_PATH length.
708     int nVariation;
709     if (pszSetDataDir[0] != 0)
710     {
711         strlcpy(pszDir, pszSetDataDir, MAX_PATH);
712         nVariation = 0;
713     }
714     else
715     {
716         // This can be called during exceptions by printf, so we cache the
717         // value so we don't have to do memory allocations after that.
718         static char pszCachedDir[MAX_PATH];
719         if (pszCachedDir[0] == 0)
720             strlcpy(pszCachedDir, GetDefaultDataDir().c_str(), sizeof(pszCachedDir));
721         strlcpy(pszDir, pszCachedDir, MAX_PATH);
722         nVariation = 1;
723     }
724     if (fTestNet)
725     {
726         char* p = pszDir + strlen(pszDir);
727         if (p > pszDir && p[-1] != '/' && p[-1] != '\\')
728             *p++ = '/';
729         strcpy(p, "testnet");
730         nVariation += 2;
731     }
732     static bool pfMkdir[4];
733     if (!pfMkdir[nVariation])
734     {
735         pfMkdir[nVariation] = true;
736         boost::filesystem::create_directory(pszDir);
737     }
738 }
739
740 string GetDataDir()
741 {
742     char pszDir[MAX_PATH];
743     GetDataDir(pszDir);
744     return pszDir;
745 }
746
747 string GetConfigFile()
748 {
749     namespace fs = boost::filesystem;
750     fs::path pathConfig(GetArg("-conf", "bitcoin.conf"));
751     if (!pathConfig.is_complete())
752         pathConfig = fs::path(GetDataDir()) / pathConfig;
753     return pathConfig.string();
754 }
755
756 void ReadConfigFile(map<string, string>& mapSettingsRet,
757                     map<string, vector<string> >& mapMultiSettingsRet)
758 {
759     namespace fs = boost::filesystem;
760     namespace pod = boost::program_options::detail;
761
762     fs::ifstream streamConfig(GetConfigFile());
763     if (!streamConfig.good())
764         return;
765
766     set<string> setOptions;
767     setOptions.insert("*");
768     
769     for (pod::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
770     {
771         // Don't overwrite existing settings so command line settings override bitcoin.conf
772         string strKey = string("-") + it->string_key;
773         if (mapSettingsRet.count(strKey) == 0)
774             mapSettingsRet[strKey] = it->value[0];
775         mapMultiSettingsRet[strKey].push_back(it->value[0]);
776     }
777 }
778
779 string GetPidFile()
780 {
781     namespace fs = boost::filesystem;
782     fs::path pathConfig(GetArg("-pid", "bitcoind.pid"));
783     if (!pathConfig.is_complete())
784         pathConfig = fs::path(GetDataDir()) / pathConfig;
785     return pathConfig.string();
786 }
787
788 void CreatePidFile(string pidFile, pid_t pid)
789 {
790     FILE* file = fopen(pidFile.c_str(), "w");
791     if (file)
792     {
793         fprintf(file, "%d\n", pid);
794         fclose(file);
795     }
796 }
797
798 int GetFilesize(FILE* file)
799 {
800     int nSavePos = ftell(file);
801     int nFilesize = -1;
802     if (fseek(file, 0, SEEK_END) == 0)
803         nFilesize = ftell(file);
804     fseek(file, nSavePos, SEEK_SET);
805     return nFilesize;
806 }
807
808 void ShrinkDebugFile()
809 {
810     // Scroll debug.log if it's getting too big
811     string strFile = GetDataDir() + "/debug.log";
812     FILE* file = fopen(strFile.c_str(), "r");
813     if (file && GetFilesize(file) > 10 * 1000000)
814     {
815         // Restart the file with some of the end
816         char pch[200000];
817         fseek(file, -sizeof(pch), SEEK_END);
818         int nBytes = fread(pch, 1, sizeof(pch), file);
819         fclose(file);
820
821         file = fopen(strFile.c_str(), "w");
822         if (file)
823         {
824             fwrite(pch, 1, nBytes, file);
825             fclose(file);
826         }
827     }
828 }
829
830
831
832
833
834
835
836
837 //
838 // "Never go to sea with two chronometers; take one or three."
839 // Our three time sources are:
840 //  - System clock
841 //  - Median of other nodes's clocks
842 //  - The user (asking the user to fix the system clock if the first two disagree)
843 //
844 int64 GetTime()
845 {
846     return time(NULL);
847 }
848
849 static int64 nTimeOffset = 0;
850
851 int64 GetAdjustedTime()
852 {
853     return GetTime() + nTimeOffset;
854 }
855
856 void AddTimeData(unsigned int ip, int64 nTime)
857 {
858     int64 nOffsetSample = nTime - GetTime();
859
860     // Ignore duplicates
861     static set<unsigned int> setKnown;
862     if (!setKnown.insert(ip).second)
863         return;
864
865     // Add data
866     static vector<int64> vTimeOffsets;
867     if (vTimeOffsets.empty())
868         vTimeOffsets.push_back(0);
869     vTimeOffsets.push_back(nOffsetSample);
870     printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), vTimeOffsets.back(), vTimeOffsets.back()/60);
871     if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
872     {
873         sort(vTimeOffsets.begin(), vTimeOffsets.end());
874         int64 nMedian = vTimeOffsets[vTimeOffsets.size()/2];
875         // Only let other nodes change our time by so much
876         if (abs64(nMedian) < 70 * 60)
877         {
878             nTimeOffset = nMedian;
879         }
880         else
881         {
882             nTimeOffset = 0;
883
884             static bool fDone;
885             if (!fDone)
886             {
887                 // If nobody has a time different than ours but within 5 minutes of ours, give a warning
888                 bool fMatch = false;
889                 BOOST_FOREACH(int64 nOffset, vTimeOffsets)
890                     if (nOffset != 0 && abs64(nOffset) < 5 * 60)
891                         fMatch = true;
892
893                 if (!fMatch)
894                 {
895                     fDone = true;
896                     string strMessage = _("Warning: Please check that your computer's date and time are correct.  If your clock is wrong Bitcoin will not work properly.");
897                     strMiscWarning = strMessage;
898                     printf("*** %s\n", strMessage.c_str());
899                     boost::thread(boost::bind(ThreadSafeMessageBox, strMessage+" ", string("Bitcoin"), wxOK | wxICON_EXCLAMATION, (wxWindow*)NULL, -1, -1));
900                 }
901             }
902         }
903         BOOST_FOREACH(int64 n, vTimeOffsets)
904             printf("%+"PRI64d"  ", n);
905         printf("|  nTimeOffset = %+"PRI64d"  (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
906     }
907 }
908
909
910
911
912
913
914
915
916
917 string FormatVersion(int nVersion)
918 {
919     if (nVersion%100 == 0)
920         return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
921     else
922         return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
923 }
924
925 string FormatFullVersion()
926 {
927     string s = FormatVersion(VERSION) + pszSubVer;
928     if (VERSION_IS_BETA) {
929         s += "-";
930         s += _("beta");
931     }
932     return s;
933 }
934
935
936
937
938 #ifdef DEBUG_LOCKORDER
939 //
940 // Early deadlock detection.
941 // Problem being solved:
942 //    Thread 1 locks  A, then B, then C
943 //    Thread 2 locks  D, then C, then A
944 //     --> may result in deadlock between the two threads, depending on when they run.
945 // Solution implemented here:
946 // Keep track of pairs of locks: (A before B), (A before C), etc.
947 // Complain if any thread trys to lock in a different order.
948 //
949
950 struct CLockLocation
951 {
952     CLockLocation(const char* pszName, const char* pszFile, int nLine)
953     {
954         mutexName = pszName;
955         sourceFile = pszFile;
956         sourceLine = nLine;
957     }
958
959     std::string ToString() const
960     {
961         return mutexName+"  "+sourceFile+":"+itostr(sourceLine);
962     }
963
964 private:
965     std::string mutexName;
966     std::string sourceFile;
967     int sourceLine;
968 };
969
970 typedef std::vector< std::pair<CCriticalSection*, CLockLocation> > LockStack;
971
972 static boost::interprocess::interprocess_mutex dd_mutex;
973 static std::map<std::pair<CCriticalSection*, CCriticalSection*>, LockStack> lockorders;
974 static boost::thread_specific_ptr<LockStack> lockstack;
975
976
977 static void potential_deadlock_detected(const std::pair<CCriticalSection*, CCriticalSection*>& mismatch, const LockStack& s1, const LockStack& s2)
978 {
979     printf("POTENTIAL DEADLOCK DETECTED\n");
980     printf("Previous lock order was:\n");
981     BOOST_FOREACH(const PAIRTYPE(CCriticalSection*, CLockLocation)& i, s2)
982     {
983         if (i.first == mismatch.first) printf(" (1)");
984         if (i.first == mismatch.second) printf(" (2)");
985         printf(" %s\n", i.second.ToString().c_str());
986     }
987     printf("Current lock order is:\n");
988     BOOST_FOREACH(const PAIRTYPE(CCriticalSection*, CLockLocation)& i, s1)
989     {
990         if (i.first == mismatch.first) printf(" (1)");
991         if (i.first == mismatch.second) printf(" (2)");
992         printf(" %s\n", i.second.ToString().c_str());
993     }
994 }
995
996 static void push_lock(CCriticalSection* c, const CLockLocation& locklocation)
997 {
998     bool fOrderOK = true;
999     if (lockstack.get() == NULL)
1000         lockstack.reset(new LockStack);
1001
1002     if (fDebug) printf("Locking: %s\n", locklocation.ToString().c_str());
1003     dd_mutex.lock();
1004
1005     (*lockstack).push_back(std::make_pair(c, locklocation));
1006
1007     BOOST_FOREACH(const PAIRTYPE(CCriticalSection*, CLockLocation)& i, (*lockstack))
1008     {
1009         if (i.first == c) break;
1010
1011         std::pair<CCriticalSection*, CCriticalSection*> p1 = std::make_pair(i.first, c);
1012         if (lockorders.count(p1))
1013             continue;
1014         lockorders[p1] = (*lockstack);
1015
1016         std::pair<CCriticalSection*, CCriticalSection*> p2 = std::make_pair(c, i.first);
1017         if (lockorders.count(p2))
1018         {
1019             potential_deadlock_detected(p1, lockorders[p2], lockorders[p1]);
1020             break;
1021         }
1022     }
1023     dd_mutex.unlock();
1024 }
1025
1026 static void pop_lock()
1027 {
1028     if (fDebug) 
1029     {
1030         const CLockLocation& locklocation = (*lockstack).rbegin()->second;
1031         printf("Unlocked: %s\n", locklocation.ToString().c_str());
1032     }
1033     dd_mutex.lock();
1034     (*lockstack).pop_back();
1035     dd_mutex.unlock();
1036 }
1037
1038 void CCriticalSection::Enter(const char* pszName, const char* pszFile, int nLine)
1039 {
1040     push_lock(this, CLockLocation(pszName, pszFile, nLine));
1041     mutex.lock();
1042 }
1043 void CCriticalSection::Leave()
1044 {
1045     mutex.unlock();
1046     pop_lock();
1047 }
1048 bool CCriticalSection::TryEnter(const char* pszName, const char* pszFile, int nLine)
1049 {
1050     push_lock(this, CLockLocation(pszName, pszFile, nLine));
1051     bool result = mutex.try_lock();
1052     if (!result) pop_lock();
1053     return result;
1054 }
1055
1056 #else
1057
1058 void CCriticalSection::Enter(const char*, const char*, int)
1059 {
1060     mutex.lock();
1061 }
1062
1063 void CCriticalSection::Leave()
1064 {
1065     mutex.unlock();
1066 }
1067
1068 bool CCriticalSection::TryEnter(const char*, const char*, int)
1069 {
1070     bool result = mutex.try_lock();
1071     return result;
1072 }
1073
1074 #endif /* DEBUG_LOCKORDER */