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", MakeUnorderedList(errors));
506  return false;
507  }
508  if (!WriteSettingsFile(&errors)) {
509  error = strprintf("Failed saving settings file:\n%s\n", MakeUnorderedList(errors));
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  // not ok to have a config file specified that cannot be opened
908  if (IsArgSet("-conf") && !stream.good()) {
909  error = strprintf("specified config file \"%s\" could not be opened.", confPath);
910  return false;
911  }
912  // ok to not have a config file
913  if (stream.good()) {
914  if (!ReadConfigStream(stream, confPath, error, ignore_invalid_keys)) {
915  return false;
916  }
917  // `-includeconf` cannot be included in the command line arguments except
918  // as `-noincludeconf` (which indicates that no included conf file should be used).
919  bool use_conf_file{true};
920  {
921  LOCK(cs_args);
922  if (auto* includes = util::FindKey(m_settings.command_line_options, "includeconf")) {
923  // ParseParameters() fails if a non-negated -includeconf is passed on the command-line
924  assert(util::SettingsSpan(*includes).last_negated());
925  use_conf_file = false;
926  }
927  }
928  if (use_conf_file) {
929  std::string chain_id = GetChainName();
930  std::vector<std::string> conf_file_names;
931 
932  auto add_includes = [&](const std::string& network, size_t skip = 0) {
933  size_t num_values = 0;
934  LOCK(cs_args);
935  if (auto* section = util::FindKey(m_settings.ro_config, network)) {
936  if (auto* values = util::FindKey(*section, "includeconf")) {
937  for (size_t i = std::max(skip, util::SettingsSpan(*values).negated()); i < values->size(); ++i) {
938  conf_file_names.push_back((*values)[i].get_str());
939  }
940  num_values = values->size();
941  }
942  }
943  return num_values;
944  };
945 
946  // We haven't set m_network yet (that happens in SelectParams()), so manually check
947  // for network.includeconf args.
948  const size_t chain_includes = add_includes(chain_id);
949  const size_t default_includes = add_includes({});
950 
951  for (const std::string& conf_file_name : conf_file_names) {
952  fsbridge::ifstream conf_file_stream(GetConfigFile(conf_file_name));
953  if (conf_file_stream.good()) {
954  if (!ReadConfigStream(conf_file_stream, conf_file_name, error, ignore_invalid_keys)) {
955  return false;
956  }
957  LogPrintf("Included configuration file %s\n", conf_file_name);
958  } else {
959  error = "Failed to include configuration file " + conf_file_name;
960  return false;
961  }
962  }
963 
964  // Warn about recursive -includeconf
965  conf_file_names.clear();
966  add_includes(chain_id, /* skip= */ chain_includes);
967  add_includes({}, /* skip= */ default_includes);
968  std::string chain_id_final = GetChainName();
969  if (chain_id_final != chain_id) {
970  // Also warn about recursive includeconf for the chain that was specified in one of the includeconfs
971  add_includes(chain_id_final);
972  }
973  for (const std::string& conf_file_name : conf_file_names) {
974  tfm::format(std::cerr, "warning: -includeconf cannot be used from included files; ignoring -includeconf=%s\n", conf_file_name);
975  }
976  }
977  }
978 
979  // If datadir is changed in .conf file:
981  if (!CheckDataDirOption()) {
982  error = strprintf("specified data directory \"%s\" does not exist.", GetArg("-datadir", ""));
983  return false;
984  }
985  return true;
986 }
987 
988 std::string ArgsManager::GetChainName() const
989 {
990  auto get_net = [&](const std::string& arg) {
991  LOCK(cs_args);
992  util::SettingsValue value = util::GetSetting(m_settings, /* section= */ "", SettingName(arg),
993  /* ignore_default_section_config= */ false,
994  /* get_chain_name= */ true);
995  return value.isNull() ? false : value.isBool() ? value.get_bool() : InterpretBool(value.get_str());
996  };
997 
998  const bool fRegTest = get_net("-regtest");
999  const bool fSigNet = get_net("-signet");
1000  const bool fTestNet = get_net("-testnet");
1001  const bool is_chain_arg_set = IsArgSet("-chain");
1002 
1003  if ((int)is_chain_arg_set + (int)fRegTest + (int)fSigNet + (int)fTestNet > 1) {
1004  throw std::runtime_error("Invalid combination of -regtest, -signet, -testnet and -chain. Can use at most one.");
1005  }
1006  if (fRegTest)
1008  if (fSigNet) {
1009  return CBaseChainParams::SIGNET;
1010  }
1011  if (fTestNet)
1013 
1014  return GetArg("-chain", CBaseChainParams::MAIN);
1015 }
1016 
1017 bool ArgsManager::UseDefaultSection(const std::string& arg) const
1018 {
1019  return m_network == CBaseChainParams::MAIN || m_network_only_args.count(arg) == 0;
1020 }
1021 
1022 util::SettingsValue ArgsManager::GetSetting(const std::string& arg) const
1023 {
1024  LOCK(cs_args);
1025  return util::GetSetting(
1026  m_settings, m_network, SettingName(arg), !UseDefaultSection(arg), /* get_chain_name= */ false);
1027 }
1028 
1029 std::vector<util::SettingsValue> ArgsManager::GetSettingsList(const std::string& arg) const
1030 {
1031  LOCK(cs_args);
1032  return util::GetSettingsList(m_settings, m_network, SettingName(arg), !UseDefaultSection(arg));
1033 }
1034 
1036  const std::string& prefix,
1037  const std::string& section,
1038  const std::map<std::string, std::vector<util::SettingsValue>>& args) const
1039 {
1040  std::string section_str = section.empty() ? "" : "[" + section + "] ";
1041  for (const auto& arg : args) {
1042  for (const auto& value : arg.second) {
1043  std::optional<unsigned int> flags = GetArgFlags('-' + arg.first);
1044  if (flags) {
1045  std::string value_str = (*flags & SENSITIVE) ? "****" : value.write();
1046  LogPrintf("%s %s%s=%s\n", prefix, section_str, arg.first, value_str);
1047  }
1048  }
1049  }
1050 }
1051 
1053 {
1054  LOCK(cs_args);
1055  for (const auto& section : m_settings.ro_config) {
1056  logArgsPrefix("Config file arg:", section.first, section.second);
1057  }
1058  for (const auto& setting : m_settings.rw_settings) {
1059  LogPrintf("Setting file arg: %s = %s\n", setting.first, setting.second.write());
1060  }
1061  logArgsPrefix("Command-line arg:", "", m_settings.command_line_options);
1062 }
1063 
1064 bool RenameOver(fs::path src, fs::path dest)
1065 {
1066 #ifdef WIN32
1067  return MoveFileExW(src.wstring().c_str(), dest.wstring().c_str(),
1068  MOVEFILE_REPLACE_EXISTING) != 0;
1069 #else
1070  int rc = std::rename(src.string().c_str(), dest.string().c_str());
1071  return (rc == 0);
1072 #endif /* WIN32 */
1073 }
1074 
1080 bool TryCreateDirectories(const fs::path& p)
1081 {
1082  try
1083  {
1084  return fs::create_directories(p);
1085  } catch (const fs::filesystem_error&) {
1086  if (!fs::exists(p) || !fs::is_directory(p))
1087  throw;
1088  }
1089 
1090  // create_directories didn't create the directory, it had to have existed already
1091  return false;
1092 }
1093 
1094 bool FileCommit(FILE *file)
1095 {
1096  if (fflush(file) != 0) { // harmless if redundantly called
1097  LogPrintf("%s: fflush failed: %d\n", __func__, errno);
1098  return false;
1099  }
1100 #ifdef WIN32
1101  HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
1102  if (FlushFileBuffers(hFile) == 0) {
1103  LogPrintf("%s: FlushFileBuffers failed: %d\n", __func__, GetLastError());
1104  return false;
1105  }
1106 #elif defined(MAC_OSX) && defined(F_FULLFSYNC)
1107  if (fcntl(fileno(file), F_FULLFSYNC, 0) == -1) { // Manpage says "value other than -1" is returned on success
1108  LogPrintf("%s: fcntl F_FULLFSYNC failed: %d\n", __func__, errno);
1109  return false;
1110  }
1111 #elif HAVE_FDATASYNC
1112  if (fdatasync(fileno(file)) != 0 && errno != EINVAL) { // Ignore EINVAL for filesystems that don't support sync
1113  LogPrintf("%s: fdatasync failed: %d\n", __func__, errno);
1114  return false;
1115  }
1116 #else
1117  if (fsync(fileno(file)) != 0 && errno != EINVAL) {
1118  LogPrintf("%s: fsync failed: %d\n", __func__, errno);
1119  return false;
1120  }
1121 #endif
1122  return true;
1123 }
1124 
1125 void DirectoryCommit(const fs::path &dirname)
1126 {
1127 #ifndef WIN32
1128  FILE* file = fsbridge::fopen(dirname, "r");
1129  if (file) {
1130  fsync(fileno(file));
1131  fclose(file);
1132  }
1133 #endif
1134 }
1135 
1136 bool TruncateFile(FILE *file, unsigned int length) {
1137 #if defined(WIN32)
1138  return _chsize(_fileno(file), length) == 0;
1139 #else
1140  return ftruncate(fileno(file), length) == 0;
1141 #endif
1142 }
1143 
1148 int RaiseFileDescriptorLimit(int nMinFD) {
1149 #if defined(WIN32)
1150  return 2048;
1151 #else
1152  struct rlimit limitFD;
1153  if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) {
1154  if (limitFD.rlim_cur < (rlim_t)nMinFD) {
1155  limitFD.rlim_cur = nMinFD;
1156  if (limitFD.rlim_cur > limitFD.rlim_max)
1157  limitFD.rlim_cur = limitFD.rlim_max;
1158  setrlimit(RLIMIT_NOFILE, &limitFD);
1159  getrlimit(RLIMIT_NOFILE, &limitFD);
1160  }
1161  return limitFD.rlim_cur;
1162  }
1163  return nMinFD; // getrlimit failed, assume it's fine
1164 #endif
1165 }
1166 
1171 void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length) {
1172 #if defined(WIN32)
1173  // Windows-specific version
1174  HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
1175  LARGE_INTEGER nFileSize;
1176  int64_t nEndPos = (int64_t)offset + length;
1177  nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF;
1178  nFileSize.u.HighPart = nEndPos >> 32;
1179  SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN);
1180  SetEndOfFile(hFile);
1181 #elif defined(MAC_OSX)
1182  // OSX specific version
1183  // NOTE: Contrary to other OS versions, the OSX version assumes that
1184  // NOTE: offset is the size of the file.
1185  fstore_t fst;
1186  fst.fst_flags = F_ALLOCATECONTIG;
1187  fst.fst_posmode = F_PEOFPOSMODE;
1188  fst.fst_offset = 0;
1189  fst.fst_length = length; // mac os fst_length takes the # of free bytes to allocate, not desired file size
1190  fst.fst_bytesalloc = 0;
1191  if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) {
1192  fst.fst_flags = F_ALLOCATEALL;
1193  fcntl(fileno(file), F_PREALLOCATE, &fst);
1194  }
1195  ftruncate(fileno(file), static_cast<off_t>(offset) + length);
1196 #else
1197  #if defined(HAVE_POSIX_FALLOCATE)
1198  // Version using posix_fallocate
1199  off_t nEndPos = (off_t)offset + length;
1200  if (0 == posix_fallocate(fileno(file), 0, nEndPos)) return;
1201  #endif
1202  // Fallback version
1203  // TODO: just write one byte per block
1204  static const char buf[65536] = {};
1205  if (fseek(file, offset, SEEK_SET)) {
1206  return;
1207  }
1208  while (length > 0) {
1209  unsigned int now = 65536;
1210  if (length < now)
1211  now = length;
1212  fwrite(buf, 1, now, file); // allowed to fail; this function is advisory anyway
1213  length -= now;
1214  }
1215 #endif
1216 }
1217 
1218 #ifdef WIN32
1219 fs::path GetSpecialFolderPath(int nFolder, bool fCreate)
1220 {
1221  WCHAR pszPath[MAX_PATH] = L"";
1222 
1223  if(SHGetSpecialFolderPathW(nullptr, pszPath, nFolder, fCreate))
1224  {
1225  return fs::path(pszPath);
1226  }
1227 
1228  LogPrintf("SHGetSpecialFolderPathW() failed, could not obtain requested path.\n");
1229  return fs::path("");
1230 }
1231 #endif
1232 
1233 #ifndef WIN32
1234 std::string ShellEscape(const std::string& arg)
1235 {
1236  std::string escaped = arg;
1237  boost::replace_all(escaped, "'", "'\"'\"'");
1238  return "'" + escaped + "'";
1239 }
1240 #endif
1241 
1242 #if HAVE_SYSTEM
1243 void runCommand(const std::string& strCommand)
1244 {
1245  if (strCommand.empty()) return;
1246 #ifndef WIN32
1247  int nErr = ::system(strCommand.c_str());
1248 #else
1249  int nErr = ::_wsystem(std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>,wchar_t>().from_bytes(strCommand).c_str());
1250 #endif
1251  if (nErr)
1252  LogPrintf("runCommand error: system(%s) returned %d\n", strCommand, nErr);
1253 }
1254 #endif
1255 
1256 UniValue RunCommandParseJSON(const std::string& str_command, const std::string& str_std_in)
1257 {
1258 #ifdef ENABLE_EXTERNAL_SIGNER
1259  namespace bp = boost::process;
1260 
1261  UniValue result_json;
1262  bp::opstream stdin_stream;
1263  bp::ipstream stdout_stream;
1264  bp::ipstream stderr_stream;
1265 
1266  if (str_command.empty()) return UniValue::VNULL;
1267 
1268  bp::child c(
1269  str_command,
1270  bp::std_out > stdout_stream,
1271  bp::std_err > stderr_stream,
1272  bp::std_in < stdin_stream
1273  );
1274  if (!str_std_in.empty()) {
1275  stdin_stream << str_std_in << std::endl;
1276  }
1277  stdin_stream.pipe().close();
1278 
1279  std::string result;
1280  std::string error;
1281  std::getline(stdout_stream, result);
1282  std::getline(stderr_stream, error);
1283 
1284  c.wait();
1285  const int n_error = c.exit_code();
1286  if (n_error) throw std::runtime_error(strprintf("RunCommandParseJSON error: process(%s) returned %d: %s\n", str_command, n_error, error));
1287  if (!result_json.read(result)) throw std::runtime_error("Unable to parse JSON: " + result);
1288 
1289  return result_json;
1290 #else
1291  throw std::runtime_error("Compiled without external signing support (required for external signing).");
1292 #endif // ENABLE_EXTERNAL_SIGNER
1293 }
1294 
1296 {
1297 #ifdef HAVE_MALLOPT_ARENA_MAX
1298  // glibc-specific: On 32-bit systems set the number of arenas to 1.
1299  // By default, since glibc 2.10, the C library will create up to two heap
1300  // arenas per core. This is known to cause excessive virtual address space
1301  // usage in our usage. Work around it by setting the maximum number of
1302  // arenas to 1.
1303  if (sizeof(void*) == 4) {
1304  mallopt(M_ARENA_MAX, 1);
1305  }
1306 #endif
1307  // On most POSIX systems (e.g. Linux, but not BSD) the environment's locale
1308  // may be invalid, in which case the "C.UTF-8" locale is used as fallback.
1309 #if !defined(WIN32) && !defined(MAC_OSX) && !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
1310  try {
1311  std::locale(""); // Raises a runtime error if current locale is invalid
1312  } catch (const std::runtime_error&) {
1313  setenv("LC_ALL", "C.UTF-8", 1);
1314  }
1315 #elif defined(WIN32)
1316  // Set the default input/output charset is utf-8
1317  SetConsoleCP(CP_UTF8);
1318  SetConsoleOutputCP(CP_UTF8);
1319 #endif
1320  // The path locale is lazy initialized and to avoid deinitialization errors
1321  // in multithreading environments, it is set explicitly by the main thread.
1322  // A dummy locale is used to extract the internal default locale, used by
1323  // fs::path, which is then used to explicitly imbue the path.
1324  std::locale loc = fs::path::imbue(std::locale::classic());
1325 #ifndef WIN32
1326  fs::path::imbue(loc);
1327 #else
1328  fs::path::imbue(std::locale(loc, new std::codecvt_utf8_utf16<wchar_t>()));
1329 #endif
1330 }
1331 
1333 {
1334 #ifdef WIN32
1335  // Initialize Windows Sockets
1336  WSADATA wsadata;
1337  int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
1338  if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2)
1339  return false;
1340 #endif
1341  return true;
1342 }
1343 
1345 {
1346  return std::thread::hardware_concurrency();
1347 }
1348 
1349 std::string CopyrightHolders(const std::string& strPrefix)
1350 {
1351  const auto copyright_devs = strprintf(_(COPYRIGHT_HOLDERS).translated, COPYRIGHT_HOLDERS_SUBSTITUTION);
1352  std::string strCopyrightHolders = strPrefix + copyright_devs;
1353 
1354  // Make sure Bitcoin Core copyright is not removed by accident
1355  if (copyright_devs.find("Bitcoin Core") == std::string::npos) {
1356  strCopyrightHolders += "\n" + strPrefix + "The Bitcoin Core developers";
1357  }
1358  return strCopyrightHolders;
1359 }
1360 
1361 // Obtain the application startup time (used for uptime calculation)
1363 {
1364  return nStartupTime;
1365 }
1366 
1367 fs::path AbsPathForConfigVal(const fs::path& path, bool net_specific)
1368 {
1369  if (path.is_absolute()) {
1370  return path;
1371  }
1372  return fsbridge::AbsPathJoin(net_specific ? gArgs.GetDataDirNet() : gArgs.GetDataDirBase(), path);
1373 }
1374 
1376 {
1377 #ifdef SCHED_BATCH
1378  const static sched_param param{};
1379  const int rc = pthread_setschedparam(pthread_self(), SCHED_BATCH, &param);
1380  if (rc != 0) {
1381  LogPrintf("Failed to pthread_setschedparam: %s\n", strerror(rc));
1382  }
1383 #endif
1384 }
1385 
1386 namespace util {
1387 #ifdef WIN32
1388 WinCmdLineArgs::WinCmdLineArgs()
1389 {
1390  wchar_t** wargv = CommandLineToArgvW(GetCommandLineW(), &argc);
1391  std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t> utf8_cvt;
1392  argv = new char*[argc];
1393  args.resize(argc);
1394  for (int i = 0; i < argc; i++) {
1395  args[i] = utf8_cvt.to_bytes(wargv[i]);
1396  argv[i] = &*args[i].begin();
1397  }
1398  LocalFree(wargv);
1399 }
1400 
1401 WinCmdLineArgs::~WinCmdLineArgs()
1402 {
1403  delete[] argv;
1404 }
1405 
1406 std::pair<int, char**> WinCmdLineArgs::get()
1407 {
1408  return std::make_pair(argc, argv);
1409 }
1410 #endif
1411 } // namespace util
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:101
ArgsManager::LogArgs
void LogArgs() const
Log the config file options and the command line arguments, useful for troubleshooting.
Definition: system.cpp:1052
atoi64
int64_t atoi64(const std::string &str)
Definition: strencodings.cpp:440
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:1367
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
UniValue::isBool
bool isBool() const
Definition: univalue.h:80
ScheduleBatchPriority
void ScheduleBatchPriority()
On platforms that support it, tell the kernel the calling thread is CPU-intensive and non-interactive...
Definition: system.cpp:1375
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
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:238
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:63
fsbridge::ifstream
fs::ifstream ifstream
Definition: fs.h:101
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
ReleaseDirectoryLocks
void ReleaseDirectoryLocks()
Release all directory locks.
Definition: system.cpp:125
assert
assert(!tx.IsCoinBase())
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
DirIsWritable
bool DirIsWritable(const fs::path &directory)
Definition: system.cpp:131
BITCOIN_SETTINGS_FILENAME
const char *const BITCOIN_SETTINGS_FILENAME
Definition: system.cpp:82
GetDefaultDataDir
fs::path GetDefaultDataDir()
Definition: system.cpp:786
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
OptionsCategory::RPC
@ RPC
fsbridge::fopen
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:24
help
void help(char **argv)
Definition: bench_ecmult.c:21
flags
int flags
Definition: bitcoin-tx.cpp:513
ArgsManager::GetSetting
util::SettingsValue GetSetting(const std::string &arg) const
Get setting value.
Definition: system.cpp:1022
ArgsManager::GetDataDirNet
const fs::path & GetDataDirNet() const
Get data directory path with appended network identifier.
Definition: system.h:282
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:1017
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:1171
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
ArgsManager::GetBlocksDirPath
const fs::path & GetBlocksDirPath() const
Get blocks directory path.
Definition: system.cpp:397
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:1256
sync.h
util::SettingsSpan::last_negated
bool last_negated() const
True if the last value is negated.
Definition: settings.cpp:237
ArgsManager::GetHelpMessage
std::string GetHelpMessage() const
Get the help string.
Definition: system.cpp:668
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
string.h
atoi
int atoi(const std::string &str)
Definition: strencodings.cpp:449
chainparamsbase.h
ArgsManager::ALLOW_ANY
@ ALLOW_ANY
Definition: system.h:166
FileCommit
bool FileCommit(FILE *file)
Ensure file contents are fully committed to disk, using a platform-specific feature analogous to fsyn...
Definition: system.cpp:1094
ArgsManager::GetChainName
std::string GetChainName() const
Returns the appropriate chain name from the program arguments.
Definition: system.cpp:988
ArgsManager::IsArgSet
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: system.cpp:492
cs_dir_locks
static Mutex cs_dir_locks
Mutex to protect dir_locks.
Definition: system.cpp:87
CBaseChainParams::TESTNET
static const std::string TESTNET
Definition: chainparamsbase.h:23
SetupEnvironment
void SetupEnvironment()
Definition: system.cpp:1295
CopyrightHolders
std::string CopyrightHolders(const std::string &strPrefix)
Definition: system.cpp:1349
GetTime
int64_t GetTime()
DEPRECATED Use either GetTimeSeconds (not mockable) or GetTime<T> (mockable)
Definition: time.cpp:26
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 >
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
GetStartupTime
int64_t GetStartupTime()
Definition: system.cpp:1362
ArgsManager::InitSettings
bool InitSettings(std::string &error)
Read and update settings file with saved settings.
Definition: system.cpp:497
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
HelpRequested
bool HelpRequested(const ArgsManager &args)
Definition: system.cpp:737
COPYRIGHT_HOLDERS_SUBSTITUTION
#define COPYRIGHT_HOLDERS_SUBSTITUTION
Definition: bitcoin-config.h:33
UniValue::isNum
bool isNum() const
Definition: univalue.h:82
SetupHelpOptions
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
Definition: system.cpp:742
Assert
#define Assert(val)
Identity function.
Definition: check.h:57
ArgsManager::DEBUG_ONLY
@ DEBUG_ONLY
Definition: system.h:167
BITCOIN_CONF_FILENAME
const char *const BITCOIN_CONF_FILENAME
Definition: system.cpp:81
LockDirectory
bool LockDirectory(const fs::path &directory, const std::string lockfile_name, bool probe_only)
Definition: system.cpp:95
UniValue
Definition: univalue.h:19
ArgsManager::~ArgsManager
~ArgsManager()
Definition: system.cpp:260
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
MakeUnorderedList
std::string MakeUnorderedList(const std::vector< std::string > &items)
Create an unordered multi-line list of items.
Definition: string.h:70
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
strencodings.h
RenameOver
bool RenameOver(fs::path src, fs::path dest)
Definition: system.cpp:1064
ArgsManager::cs_args
RecursiveMutex cs_args
Definition: system.h:187
UnlockDirectory
void UnlockDirectory(const fs::path &directory, const std::string &lockfile_name)
Definition: system.cpp:119
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
OptionsCategory::NODE_RELAY
@ NODE_RELAY
values
static const int64_t values[]
A selection of numbers that do not trigger int64_t overflow when added/subtracted.
Definition: scriptnum_tests.cpp:17
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
CheckDiskSpace
bool CheckDiskSpace(const fs::path &dir, uint64_t additional_bytes)
Definition: system.cpp:144
COPYRIGHT_HOLDERS
#define COPYRIGHT_HOLDERS
Definition: bitcoin-config.h:27
screenWidth
static const int screenWidth
Definition: system.cpp:748
InterpretBool
static bool InterpretBool(const std::string &strValue)
Interpret a string argument as a boolean.
Definition: system.cpp:175
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
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.
CBaseChainParams::REGTEST
static const std::string REGTEST
Definition: chainparamsbase.h:25
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
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:185
OptionsCategory::OPTIONS
@ OPTIONS
GetFileSize
std::streampos GetFileSize(const char *path, std::streamsize max)
Get the size of a file by scanning it.
Definition: system.cpp:152
ArgsManager::Command::command
std::string command
The command (if one has been registered with AddCommand), or empty.
Definition: system.h:249
optIndent
static const int optIndent
Definition: system.cpp:749
ArgsManager::ArgsManager
ArgsManager()
Definition: system.cpp:259
SaveErrors
static void SaveErrors(const std::vector< std::string > errors, std::vector< std::string > *error_out)
Definition: system.cpp:527
ArgsManager::ParseParameters
bool ParseParameters(int argc, const char *const argv[], std::string &error)
Definition: system.cpp:304
GetNumCores
int GetNumCores()
Return the number of cores available on the current system.
Definition: system.cpp:1344
ArgsManager::ReadConfigFiles
bool ReadConfigFiles(std::string &error, bool ignore_invalid_keys=false)
Definition: system.cpp:896
gArgs
ArgsManager gArgs
Definition: system.cpp:84
RaiseFileDescriptorLimit
int RaiseFileDescriptorLimit(int nMinFD)
this function tries to raise the file descriptor limit to the requested number.
Definition: system.cpp:1148
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
CheckDataDirOption
bool CheckDataDirOption()
Definition: system.cpp:811
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:1029
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
ArgsManager::COMMAND
@ COMMAND
Definition: system.h:176
GetConfigFile
fs::path GetConfigFile(const std::string &confPath)
Definition: system.cpp:817
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:226
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:218
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:1035
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:120
msgIndent
static const int msgIndent
Definition: system.cpp:750
ArgsManager::GetUnrecognizedSections
const std::list< SectionInfo > GetUnrecognizedSections() const
Log warnings for unrecognized section names in the config file.
Definition: system.cpp:282
FormatException
static std::string FormatException(const std::exception *pex, const char *pszThread)
Definition: system.cpp:763
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
SetupNetworking
bool SetupNetworking()
Definition: system.cpp:1332
getuniquepath.h
m_command
CRPCCommand m_command
Definition: interfaces.cpp:425
nStartupTime
const int64_t nStartupTime
Definition: system.cpp:79
OptionsCategory::COMMANDS
@ COMMANDS
ArgsManager::ALLOW_BOOL
@ ALLOW_BOOL
Definition: system.h:163
PrintExceptionContinue
void PrintExceptionContinue(const std::exception *pex, const char *pszThread)
Definition: system.cpp:779
SettingName
static std::string SettingName(const std::string &arg)
Definition: system.cpp:182
OptionsCategory::REGISTER_COMMANDS
@ REGISTER_COMMANDS
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:173
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
TruncateFile
bool TruncateFile(FILE *file, unsigned int length)
Definition: system.cpp:1136
MAX_PATH
#define MAX_PATH
Definition: compat.h:71
util
Definition: settings.cpp:10
DirectoryCommit
void DirectoryCommit(const fs::path &dirname)
Sync directory contents.
Definition: system.cpp:1125
GetUniquePath
fs::path GetUniquePath(const fs::path &base)
Helper function for getting a unique path.
Definition: getuniquepath.cpp:9
ShellEscape
std::string ShellEscape(const std::string &arg)
Definition: system.cpp:1234
ArgsManager::AddCommand
void AddCommand(const std::string &cmd, const std::string &help)
Add subcommand.
Definition: system.cpp:628
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
TryCreateDirectories
bool TryCreateDirectories(const fs::path &p)
Ignores exceptions thrown by Boost's create_directories if the requested directory exists.
Definition: system.cpp:1080