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