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