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