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