Anoncoin  0.9.4
P2P Digital Currency
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 // Copyright (c) 2013-2014 The Anoncoin Core developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 
7 #include "util.h"
8 
9 #include "chainparams.h"
10 #include "netbase.h"
11 #include "sync.h"
12 #include "ui_interface.h"
13 #include "uint256.h"
14 #include "version.h"
15 
16 #include <stdarg.h>
17 
18 #ifndef WIN32
19 // for posix_fallocate
20 #ifdef __linux_
21 
22 #ifdef _POSIX_C_SOURCE
23 #undef _POSIX_C_SOURCE
24 #endif
25 
26 #define _POSIX_C_SOURCE 200112L
27 #include <sys/prctl.h>
28 #endif // __linux_
29 
30 #include <algorithm>
31 #include <fcntl.h>
32 #include <sys/resource.h>
33 #include <sys/stat.h>
34 
35 #else // is WIN32
36 
37 #ifdef _MSC_VER
38 #pragma warning(disable:4786)
39 #pragma warning(disable:4804)
40 #pragma warning(disable:4805)
41 #pragma warning(disable:4717)
42 #endif // _MSC_VER
43 
44 #ifdef _WIN32_WINNT
45 #undef _WIN32_WINNT
46 #endif
47 #define _WIN32_WINNT 0x0501
48 
49 #ifdef _WIN32_IE
50 #undef _WIN32_IE
51 #endif
52 #define _WIN32_IE 0x0501
53 
54 #define WIN32_LEAN_AND_MEAN 1
55 #ifndef NOMINMAX
56 #define NOMINMAX
57 #endif
58 
59 #include <io.h> /* for _commit */
60 #include <shlobj.h>
61 #endif // WIN32
62 
63 #include <boost/algorithm/string/case_conv.hpp> // for to_lower()
64 #include <boost/algorithm/string/join.hpp>
65 #include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
66 #include <boost/date_time/posix_time/posix_time.hpp>
67 #include <boost/filesystem.hpp>
68 #include <boost/filesystem/fstream.hpp>
69 #include <boost/foreach.hpp>
70 #include <boost/program_options/detail/config_file.hpp>
71 #include <boost/program_options/parsers.hpp>
72 
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
103 static CCriticalSection** ppmutexOpenSSL;
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  // Keep in mind here, appears non-win32 builds will be case sensitive on parameter names
480  if (str[0] != '-')
481  break;
482 
483  mapArgs[str] = strValue;
484  mapMultiArgs[str].push_back(strValue);
485  }
486 
487  // New 0.6 features:
488  BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs)
489  {
490  string name = entry.first;
491 
492  // interpret --foo as -foo (as long as both are not set)
493  if (name.find("--") == 0)
494  {
495  std::string singleDash(name.begin()+1, name.end());
496  if (mapArgs.count(singleDash) == 0)
497  mapArgs[singleDash] = entry.second;
498  name = singleDash;
499  }
500 
501  // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
502  InterpretNegativeSetting(name, mapArgs);
503  }
504 }
505 
506 std::string GetArg(const std::string& strArg, const std::string& strDefault)
507 {
508  if (mapArgs.count(strArg))
509  return mapArgs[strArg];
510  return strDefault;
511 }
512 
513 int64_t GetArg(const std::string& strArg, int64_t nDefault)
514 {
515  if (mapArgs.count(strArg))
516  return atoi64(mapArgs[strArg]);
517  return nDefault;
518 }
519 
520 bool GetBoolArg(const std::string& strArg, bool fDefault)
521 {
522  if (mapArgs.count(strArg))
523  {
524  if (mapArgs[strArg].empty())
525  return true;
526  return (atoi(mapArgs[strArg]) != 0);
527  }
528  return fDefault;
529 }
530 
531 bool SoftSetArg(const std::string& strArg, const std::string& strValue)
532 {
533  if (mapArgs.count(strArg))
534  return false;
535  mapArgs[strArg] = strValue;
536  return true;
537 }
538 
539 bool SoftSetBoolArg(const std::string& strArg, bool fValue)
540 {
541  if (fValue)
542  return SoftSetArg(strArg, std::string("1"));
543  else
544  return SoftSetArg(strArg, std::string("0"));
545 }
546 
547 
548 string EncodeBase64(const unsigned char* pch, size_t len)
549 {
550  static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
551 
552  string strRet="";
553  strRet.reserve((len+2)/3*4);
554 
555  int mode=0, left=0;
556  const unsigned char *pchEnd = pch+len;
557 
558  while (pch<pchEnd)
559  {
560  int enc = *(pch++);
561  switch (mode)
562  {
563  case 0: // we have no bits
564  strRet += pbase64[enc >> 2];
565  left = (enc & 3) << 4;
566  mode = 1;
567  break;
568 
569  case 1: // we have two bits
570  strRet += pbase64[left | (enc >> 4)];
571  left = (enc & 15) << 2;
572  mode = 2;
573  break;
574 
575  case 2: // we have four bits
576  strRet += pbase64[left | (enc >> 6)];
577  strRet += pbase64[enc & 63];
578  mode = 0;
579  break;
580  }
581  }
582 
583  if (mode)
584  {
585  strRet += pbase64[left];
586  strRet += '=';
587  if (mode == 1)
588  strRet += '=';
589  }
590 
591  return strRet;
592 }
593 
594 string EncodeBase64(const string& str)
595 {
596  return EncodeBase64((const unsigned char*)str.c_str(), str.size());
597 }
598 
599 vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
600 {
601  static const int decode64_table[256] =
602  {
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, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
605  -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
606  -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
607  15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
608  29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
609  49, 50, 51, -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, -1, -1, -1, -1,
615  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
616  };
617 
618  if (pfInvalid)
619  *pfInvalid = false;
620 
621  vector<unsigned char> vchRet;
622  vchRet.reserve(strlen(p)*3/4);
623 
624  int mode = 0;
625  int left = 0;
626 
627  while (1)
628  {
629  int dec = decode64_table[(unsigned char)*p];
630  if (dec == -1) break;
631  p++;
632  switch (mode)
633  {
634  case 0: // we have no bits and get 6
635  left = dec;
636  mode = 1;
637  break;
638 
639  case 1: // we have 6 bits and keep 4
640  vchRet.push_back((left<<2) | (dec>>4));
641  left = dec & 15;
642  mode = 2;
643  break;
644 
645  case 2: // we have 4 bits and get 6, we keep 2
646  vchRet.push_back((left<<4) | (dec>>2));
647  left = dec & 3;
648  mode = 3;
649  break;
650 
651  case 3: // we have 2 bits and get 6
652  vchRet.push_back((left<<6) | dec);
653  mode = 0;
654  break;
655  }
656  }
657 
658  if (pfInvalid)
659  switch (mode)
660  {
661  case 0: // 4n base64 characters processed: ok
662  break;
663 
664  case 1: // 4n+1 base64 character processed: impossible
665  *pfInvalid = true;
666  break;
667 
668  case 2: // 4n+2 base64 characters processed: require '=='
669  if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1)
670  *pfInvalid = true;
671  break;
672 
673  case 3: // 4n+3 base64 characters processed: require '='
674  if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1)
675  *pfInvalid = true;
676  break;
677  }
678 
679  return vchRet;
680 }
681 
682 string DecodeBase64(const string& str)
683 {
684  vector<unsigned char> vchRet = DecodeBase64(str.c_str());
685  return string((const char*)&vchRet[0], vchRet.size());
686 }
687 
688 string EncodeBase32(const unsigned char* pch, size_t len)
689 {
690  static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567";
691 
692  string strRet="";
693  strRet.reserve((len+4)/5*8);
694 
695  int mode=0, left=0;
696  const unsigned char *pchEnd = pch+len;
697 
698  while (pch<pchEnd)
699  {
700  int enc = *(pch++);
701  switch (mode)
702  {
703  case 0: // we have no bits
704  strRet += pbase32[enc >> 3];
705  left = (enc & 7) << 2;
706  mode = 1;
707  break;
708 
709  case 1: // we have three bits
710  strRet += pbase32[left | (enc >> 6)];
711  strRet += pbase32[(enc >> 1) & 31];
712  left = (enc & 1) << 4;
713  mode = 2;
714  break;
715 
716  case 2: // we have one bit
717  strRet += pbase32[left | (enc >> 4)];
718  left = (enc & 15) << 1;
719  mode = 3;
720  break;
721 
722  case 3: // we have four bits
723  strRet += pbase32[left | (enc >> 7)];
724  strRet += pbase32[(enc >> 2) & 31];
725  left = (enc & 3) << 3;
726  mode = 4;
727  break;
728 
729  case 4: // we have two bits
730  strRet += pbase32[left | (enc >> 5)];
731  strRet += pbase32[enc & 31];
732  mode = 0;
733  }
734  }
735 
736  static const int nPadding[5] = {0, 6, 4, 3, 1};
737  if (mode)
738  {
739  strRet += pbase32[left];
740  for (int n=0; n<nPadding[mode]; n++)
741  strRet += '=';
742  }
743 
744  return strRet;
745 }
746 
747 string EncodeBase32(const string& str)
748 {
749  return EncodeBase32((const unsigned char*)str.c_str(), str.size());
750 }
751 
752 vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid)
753 {
754  static const int decode32_table[256] =
755  {
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, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
758  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1,
759  -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
760  15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 0, 1, 2,
761  3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
762  23, 24, 25, -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, -1, -1, -1, -1,
768  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
769  };
770 
771  if (pfInvalid)
772  *pfInvalid = false;
773 
774  vector<unsigned char> vchRet;
775  vchRet.reserve((strlen(p))*5/8);
776 
777  int mode = 0;
778  int left = 0;
779 
780  while (1)
781  {
782  int dec = decode32_table[(unsigned char)*p];
783  if (dec == -1) break;
784  p++;
785  switch (mode)
786  {
787  case 0: // we have no bits and get 5
788  left = dec;
789  mode = 1;
790  break;
791 
792  case 1: // we have 5 bits and keep 2
793  vchRet.push_back((left<<3) | (dec>>2));
794  left = dec & 3;
795  mode = 2;
796  break;
797 
798  case 2: // we have 2 bits and keep 7
799  left = left << 5 | dec;
800  mode = 3;
801  break;
802 
803  case 3: // we have 7 bits and keep 4
804  vchRet.push_back((left<<1) | (dec>>4));
805  left = dec & 15;
806  mode = 4;
807  break;
808 
809  case 4: // we have 4 bits, and keep 1
810  vchRet.push_back((left<<4) | (dec>>1));
811  left = dec & 1;
812  mode = 5;
813  break;
814 
815  case 5: // we have 1 bit, and keep 6
816  left = left << 5 | dec;
817  mode = 6;
818  break;
819 
820  case 6: // we have 6 bits, and keep 3
821  vchRet.push_back((left<<2) | (dec>>3));
822  left = dec & 7;
823  mode = 7;
824  break;
825 
826  case 7: // we have 3 bits, and keep 0
827  vchRet.push_back((left<<5) | dec);
828  mode = 0;
829  break;
830  }
831  }
832 
833  if (pfInvalid)
834  switch (mode)
835  {
836  case 0: // 8n base32 characters processed: ok
837  break;
838 
839  case 1: // 8n+1 base32 characters processed: impossible
840  case 3: // +3
841  case 6: // +6
842  *pfInvalid = true;
843  break;
844 
845  case 2: // 8n+2 base32 characters processed: require '======'
846  if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || p[4] != '=' || p[5] != '=' || decode32_table[(unsigned char)p[6]] != -1)
847  *pfInvalid = true;
848  break;
849 
850  case 4: // 8n+4 base32 characters processed: require '===='
851  if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || decode32_table[(unsigned char)p[4]] != -1)
852  *pfInvalid = true;
853  break;
854 
855  case 5: // 8n+5 base32 characters processed: require '==='
856  if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || decode32_table[(unsigned char)p[3]] != -1)
857  *pfInvalid = true;
858  break;
859 
860  case 7: // 8n+7 base32 characters processed: require '='
861  if (left || p[0] != '=' || decode32_table[(unsigned char)p[1]] != -1)
862  *pfInvalid = true;
863  break;
864  }
865 
866  return vchRet;
867 }
868 
869 string DecodeBase32(const string& str)
870 {
871  vector<unsigned char> vchRet = DecodeBase32(str.c_str());
872  return string((const char*)&vchRet[0], vchRet.size());
873 }
874 
875 
876 bool WildcardMatch(const char* psz, const char* mask)
877 {
878  while (true)
879  {
880  switch (*mask)
881  {
882  case '\0':
883  return (*psz == '\0');
884  case '*':
885  return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
886  case '?':
887  if (*psz == '\0')
888  return false;
889  break;
890  default:
891  if (*psz != *mask)
892  return false;
893  break;
894  }
895  psz++;
896  mask++;
897  }
898 }
899 
900 bool WildcardMatch(const string& str, const string& mask)
901 {
902  return WildcardMatch(str.c_str(), mask.c_str());
903 }
904 
905 
906 static std::string FormatException(std::exception* pex, const char* pszThread)
907 {
908 #ifdef WIN32
909  char pszModule[MAX_PATH] = "";
910  GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
911 #else
912  const char* pszModule = "anoncoin";
913 #endif
914  if (pex)
915  return strprintf(
916  "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
917  else
918  return strprintf(
919  "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
920 }
921 
922 void LogException(std::exception* pex, const char* pszThread)
923 {
924  std::string message = FormatException(pex, pszThread);
925  LogPrintf("\n%s", message);
926 }
927 
928 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
929 {
930  std::string message = FormatException(pex, pszThread);
931  LogPrintf("\n\n************************\n%s\n", message);
932  fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
933  strMiscWarning = message;
934 }
935 
936 boost::filesystem::path GetDefaultDataDir()
937 {
938  namespace fs = boost::filesystem;
939  // Windows < Vista: C:\Documents and Settings\Username\Application Data\Anoncoin
940  // Windows >= Vista: C:\Users\Username\AppData\Roaming\Anoncoin
941  // Mac: ~/Library/Application Support/Anoncoin
942  // Unix: ~/.anoncoin
943 #ifdef WIN32
944  // Windows
945  return GetSpecialFolderPath(CSIDL_APPDATA) / "Anoncoin";
946 #else
947  fs::path pathRet;
948  char* pszHome = getenv("HOME");
949  if (pszHome == NULL || strlen(pszHome) == 0)
950  pathRet = fs::path("/");
951  else
952  pathRet = fs::path(pszHome);
953 #ifdef MAC_OSX
954  // Mac
955  pathRet /= "Library/Application Support";
956  TryCreateDirectory(pathRet);
957  return pathRet / "Anoncoin";
958 #else
959  // Unix
960  return pathRet / ".anoncoin";
961 #endif // MAC_OSX
962 #endif // WIN32
963 }
964 
965 static boost::filesystem::path pathCached[CChainParams::MAX_NETWORK_TYPES+1];
966 static CCriticalSection csPathCached;
967 
968 const boost::filesystem::path &GetDataDir(bool fNetSpecific)
969 {
970  namespace fs = boost::filesystem;
971 
972  LOCK(csPathCached);
973 
975  if (fNetSpecific) nNet = Params().NetworkID();
976 
977  fs::path &path = pathCached[nNet];
978 
979  // This can be called during exceptions by LogPrintf(), so we cache the
980  // value so we don't have to do memory allocations after that.
981  if (!path.empty())
982  return path;
983 
984  if (mapArgs.count("-datadir")) {
985  path = fs::system_complete(mapArgs["-datadir"]);
986  if (!fs::is_directory(path)) {
987  path = "";
988  return path;
989  }
990  } else {
991  path = GetDefaultDataDir();
992  }
993  if (fNetSpecific)
994  path /= Params().DataDir();
995 
996  fs::create_directories(path);
997 
998  return path;
999 }
1000 
1002 {
1003  std::fill(&pathCached[0], &pathCached[CChainParams::MAX_NETWORK_TYPES+1],
1004  boost::filesystem::path());
1005 }
1006 
1007 boost::filesystem::path GetConfigFile()
1008 {
1009  boost::filesystem::path pathConfigFile(GetArg("-conf", "anoncoin.conf"));
1010  if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
1011  return pathConfigFile;
1012 }
1013 
1014 boost::filesystem::path GetQtStyleFile()
1015 {
1016  boost::filesystem::path pathConfigFile(GetArg("-style", "anoncoin.qss"));
1017  if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
1018  return pathConfigFile;
1019 }
1020 
1021 void ReadConfigFile(map<string, string>& mapSettingsRet,
1022  map<string, vector<string> >& mapMultiSettingsRet)
1023 {
1024  boost::filesystem::ifstream streamConfig(GetConfigFile());
1025  if (!streamConfig.good())
1026  {
1027  // ToDo: This is where I could write a 'firstconfig'....
1028  return; // No anoncoin.conf file is OK
1029  }
1030 
1031  set<string> setOptions;
1032  setOptions.insert("*");
1033 
1034  for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
1035  {
1036  // Don't overwrite existing settings so command line settings override anoncoin.conf
1037  string strKey = string("-") + it->string_key;
1038  if (mapSettingsRet.count(strKey) == 0)
1039  {
1040  mapSettingsRet[strKey] = it->value[0];
1041  // interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
1042  InterpretNegativeSetting(strKey, mapSettingsRet);
1043  }
1044  mapMultiSettingsRet[strKey].push_back(it->value[0]);
1045  }
1046  // If datadir is changed in .conf file:
1048 }
1049 
1050 boost::filesystem::path GetPidFile()
1051 {
1052  boost::filesystem::path pathPidFile(GetArg("-pid", "anoncoin.pid"));
1053  if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
1054  return pathPidFile;
1055 }
1056 
1057 #ifndef WIN32
1058 void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
1059 {
1060  FILE* file = fopen(path.string().c_str(), "w");
1061  if (file)
1062  {
1063  fprintf(file, "%d\n", pid);
1064  fclose(file);
1065  }
1066 }
1067 #endif
1068 
1069 bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
1070 {
1071 #ifdef WIN32
1072  return MoveFileExA(src.string().c_str(), dest.string().c_str(),
1073  MOVEFILE_REPLACE_EXISTING);
1074 #else
1075  int rc = std::rename(src.string().c_str(), dest.string().c_str());
1076  return (rc == 0);
1077 #endif /* WIN32 */
1078 }
1079 
1080 
1081 // Ignores exceptions thrown by boost's create_directory if the requested directory exists.
1082 // Specifically handles case where path p exists, but it wasn't possible for the user to write to the parent directory.
1083 bool TryCreateDirectory(const boost::filesystem::path& p)
1084 {
1085  try
1086  {
1087  return boost::filesystem::create_directory(p);
1088  } catch (boost::filesystem::filesystem_error) {
1089  if (!boost::filesystem::exists(p) || !boost::filesystem::is_directory(p))
1090  throw;
1091  }
1092 
1093  // create_directory didn't create the directory, it had to have existed already
1094  return false;
1095 }
1096 
1097 void FileCommit(FILE *fileout)
1098 {
1099  fflush(fileout); // harmless if redundantly called
1100 #ifdef WIN32
1101  HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(fileout));
1102  FlushFileBuffers(hFile);
1103 #else
1104  #if defined(__linux__) || defined(__NetBSD__)
1105  fdatasync(fileno(fileout));
1106  #elif defined(__APPLE__) && defined(F_FULLFSYNC)
1107  fcntl(fileno(fileout), F_FULLFSYNC, 0);
1108  #else
1109  fsync(fileno(fileout));
1110  #endif
1111 #endif
1112 }
1113 
1114 bool TruncateFile(FILE *file, unsigned int length) {
1115 #if defined(WIN32)
1116  return _chsize(_fileno(file), length) == 0;
1117 #else
1118  return ftruncate(fileno(file), length) == 0;
1119 #endif
1120 }
1121 
1122 // this function tries to raise the file descriptor limit to the requested number.
1123 // It returns the actual file descriptor limit (which may be more or less than nMinFD)
1124 int RaiseFileDescriptorLimit(int nMinFD) {
1125 #if defined(WIN32)
1126  return 2048;
1127 #else
1128  struct rlimit limitFD;
1129  if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) {
1130  if (limitFD.rlim_cur < (rlim_t)nMinFD) {
1131  limitFD.rlim_cur = nMinFD;
1132  if (limitFD.rlim_cur > limitFD.rlim_max)
1133  limitFD.rlim_cur = limitFD.rlim_max;
1134  setrlimit(RLIMIT_NOFILE, &limitFD);
1135  getrlimit(RLIMIT_NOFILE, &limitFD);
1136  }
1137  return limitFD.rlim_cur;
1138  }
1139  return nMinFD; // getrlimit failed, assume it's fine
1140 #endif
1141 }
1142 
1143 // this function tries to make a particular range of a file allocated (corresponding to disk space)
1144 // it is advisory, and the range specified in the arguments will never contain live data
1145 void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length) {
1146 #if defined(WIN32)
1147  // Windows-specific version
1148  HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
1149  LARGE_INTEGER nFileSize;
1150  int64_t nEndPos = (int64_t)offset + length;
1151  nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF;
1152  nFileSize.u.HighPart = nEndPos >> 32;
1153  SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN);
1154  SetEndOfFile(hFile);
1155 #elif defined(MAC_OSX)
1156  // OSX specific version
1157  fstore_t fst;
1158  fst.fst_flags = F_ALLOCATECONTIG;
1159  fst.fst_posmode = F_PEOFPOSMODE;
1160  fst.fst_offset = 0;
1161  fst.fst_length = (off_t)offset + length;
1162  fst.fst_bytesalloc = 0;
1163  if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) {
1164  fst.fst_flags = F_ALLOCATEALL;
1165  fcntl(fileno(file), F_PREALLOCATE, &fst);
1166  }
1167  ftruncate(fileno(file), fst.fst_length);
1168 #elif defined(__linux__)
1169  // Version using posix_fallocate
1170  off_t nEndPos = (off_t)offset + length;
1171  posix_fallocate(fileno(file), 0, nEndPos);
1172 #else
1173  // Fallback version
1174  // TODO: just write one byte per block
1175  static const char buf[65536] = {};
1176  fseek(file, offset, SEEK_SET);
1177  while (length > 0) {
1178  unsigned int now = 65536;
1179  if (length < now)
1180  now = length;
1181  fwrite(buf, 1, now, file); // allowed to fail; this function is advisory anyway
1182  length -= now;
1183  }
1184 #endif
1185 }
1186 
1188 {
1189  // Scroll debug.log if it's getting too big
1190  boost::filesystem::path pathLog = GetDataDir() / "debug.log";
1191  FILE* file = fopen(pathLog.string().c_str(), "r");
1192  if (file && boost::filesystem::file_size(pathLog) > 10 * 1000000)
1193  {
1194  // Restart the file with some of the end
1195  char pch[200000];
1196  fseek(file, -sizeof(pch), SEEK_END);
1197  int nBytes = fread(pch, 1, sizeof(pch), file);
1198  fclose(file);
1199 
1200  file = fopen(pathLog.string().c_str(), "w");
1201  if (file)
1202  {
1203  fwrite(pch, 1, nBytes, file);
1204  fclose(file);
1205  }
1206  }
1207  else if (file != NULL)
1208  fclose(file);
1209 }
1210 
1211 //
1212 // "Never go to sea with two chronometers; take one or three."
1213 // Our three time sources are:
1214 // - System clock
1215 // - Median of other nodes clocks
1216 // - The user (asking the user to fix the system clock if the first two disagree)
1217 //
1218 static int64_t nMockTime = 0; // For unit testing
1219 
1220 int64_t GetTime()
1221 {
1222  if (nMockTime) return nMockTime;
1223 
1224  return time(NULL);
1225 }
1226 
1227 void SetMockTime(int64_t nMockTimeIn)
1228 {
1229  nMockTime = nMockTimeIn;
1230 }
1231 
1232 static CCriticalSection cs_nTimeOffset;
1233 static int64_t nTimeOffset = 0;
1234 
1235 int64_t GetTimeOffset()
1236 {
1237  LOCK(cs_nTimeOffset);
1238  return nTimeOffset;
1239 }
1240 
1242 {
1243  return GetTime() + GetTimeOffset();
1244 }
1245 
1246 void AddTimeData(const CNetAddr& ip, int64_t nTime)
1247 {
1248  int64_t nOffsetSample = nTime - GetTime();
1249 
1250  LOCK(cs_nTimeOffset);
1251  // Ignore duplicates
1252  static set<CNetAddr> setKnown;
1253  if (!setKnown.insert(ip).second)
1254  return;
1255 
1256  // Add data
1257  static CMedianFilter<int64_t> vTimeOffsets(200,0);
1258  vTimeOffsets.input(nOffsetSample);
1259  LogPrintf("Added time data, samples %d, offset %+d (%+d minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
1260  if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
1261  {
1262  int64_t nMedian = vTimeOffsets.median();
1263  std::vector<int64_t> vSorted = vTimeOffsets.sorted();
1264  // Only let other nodes change our time by so much
1265  if (abs64(nMedian) < 35 * 60)
1266  {
1267  nTimeOffset = nMedian;
1268  }
1269  else
1270  {
1271  nTimeOffset = 0;
1272 
1273  static bool fDone;
1274  if (!fDone)
1275  {
1276  // If nobody has a time different than ours but within 5 minutes of ours, give a warning
1277  bool fMatch = false;
1278  BOOST_FOREACH(int64_t nOffset, vSorted)
1279  if (nOffset != 0 && abs64(nOffset) < 5 * 60)
1280  fMatch = true;
1281 
1282  if (!fMatch)
1283  {
1284  fDone = true;
1285  string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong Anoncoin will not work properly.");
1286  strMiscWarning = strMessage;
1287  LogPrintf("*** %s\n", strMessage);
1288  uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_WARNING);
1289  }
1290  }
1291  }
1292  if (fDebug) {
1293  BOOST_FOREACH(int64_t n, vSorted)
1294  LogPrintf("%+d ", n);
1295  LogPrintf("| ");
1296  }
1297  LogPrintf("nTimeOffset = %+d (%+d minutes)\n", nTimeOffset, nTimeOffset/60);
1298  }
1299 }
1300 
1301 uint32_t insecure_rand_Rz = 11;
1302 uint32_t insecure_rand_Rw = 11;
1303 void seed_insecure_rand(bool fDeterministic)
1304 {
1305  //The seed values have some unlikely fixed points which we avoid.
1306  if(fDeterministic)
1307  {
1308  insecure_rand_Rz = insecure_rand_Rw = 11;
1309  } else {
1310  uint32_t tmp;
1311  do {
1312  RAND_bytes((unsigned char*)&tmp, 4);
1313  } while(tmp == 0 || tmp == 0x9068ffffU);
1314  insecure_rand_Rz = tmp;
1315  do {
1316  RAND_bytes((unsigned char*)&tmp, 4);
1317  } while(tmp == 0 || tmp == 0x464fffffU);
1318  insecure_rand_Rw = tmp;
1319  }
1320 }
1321 
1322 #ifdef WIN32
1323 boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate)
1324 {
1325  namespace fs = boost::filesystem;
1326 
1327  char pszPath[MAX_PATH] = "";
1328 
1329  if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
1330  {
1331  return fs::path(pszPath);
1332  }
1333 
1334  LogPrintf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
1335  return fs::path("");
1336 }
1337 #endif
1338 
1339 boost::filesystem::path GetTempPath() {
1340 #if BOOST_FILESYSTEM_VERSION == 3
1341  return boost::filesystem::temp_directory_path();
1342 #else
1343  // TODO: remove when we don't support filesystem v2 anymore
1344  boost::filesystem::path path;
1345 #ifdef WIN32
1346  char pszPath[MAX_PATH] = "";
1347 
1348  if (GetTempPathA(MAX_PATH, pszPath))
1349  path = boost::filesystem::path(pszPath);
1350 #else
1351  path = boost::filesystem::path("/tmp");
1352 #endif
1353  if (path.empty() || !boost::filesystem::is_directory(path)) {
1354  LogPrintf("GetTempPath(): failed to find temp path\n");
1355  return boost::filesystem::path("");
1356  }
1357  return path;
1358 #endif
1359 }
1360 
1361 void runCommand(std::string strCommand)
1362 {
1363  int nErr = ::system(strCommand.c_str());
1364  if (nErr)
1365  LogPrintf("runCommand error: system(%s) returned %d\n", strCommand, nErr);
1366 }
1367 
1368 void RenameThread(const char* name)
1369 {
1370 #if defined(PR_SET_NAME)
1371  // Only the first 15 characters are used (16 - NUL terminator)
1372  ::prctl(PR_SET_NAME, name, 0, 0, 0);
1373 #elif 0 && (defined(__FreeBSD__) || defined(__OpenBSD__))
1374  // TODO: This is currently disabled because it needs to be verified to work
1375  // on FreeBSD or OpenBSD first. When verified the '0 &&' part can be
1376  // removed.
1377  pthread_set_name_np(pthread_self(), name);
1378 
1379 #elif defined(MAC_OSX) && defined(__MAC_OS_X_VERSION_MAX_ALLOWED)
1380 
1381 // pthread_setname_np is XCode 10.6-and-later
1382 #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
1383  pthread_setname_np(name);
1384 #endif
1385 
1386 #else
1387  // Prevent warnings for unused parameters...
1388  (void)name;
1389 #endif
1390 }
1391 
1392 // ToDo: What's going on here, got a compiler error: stray ‘#’ in program, method defined twice, so deleted the dup with error.
1393 // GR note: Perhaps some additional thought needs to go into WIN32 environment construction, none is being provided for here.
1395 {
1396  #ifndef WIN32
1397  try
1398  {
1399  #if BOOST_FILESYSTEM_VERSION == 3
1400  boost::filesystem::path::codecvt(); // Raises runtime error if current locale is invalid
1401  #else // boost filesystem v2
1402  std::locale(); // Raises runtime error if current locale is invalid
1403  #endif
1404  } catch(std::runtime_error &e)
1405  {
1406  setenv("LC_ALL", "C", 1); // Force C locale
1407  }
1408  #endif
1409 }
1410 
1411 std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime)
1412 {
1413  // std::locale takes ownership of the pointer
1414  std::locale loc(std::locale::classic(), new boost::posix_time::time_facet(pszFormat));
1415  std::stringstream ss;
1416  ss.imbue(loc);
1417  ss << boost::posix_time::from_time_t(nTime);
1418  return ss.str();
1419 }
1420 
const boost::filesystem::path & GetDataDir(bool fNetSpecific)
Definition: util.cpp:968
void locking_callback(int mode, int i, const char *file, int line)
Definition: util.cpp:104
const string & DataDir() const
Definition: chainparams.h:83
uint64_t GetRand(uint64_t nMax)
Definition: util.cpp:186
Definition: init.h:14
void FileCommit(FILE *fileout)
Definition: util.cpp:1097
string strMiscWarning
Definition: util.cpp:96
bool fDebug
Definition: util.cpp:91
#define PAIRTYPE(t1, t2)
Definition: util.h:49
void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
Definition: util.cpp:1058
void LogException(std::exception *pex, const char *pszThread)
Definition: util.cpp:922
#define strprintf
Definition: tinyformat.h:1011
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn't already have a value.
Definition: util.cpp:539
boost::filesystem::path GetTempPath()
Definition: util.cpp:1339
boost::filesystem::path GetPidFile()
Definition: util.cpp:1050
void seed_insecure_rand(bool fDeterministic)
Seed insecure_rand using the random pool.
Definition: util.cpp:1303
Definition: util.cpp:114
Median filter over a stream of values.
Definition: util.h:419
bool IsHex(const string &str)
Definition: util.cpp:409
bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
Definition: util.cpp:1069
std::string DateTimeStrFormat(const char *pszFormat, int64_t nTime)
Definition: util.cpp:1411
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:34
void RenameThread(const char *name)
Definition: util.cpp:1368
const signed char p_util_hexdigit[256]
Definition: util.cpp:391
volatile bool fReopenDebugLog
Definition: util.cpp:99
void SetMockTime(int64_t nMockTimeIn)
Definition: util.cpp:1227
int RaiseFileDescriptorLimit(int nMinFD)
Definition: util.cpp:1124
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:18
string EncodeBase64(const unsigned char *pch, size_t len)
Definition: util.cpp:548
CClientUIInterface uiInterface
Definition: util.cpp:100
bool TruncateFile(FILE *file, unsigned int length)
Definition: util.cpp:1114
bool fNoListen
Definition: util.cpp:97
bool GetBoolArg(const std::string &strArg, bool fDefault)
Return boolean argument or default value.
Definition: util.cpp:520
#define LogPrintf(...)
Definition: util.h:118
bool SoftSetArg(const std::string &strArg, const std::string &strValue)
Set an argument if it doesn't already have a value.
Definition: util.cpp:531
int64_t GetAdjustedTime()
Definition: util.cpp:1241
void AddTimeData(const CNetAddr &ip, int64_t nTime)
Definition: util.cpp:1246
#define LEAVE_CRITICAL_SECTION(cs)
Definition: sync.h:167
string SanitizeString(const string &str)
Definition: util.cpp:380
void input(T value)
Definition: util.h:434
#define LOCK(cs)
Definition: sync.h:157
int64_t atoi64(const char *psz)
Definition: util.h:217
bool fServer
Definition: util.cpp:95
~CInit()
Definition: util.cpp:133
bool TryCreateDirectory(const boost::filesystem::path &p)
Definition: util.cpp:1083
void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length)
Definition: util.cpp:1145
string EncodeBase32(const unsigned char *pch, size_t len)
Definition: util.cpp:688
T median() const
Definition: util.h:447
void PrintExceptionContinue(std::exception *pex, const char *pszThread)
Definition: util.cpp:928
#define MAX_PATH
Definition: util.h:73
void ParseParameters(int argc, const char *const argv[])
Definition: util.cpp:460
int64_t GetTime()
Definition: util.cpp:1220
boost::filesystem::path GetQtStyleFile()
Definition: util.cpp:1014
bool fLogTimestamps
Definition: util.cpp:98
#define ENTER_CRITICAL_SECTION(cs)
Definition: sync.h:161
IP address (IPv6, or IPv4 using mapped IPv6 range (::FFFF:0:0/96))
Definition: netbase.h:45
int size() const
Definition: util.h:461
256-bit unsigned integer
Definition: uint256.h:532
int64_t GetPerformanceCounter()
Definition: util.h:291
vector< unsigned char > DecodeBase32(const char *p, bool *pfInvalid)
Definition: util.cpp:752
void ReadConfigFile(map< string, string > &mapSettingsRet, map< string, vector< string > > &mapMultiSettingsRet)
Definition: util.cpp:1021
bool fPrintToConsole
Definition: util.cpp:92
const CChainParams & Params()
Return the currently selected parameters.
bool fPrintToDebugLog
Definition: util.cpp:93
bool WildcardMatch(const char *psz, const char *mask)
Definition: util.cpp:876
std::string _(const char *psz)
Translation function: Call Translate signal on UI interface, which returns a boost::optional result...
Definition: ui_interface.h:125
int64_t GetTimeOffset()
Definition: util.cpp:1235
uint32_t insecure_rand_Rz
MWC RNG of George Marsaglia This is intended to be fast.
Definition: util.cpp:1301
bool ParseMoney(const string &str, int64_t &nRet)
Definition: util.cpp:332
void ClearDatadirCache()
Definition: util.cpp:1001
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:81
AnnotatedMixin< boost::recursive_mutex > CCriticalSection
Wrapped boost mutex: supports recursive locking, but no waiting.
Definition: sync.h:83
std::string GetArg(const std::string &strArg, const std::string &strDefault)
Return string argument or default value.
Definition: util.cpp:506
uint32_t insecure_rand_Rw
Definition: util.cpp:1302
std::vector< T > sorted() const
Definition: util.h:466
vector< unsigned char > DecodeBase64(const char *p, bool *pfInvalid)
Definition: util.cpp:599
uint256 GetRandHash()
Definition: util.cpp:206
int64_t abs64(int64_t n)
Definition: util.h:250
void SetupEnvironment()
Definition: util.cpp:1394
map< string, vector< string > > mapMultiArgs
Definition: util.cpp:90
vector< unsigned char > ParseHex(const char *psz)
Definition: util.cpp:419
virtual Network NetworkID() const =0
int LogPrintStr(const std::string &str)
Definition: util.cpp:268
void ShrinkDebugFile()
Definition: util.cpp:1187
void RandAddSeed()
Definition: util.cpp:151
map< string, string > mapArgs
Definition: util.cpp:89
int atoi(const std::string &str)
Definition: util.h:235
boost::filesystem::path GetDefaultDataDir()
Definition: util.cpp:936
void runCommand(std::string strCommand)
Definition: util.cpp:1361
boost::filesystem::path GetConfigFile()
Definition: util.cpp:1007