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