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