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