Merge branch 'rounding' of https://github.com/gavinandresen/bitcoin-git into gavinand...
[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 bool fNoListen = false;
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
162         if (!fileout)
163         {
164             char pszFile[MAX_PATH+100];
165             GetDataDir(pszFile);
166             strlcat(pszFile, "/debug.log", sizeof(pszFile));
167             fileout = fopen(pszFile, "a");
168             if (fileout) setbuf(fileout, NULL); // unbuffered
169         }
170         if (fileout)
171         {
172             //// Debug print useful for profiling
173             //fprintf(fileout, " %"PRI64d" ", GetTimeMillis());
174             va_list arg_ptr;
175             va_start(arg_ptr, pszFormat);
176             ret = vfprintf(fileout, pszFormat, arg_ptr);
177             va_end(arg_ptr);
178         }
179     }
180
181 #ifdef __WXMSW__
182     if (fPrintToDebugger)
183     {
184         static CCriticalSection cs_OutputDebugStringF;
185
186         // accumulate a line at a time
187         CRITICAL_BLOCK(cs_OutputDebugStringF)
188         {
189             static char pszBuffer[50000];
190             static char* pend;
191             if (pend == NULL)
192                 pend = pszBuffer;
193             va_list arg_ptr;
194             va_start(arg_ptr, pszFormat);
195             int limit = END(pszBuffer) - pend - 2;
196             int ret = _vsnprintf(pend, limit, pszFormat, arg_ptr);
197             va_end(arg_ptr);
198             if (ret < 0 || ret >= limit)
199             {
200                 pend = END(pszBuffer) - 2;
201                 *pend++ = '\n';
202             }
203             else
204                 pend += ret;
205             *pend = '\0';
206             char* p1 = pszBuffer;
207             char* p2;
208             while (p2 = strchr(p1, '\n'))
209             {
210                 p2++;
211                 char c = *p2;
212                 *p2 = '\0';
213                 OutputDebugStringA(p1);
214                 *p2 = c;
215                 p1 = p2;
216             }
217             if (p1 != pszBuffer)
218                 memmove(pszBuffer, p1, pend - p1 + 1);
219             pend -= (p1 - pszBuffer);
220         }
221     }
222 #endif
223     return ret;
224 }
225
226
227 // Safer snprintf
228 //  - prints up to limit-1 characters
229 //  - output string is always null terminated even if limit reached
230 //  - return value is the number of characters actually printed
231 int my_snprintf(char* buffer, size_t limit, const char* format, ...)
232 {
233     if (limit == 0)
234         return 0;
235     va_list arg_ptr;
236     va_start(arg_ptr, format);
237     int ret = _vsnprintf(buffer, limit, format, arg_ptr);
238     va_end(arg_ptr);
239     if (ret < 0 || ret >= limit)
240     {
241         ret = limit - 1;
242         buffer[limit-1] = 0;
243     }
244     return ret;
245 }
246
247
248 string strprintf(const char* format, ...)
249 {
250     char buffer[50000];
251     char* p = buffer;
252     int limit = sizeof(buffer);
253     int ret;
254     loop
255     {
256         va_list arg_ptr;
257         va_start(arg_ptr, format);
258         ret = _vsnprintf(p, limit, format, arg_ptr);
259         va_end(arg_ptr);
260         if (ret >= 0 && ret < limit)
261             break;
262         if (p != buffer)
263             delete p;
264         limit *= 2;
265         p = new char[limit];
266         if (p == NULL)
267             throw std::bad_alloc();
268     }
269     string str(p, p+ret);
270     if (p != buffer)
271         delete p;
272     return str;
273 }
274
275
276 bool error(const char* format, ...)
277 {
278     char buffer[50000];
279     int limit = sizeof(buffer);
280     va_list arg_ptr;
281     va_start(arg_ptr, format);
282     int ret = _vsnprintf(buffer, limit, format, arg_ptr);
283     va_end(arg_ptr);
284     if (ret < 0 || ret >= limit)
285     {
286         ret = limit - 1;
287         buffer[limit-1] = 0;
288     }
289     printf("ERROR: %s\n", buffer);
290     return false;
291 }
292
293
294 void ParseString(const string& str, char c, vector<string>& v)
295 {
296     if (str.empty())
297         return;
298     string::size_type i1 = 0;
299     string::size_type i2;
300     loop
301     {
302         i2 = str.find(c, i1);
303         if (i2 == str.npos)
304         {
305             v.push_back(str.substr(i1));
306             return;
307         }
308         v.push_back(str.substr(i1, i2-i1));
309         i1 = i2+1;
310     }
311 }
312
313
314 string FormatMoney(int64 n, bool fPlus)
315 {
316     string str = strprintf("%.08f", double(n > 0 ? n : -n)/double(COIN));
317
318     // Right-trim excess 0's before the decimal point:
319     int nTrim = 0;
320     for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
321         ++nTrim;
322     if (nTrim)
323         str.erase(str.size()-nTrim, nTrim);
324
325     // Insert thousands-separators:
326     size_t point = str.find(".");
327     for (int i = (str.size()-point)+3; i < str.size(); i += 4)
328         if (isdigit(str[str.size() - i - 1]))
329             str.insert(str.size() - i, 1, ',');
330     if (n < 0)
331         str.insert((unsigned int)0, 1, '-');
332     else if (fPlus && n > 0)
333         str.insert((unsigned int)0, 1, '+');
334     return str;
335 }
336
337
338 bool ParseMoney(const string& str, int64& nRet)
339 {
340     return ParseMoney(str.c_str(), nRet);
341 }
342
343 bool ParseMoney(const char* pszIn, int64& nRet)
344 {
345     string strWhole;
346     int64 nUnits = 0;
347     const char* p = pszIn;
348     while (isspace(*p))
349         p++;
350     for (; *p; p++)
351     {
352         if (*p == ',' && p > pszIn && isdigit(p[-1]) && isdigit(p[1]) && isdigit(p[2]) && isdigit(p[3]) && !isdigit(p[4]))
353             continue;
354         if (*p == '.')
355         {
356             p++;
357             int64 nMult = CENT*10;
358             while (isdigit(*p) && (nMult > 0))
359             {
360                 nUnits += nMult * (*p++ - '0');
361                 nMult /= 10;
362             }
363             break;
364         }
365         if (isspace(*p))
366             break;
367         if (!isdigit(*p))
368             return false;
369         strWhole.insert(strWhole.end(), *p);
370     }
371     for (; *p; p++)
372         if (!isspace(*p))
373             return false;
374     if (strWhole.size() > 14)
375         return false;
376     if (nUnits < 0 || nUnits > COIN)
377         return false;
378     int64 nWhole = atoi64(strWhole);
379     int64 nValue = nWhole*COIN + nUnits;
380
381     nRet = nValue;
382     return true;
383 }
384
385
386 vector<unsigned char> ParseHex(const char* psz)
387 {
388     static char phexdigit[256] =
389     { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
390       -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
391       -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
392       0,1,2,3,4,5,6,7,8,9,-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,0xa,0xb,0xc,0xd,0xe,0xf,-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       -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
406     // convert hex dump to vector
407     vector<unsigned char> vch;
408     loop
409     {
410         while (isspace(*psz))
411             psz++;
412         char c = phexdigit[(unsigned char)*psz++];
413         if (c == (char)-1)
414             break;
415         unsigned char n = (c << 4);
416         c = phexdigit[(unsigned char)*psz++];
417         if (c == (char)-1)
418             break;
419         n |= c;
420         vch.push_back(n);
421     }
422     return vch;
423 }
424
425 vector<unsigned char> ParseHex(const string& str)
426 {
427     return ParseHex(str.c_str());
428 }
429
430
431 void ParseParameters(int argc, char* argv[])
432 {
433     mapArgs.clear();
434     mapMultiArgs.clear();
435     for (int i = 1; i < argc; i++)
436     {
437         char psz[10000];
438         strlcpy(psz, argv[i], sizeof(psz));
439         char* pszValue = (char*)"";
440         if (strchr(psz, '='))
441         {
442             pszValue = strchr(psz, '=');
443             *pszValue++ = '\0';
444         }
445         #ifdef __WXMSW__
446         _strlwr(psz);
447         if (psz[0] == '/')
448             psz[0] = '-';
449         #endif
450         if (psz[0] != '-')
451             break;
452         mapArgs[psz] = pszValue;
453         mapMultiArgs[psz].push_back(pszValue);
454     }
455 }
456
457
458 const char* wxGetTranslation(const char* pszEnglish)
459 {
460 #ifdef GUI
461     // Wrapper of wxGetTranslation returning the same const char* type as was passed in
462     static CCriticalSection cs;
463     CRITICAL_BLOCK(cs)
464     {
465         // Look in cache
466         static map<string, char*> mapCache;
467         map<string, char*>::iterator mi = mapCache.find(pszEnglish);
468         if (mi != mapCache.end())
469             return (*mi).second;
470
471         // wxWidgets translation
472         wxString strTranslated = wxGetTranslation(wxString(pszEnglish, wxConvUTF8));
473
474         // We don't cache unknown strings because caller might be passing in a
475         // dynamic string and we would keep allocating memory for each variation.
476         if (strcmp(pszEnglish, strTranslated.utf8_str()) == 0)
477             return pszEnglish;
478
479         // Add to cache, memory doesn't need to be freed.  We only cache because
480         // we must pass back a pointer to permanently allocated memory.
481         char* pszCached = new char[strlen(strTranslated.utf8_str())+1];
482         strcpy(pszCached, strTranslated.utf8_str());
483         mapCache[pszEnglish] = pszCached;
484         return pszCached;
485     }
486     return NULL;
487 #else
488     return pszEnglish;
489 #endif
490 }
491
492
493 bool WildcardMatch(const char* psz, const char* mask)
494 {
495     loop
496     {
497         switch (*mask)
498         {
499         case '\0':
500             return (*psz == '\0');
501         case '*':
502             return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
503         case '?':
504             if (*psz == '\0')
505                 return false;
506             break;
507         default:
508             if (*psz != *mask)
509                 return false;
510             break;
511         }
512         psz++;
513         mask++;
514     }
515 }
516
517 bool WildcardMatch(const string& str, const string& mask)
518 {
519     return WildcardMatch(str.c_str(), mask.c_str());
520 }
521
522
523
524
525
526
527
528
529 void FormatException(char* pszMessage, std::exception* pex, const char* pszThread)
530 {
531 #ifdef __WXMSW__
532     char pszModule[MAX_PATH];
533     pszModule[0] = '\0';
534     GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
535 #else
536     const char* pszModule = "bitcoin";
537 #endif
538     if (pex)
539         snprintf(pszMessage, 1000,
540             "EXCEPTION: %s       \n%s       \n%s in %s       \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
541     else
542         snprintf(pszMessage, 1000,
543             "UNKNOWN EXCEPTION       \n%s in %s       \n", pszModule, pszThread);
544 }
545
546 void LogException(std::exception* pex, const char* pszThread)
547 {
548     char pszMessage[10000];
549     FormatException(pszMessage, pex, pszThread);
550     printf("\n%s", pszMessage);
551 }
552
553 void PrintException(std::exception* pex, const char* pszThread)
554 {
555     char pszMessage[10000];
556     FormatException(pszMessage, pex, pszThread);
557     printf("\n\n************************\n%s\n", pszMessage);
558     fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
559     strMiscWarning = pszMessage;
560 #ifdef GUI
561     if (wxTheApp && !fDaemon)
562         MyMessageBox(pszMessage, "Bitcoin", wxOK | wxICON_ERROR);
563 #endif
564     throw;
565 }
566
567 void ThreadOneMessageBox(string strMessage)
568 {
569     // Skip message boxes if one is already open
570     static bool fMessageBoxOpen;
571     if (fMessageBoxOpen)
572         return;
573     fMessageBoxOpen = true;
574     ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
575     fMessageBoxOpen = false;
576 }
577
578 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
579 {
580     char pszMessage[10000];
581     FormatException(pszMessage, pex, pszThread);
582     printf("\n\n************************\n%s\n", pszMessage);
583     fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
584     strMiscWarning = pszMessage;
585 #ifdef GUI
586     if (wxTheApp && !fDaemon)
587         boost::thread(boost::bind(ThreadOneMessageBox, string(pszMessage)));
588 #endif
589 }
590
591
592
593
594
595
596
597
598 #ifdef __WXMSW__
599 typedef WINSHELLAPI BOOL (WINAPI *PSHGETSPECIALFOLDERPATHA)(HWND hwndOwner, LPSTR lpszPath, int nFolder, BOOL fCreate);
600
601 string MyGetSpecialFolderPath(int nFolder, bool fCreate)
602 {
603     char pszPath[MAX_PATH+100] = "";
604
605     // SHGetSpecialFolderPath isn't always available on old Windows versions
606     HMODULE hShell32 = LoadLibraryA("shell32.dll");
607     if (hShell32)
608     {
609         PSHGETSPECIALFOLDERPATHA pSHGetSpecialFolderPath =
610             (PSHGETSPECIALFOLDERPATHA)GetProcAddress(hShell32, "SHGetSpecialFolderPathA");
611         if (pSHGetSpecialFolderPath)
612             (*pSHGetSpecialFolderPath)(NULL, pszPath, nFolder, fCreate);
613         FreeModule(hShell32);
614     }
615
616     // Backup option
617     if (pszPath[0] == '\0')
618     {
619         if (nFolder == CSIDL_STARTUP)
620         {
621             strcpy(pszPath, getenv("USERPROFILE"));
622             strcat(pszPath, "\\Start Menu\\Programs\\Startup");
623         }
624         else if (nFolder == CSIDL_APPDATA)
625         {
626             strcpy(pszPath, getenv("APPDATA"));
627         }
628     }
629
630     return pszPath;
631 }
632 #endif
633
634 string GetDefaultDataDir()
635 {
636     // Windows: C:\Documents and Settings\username\Application Data\Bitcoin
637     // Mac: ~/Library/Application Support/Bitcoin
638     // Unix: ~/.bitcoin
639 #ifdef __WXMSW__
640     // Windows
641     return MyGetSpecialFolderPath(CSIDL_APPDATA, true) + "\\Bitcoin";
642 #else
643     char* pszHome = getenv("HOME");
644     if (pszHome == NULL || strlen(pszHome) == 0)
645         pszHome = (char*)"/";
646     string strHome = pszHome;
647     if (strHome[strHome.size()-1] != '/')
648         strHome += '/';
649 #ifdef __WXMAC_OSX__
650     // Mac
651     strHome += "Library/Application Support/";
652     filesystem::create_directory(strHome.c_str());
653     return strHome + "Bitcoin";
654 #else
655     // Unix
656     return strHome + ".bitcoin";
657 #endif
658 #endif
659 }
660
661 void GetDataDir(char* pszDir)
662 {
663     // pszDir must be at least MAX_PATH length.
664     int nVariation;
665     if (pszSetDataDir[0] != 0)
666     {
667         strlcpy(pszDir, pszSetDataDir, MAX_PATH);
668         nVariation = 0;
669     }
670     else
671     {
672         // This can be called during exceptions by printf, so we cache the
673         // value so we don't have to do memory allocations after that.
674         static char pszCachedDir[MAX_PATH];
675         if (pszCachedDir[0] == 0)
676             strlcpy(pszCachedDir, GetDefaultDataDir().c_str(), sizeof(pszCachedDir));
677         strlcpy(pszDir, pszCachedDir, MAX_PATH);
678         nVariation = 1;
679     }
680     if (fTestNet)
681     {
682         char* p = pszDir + strlen(pszDir);
683         if (p > pszDir && p[-1] != '/' && p[-1] != '\\')
684             *p++ = '/';
685         strcpy(p, "testnet");
686         nVariation += 2;
687     }
688     static bool pfMkdir[4];
689     if (!pfMkdir[nVariation])
690     {
691         pfMkdir[nVariation] = true;
692         filesystem::create_directory(pszDir);
693     }
694 }
695
696 string GetDataDir()
697 {
698     char pszDir[MAX_PATH];
699     GetDataDir(pszDir);
700     return pszDir;
701 }
702
703 string GetConfigFile()
704 {
705     namespace fs = boost::filesystem;
706     fs::path pathConfig(GetArg("-conf", "bitcoin.conf"));
707     if (!pathConfig.is_complete())
708         pathConfig = fs::path(GetDataDir()) / pathConfig;
709     return pathConfig.string();
710 }
711
712 void ReadConfigFile(map<string, string>& mapSettingsRet,
713                     map<string, vector<string> >& mapMultiSettingsRet)
714 {
715     namespace fs = boost::filesystem;
716     namespace pod = boost::program_options::detail;
717
718     fs::ifstream streamConfig(GetConfigFile());
719     if (!streamConfig.good())
720         return;
721
722     set<string> setOptions;
723     setOptions.insert("*");
724     
725     for (pod::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
726     {
727         // Don't overwrite existing settings so command line settings override bitcoin.conf
728         string strKey = string("-") + it->string_key;
729         if (mapSettingsRet.count(strKey) == 0)
730             mapSettingsRet[strKey] = it->value[0];
731         mapMultiSettingsRet[strKey].push_back(it->value[0]);
732     }
733 }
734
735 int GetFilesize(FILE* file)
736 {
737     int nSavePos = ftell(file);
738     int nFilesize = -1;
739     if (fseek(file, 0, SEEK_END) == 0)
740         nFilesize = ftell(file);
741     fseek(file, nSavePos, SEEK_SET);
742     return nFilesize;
743 }
744
745 void ShrinkDebugFile()
746 {
747     // Scroll debug.log if it's getting too big
748     string strFile = GetDataDir() + "/debug.log";
749     FILE* file = fopen(strFile.c_str(), "r");
750     if (file && GetFilesize(file) > 10 * 1000000)
751     {
752         // Restart the file with some of the end
753         char pch[200000];
754         fseek(file, -sizeof(pch), SEEK_END);
755         int nBytes = fread(pch, 1, sizeof(pch), file);
756         fclose(file);
757         if (file = fopen(strFile.c_str(), "w"))
758         {
759             fwrite(pch, 1, nBytes, file);
760             fclose(file);
761         }
762     }
763 }
764
765
766
767
768
769
770
771
772 //
773 // "Never go to sea with two chronometers; take one or three."
774 // Our three time sources are:
775 //  - System clock
776 //  - Median of other nodes's clocks
777 //  - The user (asking the user to fix the system clock if the first two disagree)
778 //
779 int64 GetTime()
780 {
781     return time(NULL);
782 }
783
784 static int64 nTimeOffset = 0;
785
786 int64 GetAdjustedTime()
787 {
788     return GetTime() + nTimeOffset;
789 }
790
791 void AddTimeData(unsigned int ip, int64 nTime)
792 {
793     int64 nOffsetSample = nTime - GetTime();
794
795     // Ignore duplicates
796     static set<unsigned int> setKnown;
797     if (!setKnown.insert(ip).second)
798         return;
799
800     // Add data
801     static vector<int64> vTimeOffsets;
802     if (vTimeOffsets.empty())
803         vTimeOffsets.push_back(0);
804     vTimeOffsets.push_back(nOffsetSample);
805     printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), vTimeOffsets.back(), vTimeOffsets.back()/60);
806     if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
807     {
808         sort(vTimeOffsets.begin(), vTimeOffsets.end());
809         int64 nMedian = vTimeOffsets[vTimeOffsets.size()/2];
810         // Only let other nodes change our time by so much
811         if (abs64(nMedian) < 70 * 60)
812         {
813             nTimeOffset = nMedian;
814         }
815         else
816         {
817             nTimeOffset = 0;
818
819             static bool fDone;
820             if (!fDone)
821             {
822                 // If nobody has a time different than ours but within 5 minutes of ours, give a warning
823                 bool fMatch = false;
824                 foreach(int64 nOffset, vTimeOffsets)
825                     if (nOffset != 0 && abs64(nOffset) < 5 * 60)
826                         fMatch = true;
827
828                 if (!fMatch)
829                 {
830                     fDone = true;
831                     string strMessage = _("Warning: Please check that your computer's date and time are correct.  If your clock is wrong Bitcoin will not work properly.");
832                     strMiscWarning = strMessage;
833                     printf("*** %s\n", strMessage.c_str());
834                     boost::thread(boost::bind(ThreadSafeMessageBox, strMessage+" ", string("Bitcoin"), wxOK | wxICON_EXCLAMATION, (wxWindow*)NULL, -1, -1));
835                 }
836             }
837         }
838         foreach(int64 n, vTimeOffsets)
839             printf("%+"PRI64d"  ", n);
840         printf("|  nTimeOffset = %+"PRI64d"  (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
841     }
842 }