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