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