Bitcoin Core  21.99.0
P2P Digital Currency
system.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2020 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 <sync.h>
7 #include <util/system.h>
8 
9 #ifdef HAVE_BOOST_PROCESS
10 #include <boost/process.hpp>
11 #endif // HAVE_BOOST_PROCESS
12 
13 #include <chainparamsbase.h>
14 #include <util/strencodings.h>
15 #include <util/string.h>
16 #include <util/translation.h>
17 
18 
19 #if (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__))
20 #include <pthread.h>
21 #include <pthread_np.h>
22 #endif
23 
24 #ifndef WIN32
25 // for posix_fallocate, in configure.ac we check if it is present after this
26 #ifdef __linux__
27 
28 #ifdef _POSIX_C_SOURCE
29 #undef _POSIX_C_SOURCE
30 #endif
31 
32 #define _POSIX_C_SOURCE 200112L
33 
34 #endif // __linux__
35 
36 #include <algorithm>
37 #include <cassert>
38 #include <fcntl.h>
39 #include <sched.h>
40 #include <sys/resource.h>
41 #include <sys/stat.h>
42 
43 #else
44 
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 
52 #ifndef NOMINMAX
53 #define NOMINMAX
54 #endif
55 #include <codecvt>
56 
57 #include <io.h> /* for _commit */
58 #include <shellapi.h>
59 #include <shlobj.h>
60 #endif
61 
62 #ifdef HAVE_MALLOPT_ARENA_MAX
63 #include <malloc.h>
64 #endif
65 
66 #include <boost/algorithm/string/replace.hpp>
67 #include <thread>
68 #include <typeinfo>
69 #include <univalue.h>
70 
71 // Application startup time (used for uptime calculation)
72 const int64_t nStartupTime = GetTime();
73 
74 const char * const BITCOIN_CONF_FILENAME = "bitcoin.conf";
75 const char * const BITCOIN_SETTINGS_FILENAME = "settings.json";
76 
78 
86 static std::map<std::string, std::unique_ptr<fsbridge::FileLock>> dir_locks GUARDED_BY(cs_dir_locks);
87 
88 bool LockDirectory(const fs::path& directory, const std::string lockfile_name, bool probe_only)
89 {
90  LOCK(cs_dir_locks);
91  fs::path pathLockFile = directory / lockfile_name;
92 
93  // If a lock for this directory already exists in the map, don't try to re-lock it
94  if (dir_locks.count(pathLockFile.string())) {
95  return true;
96  }
97 
98  // Create empty lock file if it doesn't exist.
99  FILE* file = fsbridge::fopen(pathLockFile, "a");
100  if (file) fclose(file);
101  auto lock = MakeUnique<fsbridge::FileLock>(pathLockFile);
102  if (!lock->TryLock()) {
103  return error("Error while attempting to lock directory %s: %s", directory.string(), lock->GetReason());
104  }
105  if (!probe_only) {
106  // Lock successful and we're not just probing, put it into the map
107  dir_locks.emplace(pathLockFile.string(), std::move(lock));
108  }
109  return true;
110 }
111 
112 void UnlockDirectory(const fs::path& directory, const std::string& lockfile_name)
113 {
114  LOCK(cs_dir_locks);
115  dir_locks.erase((directory / lockfile_name).string());
116 }
117 
119 {
120  LOCK(cs_dir_locks);
121  dir_locks.clear();
122 }
123 
124 bool DirIsWritable(const fs::path& directory)
125 {
126  fs::path tmpFile = directory / fs::unique_path();
127 
128  FILE* file = fsbridge::fopen(tmpFile, "a");
129  if (!file) return false;
130 
131  fclose(file);
132  remove(tmpFile);
133 
134  return true;
135 }
136 
137 bool CheckDiskSpace(const fs::path& dir, uint64_t additional_bytes)
138 {
139  constexpr uint64_t min_disk_space = 52428800; // 50 MiB
140 
141  uint64_t free_bytes_available = fs::space(dir).available;
142  return free_bytes_available >= min_disk_space + additional_bytes;
143 }
144 
145 std::streampos GetFileSize(const char* path, std::streamsize max) {
146  std::ifstream file(path, std::ios::binary);
147  file.ignore(max);
148  return file.gcount();
149 }
150 
168 static bool InterpretBool(const std::string& strValue)
169 {
170  if (strValue.empty())
171  return true;
172  return (atoi(strValue) != 0);
173 }
174 
175 static std::string SettingName(const std::string& arg)
176 {
177  return arg.size() > 0 && arg[0] == '-' ? arg.substr(1) : arg;
178 }
179 
200 static util::SettingsValue InterpretOption(std::string& section, std::string& key, const std::string& value)
201 {
202  // Split section name from key name for keys like "testnet.foo" or "regtest.bar"
203  size_t option_index = key.find('.');
204  if (option_index != std::string::npos) {
205  section = key.substr(0, option_index);
206  key.erase(0, option_index + 1);
207  }
208  if (key.substr(0, 2) == "no") {
209  key.erase(0, 2);
210  // Double negatives like -nofoo=0 are supported (but discouraged)
211  if (!InterpretBool(value)) {
212  LogPrintf("Warning: parsed potentially confusing double-negative -%s=%s\n", key, value);
213  return true;
214  }
215  return false;
216  }
217  return value;
218 }
219 
227 static bool CheckValid(const std::string& key, const util::SettingsValue& val, unsigned int flags, std::string& error)
228 {
229  if (val.isBool() && !(flags & ArgsManager::ALLOW_BOOL)) {
230  error = strprintf("Negating of -%s is meaningless and therefore forbidden", key);
231  return false;
232  }
233  return true;
234 }
235 
236 // Define default constructor and destructor that are not inline, so code instantiating this class doesn't need to
237 // #include class definitions for all members.
238 // For example, m_settings has an internal dependency on univalue.
241 
242 const std::set<std::string> ArgsManager::GetUnsuitableSectionOnlyArgs() const
243 {
244  std::set<std::string> unsuitables;
245 
246  LOCK(cs_args);
247 
248  // if there's no section selected, don't worry
249  if (m_network.empty()) return std::set<std::string> {};
250 
251  // if it's okay to use the default section for this network, don't worry
252  if (m_network == CBaseChainParams::MAIN) return std::set<std::string> {};
253 
254  for (const auto& arg : m_network_only_args) {
255  if (OnlyHasDefaultSectionSetting(m_settings, m_network, SettingName(arg))) {
256  unsuitables.insert(arg);
257  }
258  }
259  return unsuitables;
260 }
261 
262 const std::list<SectionInfo> ArgsManager::GetUnrecognizedSections() const
263 {
264  // Section names to be recognized in the config file.
265  static const std::set<std::string> available_sections{
270  };
271 
272  LOCK(cs_args);
273  std::list<SectionInfo> unrecognized = m_config_sections;
274  unrecognized.remove_if([](const SectionInfo& appeared){ return available_sections.find(appeared.m_name) != available_sections.end(); });
275  return unrecognized;
276 }
277 
278 void ArgsManager::SelectConfigNetwork(const std::string& network)
279 {
280  LOCK(cs_args);
281  m_network = network;
282 }
283 
284 bool ArgsManager::ParseParameters(int argc, const char* const argv[], std::string& error)
285 {
286  LOCK(cs_args);
287  m_settings.command_line_options.clear();
288 
289  for (int i = 1; i < argc; i++) {
290  std::string key(argv[i]);
291 
292 #ifdef MAC_OSX
293  // At the first time when a user gets the "App downloaded from the
294  // internet" warning, and clicks the Open button, macOS passes
295  // a unique process serial number (PSN) as -psn_... command-line
296  // argument, which we filter out.
297  if (key.substr(0, 5) == "-psn_") continue;
298 #endif
299 
300  if (key == "-") break; //bitcoin-tx using stdin
301  std::string val;
302  size_t is_index = key.find('=');
303  if (is_index != std::string::npos) {
304  val = key.substr(is_index + 1);
305  key.erase(is_index);
306  }
307 #ifdef WIN32
308  key = ToLower(key);
309  if (key[0] == '/')
310  key[0] = '-';
311 #endif
312 
313  if (key[0] != '-')
314  break;
315 
316  // Transform --foo to -foo
317  if (key.length() > 1 && key[1] == '-')
318  key.erase(0, 1);
319 
320  // Transform -foo to foo
321  key.erase(0, 1);
322  std::string section;
323  util::SettingsValue value = InterpretOption(section, key, val);
325 
326  // Unknown command line options and command line options with dot
327  // characters (which are returned from InterpretOption with nonempty
328  // section strings) are not valid.
329  if (!flags || !section.empty()) {
330  error = strprintf("Invalid parameter %s", argv[i]);
331  return false;
332  }
333 
334  if (!CheckValid(key, value, *flags, error)) return false;
335 
336  m_settings.command_line_options[key].push_back(value);
337  }
338 
339  // we do not allow -includeconf from command line
340  bool success = true;
341  if (auto* includes = util::FindKey(m_settings.command_line_options, "includeconf")) {
342  for (const auto& include : util::SettingsSpan(*includes)) {
343  error += "-includeconf cannot be used from commandline; -includeconf=" + include.get_str() + "\n";
344  success = false;
345  }
346  }
347  return success;
348 }
349 
351 {
352  LOCK(cs_args);
353  for (const auto& arg_map : m_available_args) {
354  const auto search = arg_map.second.find(name);
355  if (search != arg_map.second.end()) {
356  return search->second.m_flags;
357  }
358  }
359  return nullopt;
360 }
361 
362 std::vector<std::string> ArgsManager::GetArgs(const std::string& strArg) const
363 {
364  std::vector<std::string> result;
365  for (const util::SettingsValue& value : GetSettingsList(strArg)) {
366  result.push_back(value.isFalse() ? "0" : value.isTrue() ? "1" : value.get_str());
367  }
368  return result;
369 }
370 
371 bool ArgsManager::IsArgSet(const std::string& strArg) const
372 {
373  return !GetSetting(strArg).isNull();
374 }
375 
377 {
378  if (!GetSettingsPath()) {
379  return true; // Do nothing if settings file disabled.
380  }
381 
382  std::vector<std::string> errors;
383  if (!ReadSettingsFile(&errors)) {
384  error = strprintf("Failed loading settings file:\n- %s\n", Join(errors, "\n- "));
385  return false;
386  }
387  if (!WriteSettingsFile(&errors)) {
388  error = strprintf("Failed saving settings file:\n- %s\n", Join(errors, "\n- "));
389  return false;
390  }
391  return true;
392 }
393 
394 bool ArgsManager::GetSettingsPath(fs::path* filepath, bool temp) const
395 {
396  if (IsArgNegated("-settings")) {
397  return false;
398  }
399  if (filepath) {
400  std::string settings = GetArg("-settings", BITCOIN_SETTINGS_FILENAME);
401  *filepath = fs::absolute(temp ? settings + ".tmp" : settings, GetDataDir(/* net_specific= */ true));
402  }
403  return true;
404 }
405 
406 static void SaveErrors(const std::vector<std::string> errors, std::vector<std::string>* error_out)
407 {
408  for (const auto& error : errors) {
409  if (error_out) {
410  error_out->emplace_back(error);
411  } else {
412  LogPrintf("%s\n", error);
413  }
414  }
415 }
416 
417 bool ArgsManager::ReadSettingsFile(std::vector<std::string>* errors)
418 {
419  fs::path path;
420  if (!GetSettingsPath(&path, /* temp= */ false)) {
421  return true; // Do nothing if settings file disabled.
422  }
423 
424  LOCK(cs_args);
425  m_settings.rw_settings.clear();
426  std::vector<std::string> read_errors;
427  if (!util::ReadSettings(path, m_settings.rw_settings, read_errors)) {
428  SaveErrors(read_errors, errors);
429  return false;
430  }
431  for (const auto& setting : m_settings.rw_settings) {
432  std::string section;
433  std::string key = setting.first;
434  (void)InterpretOption(section, key, /* value */ {}); // Split setting key into section and argname
435  if (!GetArgFlags('-' + key)) {
436  LogPrintf("Ignoring unknown rw_settings value %s\n", setting.first);
437  }
438  }
439  return true;
440 }
441 
442 bool ArgsManager::WriteSettingsFile(std::vector<std::string>* errors) const
443 {
444  fs::path path, path_tmp;
445  if (!GetSettingsPath(&path, /* temp= */ false) || !GetSettingsPath(&path_tmp, /* temp= */ true)) {
446  throw std::logic_error("Attempt to write settings file when dynamic settings are disabled.");
447  }
448 
449  LOCK(cs_args);
450  std::vector<std::string> write_errors;
451  if (!util::WriteSettings(path_tmp, m_settings.rw_settings, write_errors)) {
452  SaveErrors(write_errors, errors);
453  return false;
454  }
455  if (!RenameOver(path_tmp, path)) {
456  SaveErrors({strprintf("Failed renaming settings file %s to %s\n", path_tmp.string(), path.string())}, errors);
457  return false;
458  }
459  return true;
460 }
461 
462 bool ArgsManager::IsArgNegated(const std::string& strArg) const
463 {
464  return GetSetting(strArg).isFalse();
465 }
466 
467 std::string ArgsManager::GetArg(const std::string& strArg, const std::string& strDefault) const
468 {
469  const util::SettingsValue value = GetSetting(strArg);
470  return value.isNull() ? strDefault : value.isFalse() ? "0" : value.isTrue() ? "1" : value.get_str();
471 }
472 
473 int64_t ArgsManager::GetArg(const std::string& strArg, int64_t nDefault) const
474 {
475  const util::SettingsValue value = GetSetting(strArg);
476  return value.isNull() ? nDefault : value.isFalse() ? 0 : value.isTrue() ? 1 : value.isNum() ? value.get_int64() : atoi64(value.get_str());
477 }
478 
479 bool ArgsManager::GetBoolArg(const std::string& strArg, bool fDefault) const
480 {
481  const util::SettingsValue value = GetSetting(strArg);
482  return value.isNull() ? fDefault : value.isBool() ? value.get_bool() : InterpretBool(value.get_str());
483 }
484 
485 bool ArgsManager::SoftSetArg(const std::string& strArg, const std::string& strValue)
486 {
487  LOCK(cs_args);
488  if (IsArgSet(strArg)) return false;
489  ForceSetArg(strArg, strValue);
490  return true;
491 }
492 
493 bool ArgsManager::SoftSetBoolArg(const std::string& strArg, bool fValue)
494 {
495  if (fValue)
496  return SoftSetArg(strArg, std::string("1"));
497  else
498  return SoftSetArg(strArg, std::string("0"));
499 }
500 
501 void ArgsManager::ForceSetArg(const std::string& strArg, const std::string& strValue)
502 {
503  LOCK(cs_args);
504  m_settings.forced_settings[SettingName(strArg)] = strValue;
505 }
506 
507 void ArgsManager::AddArg(const std::string& name, const std::string& help, unsigned int flags, const OptionsCategory& cat)
508 {
509  // Split arg name from its help param
510  size_t eq_index = name.find('=');
511  if (eq_index == std::string::npos) {
512  eq_index = name.size();
513  }
514  std::string arg_name = name.substr(0, eq_index);
515 
516  LOCK(cs_args);
517  std::map<std::string, Arg>& arg_map = m_available_args[cat];
518  auto ret = arg_map.emplace(arg_name, Arg{name.substr(eq_index, name.size() - eq_index), help, flags});
519  assert(ret.second); // Make sure an insertion actually happened
520 
521  if (flags & ArgsManager::NETWORK_ONLY) {
522  m_network_only_args.emplace(arg_name);
523  }
524 }
525 
526 void ArgsManager::AddHiddenArgs(const std::vector<std::string>& names)
527 {
528  for (const std::string& name : names) {
530  }
531 }
532 
533 std::string ArgsManager::GetHelpMessage() const
534 {
535  const bool show_debug = GetBoolArg("-help-debug", false);
536 
537  std::string usage = "";
538  LOCK(cs_args);
539  for (const auto& arg_map : m_available_args) {
540  switch(arg_map.first) {
542  usage += HelpMessageGroup("Options:");
543  break;
545  usage += HelpMessageGroup("Connection options:");
546  break;
548  usage += HelpMessageGroup("ZeroMQ notification options:");
549  break;
551  usage += HelpMessageGroup("Debugging/Testing options:");
552  break;
554  usage += HelpMessageGroup("Node relay options:");
555  break;
557  usage += HelpMessageGroup("Block creation options:");
558  break;
560  usage += HelpMessageGroup("RPC server options:");
561  break;
563  usage += HelpMessageGroup("Wallet options:");
564  break;
566  if (show_debug) usage += HelpMessageGroup("Wallet debugging/testing options:");
567  break;
569  usage += HelpMessageGroup("Chain selection options:");
570  break;
572  usage += HelpMessageGroup("UI Options:");
573  break;
575  usage += HelpMessageGroup("Commands:");
576  break;
578  usage += HelpMessageGroup("Register Commands:");
579  break;
580  default:
581  break;
582  }
583 
584  // When we get to the hidden options, stop
585  if (arg_map.first == OptionsCategory::HIDDEN) break;
586 
587  for (const auto& arg : arg_map.second) {
588  if (show_debug || !(arg.second.m_flags & ArgsManager::DEBUG_ONLY)) {
589  std::string name;
590  if (arg.second.m_help_param.empty()) {
591  name = arg.first;
592  } else {
593  name = arg.first + arg.second.m_help_param;
594  }
595  usage += HelpMessageOpt(name, arg.second.m_help_text);
596  }
597  }
598  }
599  return usage;
600 }
601 
602 bool HelpRequested(const ArgsManager& args)
603 {
604  return args.IsArgSet("-?") || args.IsArgSet("-h") || args.IsArgSet("-help") || args.IsArgSet("-help-debug");
605 }
606 
608 {
609  args.AddArg("-?", "Print this help message and exit", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
610  args.AddHiddenArgs({"-h", "-help"});
611 }
612 
613 static const int screenWidth = 79;
614 static const int optIndent = 2;
615 static const int msgIndent = 7;
616 
617 std::string HelpMessageGroup(const std::string &message) {
618  return std::string(message) + std::string("\n\n");
619 }
620 
621 std::string HelpMessageOpt(const std::string &option, const std::string &message) {
622  return std::string(optIndent,' ') + std::string(option) +
623  std::string("\n") + std::string(msgIndent,' ') +
625  std::string("\n\n");
626 }
627 
628 static std::string FormatException(const std::exception* pex, const char* pszThread)
629 {
630 #ifdef WIN32
631  char pszModule[MAX_PATH] = "";
632  GetModuleFileNameA(nullptr, pszModule, sizeof(pszModule));
633 #else
634  const char* pszModule = "bitcoin";
635 #endif
636  if (pex)
637  return strprintf(
638  "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
639  else
640  return strprintf(
641  "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
642 }
643 
644 void PrintExceptionContinue(const std::exception* pex, const char* pszThread)
645 {
646  std::string message = FormatException(pex, pszThread);
647  LogPrintf("\n\n************************\n%s\n", message);
648  tfm::format(std::cerr, "\n\n************************\n%s\n", message);
649 }
650 
652 {
653  // Windows: C:\Users\Username\AppData\Roaming\Bitcoin
654  // macOS: ~/Library/Application Support/Bitcoin
655  // Unix-like: ~/.bitcoin
656 #ifdef WIN32
657  // Windows
658  return GetSpecialFolderPath(CSIDL_APPDATA) / "Bitcoin";
659 #else
660  fs::path pathRet;
661  char* pszHome = getenv("HOME");
662  if (pszHome == nullptr || strlen(pszHome) == 0)
663  pathRet = fs::path("/");
664  else
665  pathRet = fs::path(pszHome);
666 #ifdef MAC_OSX
667  // macOS
668  return pathRet / "Library/Application Support/Bitcoin";
669 #else
670  // Unix-like
671  return pathRet / ".bitcoin";
672 #endif
673 #endif
674 }
675 
676 namespace {
677 fs::path StripRedundantLastElementsOfPath(const fs::path& path)
678 {
679  auto result = path;
680  while (result.filename().string() == ".") {
681  result = result.parent_path();
682  }
683 
684  assert(fs::equivalent(result, path));
685  return result;
686 }
687 } // namespace
688 
690 static fs::path pathCached;
691 static fs::path pathCachedNetSpecific;
693 
694 const fs::path &GetBlocksDir()
695 {
696  LOCK(csPathCached);
697  fs::path &path = g_blocks_path_cache_net_specific;
698 
699  // Cache the path to avoid calling fs::create_directories on every call of
700  // this function
701  if (!path.empty()) return path;
702 
703  if (gArgs.IsArgSet("-blocksdir")) {
704  path = fs::system_complete(gArgs.GetArg("-blocksdir", ""));
705  if (!fs::is_directory(path)) {
706  path = "";
707  return path;
708  }
709  } else {
710  path = GetDataDir(false);
711  }
712 
713  path /= BaseParams().DataDir();
714  path /= "blocks";
715  fs::create_directories(path);
716  path = StripRedundantLastElementsOfPath(path);
717  return path;
718 }
719 
720 const fs::path &GetDataDir(bool fNetSpecific)
721 {
722  LOCK(csPathCached);
723  fs::path &path = fNetSpecific ? pathCachedNetSpecific : pathCached;
724 
725  // Cache the path to avoid calling fs::create_directories on every call of
726  // this function
727  if (!path.empty()) return path;
728 
729  std::string datadir = gArgs.GetArg("-datadir", "");
730  if (!datadir.empty()) {
731  path = fs::system_complete(datadir);
732  if (!fs::is_directory(path)) {
733  path = "";
734  return path;
735  }
736  } else {
737  path = GetDefaultDataDir();
738  }
739  if (fNetSpecific)
740  path /= BaseParams().DataDir();
741 
742  if (fs::create_directories(path)) {
743  // This is the first run, create wallets subdirectory too
744  fs::create_directories(path / "wallets");
745  }
746 
747  path = StripRedundantLastElementsOfPath(path);
748  return path;
749 }
750 
752 {
753  std::string datadir = gArgs.GetArg("-datadir", "");
754  return datadir.empty() || fs::is_directory(fs::system_complete(datadir));
755 }
756 
758 {
759  LOCK(csPathCached);
760 
761  pathCached = fs::path();
762  pathCachedNetSpecific = fs::path();
764 }
765 
766 fs::path GetConfigFile(const std::string& confPath)
767 {
768  return AbsPathForConfigVal(fs::path(confPath), false);
769 }
770 
771 static bool GetConfigOptions(std::istream& stream, const std::string& filepath, std::string& error, std::vector<std::pair<std::string, std::string>>& options, std::list<SectionInfo>& sections)
772 {
773  std::string str, prefix;
774  std::string::size_type pos;
775  int linenr = 1;
776  while (std::getline(stream, str)) {
777  bool used_hash = false;
778  if ((pos = str.find('#')) != std::string::npos) {
779  str = str.substr(0, pos);
780  used_hash = true;
781  }
782  const static std::string pattern = " \t\r\n";
783  str = TrimString(str, pattern);
784  if (!str.empty()) {
785  if (*str.begin() == '[' && *str.rbegin() == ']') {
786  const std::string section = str.substr(1, str.size() - 2);
787  sections.emplace_back(SectionInfo{section, filepath, linenr});
788  prefix = section + '.';
789  } else if (*str.begin() == '-') {
790  error = strprintf("parse error on line %i: %s, options in configuration file must be specified without leading -", linenr, str);
791  return false;
792  } else if ((pos = str.find('=')) != std::string::npos) {
793  std::string name = prefix + TrimString(str.substr(0, pos), pattern);
794  std::string value = TrimString(str.substr(pos + 1), pattern);
795  if (used_hash && name.find("rpcpassword") != std::string::npos) {
796  error = strprintf("parse error on line %i, using # in rpcpassword can be ambiguous and should be avoided", linenr);
797  return false;
798  }
799  options.emplace_back(name, value);
800  if ((pos = name.rfind('.')) != std::string::npos && prefix.length() <= pos) {
801  sections.emplace_back(SectionInfo{name.substr(0, pos), filepath, linenr});
802  }
803  } else {
804  error = strprintf("parse error on line %i: %s", linenr, str);
805  if (str.size() >= 2 && str.substr(0, 2) == "no") {
806  error += strprintf(", if you intended to specify a negated option, use %s=1 instead", str);
807  }
808  return false;
809  }
810  }
811  ++linenr;
812  }
813  return true;
814 }
815 
816 bool ArgsManager::ReadConfigStream(std::istream& stream, const std::string& filepath, std::string& error, bool ignore_invalid_keys)
817 {
818  LOCK(cs_args);
819  std::vector<std::pair<std::string, std::string>> options;
820  if (!GetConfigOptions(stream, filepath, error, options, m_config_sections)) {
821  return false;
822  }
823  for (const std::pair<std::string, std::string>& option : options) {
824  std::string section;
825  std::string key = option.first;
826  util::SettingsValue value = InterpretOption(section, key, option.second);
828  if (flags) {
829  if (!CheckValid(key, value, *flags, error)) {
830  return false;
831  }
832  m_settings.ro_config[section][key].push_back(value);
833  } else {
834  if (ignore_invalid_keys) {
835  LogPrintf("Ignoring unknown configuration value %s\n", option.first);
836  } else {
837  error = strprintf("Invalid configuration value %s", option.first);
838  return false;
839  }
840  }
841  }
842  return true;
843 }
844 
845 bool ArgsManager::ReadConfigFiles(std::string& error, bool ignore_invalid_keys)
846 {
847  {
848  LOCK(cs_args);
849  m_settings.ro_config.clear();
850  m_config_sections.clear();
851  }
852 
853  const std::string confPath = GetArg("-conf", BITCOIN_CONF_FILENAME);
854  fsbridge::ifstream stream(GetConfigFile(confPath));
855 
856  // ok to not have a config file
857  if (stream.good()) {
858  if (!ReadConfigStream(stream, confPath, error, ignore_invalid_keys)) {
859  return false;
860  }
861  // `-includeconf` cannot be included in the command line arguments except
862  // as `-noincludeconf` (which indicates that no included conf file should be used).
863  bool use_conf_file{true};
864  {
865  LOCK(cs_args);
866  if (auto* includes = util::FindKey(m_settings.command_line_options, "includeconf")) {
867  // ParseParameters() fails if a non-negated -includeconf is passed on the command-line
868  assert(util::SettingsSpan(*includes).last_negated());
869  use_conf_file = false;
870  }
871  }
872  if (use_conf_file) {
873  std::string chain_id = GetChainName();
874  std::vector<std::string> conf_file_names;
875 
876  auto add_includes = [&](const std::string& network, size_t skip = 0) {
877  size_t num_values = 0;
878  LOCK(cs_args);
879  if (auto* section = util::FindKey(m_settings.ro_config, network)) {
880  if (auto* values = util::FindKey(*section, "includeconf")) {
881  for (size_t i = std::max(skip, util::SettingsSpan(*values).negated()); i < values->size(); ++i) {
882  conf_file_names.push_back((*values)[i].get_str());
883  }
884  num_values = values->size();
885  }
886  }
887  return num_values;
888  };
889 
890  // We haven't set m_network yet (that happens in SelectParams()), so manually check
891  // for network.includeconf args.
892  const size_t chain_includes = add_includes(chain_id);
893  const size_t default_includes = add_includes({});
894 
895  for (const std::string& conf_file_name : conf_file_names) {
896  fsbridge::ifstream conf_file_stream(GetConfigFile(conf_file_name));
897  if (conf_file_stream.good()) {
898  if (!ReadConfigStream(conf_file_stream, conf_file_name, error, ignore_invalid_keys)) {
899  return false;
900  }
901  LogPrintf("Included configuration file %s\n", conf_file_name);
902  } else {
903  error = "Failed to include configuration file " + conf_file_name;
904  return false;
905  }
906  }
907 
908  // Warn about recursive -includeconf
909  conf_file_names.clear();
910  add_includes(chain_id, /* skip= */ chain_includes);
911  add_includes({}, /* skip= */ default_includes);
912  std::string chain_id_final = GetChainName();
913  if (chain_id_final != chain_id) {
914  // Also warn about recursive includeconf for the chain that was specified in one of the includeconfs
915  add_includes(chain_id_final);
916  }
917  for (const std::string& conf_file_name : conf_file_names) {
918  tfm::format(std::cerr, "warning: -includeconf cannot be used from included files; ignoring -includeconf=%s\n", conf_file_name);
919  }
920  }
921  }
922 
923  // If datadir is changed in .conf file:
925  if (!CheckDataDirOption()) {
926  error = strprintf("specified data directory \"%s\" does not exist.", GetArg("-datadir", ""));
927  return false;
928  }
929  return true;
930 }
931 
932 std::string ArgsManager::GetChainName() const
933 {
934  auto get_net = [&](const std::string& arg) {
935  LOCK(cs_args);
936  util::SettingsValue value = util::GetSetting(m_settings, /* section= */ "", SettingName(arg),
937  /* ignore_default_section_config= */ false,
938  /* get_chain_name= */ true);
939  return value.isNull() ? false : value.isBool() ? value.get_bool() : InterpretBool(value.get_str());
940  };
941 
942  const bool fRegTest = get_net("-regtest");
943  const bool fSigNet = get_net("-signet");
944  const bool fTestNet = get_net("-testnet");
945  const bool is_chain_arg_set = IsArgSet("-chain");
946 
947  if ((int)is_chain_arg_set + (int)fRegTest + (int)fSigNet + (int)fTestNet > 1) {
948  throw std::runtime_error("Invalid combination of -regtest, -signet, -testnet and -chain. Can use at most one.");
949  }
950  if (fRegTest)
952  if (fSigNet) {
954  }
955  if (fTestNet)
957 
958  return GetArg("-chain", CBaseChainParams::MAIN);
959 }
960 
961 bool ArgsManager::UseDefaultSection(const std::string& arg) const
962 {
963  return m_network == CBaseChainParams::MAIN || m_network_only_args.count(arg) == 0;
964 }
965 
966 util::SettingsValue ArgsManager::GetSetting(const std::string& arg) const
967 {
968  LOCK(cs_args);
969  return util::GetSetting(
970  m_settings, m_network, SettingName(arg), !UseDefaultSection(arg), /* get_chain_name= */ false);
971 }
972 
973 std::vector<util::SettingsValue> ArgsManager::GetSettingsList(const std::string& arg) const
974 {
975  LOCK(cs_args);
976  return util::GetSettingsList(m_settings, m_network, SettingName(arg), !UseDefaultSection(arg));
977 }
978 
980  const std::string& prefix,
981  const std::string& section,
982  const std::map<std::string, std::vector<util::SettingsValue>>& args) const
983 {
984  std::string section_str = section.empty() ? "" : "[" + section + "] ";
985  for (const auto& arg : args) {
986  for (const auto& value : arg.second) {
987  Optional<unsigned int> flags = GetArgFlags('-' + arg.first);
988  if (flags) {
989  std::string value_str = (*flags & SENSITIVE) ? "****" : value.write();
990  LogPrintf("%s %s%s=%s\n", prefix, section_str, arg.first, value_str);
991  }
992  }
993  }
994 }
995 
997 {
998  LOCK(cs_args);
999  for (const auto& section : m_settings.ro_config) {
1000  logArgsPrefix("Config file arg:", section.first, section.second);
1001  }
1002  for (const auto& setting : m_settings.rw_settings) {
1003  LogPrintf("Setting file arg: %s = %s\n", setting.first, setting.second.write());
1004  }
1005  logArgsPrefix("Command-line arg:", "", m_settings.command_line_options);
1006 }
1007 
1008 bool RenameOver(fs::path src, fs::path dest)
1009 {
1010 #ifdef WIN32
1011  return MoveFileExW(src.wstring().c_str(), dest.wstring().c_str(),
1012  MOVEFILE_REPLACE_EXISTING) != 0;
1013 #else
1014  int rc = std::rename(src.string().c_str(), dest.string().c_str());
1015  return (rc == 0);
1016 #endif /* WIN32 */
1017 }
1018 
1024 bool TryCreateDirectories(const fs::path& p)
1025 {
1026  try
1027  {
1028  return fs::create_directories(p);
1029  } catch (const fs::filesystem_error&) {
1030  if (!fs::exists(p) || !fs::is_directory(p))
1031  throw;
1032  }
1033 
1034  // create_directories didn't create the directory, it had to have existed already
1035  return false;
1036 }
1037 
1038 bool FileCommit(FILE *file)
1039 {
1040  if (fflush(file) != 0) { // harmless if redundantly called
1041  LogPrintf("%s: fflush failed: %d\n", __func__, errno);
1042  return false;
1043  }
1044 #ifdef WIN32
1045  HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
1046  if (FlushFileBuffers(hFile) == 0) {
1047  LogPrintf("%s: FlushFileBuffers failed: %d\n", __func__, GetLastError());
1048  return false;
1049  }
1050 #elif defined(MAC_OSX) && defined(F_FULLFSYNC)
1051  if (fcntl(fileno(file), F_FULLFSYNC, 0) == -1) { // Manpage says "value other than -1" is returned on success
1052  LogPrintf("%s: fcntl F_FULLFSYNC failed: %d\n", __func__, errno);
1053  return false;
1054  }
1055 #elif HAVE_FDATASYNC
1056  if (fdatasync(fileno(file)) != 0 && errno != EINVAL) { // Ignore EINVAL for filesystems that don't support sync
1057  LogPrintf("%s: fdatasync failed: %d\n", __func__, errno);
1058  return false;
1059  }
1060 #else
1061  if (fsync(fileno(file)) != 0 && errno != EINVAL) {
1062  LogPrintf("%s: fsync failed: %d\n", __func__, errno);
1063  return false;
1064  }
1065 #endif
1066  return true;
1067 }
1068 
1069 void DirectoryCommit(const fs::path &dirname)
1070 {
1071 #ifndef WIN32
1072  FILE* file = fsbridge::fopen(dirname, "r");
1073  if (file) {
1074  fsync(fileno(file));
1075  fclose(file);
1076  }
1077 #endif
1078 }
1079 
1080 bool TruncateFile(FILE *file, unsigned int length) {
1081 #if defined(WIN32)
1082  return _chsize(_fileno(file), length) == 0;
1083 #else
1084  return ftruncate(fileno(file), length) == 0;
1085 #endif
1086 }
1087 
1092 int RaiseFileDescriptorLimit(int nMinFD) {
1093 #if defined(WIN32)
1094  return 2048;
1095 #else
1096  struct rlimit limitFD;
1097  if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) {
1098  if (limitFD.rlim_cur < (rlim_t)nMinFD) {
1099  limitFD.rlim_cur = nMinFD;
1100  if (limitFD.rlim_cur > limitFD.rlim_max)
1101  limitFD.rlim_cur = limitFD.rlim_max;
1102  setrlimit(RLIMIT_NOFILE, &limitFD);
1103  getrlimit(RLIMIT_NOFILE, &limitFD);
1104  }
1105  return limitFD.rlim_cur;
1106  }
1107  return nMinFD; // getrlimit failed, assume it's fine
1108 #endif
1109 }
1110 
1115 void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length) {
1116 #if defined(WIN32)
1117  // Windows-specific version
1118  HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
1119  LARGE_INTEGER nFileSize;
1120  int64_t nEndPos = (int64_t)offset + length;
1121  nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF;
1122  nFileSize.u.HighPart = nEndPos >> 32;
1123  SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN);
1124  SetEndOfFile(hFile);
1125 #elif defined(MAC_OSX)
1126  // OSX specific version
1127  // NOTE: Contrary to other OS versions, the OSX version assumes that
1128  // NOTE: offset is the size of the file.
1129  fstore_t fst;
1130  fst.fst_flags = F_ALLOCATECONTIG;
1131  fst.fst_posmode = F_PEOFPOSMODE;
1132  fst.fst_offset = 0;
1133  fst.fst_length = length; // mac os fst_length takes the # of free bytes to allocate, not desired file size
1134  fst.fst_bytesalloc = 0;
1135  if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) {
1136  fst.fst_flags = F_ALLOCATEALL;
1137  fcntl(fileno(file), F_PREALLOCATE, &fst);
1138  }
1139  ftruncate(fileno(file), static_cast<off_t>(offset) + length);
1140 #else
1141  #if defined(HAVE_POSIX_FALLOCATE)
1142  // Version using posix_fallocate
1143  off_t nEndPos = (off_t)offset + length;
1144  if (0 == posix_fallocate(fileno(file), 0, nEndPos)) return;
1145  #endif
1146  // Fallback version
1147  // TODO: just write one byte per block
1148  static const char buf[65536] = {};
1149  if (fseek(file, offset, SEEK_SET)) {
1150  return;
1151  }
1152  while (length > 0) {
1153  unsigned int now = 65536;
1154  if (length < now)
1155  now = length;
1156  fwrite(buf, 1, now, file); // allowed to fail; this function is advisory anyway
1157  length -= now;
1158  }
1159 #endif
1160 }
1161 
1162 #ifdef WIN32
1163 fs::path GetSpecialFolderPath(int nFolder, bool fCreate)
1164 {
1165  WCHAR pszPath[MAX_PATH] = L"";
1166 
1167  if(SHGetSpecialFolderPathW(nullptr, pszPath, nFolder, fCreate))
1168  {
1169  return fs::path(pszPath);
1170  }
1171 
1172  LogPrintf("SHGetSpecialFolderPathW() failed, could not obtain requested path.\n");
1173  return fs::path("");
1174 }
1175 #endif
1176 
1177 #ifndef WIN32
1178 std::string ShellEscape(const std::string& arg)
1179 {
1180  std::string escaped = arg;
1181  boost::replace_all(escaped, "'", "'\"'\"'");
1182  return "'" + escaped + "'";
1183 }
1184 #endif
1185 
1186 #if HAVE_SYSTEM
1187 void runCommand(const std::string& strCommand)
1188 {
1189  if (strCommand.empty()) return;
1190 #ifndef WIN32
1191  int nErr = ::system(strCommand.c_str());
1192 #else
1193  int nErr = ::_wsystem(std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>,wchar_t>().from_bytes(strCommand).c_str());
1194 #endif
1195  if (nErr)
1196  LogPrintf("runCommand error: system(%s) returned %d\n", strCommand, nErr);
1197 }
1198 #endif
1199 
1200 #ifdef HAVE_BOOST_PROCESS
1201 UniValue RunCommandParseJSON(const std::string& str_command, const std::string& str_std_in)
1202 {
1203  namespace bp = boost::process;
1204 
1205  UniValue result_json;
1206  bp::opstream stdin_stream;
1207  bp::ipstream stdout_stream;
1208  bp::ipstream stderr_stream;
1209 
1210  if (str_command.empty()) return UniValue::VNULL;
1211 
1212  bp::child c(
1213  str_command,
1214  bp::std_out > stdout_stream,
1215  bp::std_err > stderr_stream,
1216  bp::std_in < stdin_stream
1217  );
1218  if (!str_std_in.empty()) {
1219  stdin_stream << str_std_in << std::endl;
1220  }
1221  stdin_stream.pipe().close();
1222 
1223  std::string result;
1224  std::string error;
1225  std::getline(stdout_stream, result);
1226  std::getline(stderr_stream, error);
1227 
1228  c.wait();
1229  const int n_error = c.exit_code();
1230  if (n_error) throw std::runtime_error(strprintf("RunCommandParseJSON error: process(%s) returned %d: %s\n", str_command, n_error, error));
1231  if (!result_json.read(result)) throw std::runtime_error("Unable to parse JSON: " + result);
1232 
1233  return result_json;
1234 }
1235 #endif // HAVE_BOOST_PROCESS
1236 
1238 {
1239 #ifdef HAVE_MALLOPT_ARENA_MAX
1240  // glibc-specific: On 32-bit systems set the number of arenas to 1.
1241  // By default, since glibc 2.10, the C library will create up to two heap
1242  // arenas per core. This is known to cause excessive virtual address space
1243  // usage in our usage. Work around it by setting the maximum number of
1244  // arenas to 1.
1245  if (sizeof(void*) == 4) {
1246  mallopt(M_ARENA_MAX, 1);
1247  }
1248 #endif
1249  // On most POSIX systems (e.g. Linux, but not BSD) the environment's locale
1250  // may be invalid, in which case the "C.UTF-8" locale is used as fallback.
1251 #if !defined(WIN32) && !defined(MAC_OSX) && !defined(__FreeBSD__) && !defined(__OpenBSD__)
1252  try {
1253  std::locale(""); // Raises a runtime error if current locale is invalid
1254  } catch (const std::runtime_error&) {
1255  setenv("LC_ALL", "C.UTF-8", 1);
1256  }
1257 #elif defined(WIN32)
1258  // Set the default input/output charset is utf-8
1259  SetConsoleCP(CP_UTF8);
1260  SetConsoleOutputCP(CP_UTF8);
1261 #endif
1262  // The path locale is lazy initialized and to avoid deinitialization errors
1263  // in multithreading environments, it is set explicitly by the main thread.
1264  // A dummy locale is used to extract the internal default locale, used by
1265  // fs::path, which is then used to explicitly imbue the path.
1266  std::locale loc = fs::path::imbue(std::locale::classic());
1267 #ifndef WIN32
1268  fs::path::imbue(loc);
1269 #else
1270  fs::path::imbue(std::locale(loc, new std::codecvt_utf8_utf16<wchar_t>()));
1271 #endif
1272 }
1273 
1275 {
1276 #ifdef WIN32
1277  // Initialize Windows Sockets
1278  WSADATA wsadata;
1279  int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
1280  if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2)
1281  return false;
1282 #endif
1283  return true;
1284 }
1285 
1287 {
1288  return std::thread::hardware_concurrency();
1289 }
1290 
1291 std::string CopyrightHolders(const std::string& strPrefix)
1292 {
1293  const auto copyright_devs = strprintf(_(COPYRIGHT_HOLDERS).translated, COPYRIGHT_HOLDERS_SUBSTITUTION);
1294  std::string strCopyrightHolders = strPrefix + copyright_devs;
1295 
1296  // Make sure Bitcoin Core copyright is not removed by accident
1297  if (copyright_devs.find("Bitcoin Core") == std::string::npos) {
1298  strCopyrightHolders += "\n" + strPrefix + "The Bitcoin Core developers";
1299  }
1300  return strCopyrightHolders;
1301 }
1302 
1303 // Obtain the application startup time (used for uptime calculation)
1305 {
1306  return nStartupTime;
1307 }
1308 
1309 fs::path AbsPathForConfigVal(const fs::path& path, bool net_specific)
1310 {
1311  if (path.is_absolute()) {
1312  return path;
1313  }
1314  return fs::absolute(path, GetDataDir(net_specific));
1315 }
1316 
1318 {
1319 #ifdef SCHED_BATCH
1320  const static sched_param param{};
1321  const int rc = pthread_setschedparam(pthread_self(), SCHED_BATCH, &param);
1322  if (rc != 0) {
1323  LogPrintf("Failed to pthread_setschedparam: %s\n", strerror(rc));
1324  }
1325 #endif
1326 }
1327 
1328 namespace util {
1329 #ifdef WIN32
1330 WinCmdLineArgs::WinCmdLineArgs()
1331 {
1332  wchar_t** wargv = CommandLineToArgvW(GetCommandLineW(), &argc);
1333  std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t> utf8_cvt;
1334  argv = new char*[argc];
1335  args.resize(argc);
1336  for (int i = 0; i < argc; i++) {
1337  args[i] = utf8_cvt.to_bytes(wargv[i]);
1338  argv[i] = &*args[i].begin();
1339  }
1340  LocalFree(wargv);
1341 }
1342 
1343 WinCmdLineArgs::~WinCmdLineArgs()
1344 {
1345  delete[] argv;
1346 }
1347 
1348 std::pair<int, char**> WinCmdLineArgs::get()
1349 {
1350  return std::make_pair(argc, argv);
1351 }
1352 #endif
1353 } // namespace util
bool ReadConfigFiles(std::string &error, bool ignore_invalid_keys=false)
Definition: system.cpp:845
static const int optIndent
Definition: system.cpp:614
#define COPYRIGHT_HOLDERS_SUBSTITUTION
#define COPYRIGHT_HOLDERS
bool OnlyHasDefaultSectionSetting(const Settings &settings, const std::string &section, const std::string &name)
Return true if a setting is set in the default config file section, and not overridden by a higher pr...
Definition: settings.cpp:212
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: system.cpp:371
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...
bool isBool() const
Definition: univalue.h:80
bool FileCommit(FILE *file)
Ensure file contents are fully committed to disk, using a platform-specific feature analogous to fsyn...
Definition: system.cpp:1038
Definition: httprpc.h:8
const std::chrono::seconds now
std::string ToLower(const std::string &str)
Returns the lowercase equivalent of the given string.
const char *const BITCOIN_SETTINGS_FILENAME
Definition: system.cpp:75
bool GetSettingsPath(fs::path *filepath=nullptr, bool temp=false) const
Get settings file path, or return false if read-write settings were disabled with -nosettings...
Definition: system.cpp:394
bool DirIsWritable(const fs::path &directory)
Definition: system.cpp:124
assert(!tx.IsCoinBase())
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:24
size_t negated() const
Number of negated values.
Definition: settings.cpp:232
fs::path GetDefaultDataDir()
Definition: system.cpp:651
bool get_bool() const
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn&#39;t already have a value.
Definition: system.cpp:493
static const int msgIndent
Definition: system.cpp:615
static const std::string REGTEST
static std::map< std::string, std::unique_ptr< fsbridge::FileLock > > dir_locks GUARDED_BY(cs_dir_locks)
A map that contains all the currently held directory locks.
int GetNumCores()
Return the number of cores available on the current system.
Definition: system.cpp:1286
auto Join(const std::vector< T > &list, const BaseType &separator, UnaryOp unary_op) -> decltype(unary_op(list.at(0)))
Join a list of items.
Definition: string.h:36
bool read(const char *raw, size_t len)
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
const char * prefix
Definition: rest.cpp:670
void AddHiddenArgs(const std::vector< std::string > &args)
Add many hidden arguments.
Definition: system.cpp:526
SettingsValue GetSetting(const Settings &settings, const std::string &section, const std::string &name, bool ignore_default_section_config, bool get_chain_name)
Get settings value from combined sources: forced settings, command line arguments, runtime read-write settings, and the read-only config file.
Definition: settings.cpp:114
~ArgsManager()
Definition: system.cpp:240
bool TryCreateDirectories(const fs::path &p)
Ignores exceptions thrown by Boost&#39;s create_directories if the requested directory exists...
Definition: system.cpp:1024
fs::ifstream ifstream
Definition: fs.h:90
#define MAX_PATH
Definition: compat.h:62
static std::string SettingName(const std::string &arg)
Definition: system.cpp:175
bool last_negated() const
True if the last value is negated.
Definition: settings.cpp:231
void SetupEnvironment()
Definition: system.cpp:1237
static bool InterpretBool(const std::string &strValue)
Interpret a string argument as a boolean.
Definition: system.cpp:168
std::string CopyrightHolders(const std::string &strPrefix)
Definition: system.cpp:1291
void SelectConfigNetwork(const std::string &network)
Select the network in use.
Definition: system.cpp:278
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
bool WriteSettingsFile(std::vector< std::string > *errors=nullptr) const
Write settings file.
Definition: system.cpp:442
bool ReadConfigStream(std::istream &stream, const std::string &filepath, std::string &error, bool ignore_invalid_keys=false)
Definition: system.cpp:816
static void LogPrintf(const char *fmt, const Args &... args)
Definition: logging.h:166
util::SettingsValue GetSetting(const std::string &arg) const
Get setting value.
Definition: system.cpp:966
const std::string & get_str() const
static auto & nullopt
Substitute for C++17 std::nullopt DEPRECATED use std::nullopt in new code.
Definition: optional.h:18
bool isNum() const
Definition: univalue.h:82
bool ParseParameters(int argc, const char *const argv[], std::string &error)
Definition: system.cpp:284
const fs::path & GetBlocksDir()
Definition: system.cpp:694
int RaiseFileDescriptorLimit(int nMinFD)
this function tries to raise the file descriptor limit to the requested number.
Definition: system.cpp:1092
RecursiveMutex cs_args
Definition: system.h:196
void ReleaseDirectoryLocks()
Release all directory locks.
Definition: system.cpp:118
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:479
int64_t get_int64() const
void ClearDatadirCache()
Tests only.
Definition: system.cpp:757
void ForceSetArg(const std::string &strArg, const std::string &strValue)
Definition: system.cpp:501
bool CheckDiskSpace(const fs::path &dir, uint64_t additional_bytes)
Definition: system.cpp:137
Optional< unsigned int > GetArgFlags(const std::string &name) const
Return Flags for known arg.
Definition: system.cpp:350
const char *const BITCOIN_CONF_FILENAME
Definition: system.cpp:74
bool SetupNetworking()
Definition: system.cpp:1274
static RecursiveMutex csPathCached
Definition: system.cpp:692
bool SoftSetArg(const std::string &strArg, const std::string &strValue)
Set an argument if it doesn&#39;t already have a value.
Definition: system.cpp:485
auto FindKey(Map &&map, Key &&key) -> decltype(&map.at(key))
Map lookup helper.
Definition: settings.h:100
std::string m_name
Definition: system.h:163
const std::string & DataDir() const
std::string TrimString(const std::string &str, const std::string &pattern=" \\\)
Definition: string.h:18
std::string GetHelpMessage() const
Get the help string.
Definition: system.cpp:533
static const std::string MAIN
Chain name strings.
bool CheckDataDirOption()
Definition: system.cpp:751
std::vector< SettingsValue > GetSettingsList(const Settings &settings, const std::string &section, const std::string &name, bool ignore_default_section_config)
Get combined setting value similar to GetSetting(), except if setting was specified multiple times...
Definition: settings.cpp:167
bool WriteSettings(const fs::path &path, const std::map< std::string, SettingsValue > &values, std::vector< std::string > &errors)
Write settings file.
Definition: settings.cpp:95
bool LockDirectory(const fs::path &directory, const std::string lockfile_name, bool probe_only)
Definition: system.cpp:88
bool ReadSettingsFile(std::vector< std::string > *errors=nullptr)
Read settings file.
Definition: system.cpp:417
bool IsArgNegated(const std::string &strArg) const
Return true if the argument was originally passed as a negated option, i.e.
Definition: system.cpp:462
bool isFalse() const
Definition: univalue.h:79
#define LOCK(cs)
Definition: sync.h:232
const char * name
Definition: rest.cpp:41
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:57
int atoi(const std::string &str)
void format(std::ostream &out, const char *fmt, const Args &... args)
Format list of arguments to the stream according to given format string.
Definition: tinyformat.h:1062
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
Definition: system.cpp:507
bool HelpRequested(const ArgsManager &args)
Definition: system.cpp:602
const fs::path & GetDataDir(bool fNetSpecific)
Definition: system.cpp:720
static util::SettingsValue InterpretOption(std::string &section, std::string &key, const std::string &value)
Interpret -nofoo as if the user supplied -foo=0.
Definition: system.cpp:200
void PrintExceptionContinue(const std::exception *pex, const char *pszThread)
Definition: system.cpp:644
void logArgsPrefix(const std::string &prefix, const std::string &section, const std::map< std::string, std::vector< util::SettingsValue >> &args) const
Definition: system.cpp:979
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: system.cpp:1309
void DirectoryCommit(const fs::path &dirname)
Sync directory contents.
Definition: system.cpp:1069
bool isNull() const
Definition: univalue.h:77
bool isTrue() const
Definition: univalue.h:78
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: system.cpp:1115
int64_t atoi64(const std::string &str)
bool RenameOver(fs::path src, fs::path dest)
Definition: system.cpp:1008
int flags
Definition: bitcoin-tx.cpp:512
std::string ShellEscape(const std::string &arg)
Definition: system.cpp:1178
Accessor for list of settings that skips negated values when iterated over.
Definition: settings.h:83
static Mutex cs_dir_locks
Mutex to protect dir_locks.
Definition: system.cpp:80
static fs::path g_blocks_path_cache_net_specific
Definition: system.cpp:689
int64_t GetStartupTime()
Definition: system.cpp:1304
bool InitSettings(std::string &error)
Read and update settings file with saved settings.
Definition: system.cpp:376
static const int screenWidth
Definition: system.cpp:613
bool TruncateFile(FILE *file, unsigned int length)
Definition: system.cpp:1080
fs::path GetConfigFile(const std::string &confPath)
Definition: system.cpp:766
void UnlockDirectory(const fs::path &directory, const std::string &lockfile_name)
Definition: system.cpp:112
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:467
static bool GetConfigOptions(std::istream &stream, const std::string &filepath, std::string &error, std::vector< std::pair< std::string, std::string >> &options, std::list< SectionInfo > &sections)
Definition: system.cpp:771
static void SaveErrors(const std::vector< std::string > errors, std::vector< std::string > *error_out)
Definition: system.cpp:406
ArgsManager gArgs
Definition: system.cpp:77
void LogArgs() const
Log the config file options and the command line arguments, useful for troubleshooting.
Definition: system.cpp:996
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
Definition: system.cpp:607
static fs::path pathCachedNetSpecific
Definition: system.cpp:691
static const std::string TESTNET
std::streampos GetFileSize(const char *path, std::streamsize max)
Get the size of a file by scanning it.
Definition: system.cpp:145
UniValue RunCommandParseJSON(const std::string &str_command, const std::string &str_std_in)
Execute a command which returns JSON, and parse the result.
Definition: system.cpp:1201
std::string GetChainName() const
Returns the appropriate chain name from the program arguments.
Definition: system.cpp:932
const std::list< SectionInfo > GetUnrecognizedSections() const
Log warnings for unrecognized section names in the config file.
Definition: system.cpp:262
static fs::path pathCached
Definition: system.cpp:690
OptionsCategory
Definition: system.h:143
void ScheduleBatchPriority()
On platforms that support it, tell the kernel the calling thread is CPU-intensive and non-interactive...
Definition: system.cpp:1317
const int64_t nStartupTime
Definition: system.cpp:72
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
Definition: system.cpp:362
std::string HelpMessageOpt(const std::string &option, const std::string &message)
Format a string to be used as option description in help messages.
Definition: system.cpp:621
int64_t GetTime()
Return system time (or mocked time, if set)
Definition: time.cpp:23
std::string HelpMessageGroup(const std::string &message)
Format a string to be used as group of options in help messages.
Definition: system.cpp:617
std::vector< util::SettingsValue > GetSettingsList(const std::string &arg) const
Get list of setting values.
Definition: system.cpp:973
static std::string FormatException(const std::exception *pex, const char *pszThread)
Definition: system.cpp:628
static RPCHelpMan help()
Definition: server.cpp:133
const std::set< std::string > GetUnsuitableSectionOnlyArgs() const
Log warnings for options in m_section_only_args when they are specified in the default section but no...
Definition: system.cpp:242
bool error(const char *fmt, const Args &... args)
Definition: system.h:52
static const std::string SIGNET
static bool CheckValid(const std::string &key, const util::SettingsValue &val, unsigned int flags, std::string &error)
Check settings value validity according to flags.
Definition: system.cpp:227
std::optional< T > Optional
Substitute for C++17 std::optional DEPRECATED use std::optional in new code.
Definition: optional.h:14
bool UseDefaultSection(const std::string &arg) const EXCLUSIVE_LOCKS_REQUIRED(cs_args)
Returns true if settings values from the default section should be used, depending on the current net...
Definition: system.cpp:961
bool ReadSettings(const fs::path &path, std::map< std::string, SettingsValue > &values, std::vector< std::string > &errors)
Read settings file.
Definition: settings.cpp:58