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