Only include strlcpy.h when we have to
[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
7 using namespace std;
8 using namespace boost;
9
10 map<string, string> mapArgs;
11 map<string, vector<string> > mapMultiArgs;
12 bool fDebug = false;
13 bool fPrintToConsole = false;
14 bool fPrintToDebugger = false;
15 char pszSetDataDir[MAX_PATH] = "";
16 bool fRequestShutdown = false;
17 bool fShutdown = false;
18 bool fDaemon = false;
19 bool fServer = false;
20 bool fCommandLine = false;
21 string strMiscWarning;
22 bool fTestNet = false;
23 bool fNoListen = false;
24 bool fLogTimestamps = false;
25
26
27
28
29 // Workaround for "multiple definition of `_tls_used'"
30 // http://svn.boost.org/trac/boost/ticket/4258
31 extern "C" void tss_cleanup_implemented() { }
32
33
34
35
36
37 // Init openssl library multithreading support
38 static boost::interprocess::interprocess_mutex** ppmutexOpenSSL;
39 void locking_callback(int mode, int i, const char* file, int line)
40 {
41     if (mode & CRYPTO_LOCK)
42         ppmutexOpenSSL[i]->lock();
43     else
44         ppmutexOpenSSL[i]->unlock();
45 }
46
47 // Init
48 class CInit
49 {
50 public:
51     CInit()
52     {
53         // Init openssl library multithreading support
54         ppmutexOpenSSL = (boost::interprocess::interprocess_mutex**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(boost::interprocess::interprocess_mutex*));
55         for (int i = 0; i < CRYPTO_num_locks(); i++)
56             ppmutexOpenSSL[i] = new boost::interprocess::interprocess_mutex();
57         CRYPTO_set_locking_callback(locking_callback);
58
59 #ifdef __WXMSW__
60         // Seed random number generator with screen scrape and other hardware sources
61         RAND_screen();
62 #endif
63
64         // Seed random number generator with performance counter
65         RandAddSeed();
66     }
67     ~CInit()
68     {
69         // Shutdown openssl library multithreading support
70         CRYPTO_set_locking_callback(NULL);
71         for (int i = 0; i < CRYPTO_num_locks(); i++)
72             delete ppmutexOpenSSL[i];
73         OPENSSL_free(ppmutexOpenSSL);
74     }
75 }
76 instance_of_cinit;
77
78
79
80
81
82
83
84
85 void RandAddSeed()
86 {
87     // Seed with CPU performance counter
88     int64 nCounter = GetPerformanceCounter();
89     RAND_add(&nCounter, sizeof(nCounter), 1.5);
90     memset(&nCounter, 0, sizeof(nCounter));
91 }
92
93 void RandAddSeedPerfmon()
94 {
95     RandAddSeed();
96
97     // This can take up to 2 seconds, so only do it every 10 minutes
98     static int64 nLastPerfmon;
99     if (GetTime() < nLastPerfmon + 10 * 60)
100         return;
101     nLastPerfmon = GetTime();
102
103 #ifdef __WXMSW__
104     // Don't need this on Linux, OpenSSL automatically uses /dev/urandom
105     // Seed with the entire set of perfmon data
106     unsigned char pdata[250000];
107     memset(pdata, 0, sizeof(pdata));
108     unsigned long nSize = sizeof(pdata);
109     long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
110     RegCloseKey(HKEY_PERFORMANCE_DATA);
111     if (ret == ERROR_SUCCESS)
112     {
113         RAND_add(pdata, nSize, nSize/100.0);
114         memset(pdata, 0, nSize);
115         printf("%s RandAddSeed() %d bytes\n", DateTimeStrFormat("%x %H:%M", GetTime()).c_str(), nSize);
116     }
117 #endif
118 }
119
120 uint64 GetRand(uint64 nMax)
121 {
122     if (nMax == 0)
123         return 0;
124
125     // The range of the random source must be a multiple of the modulus
126     // to give every possible output value an equal possibility
127     uint64 nRange = (UINT64_MAX / nMax) * nMax;
128     uint64 nRand = 0;
129     do
130         RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
131     while (nRand >= nRange);
132     return (nRand % nMax);
133 }
134
135 int GetRandInt(int nMax)
136 {
137     return GetRand(nMax);
138 }
139
140
141
142
143
144
145
146
147
148
149
150 inline int OutputDebugStringF(const char* pszFormat, ...)
151 {
152     int ret = 0;
153     if (fPrintToConsole)
154     {
155         // print to console
156         va_list arg_ptr;
157         va_start(arg_ptr, pszFormat);
158         ret = vprintf(pszFormat, arg_ptr);
159         va_end(arg_ptr);
160     }
161     else
162     {
163         // print to debug.log
164         static FILE* fileout = NULL;
165
166         if (!fileout)
167         {
168             char pszFile[MAX_PATH+100];
169             GetDataDir(pszFile);
170             strlcat(pszFile, "/debug.log", sizeof(pszFile));
171             fileout = fopen(pszFile, "a");
172             if (fileout) setbuf(fileout, NULL); // unbuffered
173         }
174         if (fileout)
175         {
176             static bool fStartedNewLine = true;
177
178             // Debug print useful for profiling
179             if (fLogTimestamps && fStartedNewLine)
180                 fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
181             if (pszFormat[strlen(pszFormat) - 1] == '\n')
182                 fStartedNewLine = true;
183             else
184                 fStartedNewLine = false;
185
186             va_list arg_ptr;
187             va_start(arg_ptr, pszFormat);
188             ret = vfprintf(fileout, pszFormat, arg_ptr);
189             va_end(arg_ptr);
190         }
191     }
192
193 #ifdef __WXMSW__
194     if (fPrintToDebugger)
195     {
196         static CCriticalSection cs_OutputDebugStringF;
197
198         // accumulate a line at a time
199         CRITICAL_BLOCK(cs_OutputDebugStringF)
200         {
201             static char pszBuffer[50000];
202             static char* pend;
203             if (pend == NULL)
204                 pend = pszBuffer;
205             va_list arg_ptr;
206             va_start(arg_ptr, pszFormat);
207             int limit = END(pszBuffer) - pend - 2;
208             int ret = _vsnprintf(pend, limit, pszFormat, arg_ptr);
209             va_end(arg_ptr);
210             if (ret < 0 || ret >= limit)
211             {
212                 pend = END(pszBuffer) - 2;
213                 *pend++ = '\n';
214             }
215             else
216                 pend += ret;
217             *pend = '\0';
218             char* p1 = pszBuffer;
219             char* p2;
220             while (p2 = strchr(p1, '\n'))
221             {
222                 p2++;
223                 char c = *p2;
224                 *p2 = '\0';
225                 OutputDebugStringA(p1);
226                 *p2 = c;
227                 p1 = p2;
228             }
229             if (p1 != pszBuffer)
230                 memmove(pszBuffer, p1, pend - p1 + 1);
231             pend -= (p1 - pszBuffer);
232         }
233     }
234 #endif
235     return ret;
236 }
237
238
239 // Safer snprintf
240 //  - prints up to limit-1 characters
241 //  - output string is always null terminated even if limit reached
242 //  - return value is the number of characters actually printed
243 int my_snprintf(char* buffer, size_t limit, const char* format, ...)
244 {
245     if (limit == 0)
246         return 0;
247     va_list arg_ptr;
248     va_start(arg_ptr, format);
249     int ret = _vsnprintf(buffer, limit, format, arg_ptr);
250     va_end(arg_ptr);
251     if (ret < 0 || ret >= limit)
252     {
253         ret = limit - 1;
254         buffer[limit-1] = 0;
255     }
256     return ret;
257 }
258
259
260 string strprintf(const char* format, ...)
261 {
262     char buffer[50000];
263     char* p = buffer;
264     int limit = sizeof(buffer);
265     int ret;
266     loop
267     {
268         va_list arg_ptr;
269         va_start(arg_ptr, format);
270         ret = _vsnprintf(p, limit, format, arg_ptr);
271         va_end(arg_ptr);
272         if (ret >= 0 && ret < limit)
273             break;
274         if (p != buffer)
275             delete p;
276         limit *= 2;
277         p = new char[limit];
278         if (p == NULL)
279             throw std::bad_alloc();
280     }
281     string str(p, p+ret);
282     if (p != buffer)
283         delete p;
284     return str;
285 }
286
287
288 bool error(const char* format, ...)
289 {
290     char buffer[50000];
291     int limit = sizeof(buffer);
292     va_list arg_ptr;
293     va_start(arg_ptr, format);
294     int ret = _vsnprintf(buffer, limit, format, arg_ptr);
295     va_end(arg_ptr);
296     if (ret < 0 || ret >= limit)
297     {
298         ret = limit - 1;
299         buffer[limit-1] = 0;
300     }
301     printf("ERROR: %s\n", buffer);
302     return false;
303 }
304
305
306 void ParseString(const string& str, char c, vector<string>& v)
307 {
308     if (str.empty())
309         return;
310     string::size_type i1 = 0;
311     string::size_type i2;
312     loop
313     {
314         i2 = str.find(c, i1);
315         if (i2 == str.npos)
316         {
317             v.push_back(str.substr(i1));
318             return;
319         }
320         v.push_back(str.substr(i1, i2-i1));
321         i1 = i2+1;
322     }
323 }
324
325
326 string FormatMoney(int64 n, bool fPlus)
327 {
328     // Note: not using straight sprintf here because we do NOT want
329     // localized number formatting.
330     int64 n_abs = (n > 0 ? n : -n);
331     int64 quotient = n_abs/COIN;
332     int64 remainder = n_abs%COIN;
333     string str = strprintf("%"PRI64d".%08"PRI64d, quotient, remainder);
334
335     // Right-trim excess 0's before the decimal point:
336     int nTrim = 0;
337     for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
338         ++nTrim;
339     if (nTrim)
340         str.erase(str.size()-nTrim, nTrim);
341
342     // Insert thousands-separators:
343     size_t point = str.find(".");
344     for (int i = (str.size()-point)+3; i < str.size(); i += 4)
345         if (isdigit(str[str.size() - i - 1]))
346             str.insert(str.size() - i, 1, ',');
347     if (n < 0)
348         str.insert((unsigned int)0, 1, '-');
349     else if (fPlus && n > 0)
350         str.insert((unsigned int)0, 1, '+');
351     return str;
352 }
353
354
355 bool ParseMoney(const string& str, int64& nRet)
356 {
357     return ParseMoney(str.c_str(), nRet);
358 }
359
360 bool ParseMoney(const char* pszIn, int64& nRet)
361 {
362     string strWhole;
363     int64 nUnits = 0;
364     const char* p = pszIn;
365     while (isspace(*p))
366         p++;
367     for (; *p; p++)
368     {
369         if (*p == ',' && p > pszIn && isdigit(p[-1]) && isdigit(p[1]) && isdigit(p[2]) && isdigit(p[3]) && !isdigit(p[4]))
370             continue;
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 += _("-beta");
901     return s;
902 }
903
904
905
906
907