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