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