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