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