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