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