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