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