You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

util.cpp 41KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2012 The Bitcoin developers
  3. // Distributed under the MIT/X11 software license, see the accompanying
  4. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5. #ifndef WIN32
  6. // for posix_fallocate
  7. #ifdef __linux__
  8. #define _POSIX_C_SOURCE 200112L
  9. #endif
  10. #include <fcntl.h>
  11. #include <sys/stat.h>
  12. #include <sys/resource.h>
  13. #endif
  14. #include "chainparams.h"
  15. #include "util.h"
  16. #include "sync.h"
  17. #include "version.h"
  18. #include "ui_interface.h"
  19. #include <boost/algorithm/string/join.hpp>
  20. #include <boost/algorithm/string/case_conv.hpp> // for to_lower()
  21. #include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
  22. // Work around clang compilation problem in Boost 1.46:
  23. // /usr/include/boost/program_options/detail/config_file.hpp:163:17: error: call to function 'to_internal' that is neither visible in the template definition nor found by argument-dependent lookup
  24. // See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options
  25. // http://clang.debian.net/status.php?version=3.0&key=CANNOT_FIND_FUNCTION
  26. namespace boost {
  27. namespace program_options {
  28. std::string to_internal(const std::string&);
  29. }
  30. }
  31. #include <boost/program_options/detail/config_file.hpp>
  32. #include <boost/program_options/parsers.hpp>
  33. #include <boost/filesystem.hpp>
  34. #include <boost/filesystem/fstream.hpp>
  35. #include <boost/foreach.hpp>
  36. #include <boost/thread.hpp>
  37. #include <openssl/crypto.h>
  38. #include <openssl/rand.h>
  39. #include <stdarg.h>
  40. #ifdef WIN32
  41. #ifdef _MSC_VER
  42. #pragma warning(disable:4786)
  43. #pragma warning(disable:4804)
  44. #pragma warning(disable:4805)
  45. #pragma warning(disable:4717)
  46. #endif
  47. #ifdef _WIN32_WINNT
  48. #undef _WIN32_WINNT
  49. #endif
  50. #define _WIN32_WINNT 0x0501
  51. #ifdef _WIN32_IE
  52. #undef _WIN32_IE
  53. #endif
  54. #define _WIN32_IE 0x0501
  55. #define WIN32_LEAN_AND_MEAN 1
  56. #ifndef NOMINMAX
  57. #define NOMINMAX
  58. #endif
  59. #include <io.h> /* for _commit */
  60. #include "shlobj.h"
  61. #elif defined(__linux__)
  62. # include <sys/prctl.h>
  63. #endif
  64. using namespace std;
  65. map<string, string> mapArgs;
  66. map<string, vector<string> > mapMultiArgs;
  67. bool fDebug = false;
  68. bool fDebugNet = false;
  69. bool fPrintToConsole = false;
  70. bool fPrintToDebugger = false;
  71. bool fDaemon = false;
  72. bool fServer = false;
  73. bool fCommandLine = false;
  74. string strMiscWarning;
  75. bool fNoListen = false;
  76. bool fLogTimestamps = false;
  77. CMedianFilter<int64> vTimeOffsets(200,0);
  78. volatile bool fReopenDebugLog = false;
  79. bool fCachedPath[2] = {false, false};
  80. // Init OpenSSL library multithreading support
  81. static CCriticalSection** ppmutexOpenSSL;
  82. void locking_callback(int mode, int i, const char* file, int line)
  83. {
  84. if (mode & CRYPTO_LOCK) {
  85. ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
  86. } else {
  87. LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
  88. }
  89. }
  90. LockedPageManager LockedPageManager::instance;
  91. // Init
  92. class CInit
  93. {
  94. public:
  95. CInit()
  96. {
  97. // Init OpenSSL library multithreading support
  98. ppmutexOpenSSL = (CCriticalSection**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(CCriticalSection*));
  99. for (int i = 0; i < CRYPTO_num_locks(); i++)
  100. ppmutexOpenSSL[i] = new CCriticalSection();
  101. CRYPTO_set_locking_callback(locking_callback);
  102. #ifdef WIN32
  103. // Seed random number generator with screen scrape and other hardware sources
  104. RAND_screen();
  105. #endif
  106. // Seed random number generator with performance counter
  107. RandAddSeed();
  108. }
  109. ~CInit()
  110. {
  111. // Shutdown OpenSSL library multithreading support
  112. CRYPTO_set_locking_callback(NULL);
  113. for (int i = 0; i < CRYPTO_num_locks(); i++)
  114. delete ppmutexOpenSSL[i];
  115. OPENSSL_free(ppmutexOpenSSL);
  116. }
  117. }
  118. instance_of_cinit;
  119. void RandAddSeed()
  120. {
  121. // Seed with CPU performance counter
  122. int64 nCounter = GetPerformanceCounter();
  123. RAND_add(&nCounter, sizeof(nCounter), 1.5);
  124. memset(&nCounter, 0, sizeof(nCounter));
  125. }
  126. void RandAddSeedPerfmon()
  127. {
  128. RandAddSeed();
  129. // This can take up to 2 seconds, so only do it every 10 minutes
  130. static int64 nLastPerfmon;
  131. if (GetTime() < nLastPerfmon + 10 * 60)
  132. return;
  133. nLastPerfmon = GetTime();
  134. #ifdef WIN32
  135. // Don't need this on Linux, OpenSSL automatically uses /dev/urandom
  136. // Seed with the entire set of perfmon data
  137. unsigned char pdata[250000];
  138. memset(pdata, 0, sizeof(pdata));
  139. unsigned long nSize = sizeof(pdata);
  140. long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
  141. RegCloseKey(HKEY_PERFORMANCE_DATA);
  142. if (ret == ERROR_SUCCESS)
  143. {
  144. RAND_add(pdata, nSize, nSize/100.0);
  145. OPENSSL_cleanse(pdata, nSize);
  146. printf("RandAddSeed() %lu bytes\n", nSize);
  147. }
  148. #endif
  149. }
  150. uint64 GetRand(uint64 nMax)
  151. {
  152. if (nMax == 0)
  153. return 0;
  154. // The range of the random source must be a multiple of the modulus
  155. // to give every possible output value an equal possibility
  156. uint64 nRange = (std::numeric_limits<uint64>::max() / nMax) * nMax;
  157. uint64 nRand = 0;
  158. do
  159. RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
  160. while (nRand >= nRange);
  161. return (nRand % nMax);
  162. }
  163. int GetRandInt(int nMax)
  164. {
  165. return GetRand(nMax);
  166. }
  167. uint256 GetRandHash()
  168. {
  169. uint256 hash;
  170. RAND_bytes((unsigned char*)&hash, sizeof(hash));
  171. return hash;
  172. }
  173. //
  174. // OutputDebugStringF (aka printf -- there is a #define that we really
  175. // should get rid of one day) has been broken a couple of times now
  176. // by well-meaning people adding mutexes in the most straightforward way.
  177. // It breaks because it may be called by global destructors during shutdown.
  178. // Since the order of destruction of static/global objects is undefined,
  179. // defining a mutex as a global object doesn't work (the mutex gets
  180. // destroyed, and then some later destructor calls OutputDebugStringF,
  181. // maybe indirectly, and you get a core dump at shutdown trying to lock
  182. // the mutex).
  183. static boost::once_flag debugPrintInitFlag = BOOST_ONCE_INIT;
  184. // We use boost::call_once() to make sure these are initialized in
  185. // in a thread-safe manner the first time it is called:
  186. static FILE* fileout = NULL;
  187. static boost::mutex* mutexDebugLog = NULL;
  188. static void DebugPrintInit()
  189. {
  190. assert(fileout == NULL);
  191. assert(mutexDebugLog == NULL);
  192. boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
  193. fileout = fopen(pathDebug.string().c_str(), "a");
  194. if (fileout) setbuf(fileout, NULL); // unbuffered
  195. mutexDebugLog = new boost::mutex();
  196. }
  197. int OutputDebugStringF(const char* pszFormat, ...)
  198. {
  199. int ret = 0; // Returns total number of characters written
  200. if (fPrintToConsole)
  201. {
  202. // print to console
  203. va_list arg_ptr;
  204. va_start(arg_ptr, pszFormat);
  205. ret += vprintf(pszFormat, arg_ptr);
  206. va_end(arg_ptr);
  207. }
  208. else if (!fPrintToDebugger)
  209. {
  210. static bool fStartedNewLine = true;
  211. boost::call_once(&DebugPrintInit, debugPrintInitFlag);
  212. if (fileout == NULL)
  213. return ret;
  214. boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
  215. // reopen the log file, if requested
  216. if (fReopenDebugLog) {
  217. fReopenDebugLog = false;
  218. boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
  219. if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL)
  220. setbuf(fileout, NULL); // unbuffered
  221. }
  222. // Debug print useful for profiling
  223. if (fLogTimestamps && fStartedNewLine)
  224. ret += fprintf(fileout, "%s ", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()).c_str());
  225. if (pszFormat[strlen(pszFormat) - 1] == '\n')
  226. fStartedNewLine = true;
  227. else
  228. fStartedNewLine = false;
  229. va_list arg_ptr;
  230. va_start(arg_ptr, pszFormat);
  231. ret += vfprintf(fileout, pszFormat, arg_ptr);
  232. va_end(arg_ptr);
  233. }
  234. #ifdef WIN32
  235. if (fPrintToDebugger)
  236. {
  237. static CCriticalSection cs_OutputDebugStringF;
  238. // accumulate and output a line at a time
  239. {
  240. LOCK(cs_OutputDebugStringF);
  241. static std::string buffer;
  242. va_list arg_ptr;
  243. va_start(arg_ptr, pszFormat);
  244. buffer += vstrprintf(pszFormat, arg_ptr);
  245. va_end(arg_ptr);
  246. int line_start = 0, line_end;
  247. while((line_end = buffer.find('\n', line_start)) != -1)
  248. {
  249. OutputDebugStringA(buffer.substr(line_start, line_end - line_start).c_str());
  250. line_start = line_end + 1;
  251. ret += line_end-line_start;
  252. }
  253. buffer.erase(0, line_start);
  254. }
  255. }
  256. #endif
  257. return ret;
  258. }
  259. string vstrprintf(const char *format, va_list ap)
  260. {
  261. char buffer[50000];
  262. char* p = buffer;
  263. int limit = sizeof(buffer);
  264. int ret;
  265. loop
  266. {
  267. va_list arg_ptr;
  268. va_copy(arg_ptr, ap);
  269. #ifdef WIN32
  270. ret = _vsnprintf(p, limit, format, arg_ptr);
  271. #else
  272. ret = vsnprintf(p, limit, format, arg_ptr);
  273. #endif
  274. va_end(arg_ptr);
  275. if (ret >= 0 && ret < limit)
  276. break;
  277. if (p != buffer)
  278. delete[] p;
  279. limit *= 2;
  280. p = new char[limit];
  281. if (p == NULL)
  282. throw std::bad_alloc();
  283. }
  284. string str(p, p+ret);
  285. if (p != buffer)
  286. delete[] p;
  287. return str;
  288. }
  289. string real_strprintf(const char *format, int dummy, ...)
  290. {
  291. va_list arg_ptr;
  292. va_start(arg_ptr, dummy);
  293. string str = vstrprintf(format, arg_ptr);
  294. va_end(arg_ptr);
  295. return str;
  296. }
  297. string real_strprintf(const std::string &format, int dummy, ...)
  298. {
  299. va_list arg_ptr;
  300. va_start(arg_ptr, dummy);
  301. string str = vstrprintf(format.c_str(), arg_ptr);
  302. va_end(arg_ptr);
  303. return str;
  304. }
  305. bool error(const char *format, ...)
  306. {
  307. va_list arg_ptr;
  308. va_start(arg_ptr, format);
  309. std::string str = vstrprintf(format, arg_ptr);
  310. va_end(arg_ptr);
  311. printf("ERROR: %s\n", str.c_str());
  312. return false;
  313. }
  314. void ParseString(const string& str, char c, vector<string>& v)
  315. {
  316. if (str.empty())
  317. return;
  318. string::size_type i1 = 0;
  319. string::size_type i2;
  320. loop
  321. {
  322. i2 = str.find(c, i1);
  323. if (i2 == str.npos)
  324. {
  325. v.push_back(str.substr(i1));
  326. return;
  327. }
  328. v.push_back(str.substr(i1, i2-i1));
  329. i1 = i2+1;
  330. }
  331. }
  332. string FormatMoney(int64 n, bool fPlus)
  333. {
  334. // Note: not using straight sprintf here because we do NOT want
  335. // localized number formatting.
  336. int64 n_abs = (n > 0 ? n : -n);
  337. int64 quotient = n_abs/COIN;
  338. int64 remainder = n_abs%COIN;
  339. string str = strprintf("%"PRI64d".%08"PRI64d, quotient, remainder);
  340. // Right-trim excess zeros before the decimal point:
  341. int nTrim = 0;
  342. for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
  343. ++nTrim;
  344. if (nTrim)
  345. str.erase(str.size()-nTrim, nTrim);
  346. if (n < 0)
  347. str.insert((unsigned int)0, 1, '-');
  348. else if (fPlus && n > 0)
  349. str.insert((unsigned int)0, 1, '+');
  350. return str;
  351. }
  352. bool ParseMoney(const string& str, int64& nRet)
  353. {
  354. return ParseMoney(str.c_str(), nRet);
  355. }
  356. bool ParseMoney(const char* pszIn, int64& nRet)
  357. {
  358. string strWhole;
  359. int64 nUnits = 0;
  360. const char* p = pszIn;
  361. while (isspace(*p))
  362. p++;
  363. for (; *p; p++)
  364. {
  365. if (*p == '.')
  366. {
  367. p++;
  368. int64 nMult = CENT*10;
  369. while (isdigit(*p) && (nMult > 0))
  370. {
  371. nUnits += nMult * (*p++ - '0');
  372. nMult /= 10;
  373. }
  374. break;
  375. }
  376. if (isspace(*p))
  377. break;
  378. if (!isdigit(*p))
  379. return false;
  380. strWhole.insert(strWhole.end(), *p);
  381. }
  382. for (; *p; p++)
  383. if (!isspace(*p))
  384. return false;
  385. if (strWhole.size() > 10) // guard against 63 bit overflow
  386. return false;
  387. if (nUnits < 0 || nUnits > COIN)
  388. return false;
  389. int64 nWhole = atoi64(strWhole);
  390. int64 nValue = nWhole*COIN + nUnits;
  391. nRet = nValue;
  392. return true;
  393. }
  394. static const signed char phexdigit[256] =
  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. 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
  399. -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
  400. -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
  401. -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
  402. -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
  403. -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
  404. -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
  405. -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. bool IsHex(const string& str)
  412. {
  413. BOOST_FOREACH(unsigned char c, str)
  414. {
  415. if (phexdigit[c] < 0)
  416. return false;
  417. }
  418. return (str.size() > 0) && (str.size()%2 == 0);
  419. }
  420. vector<unsigned char> ParseHex(const char* psz)
  421. {
  422. // convert hex dump to vector
  423. vector<unsigned char> vch;
  424. loop
  425. {
  426. while (isspace(*psz))
  427. psz++;
  428. signed char c = phexdigit[(unsigned char)*psz++];
  429. if (c == (signed char)-1)
  430. break;
  431. unsigned char n = (c << 4);
  432. c = phexdigit[(unsigned char)*psz++];
  433. if (c == (signed char)-1)
  434. break;
  435. n |= c;
  436. vch.push_back(n);
  437. }
  438. return vch;
  439. }
  440. vector<unsigned char> ParseHex(const string& str)
  441. {
  442. return ParseHex(str.c_str());
  443. }
  444. static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
  445. {
  446. // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
  447. if (name.find("-no") == 0)
  448. {
  449. std::string positive("-");
  450. positive.append(name.begin()+3, name.end());
  451. if (mapSettingsRet.count(positive) == 0)
  452. {
  453. bool value = !GetBoolArg(name, false);
  454. mapSettingsRet[positive] = (value ? "1" : "0");
  455. }
  456. }
  457. }
  458. void ParseParameters(int argc, const char* const argv[])
  459. {
  460. mapArgs.clear();
  461. mapMultiArgs.clear();
  462. for (int i = 1; i < argc; i++)
  463. {
  464. std::string str(argv[i]);
  465. std::string strValue;
  466. size_t is_index = str.find('=');
  467. if (is_index != std::string::npos)
  468. {
  469. strValue = str.substr(is_index+1);
  470. str = str.substr(0, is_index);
  471. }
  472. #ifdef WIN32
  473. boost::to_lower(str);
  474. if (boost::algorithm::starts_with(str, "/"))
  475. str = "-" + str.substr(1);
  476. #endif
  477. if (str[0] != '-')
  478. break;
  479. mapArgs[str] = strValue;
  480. mapMultiArgs[str].push_back(strValue);
  481. }
  482. // New 0.6 features:
  483. BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs)
  484. {
  485. string name = entry.first;
  486. // interpret --foo as -foo (as long as both are not set)
  487. if (name.find("--") == 0)
  488. {
  489. std::string singleDash(name.begin()+1, name.end());
  490. if (mapArgs.count(singleDash) == 0)
  491. mapArgs[singleDash] = entry.second;
  492. name = singleDash;
  493. }
  494. // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
  495. InterpretNegativeSetting(name, mapArgs);
  496. }
  497. }
  498. std::string GetArg(const std::string& strArg, const std::string& strDefault)
  499. {
  500. if (mapArgs.count(strArg))
  501. return mapArgs[strArg];
  502. return strDefault;
  503. }
  504. int64 GetArg(const std::string& strArg, int64 nDefault)
  505. {
  506. if (mapArgs.count(strArg))
  507. return atoi64(mapArgs[strArg]);
  508. return nDefault;
  509. }
  510. bool GetBoolArg(const std::string& strArg, bool fDefault)
  511. {
  512. if (mapArgs.count(strArg))
  513. {
  514. if (mapArgs[strArg].empty())
  515. return true;
  516. return (atoi(mapArgs[strArg]) != 0);
  517. }
  518. return fDefault;
  519. }
  520. bool SoftSetArg(const std::string& strArg, const std::string& strValue)
  521. {
  522. if (mapArgs.count(strArg))
  523. return false;
  524. mapArgs[strArg] = strValue;
  525. return true;
  526. }
  527. bool SoftSetBoolArg(const std::string& strArg, bool fValue)
  528. {
  529. if (fValue)
  530. return SoftSetArg(strArg, std::string("1"));
  531. else
  532. return SoftSetArg(strArg, std::string("0"));
  533. }
  534. string EncodeBase64(const unsigned char* pch, size_t len)
  535. {
  536. static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  537. string strRet="";
  538. strRet.reserve((len+2)/3*4);
  539. int mode=0, left=0;
  540. const unsigned char *pchEnd = pch+len;
  541. while (pch<pchEnd)
  542. {
  543. int enc = *(pch++);
  544. switch (mode)
  545. {
  546. case 0: // we have no bits
  547. strRet += pbase64[enc >> 2];
  548. left = (enc & 3) << 4;
  549. mode = 1;
  550. break;
  551. case 1: // we have two bits
  552. strRet += pbase64[left | (enc >> 4)];
  553. left = (enc & 15) << 2;
  554. mode = 2;
  555. break;
  556. case 2: // we have four bits
  557. strRet += pbase64[left | (enc >> 6)];
  558. strRet += pbase64[enc & 63];
  559. mode = 0;
  560. break;
  561. }
  562. }
  563. if (mode)
  564. {
  565. strRet += pbase64[left];
  566. strRet += '=';
  567. if (mode == 1)
  568. strRet += '=';
  569. }
  570. return strRet;
  571. }
  572. string EncodeBase64(const string& str)
  573. {
  574. return EncodeBase64((const unsigned char*)str.c_str(), str.size());
  575. }
  576. vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
  577. {
  578. static const int decode64_table[256] =
  579. {
  580. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  581. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  582. -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
  583. -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  584. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
  585. 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
  586. 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  587. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  588. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  589. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  590. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  591. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  592. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
  593. };
  594. if (pfInvalid)
  595. *pfInvalid = false;
  596. vector<unsigned char> vchRet;
  597. vchRet.reserve(strlen(p)*3/4);
  598. int mode = 0;
  599. int left = 0;
  600. while (1)
  601. {
  602. int dec = decode64_table[(unsigned char)*p];
  603. if (dec == -1) break;
  604. p++;
  605. switch (mode)
  606. {
  607. case 0: // we have no bits and get 6
  608. left = dec;
  609. mode = 1;
  610. break;
  611. case 1: // we have 6 bits and keep 4
  612. vchRet.push_back((left<<2) | (dec>>4));
  613. left = dec & 15;
  614. mode = 2;
  615. break;
  616. case 2: // we have 4 bits and get 6, we keep 2
  617. vchRet.push_back((left<<4) | (dec>>2));
  618. left = dec & 3;
  619. mode = 3;
  620. break;
  621. case 3: // we have 2 bits and get 6
  622. vchRet.push_back((left<<6) | dec);
  623. mode = 0;
  624. break;
  625. }
  626. }
  627. if (pfInvalid)
  628. switch (mode)
  629. {
  630. case 0: // 4n base64 characters processed: ok
  631. break;
  632. case 1: // 4n+1 base64 character processed: impossible
  633. *pfInvalid = true;
  634. break;
  635. case 2: // 4n+2 base64 characters processed: require '=='
  636. if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1)
  637. *pfInvalid = true;
  638. break;
  639. case 3: // 4n+3 base64 characters processed: require '='
  640. if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1)
  641. *pfInvalid = true;
  642. break;
  643. }
  644. return vchRet;
  645. }
  646. string DecodeBase64(const string& str)
  647. {
  648. vector<unsigned char> vchRet = DecodeBase64(str.c_str());
  649. return string((const char*)&vchRet[0], vchRet.size());
  650. }
  651. string EncodeBase32(const unsigned char* pch, size_t len)
  652. {
  653. static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567";
  654. string strRet="";
  655. strRet.reserve((len+4)/5*8);
  656. int mode=0, left=0;
  657. const unsigned char *pchEnd = pch+len;
  658. while (pch<pchEnd)
  659. {
  660. int enc = *(pch++);
  661. switch (mode)
  662. {
  663. case 0: // we have no bits
  664. strRet += pbase32[enc >> 3];
  665. left = (enc & 7) << 2;
  666. mode = 1;
  667. break;
  668. case 1: // we have three bits
  669. strRet += pbase32[left | (enc >> 6)];
  670. strRet += pbase32[(enc >> 1) & 31];
  671. left = (enc & 1) << 4;
  672. mode = 2;
  673. break;
  674. case 2: // we have one bit
  675. strRet += pbase32[left | (enc >> 4)];
  676. left = (enc & 15) << 1;
  677. mode = 3;
  678. break;
  679. case 3: // we have four bits
  680. strRet += pbase32[left | (enc >> 7)];
  681. strRet += pbase32[(enc >> 2) & 31];
  682. left = (enc & 3) << 3;
  683. mode = 4;
  684. break;
  685. case 4: // we have two bits
  686. strRet += pbase32[left | (enc >> 5)];
  687. strRet += pbase32[enc & 31];
  688. mode = 0;
  689. }
  690. }
  691. static const int nPadding[5] = {0, 6, 4, 3, 1};
  692. if (mode)
  693. {
  694. strRet += pbase32[left];
  695. for (int n=0; n<nPadding[mode]; n++)
  696. strRet += '=';
  697. }
  698. return strRet;
  699. }
  700. string EncodeBase32(const string& str)
  701. {
  702. return EncodeBase32((const unsigned char*)str.c_str(), str.size());
  703. }
  704. vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid)
  705. {
  706. static const int decode32_table[256] =
  707. {
  708. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  709. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  710. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1,
  711. -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  712. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 0, 1, 2,
  713. 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
  714. 23, 24, 25, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  715. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  716. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  717. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  718. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  719. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  720. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
  721. };
  722. if (pfInvalid)
  723. *pfInvalid = false;
  724. vector<unsigned char> vchRet;
  725. vchRet.reserve((strlen(p))*5/8);
  726. int mode = 0;
  727. int left = 0;
  728. while (1)
  729. {
  730. int dec = decode32_table[(unsigned char)*p];
  731. if (dec == -1) break;
  732. p++;
  733. switch (mode)
  734. {
  735. case 0: // we have no bits and get 5
  736. left = dec;
  737. mode = 1;
  738. break;
  739. case 1: // we have 5 bits and keep 2
  740. vchRet.push_back((left<<3) | (dec>>2));
  741. left = dec & 3;
  742. mode = 2;
  743. break;
  744. case 2: // we have 2 bits and keep 7
  745. left = left << 5 | dec;
  746. mode = 3;
  747. break;
  748. case 3: // we have 7 bits and keep 4
  749. vchRet.push_back((left<<1) | (dec>>4));
  750. left = dec & 15;
  751. mode = 4;
  752. break;
  753. case 4: // we have 4 bits, and keep 1
  754. vchRet.push_back((left<<4) | (dec>>1));
  755. left = dec & 1;
  756. mode = 5;
  757. break;
  758. case 5: // we have 1 bit, and keep 6
  759. left = left << 5 | dec;
  760. mode = 6;
  761. break;
  762. case 6: // we have 6 bits, and keep 3
  763. vchRet.push_back((left<<2) | (dec>>3));
  764. left = dec & 7;
  765. mode = 7;
  766. break;
  767. case 7: // we have 3 bits, and keep 0
  768. vchRet.push_back((left<<5) | dec);
  769. mode = 0;
  770. break;
  771. }
  772. }
  773. if (pfInvalid)
  774. switch (mode)
  775. {
  776. case 0: // 8n base32 characters processed: ok
  777. break;
  778. case 1: // 8n+1 base32 characters processed: impossible
  779. case 3: // +3
  780. case 6: // +6
  781. *pfInvalid = true;
  782. break;
  783. case 2: // 8n+2 base32 characters processed: require '======'
  784. if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || p[4] != '=' || p[5] != '=' || decode32_table[(unsigned char)p[6]] != -1)
  785. *pfInvalid = true;
  786. break;
  787. case 4: // 8n+4 base32 characters processed: require '===='
  788. if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || decode32_table[(unsigned char)p[4]] != -1)
  789. *pfInvalid = true;
  790. break;
  791. case 5: // 8n+5 base32 characters processed: require '==='
  792. if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || decode32_table[(unsigned char)p[3]] != -1)
  793. *pfInvalid = true;
  794. break;
  795. case 7: // 8n+7 base32 characters processed: require '='
  796. if (left || p[0] != '=' || decode32_table[(unsigned char)p[1]] != -1)
  797. *pfInvalid = true;
  798. break;
  799. }
  800. return vchRet;
  801. }
  802. string DecodeBase32(const string& str)
  803. {
  804. vector<unsigned char> vchRet = DecodeBase32(str.c_str());
  805. return string((const char*)&vchRet[0], vchRet.size());
  806. }
  807. bool WildcardMatch(const char* psz, const char* mask)
  808. {
  809. loop
  810. {
  811. switch (*mask)
  812. {
  813. case '\0':
  814. return (*psz == '\0');
  815. case '*':
  816. return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
  817. case '?':
  818. if (*psz == '\0')
  819. return false;
  820. break;
  821. default:
  822. if (*psz != *mask)
  823. return false;
  824. break;
  825. }
  826. psz++;
  827. mask++;
  828. }
  829. }
  830. bool WildcardMatch(const string& str, const string& mask)
  831. {
  832. return WildcardMatch(str.c_str(), mask.c_str());
  833. }
  834. static std::string FormatException(std::exception* pex, const char* pszThread)
  835. {
  836. #ifdef WIN32
  837. char pszModule[MAX_PATH] = "";
  838. GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
  839. #else
  840. const char* pszModule = "bitcoin";
  841. #endif
  842. if (pex)
  843. return strprintf(
  844. "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
  845. else
  846. return strprintf(
  847. "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
  848. }
  849. void LogException(std::exception* pex, const char* pszThread)
  850. {
  851. std::string message = FormatException(pex, pszThread);
  852. printf("\n%s", message.c_str());
  853. }
  854. void PrintException(std::exception* pex, const char* pszThread)
  855. {
  856. std::string message = FormatException(pex, pszThread);
  857. printf("\n\n************************\n%s\n", message.c_str());
  858. fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
  859. strMiscWarning = message;
  860. throw;
  861. }
  862. void PrintExceptionContinue(std::exception* pex, const char* pszThread)
  863. {
  864. std::string message = FormatException(pex, pszThread);
  865. printf("\n\n************************\n%s\n", message.c_str());
  866. fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
  867. strMiscWarning = message;
  868. }
  869. boost::filesystem::path GetDefaultDataDir()
  870. {
  871. namespace fs = boost::filesystem;
  872. // Windows < Vista: C:\Documents and Settings\Username\Application Data\Bitcoin
  873. // Windows >= Vista: C:\Users\Username\AppData\Roaming\Bitcoin
  874. // Mac: ~/Library/Application Support/Bitcoin
  875. // Unix: ~/.bitcoin
  876. #ifdef WIN32
  877. // Windows
  878. return GetSpecialFolderPath(CSIDL_APPDATA) / "Bitcoin";
  879. #else
  880. fs::path pathRet;
  881. char* pszHome = getenv("HOME");
  882. if (pszHome == NULL || strlen(pszHome) == 0)
  883. pathRet = fs::path("/");
  884. else
  885. pathRet = fs::path(pszHome);
  886. #ifdef MAC_OSX
  887. // Mac
  888. pathRet /= "Library/Application Support";
  889. fs::create_directory(pathRet);
  890. return pathRet / "Bitcoin";
  891. #else
  892. // Unix
  893. return pathRet / ".bitcoin";
  894. #endif
  895. #endif
  896. }
  897. const boost::filesystem::path &GetDataDir(bool fNetSpecific)
  898. {
  899. namespace fs = boost::filesystem;
  900. static fs::path pathCached[2];
  901. static CCriticalSection csPathCached;
  902. fs::path &path = pathCached[fNetSpecific];
  903. // This can be called during exceptions by printf, so we cache the
  904. // value so we don't have to do memory allocations after that.
  905. if (fCachedPath[fNetSpecific])
  906. return path;
  907. LOCK(csPathCached);
  908. if (mapArgs.count("-datadir")) {
  909. path = fs::system_complete(mapArgs["-datadir"]);
  910. if (!fs::is_directory(path)) {
  911. path = "";
  912. return path;
  913. }
  914. } else {
  915. path = GetDefaultDataDir();
  916. }
  917. if (fNetSpecific)
  918. path /= Params().DataDir();
  919. fs::create_directories(path);
  920. fCachedPath[fNetSpecific] = true;
  921. return path;
  922. }
  923. boost::filesystem::path GetConfigFile()
  924. {
  925. boost::filesystem::path pathConfigFile(GetArg("-conf", "bitcoin.conf"));
  926. if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
  927. return pathConfigFile;
  928. }
  929. void ReadConfigFile(map<string, string>& mapSettingsRet,
  930. map<string, vector<string> >& mapMultiSettingsRet)
  931. {
  932. boost::filesystem::ifstream streamConfig(GetConfigFile());
  933. if (!streamConfig.good())
  934. return; // No bitcoin.conf file is OK
  935. // clear path cache after loading config file
  936. fCachedPath[0] = fCachedPath[1] = false;
  937. set<string> setOptions;
  938. setOptions.insert("*");
  939. for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
  940. {
  941. // Don't overwrite existing settings so command line settings override bitcoin.conf
  942. string strKey = string("-") + it->string_key;
  943. if (mapSettingsRet.count(strKey) == 0)
  944. {
  945. mapSettingsRet[strKey] = it->value[0];
  946. // interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
  947. InterpretNegativeSetting(strKey, mapSettingsRet);
  948. }
  949. mapMultiSettingsRet[strKey].push_back(it->value[0]);
  950. }
  951. }
  952. boost::filesystem::path GetPidFile()
  953. {
  954. boost::filesystem::path pathPidFile(GetArg("-pid", "bitcoind.pid"));
  955. if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
  956. return pathPidFile;
  957. }
  958. void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
  959. {
  960. FILE* file = fopen(path.string().c_str(), "w");
  961. if (file)
  962. {
  963. fprintf(file, "%d\n", pid);
  964. fclose(file);
  965. }
  966. }
  967. bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
  968. {
  969. #ifdef WIN32
  970. return MoveFileExA(src.string().c_str(), dest.string().c_str(),
  971. MOVEFILE_REPLACE_EXISTING);
  972. #else
  973. int rc = std::rename(src.string().c_str(), dest.string().c_str());
  974. return (rc == 0);
  975. #endif /* WIN32 */
  976. }
  977. void FileCommit(FILE *fileout)
  978. {
  979. fflush(fileout); // harmless if redundantly called
  980. #ifdef WIN32
  981. _commit(_fileno(fileout));
  982. #else
  983. #if defined(__linux__) || defined(__NetBSD__)
  984. fdatasync(fileno(fileout));
  985. #else
  986. fsync(fileno(fileout));
  987. #endif
  988. #endif
  989. }
  990. int GetFilesize(FILE* file)
  991. {
  992. int nSavePos = ftell(file);
  993. int nFilesize = -1;
  994. if (fseek(file, 0, SEEK_END) == 0)
  995. nFilesize = ftell(file);
  996. fseek(file, nSavePos, SEEK_SET);
  997. return nFilesize;
  998. }
  999. bool TruncateFile(FILE *file, unsigned int length) {
  1000. #if defined(WIN32)
  1001. return _chsize(_fileno(file), length) == 0;
  1002. #else
  1003. return ftruncate(fileno(file), length) == 0;
  1004. #endif
  1005. }
  1006. // this function tries to raise the file descriptor limit to the requested number.
  1007. // It returns the actual file descriptor limit (which may be more or less than nMinFD)
  1008. int RaiseFileDescriptorLimit(int nMinFD) {
  1009. #if defined(WIN32)
  1010. return 2048;
  1011. #else
  1012. struct rlimit limitFD;
  1013. if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) {
  1014. if (limitFD.rlim_cur < (rlim_t)nMinFD) {
  1015. limitFD.rlim_cur = nMinFD;
  1016. if (limitFD.rlim_cur > limitFD.rlim_max)
  1017. limitFD.rlim_cur = limitFD.rlim_max;
  1018. setrlimit(RLIMIT_NOFILE, &limitFD);
  1019. getrlimit(RLIMIT_NOFILE, &limitFD);
  1020. }
  1021. return limitFD.rlim_cur;
  1022. }
  1023. return nMinFD; // getrlimit failed, assume it's fine
  1024. #endif
  1025. }
  1026. // this function tries to make a particular range of a file allocated (corresponding to disk space)
  1027. // it is advisory, and the range specified in the arguments will never contain live data
  1028. void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length) {
  1029. #if defined(WIN32)
  1030. // Windows-specific version
  1031. HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
  1032. LARGE_INTEGER nFileSize;
  1033. int64 nEndPos = (int64)offset + length;
  1034. nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF;
  1035. nFileSize.u.HighPart = nEndPos >> 32;
  1036. SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN);
  1037. SetEndOfFile(hFile);
  1038. #elif defined(MAC_OSX)
  1039. // OSX specific version
  1040. fstore_t fst;
  1041. fst.fst_flags = F_ALLOCATECONTIG;
  1042. fst.fst_posmode = F_PEOFPOSMODE;
  1043. fst.fst_offset = 0;
  1044. fst.fst_length = (off_t)offset + length;
  1045. fst.fst_bytesalloc = 0;
  1046. if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) {
  1047. fst.fst_flags = F_ALLOCATEALL;
  1048. fcntl(fileno(file), F_PREALLOCATE, &fst);
  1049. }
  1050. ftruncate(fileno(file), fst.fst_length);
  1051. #elif defined(__linux__)
  1052. // Version using posix_fallocate
  1053. off_t nEndPos = (off_t)offset + length;
  1054. posix_fallocate(fileno(file), 0, nEndPos);
  1055. #else
  1056. // Fallback version
  1057. // TODO: just write one byte per block
  1058. static const char buf[65536] = {};
  1059. fseek(file, offset, SEEK_SET);
  1060. while (length > 0) {
  1061. unsigned int now = 65536;
  1062. if (length < now)
  1063. now = length;
  1064. fwrite(buf, 1, now, file); // allowed to fail; this function is advisory anyway
  1065. length -= now;
  1066. }
  1067. #endif
  1068. }
  1069. void ShrinkDebugFile()
  1070. {
  1071. // Scroll debug.log if it's getting too big
  1072. boost::filesystem::path pathLog = GetDataDir() / "debug.log";
  1073. FILE* file = fopen(pathLog.string().c_str(), "r");
  1074. if (file && GetFilesize(file) > 10 * 1000000)
  1075. {
  1076. // Restart the file with some of the end
  1077. char pch[200000];
  1078. fseek(file, -sizeof(pch), SEEK_END);
  1079. int nBytes = fread(pch, 1, sizeof(pch), file);
  1080. fclose(file);
  1081. file = fopen(pathLog.string().c_str(), "w");
  1082. if (file)
  1083. {
  1084. fwrite(pch, 1, nBytes, file);
  1085. fclose(file);
  1086. }
  1087. }
  1088. else if (file != NULL)
  1089. fclose(file);
  1090. }
  1091. //
  1092. // "Never go to sea with two chronometers; take one or three."
  1093. // Our three time sources are:
  1094. // - System clock
  1095. // - Median of other nodes clocks
  1096. // - The user (asking the user to fix the system clock if the first two disagree)
  1097. //
  1098. static int64 nMockTime = 0; // For unit testing
  1099. int64 GetTime()
  1100. {
  1101. if (nMockTime) return nMockTime;
  1102. return time(NULL);
  1103. }
  1104. void SetMockTime(int64 nMockTimeIn)
  1105. {
  1106. nMockTime = nMockTimeIn;
  1107. }
  1108. static int64 nTimeOffset = 0;
  1109. int64 GetTimeOffset()
  1110. {
  1111. return nTimeOffset;
  1112. }
  1113. int64 GetAdjustedTime()
  1114. {
  1115. return GetTime() + GetTimeOffset();
  1116. }
  1117. void AddTimeData(const CNetAddr& ip, int64 nTime)
  1118. {
  1119. int64 nOffsetSample = nTime - GetTime();
  1120. // Ignore duplicates
  1121. static set<CNetAddr> setKnown;
  1122. if (!setKnown.insert(ip).second)
  1123. return;
  1124. // Add data
  1125. vTimeOffsets.input(nOffsetSample);
  1126. printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
  1127. if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
  1128. {
  1129. int64 nMedian = vTimeOffsets.median();
  1130. std::vector<int64> vSorted = vTimeOffsets.sorted();
  1131. // Only let other nodes change our time by so much
  1132. if (abs64(nMedian) < 70 * 60)
  1133. {
  1134. nTimeOffset = nMedian;
  1135. }
  1136. else
  1137. {
  1138. nTimeOffset = 0;
  1139. static bool fDone;
  1140. if (!fDone)
  1141. {
  1142. // If nobody has a time different than ours but within 5 minutes of ours, give a warning
  1143. bool fMatch = false;
  1144. BOOST_FOREACH(int64 nOffset, vSorted)
  1145. if (nOffset != 0 && abs64(nOffset) < 5 * 60)
  1146. fMatch = true;
  1147. if (!fMatch)
  1148. {
  1149. fDone = true;
  1150. string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong Bitcoin will not work properly.");
  1151. strMiscWarning = strMessage;
  1152. printf("*** %s\n", strMessage.c_str());
  1153. uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_WARNING);
  1154. }
  1155. }
  1156. }
  1157. if (fDebug) {
  1158. BOOST_FOREACH(int64 n, vSorted)
  1159. printf("%+"PRI64d" ", n);
  1160. printf("| ");
  1161. }
  1162. printf("nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
  1163. }
  1164. }
  1165. uint32_t insecure_rand_Rz = 11;
  1166. uint32_t insecure_rand_Rw = 11;
  1167. void seed_insecure_rand(bool fDeterministic)
  1168. {
  1169. //The seed values have some unlikely fixed points which we avoid.
  1170. if(fDeterministic)
  1171. {
  1172. insecure_rand_Rz = insecure_rand_Rw = 11;
  1173. } else {
  1174. uint32_t tmp;
  1175. do {
  1176. RAND_bytes((unsigned char*)&tmp, 4);
  1177. } while(tmp == 0 || tmp == 0x9068ffffU);
  1178. insecure_rand_Rz = tmp;
  1179. do {
  1180. RAND_bytes((unsigned char*)&tmp, 4);
  1181. } while(tmp == 0 || tmp == 0x464fffffU);
  1182. insecure_rand_Rw = tmp;
  1183. }
  1184. }
  1185. string FormatVersion(int nVersion)
  1186. {
  1187. if (nVersion%100 == 0)
  1188. return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
  1189. else
  1190. return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
  1191. }
  1192. string FormatFullVersion()
  1193. {
  1194. return CLIENT_BUILD;
  1195. }
  1196. // Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
  1197. std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
  1198. {
  1199. std::ostringstream ss;
  1200. ss << "/";
  1201. ss << name << ":" << FormatVersion(nClientVersion);
  1202. if (!comments.empty())
  1203. ss << "(" << boost::algorithm::join(comments, "; ") << ")";
  1204. ss << "/";
  1205. return ss.str();
  1206. }
  1207. #ifdef WIN32
  1208. boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate)
  1209. {
  1210. namespace fs = boost::filesystem;
  1211. char pszPath[MAX_PATH] = "";
  1212. if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
  1213. {
  1214. return fs::path(pszPath);
  1215. }
  1216. printf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
  1217. return fs::path("");
  1218. }
  1219. #endif
  1220. boost::filesystem::path GetTempPath() {
  1221. #if BOOST_FILESYSTEM_VERSION == 3
  1222. return boost::filesystem::temp_directory_path();
  1223. #else
  1224. // TODO: remove when we don't support filesystem v2 anymore
  1225. boost::filesystem::path path;
  1226. #ifdef WIN32
  1227. char pszPath[MAX_PATH] = "";
  1228. if (GetTempPathA(MAX_PATH, pszPath))
  1229. path = boost::filesystem::path(pszPath);
  1230. #else
  1231. path = boost::filesystem::path("/tmp");
  1232. #endif
  1233. if (path.empty() || !boost::filesystem::is_directory(path)) {
  1234. printf("GetTempPath(): failed to find temp path\n");
  1235. return boost::filesystem::path("");
  1236. }
  1237. return path;
  1238. #endif
  1239. }
  1240. void runCommand(std::string strCommand)
  1241. {
  1242. int nErr = ::system(strCommand.c_str());
  1243. if (nErr)
  1244. printf("runCommand error: system(%s) returned %d\n", strCommand.c_str(), nErr);
  1245. }
  1246. void RenameThread(const char* name)
  1247. {
  1248. #if defined(PR_SET_NAME)
  1249. // Only the first 15 characters are used (16 - NUL terminator)
  1250. ::prctl(PR_SET_NAME, name, 0, 0, 0);
  1251. #elif 0 && (defined(__FreeBSD__) || defined(__OpenBSD__))
  1252. // TODO: This is currently disabled because it needs to be verified to work
  1253. // on FreeBSD or OpenBSD first. When verified the '0 &&' part can be
  1254. // removed.
  1255. pthread_set_name_np(pthread_self(), name);
  1256. #elif defined(MAC_OSX) && defined(__MAC_OS_X_VERSION_MAX_ALLOWED)
  1257. // pthread_setname_np is XCode 10.6-and-later
  1258. #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
  1259. pthread_setname_np(name);
  1260. #endif
  1261. #else
  1262. // Prevent warnings for unused parameters...
  1263. (void)name;
  1264. #endif
  1265. }