BSHA3  0.17.99
P2P Blockchain, based on Bitcoin
util.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2018 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 
6 #include <util.h>
7 
8 #include <chainparamsbase.h>
9 #include <random.h>
10 #include <serialize.h>
11 #include <utilstrencodings.h>
12 
13 #include <stdarg.h>
14 
15 #if (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__))
16 #include <pthread.h>
17 #include <pthread_np.h>
18 #endif
19 
20 #ifndef WIN32
21 // for posix_fallocate
22 #ifdef __linux__
23 
24 #ifdef _POSIX_C_SOURCE
25 #undef _POSIX_C_SOURCE
26 #endif
27 
28 #define _POSIX_C_SOURCE 200112L
29 
30 #endif // __linux__
31 
32 #include <algorithm>
33 #include <fcntl.h>
34 #include <sched.h>
35 #include <sys/resource.h>
36 #include <sys/stat.h>
37 
38 #else
39 
40 #ifdef _MSC_VER
41 #pragma warning(disable:4786)
42 #pragma warning(disable:4804)
43 #pragma warning(disable:4805)
44 #pragma warning(disable:4717)
45 #endif
46 
47 #ifdef _WIN32_WINNT
48 #undef _WIN32_WINNT
49 #endif
50 #define _WIN32_WINNT 0x0501
51 
52 #ifdef _WIN32_IE
53 #undef _WIN32_IE
54 #endif
55 #define _WIN32_IE 0x0501
56 
57 #define WIN32_LEAN_AND_MEAN 1
58 #ifndef NOMINMAX
59 #define NOMINMAX
60 #endif
61 #include <codecvt>
62 
63 #include <io.h> /* for _commit */
64 #include <shellapi.h>
65 #include <shlobj.h>
66 #endif
67 
68 #ifdef HAVE_SYS_PRCTL_H
69 #include <sys/prctl.h>
70 #endif
71 
72 #ifdef HAVE_MALLOPT_ARENA_MAX
73 #include <malloc.h>
74 #endif
75 
76 #include <boost/thread.hpp>
77 #include <openssl/crypto.h>
78 #include <openssl/rand.h>
79 #include <openssl/conf.h>
80 #include <thread>
81 
82 // Application startup time (used for uptime calculation)
83 const int64_t nStartupTime = GetTime();
84 
85 const char * const BITCOIN_CONF_FILENAME = "bitcoin.conf";
86 const char * const BITCOIN_PID_FILENAME = "bsha3d.pid";
87 
89 
91 static std::unique_ptr<CCriticalSection[]> ppmutexOpenSSL;
92 void locking_callback(int mode, int i, const char* file, int line) NO_THREAD_SAFETY_ANALYSIS
93 {
94  if (mode & CRYPTO_LOCK) {
95  ENTER_CRITICAL_SECTION(ppmutexOpenSSL[i]);
96  } else {
97  LEAVE_CRITICAL_SECTION(ppmutexOpenSSL[i]);
98  }
99 }
100 
101 // Singleton for wrapping OpenSSL setup/teardown.
102 class CInit
103 {
104 public:
106  {
107  // Init OpenSSL library multithreading support
108  ppmutexOpenSSL.reset(new CCriticalSection[CRYPTO_num_locks()]);
109  CRYPTO_set_locking_callback(locking_callback);
110 
111  // OpenSSL can optionally load a config file which lists optional loadable modules and engines.
112  // We don't use them so we don't require the config. However some of our libs may call functions
113  // which attempt to load the config file, possibly resulting in an exit() or crash if it is missing
114  // or corrupt. Explicitly tell OpenSSL not to try to load the file. The result for our libs will be
115  // that the config appears to have been loaded and there are no modules/engines available.
116  OPENSSL_no_config();
117 
118 #ifdef WIN32
119  // Seed OpenSSL PRNG with current contents of the screen
120  RAND_screen();
121 #endif
122 
123  // Seed OpenSSL PRNG with performance counter
124  RandAddSeed();
125  }
127  {
128  // Securely erase the memory used by the PRNG
129  RAND_cleanup();
130  // Shutdown OpenSSL library multithreading support
131  CRYPTO_set_locking_callback(nullptr);
132  // Clear the set of locks now to maintain symmetry with the constructor.
133  ppmutexOpenSSL.reset();
134  }
135 }
137 
143 static std::map<std::string, std::unique_ptr<fsbridge::FileLock>> dir_locks;
145 static std::mutex cs_dir_locks;
146 
147 bool LockDirectory(const fs::path& directory, const std::string lockfile_name, bool probe_only)
148 {
149  std::lock_guard<std::mutex> ulock(cs_dir_locks);
150  fs::path pathLockFile = directory / lockfile_name;
151 
152  // If a lock for this directory already exists in the map, don't try to re-lock it
153  if (dir_locks.count(pathLockFile.string())) {
154  return true;
155  }
156 
157  // Create empty lock file if it doesn't exist.
158  FILE* file = fsbridge::fopen(pathLockFile, "a");
159  if (file) fclose(file);
160  auto lock = MakeUnique<fsbridge::FileLock>(pathLockFile);
161  if (!lock->TryLock()) {
162  return error("Error while attempting to lock directory %s: %s", directory.string(), lock->GetReason());
163  }
164  if (!probe_only) {
165  // Lock successful and we're not just probing, put it into the map
166  dir_locks.emplace(pathLockFile.string(), std::move(lock));
167  }
168  return true;
169 }
170 
172 {
173  std::lock_guard<std::mutex> ulock(cs_dir_locks);
174  dir_locks.clear();
175 }
176 
177 bool DirIsWritable(const fs::path& directory)
178 {
179  fs::path tmpFile = directory / fs::unique_path();
180 
181  FILE* file = fsbridge::fopen(tmpFile, "a");
182  if (!file) return false;
183 
184  fclose(file);
185  remove(tmpFile);
186 
187  return true;
188 }
189 
207 static bool InterpretBool(const std::string& strValue)
208 {
209  if (strValue.empty())
210  return true;
211  return (atoi(strValue) != 0);
212 }
213 
216 public:
217  typedef std::map<std::string, std::vector<std::string>> MapArgs;
218 
221  static inline bool UseDefaultSection(const ArgsManager& am, const std::string& arg) EXCLUSIVE_LOCKS_REQUIRED(am.cs_args)
222  {
223  return (am.m_network == CBaseChainParams::MAIN || am.m_network_only_args.count(arg) == 0);
224  }
225 
227  static inline std::string NetworkArg(const ArgsManager& am, const std::string& arg)
228  {
229  assert(arg.length() > 1 && arg[0] == '-');
230  return "-" + am.m_network + "." + arg.substr(1);
231  }
232 
234  static inline void AddArgs(std::vector<std::string>& res, const MapArgs& map_args, const std::string& arg)
235  {
236  auto it = map_args.find(arg);
237  if (it != map_args.end()) {
238  res.insert(res.end(), it->second.begin(), it->second.end());
239  }
240  }
241 
245  static inline std::pair<bool,std::string> GetArgHelper(const MapArgs& map_args, const std::string& arg, bool getLast = false)
246  {
247  auto it = map_args.find(arg);
248 
249  if (it == map_args.end() || it->second.empty()) {
250  return std::make_pair(false, std::string());
251  }
252 
253  if (getLast) {
254  return std::make_pair(true, it->second.back());
255  } else {
256  return std::make_pair(true, it->second.front());
257  }
258  }
259 
260  /* Get the string value of an argument, returning a pair of a boolean
261  * indicating the argument was found, and the value for the argument
262  * if it was found (or the empty string if not found).
263  */
264  static inline std::pair<bool,std::string> GetArg(const ArgsManager &am, const std::string& arg)
265  {
266  LOCK(am.cs_args);
267  std::pair<bool,std::string> found_result(false, std::string());
268 
269  // We pass "true" to GetArgHelper in order to return the last
270  // argument value seen from the command line (so "bsha3d -foo=bar
271  // -foo=baz" gives GetArg(am,"foo")=={true,"baz"}
272  found_result = GetArgHelper(am.m_override_args, arg, true);
273  if (found_result.first) {
274  return found_result;
275  }
276 
277  // But in contrast we return the first argument seen in a config file,
278  // so "foo=bar \n foo=baz" in the config file gives
279  // GetArg(am,"foo")={true,"bar"}
280  if (!am.m_network.empty()) {
281  found_result = GetArgHelper(am.m_config_args, NetworkArg(am, arg));
282  if (found_result.first) {
283  return found_result;
284  }
285  }
286 
287  if (UseDefaultSection(am, arg)) {
288  found_result = GetArgHelper(am.m_config_args, arg);
289  if (found_result.first) {
290  return found_result;
291  }
292  }
293 
294  return found_result;
295  }
296 
297  /* Special test for -testnet and -regtest args, because we
298  * don't want to be confused by craziness like "[regtest] testnet=1"
299  */
300  static inline bool GetNetBoolArg(const ArgsManager &am, const std::string& net_arg) EXCLUSIVE_LOCKS_REQUIRED(am.cs_args)
301  {
302  std::pair<bool,std::string> found_result(false,std::string());
303  found_result = GetArgHelper(am.m_override_args, net_arg, true);
304  if (!found_result.first) {
305  found_result = GetArgHelper(am.m_config_args, net_arg, true);
306  if (!found_result.first) {
307  return false; // not set
308  }
309  }
310  return InterpretBool(found_result.second); // is set, so evaluate
311  }
312 };
313 
335 static bool InterpretNegatedOption(std::string& key, std::string& val)
336 {
337  assert(key[0] == '-');
338 
339  size_t option_index = key.find('.');
340  if (option_index == std::string::npos) {
341  option_index = 1;
342  } else {
343  ++option_index;
344  }
345  if (key.substr(option_index, 2) == "no") {
346  bool bool_val = InterpretBool(val);
347  key.erase(option_index, 2);
348  if (!bool_val ) {
349  // Double negatives like -nofoo=0 are supported (but discouraged)
350  LogPrintf("Warning: parsed potentially confusing double-negative %s=%s\n", key, val);
351  val = "1";
352  } else {
353  return true;
354  }
355  }
356  return false;
357 }
358 
360  /* These options would cause cross-contamination if values for
361  * mainnet were used while running on regtest/testnet (or vice-versa).
362  * Setting them as section_only_args ensures that sharing a config file
363  * between mainnet and regtest/testnet won't cause problems due to these
364  * parameters by accident. */
365  m_network_only_args{
366  "-addnode", "-connect",
367  "-port", "-bind",
368  "-rpcport", "-rpcbind",
369  "-wallet",
370  }
371 {
372  // nothing to do
373 }
374 
376 {
377  LOCK(cs_args);
378 
379  // if there's no section selected, don't worry
380  if (m_network.empty()) return;
381 
382  // if it's okay to use the default section for this network, don't worry
383  if (m_network == CBaseChainParams::MAIN) return;
384 
385  for (const auto& arg : m_network_only_args) {
386  std::pair<bool, std::string> found_result;
387 
388  // if this option is overridden it's fine
389  found_result = ArgsManagerHelper::GetArgHelper(m_override_args, arg);
390  if (found_result.first) continue;
391 
392  // if there's a network-specific value for this option, it's fine
393  found_result = ArgsManagerHelper::GetArgHelper(m_config_args, ArgsManagerHelper::NetworkArg(*this, arg));
394  if (found_result.first) continue;
395 
396  // if there isn't a default value for this option, it's fine
397  found_result = ArgsManagerHelper::GetArgHelper(m_config_args, arg);
398  if (!found_result.first) continue;
399 
400  // otherwise, issue a warning
401  LogPrintf("Warning: Config setting for %s only applied on %s network when in [%s] section.\n", arg, m_network, m_network);
402  }
403 }
404 
405 void ArgsManager::SelectConfigNetwork(const std::string& network)
406 {
407  LOCK(cs_args);
408  m_network = network;
409 }
410 
411 bool ArgsManager::ParseParameters(int argc, const char* const argv[], std::string& error)
412 {
413  LOCK(cs_args);
414  m_override_args.clear();
415 
416  for (int i = 1; i < argc; i++) {
417  std::string key(argv[i]);
418  std::string val;
419  size_t is_index = key.find('=');
420  if (is_index != std::string::npos) {
421  val = key.substr(is_index + 1);
422  key.erase(is_index);
423  }
424 #ifdef WIN32
425  std::transform(key.begin(), key.end(), key.begin(), ::tolower);
426  if (key[0] == '/')
427  key[0] = '-';
428 #endif
429 
430  if (key[0] != '-')
431  break;
432 
433  // Transform --foo to -foo
434  if (key.length() > 1 && key[1] == '-')
435  key.erase(0, 1);
436 
437  // Check for -nofoo
438  if (InterpretNegatedOption(key, val)) {
439  m_override_args[key].clear();
440  } else {
441  m_override_args[key].push_back(val);
442  }
443 
444  // Check that the arg is known
445  if (!(IsSwitchChar(key[0]) && key.size() == 1)) {
446  if (!IsArgKnown(key)) {
447  error = strprintf("Invalid parameter %s", key.c_str());
448  return false;
449  }
450  }
451  }
452 
453  // we do not allow -includeconf from command line, so we clear it here
454  auto it = m_override_args.find("-includeconf");
455  if (it != m_override_args.end()) {
456  if (it->second.size() > 0) {
457  for (const auto& ic : it->second) {
458  error += "-includeconf cannot be used from commandline; -includeconf=" + ic + "\n";
459  }
460  return false;
461  }
462  }
463  return true;
464 }
465 
466 bool ArgsManager::IsArgKnown(const std::string& key) const
467 {
468  size_t option_index = key.find('.');
469  std::string arg_no_net;
470  if (option_index == std::string::npos) {
471  arg_no_net = key;
472  } else {
473  arg_no_net = std::string("-") + key.substr(option_index + 1, std::string::npos);
474  }
475 
476  LOCK(cs_args);
477  for (const auto& arg_map : m_available_args) {
478  if (arg_map.second.count(arg_no_net)) return true;
479  }
480  return false;
481 }
482 
483 std::vector<std::string> ArgsManager::GetArgs(const std::string& strArg) const
484 {
485  std::vector<std::string> result = {};
486  if (IsArgNegated(strArg)) return result; // special case
487 
488  LOCK(cs_args);
489 
490  ArgsManagerHelper::AddArgs(result, m_override_args, strArg);
491  if (!m_network.empty()) {
492  ArgsManagerHelper::AddArgs(result, m_config_args, ArgsManagerHelper::NetworkArg(*this, strArg));
493  }
494 
495  if (ArgsManagerHelper::UseDefaultSection(*this, strArg)) {
496  ArgsManagerHelper::AddArgs(result, m_config_args, strArg);
497  }
498 
499  return result;
500 }
501 
502 bool ArgsManager::IsArgSet(const std::string& strArg) const
503 {
504  if (IsArgNegated(strArg)) return true; // special case
505  return ArgsManagerHelper::GetArg(*this, strArg).first;
506 }
507 
508 bool ArgsManager::IsArgNegated(const std::string& strArg) const
509 {
510  LOCK(cs_args);
511 
512  const auto& ov = m_override_args.find(strArg);
513  if (ov != m_override_args.end()) return ov->second.empty();
514 
515  if (!m_network.empty()) {
516  const auto& cfs = m_config_args.find(ArgsManagerHelper::NetworkArg(*this, strArg));
517  if (cfs != m_config_args.end()) return cfs->second.empty();
518  }
519 
520  const auto& cf = m_config_args.find(strArg);
521  if (cf != m_config_args.end()) return cf->second.empty();
522 
523  return false;
524 }
525 
526 std::string ArgsManager::GetArg(const std::string& strArg, const std::string& strDefault) const
527 {
528  if (IsArgNegated(strArg)) return "0";
529  std::pair<bool,std::string> found_res = ArgsManagerHelper::GetArg(*this, strArg);
530  if (found_res.first) return found_res.second;
531  return strDefault;
532 }
533 
534 int64_t ArgsManager::GetArg(const std::string& strArg, int64_t nDefault) const
535 {
536  if (IsArgNegated(strArg)) return 0;
537  std::pair<bool,std::string> found_res = ArgsManagerHelper::GetArg(*this, strArg);
538  if (found_res.first) return atoi64(found_res.second);
539  return nDefault;
540 }
541 
542 bool ArgsManager::GetBoolArg(const std::string& strArg, bool fDefault) const
543 {
544  if (IsArgNegated(strArg)) return false;
545  std::pair<bool,std::string> found_res = ArgsManagerHelper::GetArg(*this, strArg);
546  if (found_res.first) return InterpretBool(found_res.second);
547  return fDefault;
548 }
549 
550 bool ArgsManager::SoftSetArg(const std::string& strArg, const std::string& strValue)
551 {
552  LOCK(cs_args);
553  if (IsArgSet(strArg)) return false;
554  ForceSetArg(strArg, strValue);
555  return true;
556 }
557 
558 bool ArgsManager::SoftSetBoolArg(const std::string& strArg, bool fValue)
559 {
560  if (fValue)
561  return SoftSetArg(strArg, std::string("1"));
562  else
563  return SoftSetArg(strArg, std::string("0"));
564 }
565 
566 void ArgsManager::ForceSetArg(const std::string& strArg, const std::string& strValue)
567 {
568  LOCK(cs_args);
569  m_override_args[strArg] = {strValue};
570 }
571 
572 void ArgsManager::AddArg(const std::string& name, const std::string& help, const bool debug_only, const OptionsCategory& cat)
573 {
574  // Split arg name from its help param
575  size_t eq_index = name.find('=');
576  if (eq_index == std::string::npos) {
577  eq_index = name.size();
578  }
579 
580  LOCK(cs_args);
581  std::map<std::string, Arg>& arg_map = m_available_args[cat];
582  auto ret = arg_map.emplace(name.substr(0, eq_index), Arg(name.substr(eq_index, name.size() - eq_index), help, debug_only));
583  assert(ret.second); // Make sure an insertion actually happened
584 }
585 
586 void ArgsManager::AddHiddenArgs(const std::vector<std::string>& names)
587 {
588  for (const std::string& name : names) {
589  AddArg(name, "", false, OptionsCategory::HIDDEN);
590  }
591 }
592 
593 std::string ArgsManager::GetHelpMessage() const
594 {
595  const bool show_debug = gArgs.GetBoolArg("-help-debug", false);
596 
597  std::string usage = "";
598  LOCK(cs_args);
599  for (const auto& arg_map : m_available_args) {
600  switch(arg_map.first) {
602  usage += HelpMessageGroup("Options:");
603  break;
605  usage += HelpMessageGroup("Connection options:");
606  break;
608  usage += HelpMessageGroup("ZeroMQ notification options:");
609  break;
611  usage += HelpMessageGroup("Debugging/Testing options:");
612  break;
614  usage += HelpMessageGroup("Node relay options:");
615  break;
617  usage += HelpMessageGroup("Block creation options:");
618  break;
620  usage += HelpMessageGroup("RPC server options:");
621  break;
623  usage += HelpMessageGroup("Wallet options:");
624  break;
626  if (show_debug) usage += HelpMessageGroup("Wallet debugging/testing options:");
627  break;
629  usage += HelpMessageGroup("Chain selection options:");
630  break;
632  usage += HelpMessageGroup("UI Options:");
633  break;
635  usage += HelpMessageGroup("Commands:");
636  break;
638  usage += HelpMessageGroup("Register Commands:");
639  break;
640  default:
641  break;
642  }
643 
644  // When we get to the hidden options, stop
645  if (arg_map.first == OptionsCategory::HIDDEN) break;
646 
647  for (const auto& arg : arg_map.second) {
648  if (show_debug || !arg.second.m_debug_only) {
649  std::string name;
650  if (arg.second.m_help_param.empty()) {
651  name = arg.first;
652  } else {
653  name = arg.first + arg.second.m_help_param;
654  }
655  usage += HelpMessageOpt(name, arg.second.m_help_text);
656  }
657  }
658  }
659  return usage;
660 }
661 
662 bool HelpRequested(const ArgsManager& args)
663 {
664  return args.IsArgSet("-?") || args.IsArgSet("-h") || args.IsArgSet("-help") || args.IsArgSet("-help-debug");
665 }
666 
667 static const int screenWidth = 79;
668 static const int optIndent = 2;
669 static const int msgIndent = 7;
670 
671 std::string HelpMessageGroup(const std::string &message) {
672  return std::string(message) + std::string("\n\n");
673 }
674 
675 std::string HelpMessageOpt(const std::string &option, const std::string &message) {
676  return std::string(optIndent,' ') + std::string(option) +
677  std::string("\n") + std::string(msgIndent,' ') +
678  FormatParagraph(message, screenWidth - msgIndent, msgIndent) +
679  std::string("\n\n");
680 }
681 
682 static std::string FormatException(const std::exception* pex, const char* pszThread)
683 {
684 #ifdef WIN32
685  char pszModule[MAX_PATH] = "";
686  GetModuleFileNameA(nullptr, pszModule, sizeof(pszModule));
687 #else
688  const char* pszModule = "bitcoin";
689 #endif
690  if (pex)
691  return strprintf(
692  "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
693  else
694  return strprintf(
695  "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
696 }
697 
698 void PrintExceptionContinue(const std::exception* pex, const char* pszThread)
699 {
700  std::string message = FormatException(pex, pszThread);
701  LogPrintf("\n\n************************\n%s\n", message);
702  fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
703 }
704 
706 {
707  // Windows < Vista: C:\Documents and Settings\Username\Application Data\BSHA3
708  // Windows >= Vista: C:\Users\Username\AppData\Roaming\BSHA3
709  // Mac: ~/Library/Application Support/BSHA3
710  // Unix: ~/.bsha3
711 #ifdef WIN32
712  // Windows
713  return GetSpecialFolderPath(CSIDL_APPDATA) / "BSHA3";
714 #else
715  fs::path pathRet;
716  char* pszHome = getenv("HOME");
717  if (pszHome == nullptr || strlen(pszHome) == 0)
718  pathRet = fs::path("/");
719  else
720  pathRet = fs::path(pszHome);
721 #ifdef MAC_OSX
722  // Mac
723  return pathRet / "Library/Application Support/BSHA3";
724 #else
725  // Unix
726  return pathRet / ".bsha3";
727 #endif
728 #endif
729 }
730 
731 static fs::path g_blocks_path_cached;
732 static fs::path g_blocks_path_cache_net_specific;
733 static fs::path pathCached;
734 static fs::path pathCachedNetSpecific;
735 static CCriticalSection csPathCached;
736 
737 const fs::path &GetBlocksDir(bool fNetSpecific)
738 {
739 
740  LOCK(csPathCached);
741 
742  fs::path &path = fNetSpecific ? g_blocks_path_cache_net_specific : g_blocks_path_cached;
743 
744  // This can be called during exceptions by LogPrintf(), so we cache the
745  // value so we don't have to do memory allocations after that.
746  if (!path.empty())
747  return path;
748 
749  if (gArgs.IsArgSet("-blocksdir")) {
750  path = fs::system_complete(gArgs.GetArg("-blocksdir", ""));
751  if (!fs::is_directory(path)) {
752  path = "";
753  return path;
754  }
755  } else {
756  path = GetDataDir(false);
757  }
758  if (fNetSpecific)
759  path /= BaseParams().DataDir();
760 
761  path /= "blocks";
762  fs::create_directories(path);
763  return path;
764 }
765 
766 const fs::path &GetDataDir(bool fNetSpecific)
767 {
768 
769  LOCK(csPathCached);
770 
771  fs::path &path = fNetSpecific ? pathCachedNetSpecific : pathCached;
772 
773  // This can be called during exceptions by LogPrintf(), so we cache the
774  // value so we don't have to do memory allocations after that.
775  if (!path.empty())
776  return path;
777 
778  if (gArgs.IsArgSet("-datadir")) {
779  path = fs::system_complete(gArgs.GetArg("-datadir", ""));
780  if (!fs::is_directory(path)) {
781  path = "";
782  return path;
783  }
784  } else {
785  path = GetDefaultDataDir();
786  }
787  if (fNetSpecific)
788  path /= BaseParams().DataDir();
789 
790  if (fs::create_directories(path)) {
791  // This is the first run, create wallets subdirectory too
792  fs::create_directories(path / "wallets");
793  }
794 
795  return path;
796 }
797 
799 {
800  LOCK(csPathCached);
801 
802  pathCached = fs::path();
803  pathCachedNetSpecific = fs::path();
804  g_blocks_path_cached = fs::path();
805  g_blocks_path_cache_net_specific = fs::path();
806 }
807 
808 fs::path GetConfigFile(const std::string& confPath)
809 {
810  return AbsPathForConfigVal(fs::path(confPath), false);
811 }
812 
813 static std::string TrimString(const std::string& str, const std::string& pattern)
814 {
815  std::string::size_type front = str.find_first_not_of(pattern);
816  if (front == std::string::npos) {
817  return std::string();
818  }
819  std::string::size_type end = str.find_last_not_of(pattern);
820  return str.substr(front, end - front + 1);
821 }
822 
823 static bool GetConfigOptions(std::istream& stream, std::string& error, std::vector<std::pair<std::string, std::string>> &options)
824 {
825  std::string str, prefix;
826  std::string::size_type pos;
827  int linenr = 1;
828  while (std::getline(stream, str)) {
829  if ((pos = str.find('#')) != std::string::npos) {
830  str = str.substr(0, pos);
831  }
832  const static std::string pattern = " \t\r\n";
833  str = TrimString(str, pattern);
834  if (!str.empty()) {
835  if (*str.begin() == '[' && *str.rbegin() == ']') {
836  prefix = str.substr(1, str.size() - 2) + '.';
837  } else if (*str.begin() == '-') {
838  error = strprintf("parse error on line %i: %s, options in configuration file must be specified without leading -", linenr, str);
839  return false;
840  } else if ((pos = str.find('=')) != std::string::npos) {
841  std::string name = prefix + TrimString(str.substr(0, pos), pattern);
842  std::string value = TrimString(str.substr(pos + 1), pattern);
843  options.emplace_back(name, value);
844  } else {
845  error = strprintf("parse error on line %i: %s", linenr, str);
846  if (str.size() >= 2 && str.substr(0, 2) == "no") {
847  error += strprintf(", if you intended to specify a negated option, use %s=1 instead", str);
848  }
849  return false;
850  }
851  }
852  ++linenr;
853  }
854  return true;
855 }
856 
857 bool ArgsManager::ReadConfigStream(std::istream& stream, std::string& error, bool ignore_invalid_keys)
858 {
859  LOCK(cs_args);
860  std::vector<std::pair<std::string, std::string>> options;
861  if (!GetConfigOptions(stream, error, options)) {
862  return false;
863  }
864  for (const std::pair<std::string, std::string>& option : options) {
865  std::string strKey = std::string("-") + option.first;
866  std::string strValue = option.second;
867 
868  if (InterpretNegatedOption(strKey, strValue)) {
869  m_config_args[strKey].clear();
870  } else {
871  m_config_args[strKey].push_back(strValue);
872  }
873 
874  // Check that the arg is known
875  if (!IsArgKnown(strKey)) {
876  if (!ignore_invalid_keys) {
877  error = strprintf("Invalid configuration value %s", option.first.c_str());
878  return false;
879  } else {
880  LogPrintf("Ignoring unknown configuration value %s\n", option.first);
881  }
882  }
883  }
884  return true;
885 }
886 
887 bool ArgsManager::ReadConfigFiles(std::string& error, bool ignore_invalid_keys)
888 {
889  {
890  LOCK(cs_args);
891  m_config_args.clear();
892  }
893 
894  const std::string confPath = GetArg("-conf", BITCOIN_CONF_FILENAME);
895  fsbridge::ifstream stream(GetConfigFile(confPath));
896 
897  // ok to not have a config file
898  if (stream.good()) {
899  if (!ReadConfigStream(stream, error, ignore_invalid_keys)) {
900  return false;
901  }
902  // if there is an -includeconf in the override args, but it is empty, that means the user
903  // passed '-noincludeconf' on the command line, in which case we should not include anything
904  bool emptyIncludeConf;
905  {
906  LOCK(cs_args);
907  emptyIncludeConf = m_override_args.count("-includeconf") == 0;
908  }
909  if (emptyIncludeConf) {
910  std::string chain_id = GetChainName();
911  std::vector<std::string> includeconf(GetArgs("-includeconf"));
912  {
913  // We haven't set m_network yet (that happens in SelectParams()), so manually check
914  // for network.includeconf args.
915  std::vector<std::string> includeconf_net(GetArgs(std::string("-") + chain_id + ".includeconf"));
916  includeconf.insert(includeconf.end(), includeconf_net.begin(), includeconf_net.end());
917  }
918 
919  // Remove -includeconf from configuration, so we can warn about recursion
920  // later
921  {
922  LOCK(cs_args);
923  m_config_args.erase("-includeconf");
924  m_config_args.erase(std::string("-") + chain_id + ".includeconf");
925  }
926 
927  for (const std::string& to_include : includeconf) {
928  fsbridge::ifstream include_config(GetConfigFile(to_include));
929  if (include_config.good()) {
930  if (!ReadConfigStream(include_config, error, ignore_invalid_keys)) {
931  return false;
932  }
933  LogPrintf("Included configuration file %s\n", to_include.c_str());
934  } else {
935  error = "Failed to include configuration file " + to_include;
936  return false;
937  }
938  }
939 
940  // Warn about recursive -includeconf
941  includeconf = GetArgs("-includeconf");
942  {
943  std::vector<std::string> includeconf_net(GetArgs(std::string("-") + chain_id + ".includeconf"));
944  includeconf.insert(includeconf.end(), includeconf_net.begin(), includeconf_net.end());
945  std::string chain_id_final = GetChainName();
946  if (chain_id_final != chain_id) {
947  // Also warn about recursive includeconf for the chain that was specified in one of the includeconfs
948  includeconf_net = GetArgs(std::string("-") + chain_id_final + ".includeconf");
949  includeconf.insert(includeconf.end(), includeconf_net.begin(), includeconf_net.end());
950  }
951  }
952  for (const std::string& to_include : includeconf) {
953  fprintf(stderr, "warning: -includeconf cannot be used from included files; ignoring -includeconf=%s\n", to_include.c_str());
954  }
955  }
956  }
957 
958  // If datadir is changed in .conf file:
960  if (!fs::is_directory(GetDataDir(false))) {
961  error = strprintf("specified data directory \"%s\" does not exist.", gArgs.GetArg("-datadir", "").c_str());
962  return false;
963  }
964  return true;
965 }
966 
967 std::string ArgsManager::GetChainName() const
968 {
969  LOCK(cs_args);
970  bool fRegTest = ArgsManagerHelper::GetNetBoolArg(*this, "-regtest");
971  bool fTestNet = ArgsManagerHelper::GetNetBoolArg(*this, "-testnet");
972 
973  if (fTestNet && fRegTest)
974  throw std::runtime_error("Invalid combination of -regtest and -testnet.");
975  if (fRegTest)
977  if (fTestNet)
979  return CBaseChainParams::MAIN;
980 }
981 
982 #ifndef WIN32
983 fs::path GetPidFile()
984 {
985  return AbsPathForConfigVal(fs::path(gArgs.GetArg("-pid", BITCOIN_PID_FILENAME)));
986 }
987 
988 void CreatePidFile(const fs::path &path, pid_t pid)
989 {
990  FILE* file = fsbridge::fopen(path, "w");
991  if (file)
992  {
993  fprintf(file, "%d\n", pid);
994  fclose(file);
995  }
996 }
997 #endif
998 
999 bool RenameOver(fs::path src, fs::path dest)
1000 {
1001 #ifdef WIN32
1002  return MoveFileExW(src.wstring().c_str(), dest.wstring().c_str(),
1003  MOVEFILE_REPLACE_EXISTING) != 0;
1004 #else
1005  int rc = std::rename(src.string().c_str(), dest.string().c_str());
1006  return (rc == 0);
1007 #endif /* WIN32 */
1008 }
1009 
1015 bool TryCreateDirectories(const fs::path& p)
1016 {
1017  try
1018  {
1019  return fs::create_directories(p);
1020  } catch (const fs::filesystem_error&) {
1021  if (!fs::exists(p) || !fs::is_directory(p))
1022  throw;
1023  }
1024 
1025  // create_directories didn't create the directory, it had to have existed already
1026  return false;
1027 }
1028 
1029 bool FileCommit(FILE *file)
1030 {
1031  if (fflush(file) != 0) { // harmless if redundantly called
1032  LogPrintf("%s: fflush failed: %d\n", __func__, errno);
1033  return false;
1034  }
1035 #ifdef WIN32
1036  HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
1037  if (FlushFileBuffers(hFile) == 0) {
1038  LogPrintf("%s: FlushFileBuffers failed: %d\n", __func__, GetLastError());
1039  return false;
1040  }
1041 #else
1042  #if defined(__linux__) || defined(__NetBSD__)
1043  if (fdatasync(fileno(file)) != 0 && errno != EINVAL) { // Ignore EINVAL for filesystems that don't support sync
1044  LogPrintf("%s: fdatasync failed: %d\n", __func__, errno);
1045  return false;
1046  }
1047  #elif defined(MAC_OSX) && defined(F_FULLFSYNC)
1048  if (fcntl(fileno(file), F_FULLFSYNC, 0) == -1) { // Manpage says "value other than -1" is returned on success
1049  LogPrintf("%s: fcntl F_FULLFSYNC failed: %d\n", __func__, errno);
1050  return false;
1051  }
1052  #else
1053  if (fsync(fileno(file)) != 0 && errno != EINVAL) {
1054  LogPrintf("%s: fsync failed: %d\n", __func__, errno);
1055  return false;
1056  }
1057  #endif
1058 #endif
1059  return true;
1060 }
1061 
1062 bool TruncateFile(FILE *file, unsigned int length) {
1063 #if defined(WIN32)
1064  return _chsize(_fileno(file), length) == 0;
1065 #else
1066  return ftruncate(fileno(file), length) == 0;
1067 #endif
1068 }
1069 
1074 int RaiseFileDescriptorLimit(int nMinFD) {
1075 #if defined(WIN32)
1076  return 2048;
1077 #else
1078  struct rlimit limitFD;
1079  if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) {
1080  if (limitFD.rlim_cur < (rlim_t)nMinFD) {
1081  limitFD.rlim_cur = nMinFD;
1082  if (limitFD.rlim_cur > limitFD.rlim_max)
1083  limitFD.rlim_cur = limitFD.rlim_max;
1084  setrlimit(RLIMIT_NOFILE, &limitFD);
1085  getrlimit(RLIMIT_NOFILE, &limitFD);
1086  }
1087  return limitFD.rlim_cur;
1088  }
1089  return nMinFD; // getrlimit failed, assume it's fine
1090 #endif
1091 }
1092 
1097 void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length) {
1098 #if defined(WIN32)
1099  // Windows-specific version
1100  HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
1101  LARGE_INTEGER nFileSize;
1102  int64_t nEndPos = (int64_t)offset + length;
1103  nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF;
1104  nFileSize.u.HighPart = nEndPos >> 32;
1105  SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN);
1106  SetEndOfFile(hFile);
1107 #elif defined(MAC_OSX)
1108  // OSX specific version
1109  fstore_t fst;
1110  fst.fst_flags = F_ALLOCATECONTIG;
1111  fst.fst_posmode = F_PEOFPOSMODE;
1112  fst.fst_offset = 0;
1113  fst.fst_length = (off_t)offset + length;
1114  fst.fst_bytesalloc = 0;
1115  if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) {
1116  fst.fst_flags = F_ALLOCATEALL;
1117  fcntl(fileno(file), F_PREALLOCATE, &fst);
1118  }
1119  ftruncate(fileno(file), fst.fst_length);
1120 #elif defined(__linux__)
1121  // Version using posix_fallocate
1122  off_t nEndPos = (off_t)offset + length;
1123  posix_fallocate(fileno(file), 0, nEndPos);
1124 #else
1125  // Fallback version
1126  // TODO: just write one byte per block
1127  static const char buf[65536] = {};
1128  if (fseek(file, offset, SEEK_SET)) {
1129  return;
1130  }
1131  while (length > 0) {
1132  unsigned int now = 65536;
1133  if (length < now)
1134  now = length;
1135  fwrite(buf, 1, now, file); // allowed to fail; this function is advisory anyway
1136  length -= now;
1137  }
1138 #endif
1139 }
1140 
1141 #ifdef WIN32
1142 fs::path GetSpecialFolderPath(int nFolder, bool fCreate)
1143 {
1144  WCHAR pszPath[MAX_PATH] = L"";
1145 
1146  if(SHGetSpecialFolderPathW(nullptr, pszPath, nFolder, fCreate))
1147  {
1148  return fs::path(pszPath);
1149  }
1150 
1151  LogPrintf("SHGetSpecialFolderPathW() failed, could not obtain requested path.\n");
1152  return fs::path("");
1153 }
1154 #endif
1155 
1156 void runCommand(const std::string& strCommand)
1157 {
1158  if (strCommand.empty()) return;
1159 #ifndef WIN32
1160  int nErr = ::system(strCommand.c_str());
1161 #else
1162  int nErr = ::_wsystem(std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>,wchar_t>().from_bytes(strCommand).c_str());
1163 #endif
1164  if (nErr)
1165  LogPrintf("runCommand error: system(%s) returned %d\n", strCommand, nErr);
1166 }
1167 
1168 void RenameThread(const char* name)
1169 {
1170 #if defined(PR_SET_NAME)
1171  // Only the first 15 characters are used (16 - NUL terminator)
1172  ::prctl(PR_SET_NAME, name, 0, 0, 0);
1173 #elif (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__))
1174  pthread_set_name_np(pthread_self(), name);
1175 
1176 #elif defined(MAC_OSX)
1177  pthread_setname_np(name);
1178 #else
1179  // Prevent warnings for unused parameters...
1180  (void)name;
1181 #endif
1182 }
1183 
1185 {
1186 #ifdef HAVE_MALLOPT_ARENA_MAX
1187  // glibc-specific: On 32-bit systems set the number of arenas to 1.
1188  // By default, since glibc 2.10, the C library will create up to two heap
1189  // arenas per core. This is known to cause excessive virtual address space
1190  // usage in our usage. Work around it by setting the maximum number of
1191  // arenas to 1.
1192  if (sizeof(void*) == 4) {
1193  mallopt(M_ARENA_MAX, 1);
1194  }
1195 #endif
1196  // On most POSIX systems (e.g. Linux, but not BSD) the environment's locale
1197  // may be invalid, in which case the "C" locale is used as fallback.
1198 #if !defined(WIN32) && !defined(MAC_OSX) && !defined(__FreeBSD__) && !defined(__OpenBSD__)
1199  try {
1200  std::locale(""); // Raises a runtime error if current locale is invalid
1201  } catch (const std::runtime_error&) {
1202  setenv("LC_ALL", "C", 1);
1203  }
1204 #elif defined(WIN32)
1205  // Set the default input/output charset is utf-8
1206  SetConsoleCP(CP_UTF8);
1207  SetConsoleOutputCP(CP_UTF8);
1208 #endif
1209  // The path locale is lazy initialized and to avoid deinitialization errors
1210  // in multithreading environments, it is set explicitly by the main thread.
1211  // A dummy locale is used to extract the internal default locale, used by
1212  // fs::path, which is then used to explicitly imbue the path.
1213  std::locale loc = fs::path::imbue(std::locale::classic());
1214 #ifndef WIN32
1215  fs::path::imbue(loc);
1216 #else
1217  fs::path::imbue(std::locale(loc, new std::codecvt_utf8_utf16<wchar_t>()));
1218 #endif
1219 }
1220 
1222 {
1223 #ifdef WIN32
1224  // Initialize Windows Sockets
1225  WSADATA wsadata;
1226  int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
1227  if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2)
1228  return false;
1229 #endif
1230  return true;
1231 }
1232 
1234 {
1235  return std::thread::hardware_concurrency();
1236 }
1237 
1238 std::string CopyrightHolders(const std::string& strPrefix)
1239 {
1240  std::string strCopyrightHolders = strPrefix + strprintf(_(COPYRIGHT_HOLDERS), _(COPYRIGHT_HOLDERS_SUBSTITUTION));
1241 
1242  // Check for untranslated substitution to make sure Bitcoin Core copyright is not removed by accident
1243  if (strprintf(COPYRIGHT_HOLDERS, COPYRIGHT_HOLDERS_SUBSTITUTION).find("BSHA3") == std::string::npos) {
1244  strCopyrightHolders += "\n" + strPrefix + "The BSHA3 developers";
1245  }
1246  return strCopyrightHolders;
1247 }
1248 
1249 // Obtain the application startup time (used for uptime calculation)
1251 {
1252  return nStartupTime;
1253 }
1254 
1255 fs::path AbsPathForConfigVal(const fs::path& path, bool net_specific)
1256 {
1257  return fs::absolute(path, GetDataDir(net_specific));
1258 }
1259 
1260 void SetThreadPriority(int nPriority)
1261 {
1262 #ifdef WIN32
1263  SetThreadPriority(GetCurrentThread(), nPriority);
1264 #else // WIN32
1265 #ifdef PRIO_THREAD
1266  setpriority(PRIO_THREAD, 0, nPriority);
1267 #else // PRIO_THREAD
1268  setpriority(PRIO_PROCESS, 0, nPriority);
1269 #endif // PRIO_THREAD
1270 #endif // WIN32
1271 }
1272 
1274 {
1275 #ifdef SCHED_BATCH
1276  const static sched_param param{0};
1277  if (int ret = pthread_setschedparam(pthread_self(), SCHED_BATCH, &param)) {
1278  LogPrintf("Failed to pthread_setschedparam: %s\n", strerror(errno));
1279  return ret;
1280  }
1281  return 0;
1282 #else
1283  return 1;
1284 #endif
1285 }
1286 
1287 namespace util {
1288 #ifdef WIN32
1289 WinCmdLineArgs::WinCmdLineArgs()
1290 {
1291  wchar_t** wargv = CommandLineToArgvW(GetCommandLineW(), &argc);
1292  std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t> utf8_cvt;
1293  argv = new char*[argc];
1294  args.resize(argc);
1295  for (int i = 0; i < argc; i++) {
1296  args[i] = utf8_cvt.to_bytes(wargv[i]);
1297  argv[i] = &*args[i].begin();
1298  }
1299  LocalFree(wargv);
1300 }
1301 
1302 WinCmdLineArgs::~WinCmdLineArgs()
1303 {
1304  delete[] argv;
1305 }
1306 
1307 std::pair<int, char**> WinCmdLineArgs::get()
1308 {
1309  return std::make_pair(argc, argv);
1310 }
1311 #endif
1312 } // namespace util
bool ReadConfigFiles(std::string &error, bool ignore_invalid_keys=false)
Definition: util.cpp:887
bool FileCommit(FILE *file)
Definition: util.cpp:1029
#define COPYRIGHT_HOLDERS_SUBSTITUTION
ArgsManager()
Definition: util.cpp:359
#define COPYRIGHT_HOLDERS
bool HelpRequested(const ArgsManager &args)
Definition: util.cpp:662
std::string HelpMessageOpt(const std::string &option, const std::string &message)
Format a string to be used as option description in help messages.
Definition: util.cpp:675
#define NO_THREAD_SAFETY_ANALYSIS
Definition: threadsafety.h:53
static bool GetNetBoolArg(const ArgsManager &am, const std::string &net_arg) EXCLUSIVE_LOCKS_REQUIRED(am.cs_args)
Definition: util.cpp:300
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: util.cpp:502
const int64_t nStartupTime
Definition: util.cpp:83
bool SetupNetworking()
Definition: util.cpp:1221
Definition: util.cpp:1287
void SetThreadPriority(int nPriority)
Definition: util.cpp:1260
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:13
const char *const BITCOIN_CONF_FILENAME
Definition: util.cpp:85
void ReleaseDirectoryLocks()
Release all directory locks.
Definition: util.cpp:171
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn&#39;t already have a value.
Definition: util.cpp:558
static const std::string REGTEST
const char *const BITCOIN_PID_FILENAME
Definition: util.cpp:86
#define strprintf
Definition: tinyformat.h:1066
UniValue ret(UniValue::VARR)
Definition: rpcwallet.cpp:1140
const char * prefix
Definition: rest.cpp:581
int64_t GetStartupTime()
Server/client environment: argument handling, config file parsing, thread wrappers, startup time.
Definition: util.cpp:1250
void AddHiddenArgs(const std::vector< std::string > &args)
Add many hidden arguments.
Definition: util.cpp:586
void WarnForSectionOnlyArgs()
Log warnings for options in m_section_only_args when they are specified in the default section but no...
Definition: util.cpp:375
fs::ifstream ifstream
Definition: fs.h:90
#define MAX_PATH
Definition: compat.h:93
void SelectConfigNetwork(const std::string &network)
Select the network in use.
Definition: util.cpp:405
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
Definition: util.cpp:102
void PrintExceptionContinue(const std::exception *pex, const char *pszThread)
Definition: util.cpp:698
bool ParseParameters(int argc, const char *const argv[], std::string &error)
Definition: util.cpp:411
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: util.cpp:542
void ForceSetArg(const std::string &strArg, const std::string &strValue)
Definition: util.cpp:566
void locking_callback(int mode, int i, const char *file, int line) NO_THREAD_SAFETY_ANALYSIS
Definition: util.cpp:92
bool IsArgKnown(const std::string &key) const
Check whether we know of this arg.
Definition: util.cpp:466
static bool UseDefaultSection(const ArgsManager &am, const std::string &arg) EXCLUSIVE_LOCKS_REQUIRED(am.cs_args)
Determine whether to use config settings in the default section, See also comments around ArgsManager...
Definition: util.cpp:221
fs::path AbsPathForConfigVal(const fs::path &path, bool net_specific)
Most paths passed as configuration arguments are treated as relative to the datadir if they are not a...
Definition: util.cpp:1255
bool SoftSetArg(const std::string &strArg, const std::string &strValue)
Set an argument if it doesn&#39;t already have a value.
Definition: util.cpp:550
void RenameThread(const char *name)
Definition: util.cpp:1168
bool LockDirectory(const fs::path &directory, const std::string lockfile_name, bool probe_only)
Definition: util.cpp:147
const std::string & DataDir() const
std::string GetHelpMessage() const
Get the help string.
Definition: util.cpp:593
static const std::string MAIN
BIP70 chain name strings (main, test or regtest)
int RaiseFileDescriptorLimit(int nMinFD)
this function tries to raise the file descriptor limit to the requested number.
Definition: util.cpp:1074
class CInit instance_of_cinit
int ScheduleBatchPriority(void)
On platforms that support it, tell the kernel the calling thread is CPU-intensive and non-interactive...
Definition: util.cpp:1273
bool IsArgNegated(const std::string &strArg) const
Return true if the argument was originally passed as a negated option, i.e.
Definition: util.cpp:508
bool TruncateFile(FILE *file, unsigned int length)
Definition: util.cpp:1062
#define LEAVE_CRITICAL_SECTION(cs)
Definition: sync.h:194
#define LOCK(cs)
Definition: sync.h:181
const char * name
Definition: rest.cpp:37
fs::path GetPidFile()
Definition: util.cpp:983
bool TryCreateDirectories(const fs::path &p)
Ignores exceptions thrown by Boost&#39;s create_directories if the requested directory exists...
Definition: util.cpp:1015
~CInit()
Definition: util.cpp:126
void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length)
this function tries to make a particular range of a file allocated (corresponding to disk space) it i...
Definition: util.cpp:1097
static std::string NetworkArg(const ArgsManager &am, const std::string &arg)
Convert regular argument into the network-specific setting.
Definition: util.cpp:227
std::string FormatParagraph(const std::string &in, size_t width, size_t indent)
Format a paragraph of text to a fixed width, adding spaces for indentation to any added line...
auto end
Definition: rpcwallet.cpp:1068
CCriticalSection cs_args
Definition: util.h:145
UniValue help(const JSONRPCRequest &jsonRequest)
Definition: server.cpp:202
static std::pair< bool, std::string > GetArg(const ArgsManager &am, const std::string &arg)
Definition: util.cpp:264
bool RenameOver(fs::path src, fs::path dest)
Definition: util.cpp:999
std::map< std::string, std::vector< std::string > > MapArgs
Definition: util.cpp:217
std::string CopyrightHolders(const std::string &strPrefix)
Definition: util.cpp:1238
fs::path GetDefaultDataDir()
Definition: util.cpp:705
const fs::path & GetBlocksDir(bool fNetSpecific)
Definition: util.cpp:737
#define ENTER_CRITICAL_SECTION(cs)
Definition: sync.h:188
ArgsManager gArgs
Definition: util.cpp:88
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:51
bool IsSwitchChar(char c)
Definition: util.h:104
Internal helper functions for ArgsManager.
Definition: util.cpp:215
fs::path GetConfigFile(const std::string &confPath)
Definition: util.cpp:808
void AddArg(const std::string &name, const std::string &help, const bool debug_only, const OptionsCategory &cat)
Add argument.
Definition: util.cpp:572
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: util.cpp:526
OptionsCategory
Definition: util.h:113
bool DirIsWritable(const fs::path &directory)
Definition: util.cpp:177
void runCommand(const std::string &strCommand)
Definition: util.cpp:1156
void ClearDatadirCache()
Definition: util.cpp:798
int64_t atoi64(const char *psz)
CInit()
Definition: util.cpp:105
bool ReadConfigStream(std::istream &stream, std::string &error, bool ignore_invalid_keys=false)
Definition: util.cpp:857
bool error(const char *fmt, const Args &... args)
Definition: util.h:59
void RandAddSeed()
Definition: random.cpp:132
static const std::string TESTNET
std::string GetChainName() const
Looks for -regtest, -testnet and returns the appropriate BIP70 chain name.
Definition: util.cpp:967
const fs::path & GetDataDir(bool fNetSpecific)
Definition: util.cpp:766
void CreatePidFile(const fs::path &path, pid_t pid)
Definition: util.cpp:988
int64_t GetTime()
GetTimeMicros() and GetTimeMillis() both return the system time, but in different units...
Definition: utiltime.cpp:20
int GetNumCores()
Return the number of cores available on the current system.
Definition: util.cpp:1233
static void AddArgs(std::vector< std::string > &res, const MapArgs &map_args, const std::string &arg)
Find arguments in a map and add them to a vector.
Definition: util.cpp:234
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
Definition: util.cpp:483
void SetupEnvironment()
Definition: util.cpp:1184
std::string HelpMessageGroup(const std::string &message)
Format a string to be used as group of options in help messages.
Definition: util.cpp:671
std::string _(const char *psz)
Translation function.
Definition: util.h:50
int atoi(const std::string &str)
static std::pair< bool, std::string > GetArgHelper(const MapArgs &map_args, const std::string &arg, bool getLast=false)
Return true/false if an argument is set in a map, and also return the first (or last) of the possibly...
Definition: util.cpp:245