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