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