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