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