The -rpcssl command line option is a boolean, like -server, -daemon, -testnet, etc...
[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     n /= CENT;
317     string str = strprintf("%"PRI64d".%02"PRI64d, (n > 0 ? n : -n)/100, (n > 0 ? n : -n)%100);
318     for (int i = 6; i < str.size(); i += 4)
319         if (isdigit(str[str.size() - i - 1]))
320             str.insert(str.size() - i, 1, ',');
321     if (n < 0)
322         str.insert((unsigned int)0, 1, '-');
323     else if (fPlus && n > 0)
324         str.insert((unsigned int)0, 1, '+');
325     return str;
326 }
327
328
329 bool ParseMoney(const string& str, int64& nRet)
330 {
331     return ParseMoney(str.c_str(), nRet);
332 }
333
334 bool ParseMoney(const char* pszIn, int64& nRet)
335 {
336     string strWhole;
337     int64 nCents = 0;
338     const char* p = pszIn;
339     while (isspace(*p))
340         p++;
341     for (; *p; p++)
342     {
343         if (*p == ',' && p > pszIn && isdigit(p[-1]) && isdigit(p[1]) && isdigit(p[2]) && isdigit(p[3]) && !isdigit(p[4]))
344             continue;
345         if (*p == '.')
346         {
347             p++;
348             if (isdigit(*p))
349             {
350                 nCents = 10 * (*p++ - '0');
351                 if (isdigit(*p))
352                     nCents += (*p++ - '0');
353             }
354             break;
355         }
356         if (isspace(*p))
357             break;
358         if (!isdigit(*p))
359             return false;
360         strWhole.insert(strWhole.end(), *p);
361     }
362     for (; *p; p++)
363         if (!isspace(*p))
364             return false;
365     if (strWhole.size() > 14)
366         return false;
367     if (nCents < 0 || nCents > 99)
368         return false;
369     int64 nWhole = atoi64(strWhole);
370     int64 nPreValue = nWhole * 100 + nCents;
371     int64 nValue = nPreValue * CENT;
372     if (nValue / CENT != nPreValue)
373         return false;
374     if (nValue / COIN != nWhole)
375         return false;
376     nRet = nValue;
377     return true;
378 }
379
380
381 vector<unsigned char> ParseHex(const char* psz)
382 {
383     static char phexdigit[256] =
384     { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
385       -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
386       -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
387       0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
388       -1,0xa,0xb,0xc,0xd,0xe,0xf,-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       -1,0xa,0xb,0xc,0xd,0xe,0xf,-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       -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
393       -1,-1,-1,-1,-1,-1,-1,-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
401     // convert hex dump to vector
402     vector<unsigned char> vch;
403     loop
404     {
405         while (isspace(*psz))
406             psz++;
407         char c = phexdigit[(unsigned char)*psz++];
408         if (c == (char)-1)
409             break;
410         unsigned char n = (c << 4);
411         c = phexdigit[(unsigned char)*psz++];
412         if (c == (char)-1)
413             break;
414         n |= c;
415         vch.push_back(n);
416     }
417     return vch;
418 }
419
420 vector<unsigned char> ParseHex(const string& str)
421 {
422     return ParseHex(str.c_str());
423 }
424
425
426 void ParseParameters(int argc, char* argv[])
427 {
428     mapArgs.clear();
429     mapMultiArgs.clear();
430     for (int i = 1; i < argc; i++)
431     {
432         char psz[10000];
433         strlcpy(psz, argv[i], sizeof(psz));
434         char* pszValue = (char*)"";
435         if (strchr(psz, '='))
436         {
437             pszValue = strchr(psz, '=');
438             *pszValue++ = '\0';
439         }
440         #ifdef __WXMSW__
441         _strlwr(psz);
442         if (psz[0] == '/')
443             psz[0] = '-';
444         #endif
445         if (psz[0] != '-')
446             break;
447         mapArgs[psz] = pszValue;
448         mapMultiArgs[psz].push_back(pszValue);
449     }
450 }
451
452
453 const char* wxGetTranslation(const char* pszEnglish)
454 {
455 #ifdef GUI
456     // Wrapper of wxGetTranslation returning the same const char* type as was passed in
457     static CCriticalSection cs;
458     CRITICAL_BLOCK(cs)
459     {
460         // Look in cache
461         static map<string, char*> mapCache;
462         map<string, char*>::iterator mi = mapCache.find(pszEnglish);
463         if (mi != mapCache.end())
464             return (*mi).second;
465
466         // wxWidgets translation
467         wxString strTranslated = wxGetTranslation(wxString(pszEnglish, wxConvUTF8));
468
469         // We don't cache unknown strings because caller might be passing in a
470         // dynamic string and we would keep allocating memory for each variation.
471         if (strcmp(pszEnglish, strTranslated.utf8_str()) == 0)
472             return pszEnglish;
473
474         // Add to cache, memory doesn't need to be freed.  We only cache because
475         // we must pass back a pointer to permanently allocated memory.
476         char* pszCached = new char[strlen(strTranslated.utf8_str())+1];
477         strcpy(pszCached, strTranslated.utf8_str());
478         mapCache[pszEnglish] = pszCached;
479         return pszCached;
480     }
481     return NULL;
482 #else
483     return pszEnglish;
484 #endif
485 }
486
487
488 bool WildcardMatch(const char* psz, const char* mask)
489 {
490     loop
491     {
492         switch (*mask)
493         {
494         case '\0':
495             return (*psz == '\0');
496         case '*':
497             return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
498         case '?':
499             if (*psz == '\0')
500                 return false;
501             break;
502         default:
503             if (*psz != *mask)
504                 return false;
505             break;
506         }
507         psz++;
508         mask++;
509     }
510 }
511
512 bool WildcardMatch(const string& str, const string& mask)
513 {
514     return WildcardMatch(str.c_str(), mask.c_str());
515 }
516
517
518
519
520
521
522
523
524 void FormatException(char* pszMessage, std::exception* pex, const char* pszThread)
525 {
526 #ifdef __WXMSW__
527     char pszModule[MAX_PATH];
528     pszModule[0] = '\0';
529     GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
530 #else
531     const char* pszModule = "bitcoin";
532 #endif
533     if (pex)
534         snprintf(pszMessage, 1000,
535             "EXCEPTION: %s       \n%s       \n%s in %s       \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
536     else
537         snprintf(pszMessage, 1000,
538             "UNKNOWN EXCEPTION       \n%s in %s       \n", pszModule, pszThread);
539 }
540
541 void LogException(std::exception* pex, const char* pszThread)
542 {
543     char pszMessage[10000];
544     FormatException(pszMessage, pex, pszThread);
545     printf("\n%s", pszMessage);
546 }
547
548 void PrintException(std::exception* pex, const char* pszThread)
549 {
550     char pszMessage[10000];
551     FormatException(pszMessage, pex, pszThread);
552     printf("\n\n************************\n%s\n", pszMessage);
553     fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
554     strMiscWarning = pszMessage;
555 #ifdef GUI
556     if (wxTheApp && !fDaemon)
557         MyMessageBox(pszMessage, "Bitcoin", wxOK | wxICON_ERROR);
558 #endif
559     throw;
560 }
561
562 void ThreadOneMessageBox(string strMessage)
563 {
564     // Skip message boxes if one is already open
565     static bool fMessageBoxOpen;
566     if (fMessageBoxOpen)
567         return;
568     fMessageBoxOpen = true;
569     ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
570     fMessageBoxOpen = false;
571 }
572
573 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
574 {
575     char pszMessage[10000];
576     FormatException(pszMessage, pex, pszThread);
577     printf("\n\n************************\n%s\n", pszMessage);
578     fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
579     strMiscWarning = pszMessage;
580 #ifdef GUI
581     if (wxTheApp && !fDaemon)
582         boost::thread(boost::bind(ThreadOneMessageBox, string(pszMessage)));
583 #endif
584 }
585
586
587
588
589
590
591
592
593 #ifdef __WXMSW__
594 typedef WINSHELLAPI BOOL (WINAPI *PSHGETSPECIALFOLDERPATHA)(HWND hwndOwner, LPSTR lpszPath, int nFolder, BOOL fCreate);
595
596 string MyGetSpecialFolderPath(int nFolder, bool fCreate)
597 {
598     char pszPath[MAX_PATH+100] = "";
599
600     // SHGetSpecialFolderPath isn't always available on old Windows versions
601     HMODULE hShell32 = LoadLibraryA("shell32.dll");
602     if (hShell32)
603     {
604         PSHGETSPECIALFOLDERPATHA pSHGetSpecialFolderPath =
605             (PSHGETSPECIALFOLDERPATHA)GetProcAddress(hShell32, "SHGetSpecialFolderPathA");
606         if (pSHGetSpecialFolderPath)
607             (*pSHGetSpecialFolderPath)(NULL, pszPath, nFolder, fCreate);
608         FreeModule(hShell32);
609     }
610
611     // Backup option
612     if (pszPath[0] == '\0')
613     {
614         if (nFolder == CSIDL_STARTUP)
615         {
616             strcpy(pszPath, getenv("USERPROFILE"));
617             strcat(pszPath, "\\Start Menu\\Programs\\Startup");
618         }
619         else if (nFolder == CSIDL_APPDATA)
620         {
621             strcpy(pszPath, getenv("APPDATA"));
622         }
623     }
624
625     return pszPath;
626 }
627 #endif
628
629 string GetDefaultDataDir()
630 {
631     // Windows: C:\Documents and Settings\username\Application Data\Bitcoin
632     // Mac: ~/Library/Application Support/Bitcoin
633     // Unix: ~/.bitcoin
634 #ifdef __WXMSW__
635     // Windows
636     return MyGetSpecialFolderPath(CSIDL_APPDATA, true) + "\\Bitcoin";
637 #else
638     char* pszHome = getenv("HOME");
639     if (pszHome == NULL || strlen(pszHome) == 0)
640         pszHome = (char*)"/";
641     string strHome = pszHome;
642     if (strHome[strHome.size()-1] != '/')
643         strHome += '/';
644 #ifdef __WXMAC_OSX__
645     // Mac
646     strHome += "Library/Application Support/";
647     filesystem::create_directory(strHome.c_str());
648     return strHome + "Bitcoin";
649 #else
650     // Unix
651     return strHome + ".bitcoin";
652 #endif
653 #endif
654 }
655
656 void GetDataDir(char* pszDir)
657 {
658     // pszDir must be at least MAX_PATH length.
659     int nVariation;
660     if (pszSetDataDir[0] != 0)
661     {
662         strlcpy(pszDir, pszSetDataDir, MAX_PATH);
663         nVariation = 0;
664     }
665     else
666     {
667         // This can be called during exceptions by printf, so we cache the
668         // value so we don't have to do memory allocations after that.
669         static char pszCachedDir[MAX_PATH];
670         if (pszCachedDir[0] == 0)
671             strlcpy(pszCachedDir, GetDefaultDataDir().c_str(), sizeof(pszCachedDir));
672         strlcpy(pszDir, pszCachedDir, MAX_PATH);
673         nVariation = 1;
674     }
675     if (fTestNet)
676     {
677         char* p = pszDir + strlen(pszDir);
678         if (p > pszDir && p[-1] != '/' && p[-1] != '\\')
679             *p++ = '/';
680         strcpy(p, "testnet");
681         nVariation += 2;
682     }
683     static bool pfMkdir[4];
684     if (!pfMkdir[nVariation])
685     {
686         pfMkdir[nVariation] = true;
687         filesystem::create_directory(pszDir);
688     }
689 }
690
691 string GetDataDir()
692 {
693     char pszDir[MAX_PATH];
694     GetDataDir(pszDir);
695     return pszDir;
696 }
697
698 string GetConfigFile()
699 {
700     namespace fs = boost::filesystem;
701     fs::path pathConfig(GetArg("-conf", "bitcoin.conf"));
702     if (!pathConfig.is_complete())
703         pathConfig = fs::path(GetDataDir()) / pathConfig;
704     return pathConfig.string();
705 }
706
707 void ReadConfigFile(map<string, string>& mapSettingsRet,
708                     map<string, vector<string> >& mapMultiSettingsRet)
709 {
710     namespace fs = boost::filesystem;
711     namespace pod = boost::program_options::detail;
712
713     fs::ifstream streamConfig(GetConfigFile());
714     if (!streamConfig.good())
715         return;
716
717     set<string> setOptions;
718     setOptions.insert("*");
719     
720     for (pod::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
721     {
722         // Don't overwrite existing settings so command line settings override bitcoin.conf
723         string strKey = string("-") + it->string_key;
724         if (mapSettingsRet.count(strKey) == 0)
725             mapSettingsRet[strKey] = it->value[0];
726         mapMultiSettingsRet[strKey].push_back(it->value[0]);
727     }
728 }
729
730 int GetFilesize(FILE* file)
731 {
732     int nSavePos = ftell(file);
733     int nFilesize = -1;
734     if (fseek(file, 0, SEEK_END) == 0)
735         nFilesize = ftell(file);
736     fseek(file, nSavePos, SEEK_SET);
737     return nFilesize;
738 }
739
740 void ShrinkDebugFile()
741 {
742     // Scroll debug.log if it's getting too big
743     string strFile = GetDataDir() + "/debug.log";
744     FILE* file = fopen(strFile.c_str(), "r");
745     if (file && GetFilesize(file) > 10 * 1000000)
746     {
747         // Restart the file with some of the end
748         char pch[200000];
749         fseek(file, -sizeof(pch), SEEK_END);
750         int nBytes = fread(pch, 1, sizeof(pch), file);
751         fclose(file);
752         if (file = fopen(strFile.c_str(), "w"))
753         {
754             fwrite(pch, 1, nBytes, file);
755             fclose(file);
756         }
757     }
758 }
759
760
761
762
763
764
765
766
767 //
768 // "Never go to sea with two chronometers; take one or three."
769 // Our three time sources are:
770 //  - System clock
771 //  - Median of other nodes's clocks
772 //  - The user (asking the user to fix the system clock if the first two disagree)
773 //
774 int64 GetTime()
775 {
776     return time(NULL);
777 }
778
779 static int64 nTimeOffset = 0;
780
781 int64 GetAdjustedTime()
782 {
783     return GetTime() + nTimeOffset;
784 }
785
786 void AddTimeData(unsigned int ip, int64 nTime)
787 {
788     int64 nOffsetSample = nTime - GetTime();
789
790     // Ignore duplicates
791     static set<unsigned int> setKnown;
792     if (!setKnown.insert(ip).second)
793         return;
794
795     // Add data
796     static vector<int64> vTimeOffsets;
797     if (vTimeOffsets.empty())
798         vTimeOffsets.push_back(0);
799     vTimeOffsets.push_back(nOffsetSample);
800     printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), vTimeOffsets.back(), vTimeOffsets.back()/60);
801     if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
802     {
803         sort(vTimeOffsets.begin(), vTimeOffsets.end());
804         int64 nMedian = vTimeOffsets[vTimeOffsets.size()/2];
805         // Only let other nodes change our time by so much
806         if (abs64(nMedian) < 70 * 60)
807         {
808             nTimeOffset = nMedian;
809         }
810         else
811         {
812             nTimeOffset = 0;
813             // If nobody else has the same time as us, give a warning
814             bool fMatch = false;
815             foreach(int64 nOffset, vTimeOffsets)
816                 if (nOffset != 0 && abs64(nOffset) < 5 * 60)
817                     fMatch = true;
818             static bool fDone;
819             if (!fMatch && !fDone)
820             {
821                 fDone = true;
822                 string strMessage = _("Warning: Please check that your computer's date and time are correct.  If your clock is wrong Bitcoin will not work properly.");
823                 strMiscWarning = strMessage;
824                 printf("*** %s\n", strMessage.c_str());
825                 boost::thread(boost::bind(ThreadSafeMessageBox, strMessage+" ", string("Bitcoin"), wxOK | wxICON_EXCLAMATION, (wxWindow*)NULL, -1, -1));
826             }
827         }
828         foreach(int64 n, vTimeOffsets)
829             printf("%+"PRI64d"  ", n);
830         printf("|  nTimeOffset = %+"PRI64d"  (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
831     }
832 }