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