479c601ee585f4b590427853c5f5f529d259a824
[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
267 string strprintf(const char* format, ...)
268 {
269     char buffer[50000];
270     char* p = buffer;
271     int limit = sizeof(buffer);
272     int ret;
273     loop
274     {
275         va_list arg_ptr;
276         va_start(arg_ptr, format);
277         ret = _vsnprintf(p, limit, format, arg_ptr);
278         va_end(arg_ptr);
279         if (ret >= 0 && ret < limit)
280             break;
281         if (p != buffer)
282             delete[] p;
283         limit *= 2;
284         p = new char[limit];
285         if (p == NULL)
286             throw std::bad_alloc();
287     }
288     string str(p, p+ret);
289     if (p != buffer)
290         delete[] p;
291     return str;
292 }
293
294
295 bool error(const char* format, ...)
296 {
297     char buffer[50000];
298     int limit = sizeof(buffer);
299     va_list arg_ptr;
300     va_start(arg_ptr, format);
301     int ret = _vsnprintf(buffer, limit, format, arg_ptr);
302     va_end(arg_ptr);
303     if (ret < 0 || ret >= limit)
304     {
305         ret = limit - 1;
306         buffer[limit-1] = 0;
307     }
308     printf("ERROR: %s\n", buffer);
309     return false;
310 }
311
312
313 void ParseString(const string& str, char c, vector<string>& v)
314 {
315     if (str.empty())
316         return;
317     string::size_type i1 = 0;
318     string::size_type i2;
319     loop
320     {
321         i2 = str.find(c, i1);
322         if (i2 == str.npos)
323         {
324             v.push_back(str.substr(i1));
325             return;
326         }
327         v.push_back(str.substr(i1, i2-i1));
328         i1 = i2+1;
329     }
330 }
331
332
333 string FormatMoney(int64 n, bool fPlus)
334 {
335     // Note: not using straight sprintf here because we do NOT want
336     // localized number formatting.
337     int64 n_abs = (n > 0 ? n : -n);
338     int64 quotient = n_abs/COIN;
339     int64 remainder = n_abs%COIN;
340     string str = strprintf("%"PRI64d".%08"PRI64d, quotient, remainder);
341
342     // Right-trim excess 0's before the decimal point:
343     int nTrim = 0;
344     for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
345         ++nTrim;
346     if (nTrim)
347         str.erase(str.size()-nTrim, nTrim);
348
349     if (n < 0)
350         str.insert((unsigned int)0, 1, '-');
351     else if (fPlus && n > 0)
352         str.insert((unsigned int)0, 1, '+');
353     return str;
354 }
355
356
357 bool ParseMoney(const string& str, int64& nRet)
358 {
359     return ParseMoney(str.c_str(), nRet);
360 }
361
362 bool ParseMoney(const char* pszIn, int64& nRet)
363 {
364     string strWhole;
365     int64 nUnits = 0;
366     const char* p = pszIn;
367     while (isspace(*p))
368         p++;
369     for (; *p; p++)
370     {
371         if (*p == '.')
372         {
373             p++;
374             int64 nMult = CENT*10;
375             while (isdigit(*p) && (nMult > 0))
376             {
377                 nUnits += nMult * (*p++ - '0');
378                 nMult /= 10;
379             }
380             break;
381         }
382         if (isspace(*p))
383             break;
384         if (!isdigit(*p))
385             return false;
386         strWhole.insert(strWhole.end(), *p);
387     }
388     for (; *p; p++)
389         if (!isspace(*p))
390             return false;
391     if (strWhole.size() > 14)
392         return false;
393     if (nUnits < 0 || nUnits > COIN)
394         return false;
395     int64 nWhole = atoi64(strWhole);
396     int64 nValue = nWhole*COIN + nUnits;
397
398     nRet = nValue;
399     return true;
400 }
401
402
403 vector<unsigned char> ParseHex(const char* psz)
404 {
405     static char phexdigit[256] =
406     { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
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       0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
410       -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
411       -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
412       -1,0xa,0xb,0xc,0xd,0xe,0xf,-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       -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
423     // convert hex dump to vector
424     vector<unsigned char> vch;
425     loop
426     {
427         while (isspace(*psz))
428             psz++;
429         char c = phexdigit[(unsigned char)*psz++];
430         if (c == (char)-1)
431             break;
432         unsigned char n = (c << 4);
433         c = phexdigit[(unsigned char)*psz++];
434         if (c == (char)-1)
435             break;
436         n |= c;
437         vch.push_back(n);
438     }
439     return vch;
440 }
441
442 vector<unsigned char> ParseHex(const string& str)
443 {
444     return ParseHex(str.c_str());
445 }
446
447
448 void ParseParameters(int argc, char* argv[])
449 {
450     mapArgs.clear();
451     mapMultiArgs.clear();
452     for (int i = 1; i < argc; i++)
453     {
454         char psz[10000];
455         strlcpy(psz, argv[i], sizeof(psz));
456         char* pszValue = (char*)"";
457         if (strchr(psz, '='))
458         {
459             pszValue = strchr(psz, '=');
460             *pszValue++ = '\0';
461         }
462         #ifdef __WXMSW__
463         _strlwr(psz);
464         if (psz[0] == '/')
465             psz[0] = '-';
466         #endif
467         if (psz[0] != '-')
468             break;
469         mapArgs[psz] = pszValue;
470         mapMultiArgs[psz].push_back(pszValue);
471     }
472 }
473
474
475 const char* wxGetTranslation(const char* pszEnglish)
476 {
477 #ifdef GUI
478     // Wrapper of wxGetTranslation returning the same const char* type as was passed in
479     static CCriticalSection cs;
480     CRITICAL_BLOCK(cs)
481     {
482         // Look in cache
483         static map<string, char*> mapCache;
484         map<string, char*>::iterator mi = mapCache.find(pszEnglish);
485         if (mi != mapCache.end())
486             return (*mi).second;
487
488         // wxWidgets translation
489         wxString strTranslated = wxGetTranslation(wxString(pszEnglish, wxConvUTF8));
490
491         // We don't cache unknown strings because caller might be passing in a
492         // dynamic string and we would keep allocating memory for each variation.
493         if (strcmp(pszEnglish, strTranslated.utf8_str()) == 0)
494             return pszEnglish;
495
496         // Add to cache, memory doesn't need to be freed.  We only cache because
497         // we must pass back a pointer to permanently allocated memory.
498         char* pszCached = new char[strlen(strTranslated.utf8_str())+1];
499         strcpy(pszCached, strTranslated.utf8_str());
500         mapCache[pszEnglish] = pszCached;
501         return pszCached;
502     }
503     return NULL;
504 #else
505     return pszEnglish;
506 #endif
507 }
508
509
510 bool WildcardMatch(const char* psz, const char* mask)
511 {
512     loop
513     {
514         switch (*mask)
515         {
516         case '\0':
517             return (*psz == '\0');
518         case '*':
519             return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
520         case '?':
521             if (*psz == '\0')
522                 return false;
523             break;
524         default:
525             if (*psz != *mask)
526                 return false;
527             break;
528         }
529         psz++;
530         mask++;
531     }
532 }
533
534 bool WildcardMatch(const string& str, const string& mask)
535 {
536     return WildcardMatch(str.c_str(), mask.c_str());
537 }
538
539
540
541
542
543
544
545
546 void FormatException(char* pszMessage, std::exception* pex, const char* pszThread)
547 {
548 #ifdef __WXMSW__
549     char pszModule[MAX_PATH];
550     pszModule[0] = '\0';
551     GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
552 #else
553     const char* pszModule = "bitcoin";
554 #endif
555     if (pex)
556         snprintf(pszMessage, 1000,
557             "EXCEPTION: %s       \n%s       \n%s in %s       \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
558     else
559         snprintf(pszMessage, 1000,
560             "UNKNOWN EXCEPTION       \n%s in %s       \n", pszModule, pszThread);
561 }
562
563 void LogException(std::exception* pex, const char* pszThread)
564 {
565     char pszMessage[10000];
566     FormatException(pszMessage, pex, pszThread);
567     printf("\n%s", pszMessage);
568 }
569
570 void PrintException(std::exception* pex, const char* pszThread)
571 {
572     char pszMessage[10000];
573     FormatException(pszMessage, pex, pszThread);
574     printf("\n\n************************\n%s\n", pszMessage);
575     fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
576     strMiscWarning = pszMessage;
577 #ifdef GUI
578     if (wxTheApp && !fDaemon)
579         MyMessageBox(pszMessage, "Bitcoin", wxOK | wxICON_ERROR);
580 #endif
581     throw;
582 }
583
584 void ThreadOneMessageBox(string strMessage)
585 {
586     // Skip message boxes if one is already open
587     static bool fMessageBoxOpen;
588     if (fMessageBoxOpen)
589         return;
590     fMessageBoxOpen = true;
591     ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
592     fMessageBoxOpen = false;
593 }
594
595 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
596 {
597     char pszMessage[10000];
598     FormatException(pszMessage, pex, pszThread);
599     printf("\n\n************************\n%s\n", pszMessage);
600     fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
601     strMiscWarning = pszMessage;
602 #ifdef GUI
603     if (wxTheApp && !fDaemon)
604         boost::thread(boost::bind(ThreadOneMessageBox, string(pszMessage)));
605 #endif
606 }
607
608
609
610
611
612
613
614
615 #ifdef __WXMSW__
616 typedef WINSHELLAPI BOOL (WINAPI *PSHGETSPECIALFOLDERPATHA)(HWND hwndOwner, LPSTR lpszPath, int nFolder, BOOL fCreate);
617
618 string MyGetSpecialFolderPath(int nFolder, bool fCreate)
619 {
620     char pszPath[MAX_PATH+100] = "";
621
622     // SHGetSpecialFolderPath isn't always available on old Windows versions
623     HMODULE hShell32 = LoadLibraryA("shell32.dll");
624     if (hShell32)
625     {
626         PSHGETSPECIALFOLDERPATHA pSHGetSpecialFolderPath =
627             (PSHGETSPECIALFOLDERPATHA)GetProcAddress(hShell32, "SHGetSpecialFolderPathA");
628         if (pSHGetSpecialFolderPath)
629             (*pSHGetSpecialFolderPath)(NULL, pszPath, nFolder, fCreate);
630         FreeModule(hShell32);
631     }
632
633     // Backup option
634     if (pszPath[0] == '\0')
635     {
636         if (nFolder == CSIDL_STARTUP)
637         {
638             strcpy(pszPath, getenv("USERPROFILE"));
639             strcat(pszPath, "\\Start Menu\\Programs\\Startup");
640         }
641         else if (nFolder == CSIDL_APPDATA)
642         {
643             strcpy(pszPath, getenv("APPDATA"));
644         }
645     }
646
647     return pszPath;
648 }
649 #endif
650
651 string GetDefaultDataDir()
652 {
653     // Windows: C:\Documents and Settings\username\Application Data\Bitcoin
654     // Mac: ~/Library/Application Support/Bitcoin
655     // Unix: ~/.bitcoin
656 #ifdef __WXMSW__
657     // Windows
658     return MyGetSpecialFolderPath(CSIDL_APPDATA, true) + "\\Bitcoin";
659 #else
660     char* pszHome = getenv("HOME");
661     if (pszHome == NULL || strlen(pszHome) == 0)
662         pszHome = (char*)"/";
663     string strHome = pszHome;
664     if (strHome[strHome.size()-1] != '/')
665         strHome += '/';
666 #ifdef __WXMAC_OSX__
667     // Mac
668     strHome += "Library/Application Support/";
669     filesystem::create_directory(strHome.c_str());
670     return strHome + "Bitcoin";
671 #else
672     // Unix
673     return strHome + ".bitcoin";
674 #endif
675 #endif
676 }
677
678 void GetDataDir(char* pszDir)
679 {
680     // pszDir must be at least MAX_PATH length.
681     int nVariation;
682     if (pszSetDataDir[0] != 0)
683     {
684         strlcpy(pszDir, pszSetDataDir, MAX_PATH);
685         nVariation = 0;
686     }
687     else
688     {
689         // This can be called during exceptions by printf, so we cache the
690         // value so we don't have to do memory allocations after that.
691         static char pszCachedDir[MAX_PATH];
692         if (pszCachedDir[0] == 0)
693             strlcpy(pszCachedDir, GetDefaultDataDir().c_str(), sizeof(pszCachedDir));
694         strlcpy(pszDir, pszCachedDir, MAX_PATH);
695         nVariation = 1;
696     }
697     if (fTestNet)
698     {
699         char* p = pszDir + strlen(pszDir);
700         if (p > pszDir && p[-1] != '/' && p[-1] != '\\')
701             *p++ = '/';
702         strcpy(p, "testnet");
703         nVariation += 2;
704     }
705     static bool pfMkdir[4];
706     if (!pfMkdir[nVariation])
707     {
708         pfMkdir[nVariation] = true;
709         boost::filesystem::create_directory(pszDir);
710     }
711 }
712
713 string GetDataDir()
714 {
715     char pszDir[MAX_PATH];
716     GetDataDir(pszDir);
717     return pszDir;
718 }
719
720 string GetConfigFile()
721 {
722     namespace fs = boost::filesystem;
723     fs::path pathConfig(GetArg("-conf", "bitcoin.conf"));
724     if (!pathConfig.is_complete())
725         pathConfig = fs::path(GetDataDir()) / pathConfig;
726     return pathConfig.string();
727 }
728
729 void ReadConfigFile(map<string, string>& mapSettingsRet,
730                     map<string, vector<string> >& mapMultiSettingsRet)
731 {
732     namespace fs = boost::filesystem;
733     namespace pod = boost::program_options::detail;
734
735     fs::ifstream streamConfig(GetConfigFile());
736     if (!streamConfig.good())
737         return;
738
739     set<string> setOptions;
740     setOptions.insert("*");
741     
742     for (pod::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
743     {
744         // Don't overwrite existing settings so command line settings override bitcoin.conf
745         string strKey = string("-") + it->string_key;
746         if (mapSettingsRet.count(strKey) == 0)
747             mapSettingsRet[strKey] = it->value[0];
748         mapMultiSettingsRet[strKey].push_back(it->value[0]);
749     }
750 }
751
752 string GetPidFile()
753 {
754     namespace fs = boost::filesystem;
755     fs::path pathConfig(GetArg("-pid", "bitcoind.pid"));
756     if (!pathConfig.is_complete())
757         pathConfig = fs::path(GetDataDir()) / pathConfig;
758     return pathConfig.string();
759 }
760
761 void CreatePidFile(string pidFile, pid_t pid)
762 {
763     FILE* file;
764     if (file = fopen(pidFile.c_str(), "w"))
765     {
766         fprintf(file, "%d\n", pid);
767         fclose(file);
768     }
769 }
770
771 int GetFilesize(FILE* file)
772 {
773     int nSavePos = ftell(file);
774     int nFilesize = -1;
775     if (fseek(file, 0, SEEK_END) == 0)
776         nFilesize = ftell(file);
777     fseek(file, nSavePos, SEEK_SET);
778     return nFilesize;
779 }
780
781 void ShrinkDebugFile()
782 {
783     // Scroll debug.log if it's getting too big
784     string strFile = GetDataDir() + "/debug.log";
785     FILE* file = fopen(strFile.c_str(), "r");
786     if (file && GetFilesize(file) > 10 * 1000000)
787     {
788         // Restart the file with some of the end
789         char pch[200000];
790         fseek(file, -sizeof(pch), SEEK_END);
791         int nBytes = fread(pch, 1, sizeof(pch), file);
792         fclose(file);
793         if (file = fopen(strFile.c_str(), "w"))
794         {
795             fwrite(pch, 1, nBytes, file);
796             fclose(file);
797         }
798     }
799 }
800
801
802
803
804
805
806
807
808 //
809 // "Never go to sea with two chronometers; take one or three."
810 // Our three time sources are:
811 //  - System clock
812 //  - Median of other nodes's clocks
813 //  - The user (asking the user to fix the system clock if the first two disagree)
814 //
815 int64 GetTime()
816 {
817     return time(NULL);
818 }
819
820 static int64 nTimeOffset = 0;
821
822 int64 GetAdjustedTime()
823 {
824     return GetTime() + nTimeOffset;
825 }
826
827 void AddTimeData(unsigned int ip, int64 nTime)
828 {
829     int64 nOffsetSample = nTime - GetTime();
830
831     // Ignore duplicates
832     static set<unsigned int> setKnown;
833     if (!setKnown.insert(ip).second)
834         return;
835
836     // Add data
837     static vector<int64> vTimeOffsets;
838     if (vTimeOffsets.empty())
839         vTimeOffsets.push_back(0);
840     vTimeOffsets.push_back(nOffsetSample);
841     printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), vTimeOffsets.back(), vTimeOffsets.back()/60);
842     if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
843     {
844         sort(vTimeOffsets.begin(), vTimeOffsets.end());
845         int64 nMedian = vTimeOffsets[vTimeOffsets.size()/2];
846         // Only let other nodes change our time by so much
847         if (abs64(nMedian) < 70 * 60)
848         {
849             nTimeOffset = nMedian;
850         }
851         else
852         {
853             nTimeOffset = 0;
854
855             static bool fDone;
856             if (!fDone)
857             {
858                 // If nobody has a time different than ours but within 5 minutes of ours, give a warning
859                 bool fMatch = false;
860                 BOOST_FOREACH(int64 nOffset, vTimeOffsets)
861                     if (nOffset != 0 && abs64(nOffset) < 5 * 60)
862                         fMatch = true;
863
864                 if (!fMatch)
865                 {
866                     fDone = true;
867                     string strMessage = _("Warning: Please check that your computer's date and time are correct.  If your clock is wrong Bitcoin will not work properly.");
868                     strMiscWarning = strMessage;
869                     printf("*** %s\n", strMessage.c_str());
870                     boost::thread(boost::bind(ThreadSafeMessageBox, strMessage+" ", string("Bitcoin"), wxOK | wxICON_EXCLAMATION, (wxWindow*)NULL, -1, -1));
871                 }
872             }
873         }
874         BOOST_FOREACH(int64 n, vTimeOffsets)
875             printf("%+"PRI64d"  ", n);
876         printf("|  nTimeOffset = %+"PRI64d"  (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
877     }
878 }
879
880
881
882
883
884
885
886
887
888 string FormatVersion(int nVersion)
889 {
890     if (nVersion%100 == 0)
891         return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
892     else
893         return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
894 }
895
896 string FormatFullVersion()
897 {
898     string s = FormatVersion(VERSION) + pszSubVer;
899     if (VERSION_IS_BETA) {
900         s += "-";
901         s += _("beta");
902     }
903     return s;
904 }
905
906
907
908
909