Bitcoin Core  28.1.0
P2P Digital Currency
args.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2022 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 <common/args.h>
7 
8 #include <chainparamsbase.h>
9 #include <common/settings.h>
10 #include <logging.h>
11 #include <sync.h>
12 #include <tinyformat.h>
13 #include <univalue.h>
14 #include <util/chaintype.h>
15 #include <util/check.h>
16 #include <util/fs.h>
17 #include <util/fs_helpers.h>
18 #include <util/strencodings.h>
19 
20 #ifdef WIN32
21 #include <codecvt> /* for codecvt_utf8_utf16 */
22 #include <shellapi.h> /* for CommandLineToArgvW */
23 #include <shlobj.h> /* for CSIDL_APPDATA */
24 #endif
25 
26 #include <algorithm>
27 #include <cassert>
28 #include <cstdint>
29 #include <cstdlib>
30 #include <cstring>
31 #include <map>
32 #include <optional>
33 #include <stdexcept>
34 #include <string>
35 #include <utility>
36 #include <variant>
37 
38 const char * const BITCOIN_CONF_FILENAME = "bitcoin.conf";
39 const char * const BITCOIN_SETTINGS_FILENAME = "settings.json";
40 
42 
58 static bool InterpretBool(const std::string& strValue)
59 {
60  if (strValue.empty())
61  return true;
62  return (LocaleIndependentAtoi<int>(strValue) != 0);
63 }
64 
65 static std::string SettingName(const std::string& arg)
66 {
67  return arg.size() > 0 && arg[0] == '-' ? arg.substr(1) : arg;
68 }
69 
78 KeyInfo InterpretKey(std::string key)
79 {
80  KeyInfo result;
81  // Split section name from key name for keys like "testnet.foo" or "regtest.bar"
82  size_t option_index = key.find('.');
83  if (option_index != std::string::npos) {
84  result.section = key.substr(0, option_index);
85  key.erase(0, option_index + 1);
86  }
87  if (key.substr(0, 2) == "no") {
88  key.erase(0, 2);
89  result.negated = true;
90  }
91  result.name = key;
92  return result;
93 }
94 
106 std::optional<common::SettingsValue> InterpretValue(const KeyInfo& key, const std::string* value,
107  unsigned int flags, std::string& error)
108 {
109  // Return negated settings as false values.
110  if (key.negated) {
112  error = strprintf("Negating of -%s is meaningless and therefore forbidden", key.name);
113  return std::nullopt;
114  }
115  // Double negatives like -nofoo=0 are supported (but discouraged)
116  if (value && !InterpretBool(*value)) {
117  LogPrintf("Warning: parsed potentially confusing double-negative -%s=%s\n", key.name, *value);
118  return true;
119  }
120  return false;
121  }
122  if (!value && (flags & ArgsManager::DISALLOW_ELISION)) {
123  error = strprintf("Can not set -%s with no value. Please specify value with -%s=value.", key.name, key.name);
124  return std::nullopt;
125  }
126  return value ? *value : "";
127 }
128 
129 // Define default constructor and destructor that are not inline, so code instantiating this class doesn't need to
130 // #include class definitions for all members.
131 // For example, m_settings has an internal dependency on univalue.
132 ArgsManager::ArgsManager() = default;
133 ArgsManager::~ArgsManager() = default;
134 
135 std::set<std::string> ArgsManager::GetUnsuitableSectionOnlyArgs() const
136 {
137  std::set<std::string> unsuitables;
138 
139  LOCK(cs_args);
140 
141  // if there's no section selected, don't worry
142  if (m_network.empty()) return std::set<std::string> {};
143 
144  // if it's okay to use the default section for this network, don't worry
145  if (m_network == ChainTypeToString(ChainType::MAIN)) return std::set<std::string> {};
146 
147  for (const auto& arg : m_network_only_args) {
148  if (OnlyHasDefaultSectionSetting(m_settings, m_network, SettingName(arg))) {
149  unsuitables.insert(arg);
150  }
151  }
152  return unsuitables;
153 }
154 
155 std::list<SectionInfo> ArgsManager::GetUnrecognizedSections() const
156 {
157  // Section names to be recognized in the config file.
158  static const std::set<std::string> available_sections{
164  };
165 
166  LOCK(cs_args);
167  std::list<SectionInfo> unrecognized = m_config_sections;
168  unrecognized.remove_if([](const SectionInfo& appeared){ return available_sections.find(appeared.m_name) != available_sections.end(); });
169  return unrecognized;
170 }
171 
172 void ArgsManager::SelectConfigNetwork(const std::string& network)
173 {
174  LOCK(cs_args);
175  m_network = network;
176 }
177 
178 bool ArgsManager::ParseParameters(int argc, const char* const argv[], std::string& error)
179 {
180  LOCK(cs_args);
181  m_settings.command_line_options.clear();
182 
183  for (int i = 1; i < argc; i++) {
184  std::string key(argv[i]);
185 
186 #ifdef MAC_OSX
187  // At the first time when a user gets the "App downloaded from the
188  // internet" warning, and clicks the Open button, macOS passes
189  // a unique process serial number (PSN) as -psn_... command-line
190  // argument, which we filter out.
191  if (key.substr(0, 5) == "-psn_") continue;
192 #endif
193 
194  if (key == "-") break; //bitcoin-tx using stdin
195  std::optional<std::string> val;
196  size_t is_index = key.find('=');
197  if (is_index != std::string::npos) {
198  val = key.substr(is_index + 1);
199  key.erase(is_index);
200  }
201 #ifdef WIN32
202  key = ToLower(key);
203  if (key[0] == '/')
204  key[0] = '-';
205 #endif
206 
207  if (key[0] != '-') {
208  if (!m_accept_any_command && m_command.empty()) {
209  // The first non-dash arg is a registered command
210  std::optional<unsigned int> flags = GetArgFlags(key);
211  if (!flags || !(*flags & ArgsManager::COMMAND)) {
212  error = strprintf("Invalid command '%s'", argv[i]);
213  return false;
214  }
215  }
216  m_command.push_back(key);
217  while (++i < argc) {
218  // The remaining args are command args
219  m_command.emplace_back(argv[i]);
220  }
221  break;
222  }
223 
224  // Transform --foo to -foo
225  if (key.length() > 1 && key[1] == '-')
226  key.erase(0, 1);
227 
228  // Transform -foo to foo
229  key.erase(0, 1);
230  KeyInfo keyinfo = InterpretKey(key);
231  std::optional<unsigned int> flags = GetArgFlags('-' + keyinfo.name);
232 
233  // Unknown command line options and command line options with dot
234  // characters (which are returned from InterpretKey with nonempty
235  // section strings) are not valid.
236  if (!flags || !keyinfo.section.empty()) {
237  error = strprintf("Invalid parameter %s", argv[i]);
238  return false;
239  }
240 
241  std::optional<common::SettingsValue> value = InterpretValue(keyinfo, val ? &*val : nullptr, *flags, error);
242  if (!value) return false;
243 
244  m_settings.command_line_options[keyinfo.name].push_back(*value);
245  }
246 
247  // we do not allow -includeconf from command line, only -noincludeconf
248  if (auto* includes = common::FindKey(m_settings.command_line_options, "includeconf")) {
249  const common::SettingsSpan values{*includes};
250  // Range may be empty if -noincludeconf was passed
251  if (!values.empty()) {
252  error = "-includeconf cannot be used from commandline; -includeconf=" + values.begin()->write();
253  return false; // pick first value as example
254  }
255  }
256  return true;
257 }
258 
259 std::optional<unsigned int> ArgsManager::GetArgFlags(const std::string& name) const
260 {
261  LOCK(cs_args);
262  for (const auto& arg_map : m_available_args) {
263  const auto search = arg_map.second.find(name);
264  if (search != arg_map.second.end()) {
265  return search->second.m_flags;
266  }
267  }
268  return std::nullopt;
269 }
270 
271 fs::path ArgsManager::GetPathArg(std::string arg, const fs::path& default_value) const
272 {
273  if (IsArgNegated(arg)) return fs::path{};
274  std::string path_str = GetArg(arg, "");
275  if (path_str.empty()) return default_value;
276  fs::path result = fs::PathFromString(path_str).lexically_normal();
277  // Remove trailing slash, if present.
278  return result.has_filename() ? result : result.parent_path();
279 }
280 
282 {
283  LOCK(cs_args);
284  fs::path& path = m_cached_blocks_path;
285 
286  // Cache the path to avoid calling fs::create_directories on every call of
287  // this function
288  if (!path.empty()) return path;
289 
290  if (IsArgSet("-blocksdir")) {
291  path = fs::absolute(GetPathArg("-blocksdir"));
292  if (!fs::is_directory(path)) {
293  path = "";
294  return path;
295  }
296  } else {
297  path = GetDataDirBase();
298  }
299 
300  path /= fs::PathFromString(BaseParams().DataDir());
301  path /= "blocks";
303  return path;
304 }
305 
306 fs::path ArgsManager::GetDataDir(bool net_specific) const
307 {
308  LOCK(cs_args);
309  fs::path& path = net_specific ? m_cached_network_datadir_path : m_cached_datadir_path;
310 
311  // Used cached path if available
312  if (!path.empty()) return path;
313 
314  const fs::path datadir{GetPathArg("-datadir")};
315  if (!datadir.empty()) {
316  path = fs::absolute(datadir);
317  if (!fs::is_directory(path)) {
318  path = "";
319  return path;
320  }
321  } else {
322  path = GetDefaultDataDir();
323  }
324 
325  if (net_specific && !BaseParams().DataDir().empty()) {
326  path /= fs::PathFromString(BaseParams().DataDir());
327  }
328 
329  return path;
330 }
331 
333 {
334  LOCK(cs_args);
335 
336  m_cached_datadir_path = fs::path();
337  m_cached_network_datadir_path = fs::path();
338  m_cached_blocks_path = fs::path();
339 }
340 
341 std::optional<const ArgsManager::Command> ArgsManager::GetCommand() const
342 {
343  Command ret;
344  LOCK(cs_args);
345  auto it = m_command.begin();
346  if (it == m_command.end()) {
347  // No command was passed
348  return std::nullopt;
349  }
350  if (!m_accept_any_command) {
351  // The registered command
352  ret.command = *(it++);
353  }
354  while (it != m_command.end()) {
355  // The unregistered command and args (if any)
356  ret.args.push_back(*(it++));
357  }
358  return ret;
359 }
360 
361 std::vector<std::string> ArgsManager::GetArgs(const std::string& strArg) const
362 {
363  std::vector<std::string> result;
364  for (const common::SettingsValue& value : GetSettingsList(strArg)) {
365  result.push_back(value.isFalse() ? "0" : value.isTrue() ? "1" : value.get_str());
366  }
367  return result;
368 }
369 
370 bool ArgsManager::IsArgSet(const std::string& strArg) const
371 {
372  return !GetSetting(strArg).isNull();
373 }
374 
375 bool ArgsManager::GetSettingsPath(fs::path* filepath, bool temp, bool backup) const
376 {
377  fs::path settings = GetPathArg("-settings", BITCOIN_SETTINGS_FILENAME);
378  if (settings.empty()) {
379  return false;
380  }
381  if (backup) {
382  settings += ".bak";
383  }
384  if (filepath) {
385  *filepath = fsbridge::AbsPathJoin(GetDataDirNet(), temp ? settings + ".tmp" : settings);
386  }
387  return true;
388 }
389 
390 static void SaveErrors(const std::vector<std::string> errors, std::vector<std::string>* error_out)
391 {
392  for (const auto& error : errors) {
393  if (error_out) {
394  error_out->emplace_back(error);
395  } else {
396  LogPrintf("%s\n", error);
397  }
398  }
399 }
400 
401 bool ArgsManager::ReadSettingsFile(std::vector<std::string>* errors)
402 {
403  fs::path path;
404  if (!GetSettingsPath(&path, /* temp= */ false)) {
405  return true; // Do nothing if settings file disabled.
406  }
407 
408  LOCK(cs_args);
409  m_settings.rw_settings.clear();
410  std::vector<std::string> read_errors;
411  if (!common::ReadSettings(path, m_settings.rw_settings, read_errors)) {
412  SaveErrors(read_errors, errors);
413  return false;
414  }
415  for (const auto& setting : m_settings.rw_settings) {
416  KeyInfo key = InterpretKey(setting.first); // Split setting key into section and argname
417  if (!GetArgFlags('-' + key.name)) {
418  LogPrintf("Ignoring unknown rw_settings value %s\n", setting.first);
419  }
420  }
421  return true;
422 }
423 
424 bool ArgsManager::WriteSettingsFile(std::vector<std::string>* errors, bool backup) const
425 {
426  fs::path path, path_tmp;
427  if (!GetSettingsPath(&path, /*temp=*/false, backup) || !GetSettingsPath(&path_tmp, /*temp=*/true, backup)) {
428  throw std::logic_error("Attempt to write settings file when dynamic settings are disabled.");
429  }
430 
431  LOCK(cs_args);
432  std::vector<std::string> write_errors;
433  if (!common::WriteSettings(path_tmp, m_settings.rw_settings, write_errors)) {
434  SaveErrors(write_errors, errors);
435  return false;
436  }
437  if (!RenameOver(path_tmp, path)) {
438  SaveErrors({strprintf("Failed renaming settings file %s to %s\n", fs::PathToString(path_tmp), fs::PathToString(path))}, errors);
439  return false;
440  }
441  return true;
442 }
443 
445 {
446  LOCK(cs_args);
447  return common::GetSetting(m_settings, m_network, name, !UseDefaultSection("-" + name),
448  /*ignore_nonpersistent=*/true, /*get_chain_type=*/false);
449 }
450 
451 bool ArgsManager::IsArgNegated(const std::string& strArg) const
452 {
453  return GetSetting(strArg).isFalse();
454 }
455 
456 std::string ArgsManager::GetArg(const std::string& strArg, const std::string& strDefault) const
457 {
458  return GetArg(strArg).value_or(strDefault);
459 }
460 
461 std::optional<std::string> ArgsManager::GetArg(const std::string& strArg) const
462 {
463  const common::SettingsValue value = GetSetting(strArg);
464  return SettingToString(value);
465 }
466 
467 std::optional<std::string> SettingToString(const common::SettingsValue& value)
468 {
469  if (value.isNull()) return std::nullopt;
470  if (value.isFalse()) return "0";
471  if (value.isTrue()) return "1";
472  if (value.isNum()) return value.getValStr();
473  return value.get_str();
474 }
475 
476 std::string SettingToString(const common::SettingsValue& value, const std::string& strDefault)
477 {
478  return SettingToString(value).value_or(strDefault);
479 }
480 
481 int64_t ArgsManager::GetIntArg(const std::string& strArg, int64_t nDefault) const
482 {
483  return GetIntArg(strArg).value_or(nDefault);
484 }
485 
486 std::optional<int64_t> ArgsManager::GetIntArg(const std::string& strArg) const
487 {
488  const common::SettingsValue value = GetSetting(strArg);
489  return SettingToInt(value);
490 }
491 
492 std::optional<int64_t> SettingToInt(const common::SettingsValue& value)
493 {
494  if (value.isNull()) return std::nullopt;
495  if (value.isFalse()) return 0;
496  if (value.isTrue()) return 1;
497  if (value.isNum()) return value.getInt<int64_t>();
498  return LocaleIndependentAtoi<int64_t>(value.get_str());
499 }
500 
501 int64_t SettingToInt(const common::SettingsValue& value, int64_t nDefault)
502 {
503  return SettingToInt(value).value_or(nDefault);
504 }
505 
506 bool ArgsManager::GetBoolArg(const std::string& strArg, bool fDefault) const
507 {
508  return GetBoolArg(strArg).value_or(fDefault);
509 }
510 
511 std::optional<bool> ArgsManager::GetBoolArg(const std::string& strArg) const
512 {
513  const common::SettingsValue value = GetSetting(strArg);
514  return SettingToBool(value);
515 }
516 
517 std::optional<bool> SettingToBool(const common::SettingsValue& value)
518 {
519  if (value.isNull()) return std::nullopt;
520  if (value.isBool()) return value.get_bool();
521  return InterpretBool(value.get_str());
522 }
523 
524 bool SettingToBool(const common::SettingsValue& value, bool fDefault)
525 {
526  return SettingToBool(value).value_or(fDefault);
527 }
528 
529 bool ArgsManager::SoftSetArg(const std::string& strArg, const std::string& strValue)
530 {
531  LOCK(cs_args);
532  if (IsArgSet(strArg)) return false;
533  ForceSetArg(strArg, strValue);
534  return true;
535 }
536 
537 bool ArgsManager::SoftSetBoolArg(const std::string& strArg, bool fValue)
538 {
539  if (fValue)
540  return SoftSetArg(strArg, std::string("1"));
541  else
542  return SoftSetArg(strArg, std::string("0"));
543 }
544 
545 void ArgsManager::ForceSetArg(const std::string& strArg, const std::string& strValue)
546 {
547  LOCK(cs_args);
548  m_settings.forced_settings[SettingName(strArg)] = strValue;
549 }
550 
551 void ArgsManager::AddCommand(const std::string& cmd, const std::string& help)
552 {
553  Assert(cmd.find('=') == std::string::npos);
554  Assert(cmd.at(0) != '-');
555 
556  LOCK(cs_args);
557  m_accept_any_command = false; // latch to false
558  std::map<std::string, Arg>& arg_map = m_available_args[OptionsCategory::COMMANDS];
559  auto ret = arg_map.emplace(cmd, Arg{"", help, ArgsManager::COMMAND});
560  Assert(ret.second); // Fail on duplicate commands
561 }
562 
563 void ArgsManager::AddArg(const std::string& name, const std::string& help, unsigned int flags, const OptionsCategory& cat)
564 {
565  Assert((flags & ArgsManager::COMMAND) == 0); // use AddCommand
566 
567  // Split arg name from its help param
568  size_t eq_index = name.find('=');
569  if (eq_index == std::string::npos) {
570  eq_index = name.size();
571  }
572  std::string arg_name = name.substr(0, eq_index);
573 
574  LOCK(cs_args);
575  std::map<std::string, Arg>& arg_map = m_available_args[cat];
576  auto ret = arg_map.emplace(arg_name, Arg{name.substr(eq_index, name.size() - eq_index), help, flags});
577  assert(ret.second); // Make sure an insertion actually happened
578 
580  m_network_only_args.emplace(arg_name);
581  }
582 }
583 
584 void ArgsManager::AddHiddenArgs(const std::vector<std::string>& names)
585 {
586  for (const std::string& name : names) {
588  }
589 }
590 
591 std::string ArgsManager::GetHelpMessage() const
592 {
593  const bool show_debug = GetBoolArg("-help-debug", false);
594 
595  std::string usage;
596  LOCK(cs_args);
597  for (const auto& arg_map : m_available_args) {
598  switch(arg_map.first) {
600  usage += HelpMessageGroup("Options:");
601  break;
603  usage += HelpMessageGroup("Connection options:");
604  break;
606  usage += HelpMessageGroup("ZeroMQ notification options:");
607  break;
609  usage += HelpMessageGroup("Debugging/Testing options:");
610  break;
612  usage += HelpMessageGroup("Node relay options:");
613  break;
615  usage += HelpMessageGroup("Block creation options:");
616  break;
618  usage += HelpMessageGroup("RPC server options:");
619  break;
621  usage += HelpMessageGroup("Wallet options:");
622  break;
624  if (show_debug) usage += HelpMessageGroup("Wallet debugging/testing options:");
625  break;
627  usage += HelpMessageGroup("Chain selection options:");
628  break;
630  usage += HelpMessageGroup("UI Options:");
631  break;
633  usage += HelpMessageGroup("Commands:");
634  break;
636  usage += HelpMessageGroup("Register Commands:");
637  break;
638  default:
639  break;
640  }
641 
642  // When we get to the hidden options, stop
643  if (arg_map.first == OptionsCategory::HIDDEN) break;
644 
645  for (const auto& arg : arg_map.second) {
646  if (show_debug || !(arg.second.m_flags & ArgsManager::DEBUG_ONLY)) {
647  std::string name;
648  if (arg.second.m_help_param.empty()) {
649  name = arg.first;
650  } else {
651  name = arg.first + arg.second.m_help_param;
652  }
653  usage += HelpMessageOpt(name, arg.second.m_help_text);
654  }
655  }
656  }
657  return usage;
658 }
659 
661 {
662  return args.IsArgSet("-?") || args.IsArgSet("-h") || args.IsArgSet("-help") || args.IsArgSet("-help-debug");
663 }
664 
666 {
667  args.AddArg("-?", "Print this help message and exit", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
668  args.AddHiddenArgs({"-h", "-help"});
669 }
670 
671 static const int screenWidth = 79;
672 static const int optIndent = 2;
673 static const int msgIndent = 7;
674 
675 std::string HelpMessageGroup(const std::string &message) {
676  return std::string(message) + std::string("\n\n");
677 }
678 
679 std::string HelpMessageOpt(const std::string &option, const std::string &message) {
680  return std::string(optIndent,' ') + std::string(option) +
681  std::string("\n") + std::string(msgIndent,' ') +
683  std::string("\n\n");
684 }
685 
686 const std::vector<std::string> TEST_OPTIONS_DOC{
687  "addrman (use deterministic addrman)",
688 };
689 
690 bool HasTestOption(const ArgsManager& args, const std::string& test_option)
691 {
692  const auto options = args.GetArgs("-test");
693  return std::any_of(options.begin(), options.end(), [test_option](const auto& option) {
694  return option == test_option;
695  });
696 }
697 
699 {
700  // Windows:
701  // old: C:\Users\Username\AppData\Roaming\Bitcoin
702  // new: C:\Users\Username\AppData\Local\Bitcoin
703  // macOS: ~/Library/Application Support/Bitcoin
704  // Unix-like: ~/.bitcoin
705 #ifdef WIN32
706  // Windows
707  // Check for existence of datadir in old location and keep it there
708  fs::path legacy_path = GetSpecialFolderPath(CSIDL_APPDATA) / "Bitcoin";
709  if (fs::exists(legacy_path)) return legacy_path;
710 
711  // Otherwise, fresh installs can start in the new, "proper" location
712  return GetSpecialFolderPath(CSIDL_LOCAL_APPDATA) / "Bitcoin";
713 #else
714  fs::path pathRet;
715  char* pszHome = getenv("HOME");
716  if (pszHome == nullptr || strlen(pszHome) == 0)
717  pathRet = fs::path("/");
718  else
719  pathRet = fs::path(pszHome);
720 #ifdef MAC_OSX
721  // macOS
722  return pathRet / "Library/Application Support/Bitcoin";
723 #else
724  // Unix-like
725  return pathRet / ".bitcoin";
726 #endif
727 #endif
728 }
729 
731 {
732  const fs::path datadir{args.GetPathArg("-datadir")};
733  return datadir.empty() || fs::is_directory(fs::absolute(datadir));
734 }
735 
737 {
738  LOCK(cs_args);
739  return *Assert(m_config_path);
740 }
741 
743 {
744  LOCK(cs_args);
745  assert(!m_config_path);
746  m_config_path = path;
747 }
748 
750 {
751  std::variant<ChainType, std::string> arg = GetChainArg();
752  if (auto* parsed = std::get_if<ChainType>(&arg)) return *parsed;
753  throw std::runtime_error(strprintf("Unknown chain %s.", std::get<std::string>(arg)));
754 }
755 
757 {
758  auto arg = GetChainArg();
759  if (auto* parsed = std::get_if<ChainType>(&arg)) return ChainTypeToString(*parsed);
760  return std::get<std::string>(arg);
761 }
762 
763 std::variant<ChainType, std::string> ArgsManager::GetChainArg() const
764 {
765  auto get_net = [&](const std::string& arg) {
766  LOCK(cs_args);
767  common::SettingsValue value = common::GetSetting(m_settings, /* section= */ "", SettingName(arg),
768  /* ignore_default_section_config= */ false,
769  /*ignore_nonpersistent=*/false,
770  /* get_chain_type= */ true);
771  return value.isNull() ? false : value.isBool() ? value.get_bool() : InterpretBool(value.get_str());
772  };
773 
774  const bool fRegTest = get_net("-regtest");
775  const bool fSigNet = get_net("-signet");
776  const bool fTestNet = get_net("-testnet");
777  const bool fTestNet4 = get_net("-testnet4");
778  const auto chain_arg = GetArg("-chain");
779 
780  if ((int)chain_arg.has_value() + (int)fRegTest + (int)fSigNet + (int)fTestNet + (int)fTestNet4 > 1) {
781  throw std::runtime_error("Invalid combination of -regtest, -signet, -testnet, -testnet4 and -chain. Can use at most one.");
782  }
783  if (chain_arg) {
784  if (auto parsed = ChainTypeFromString(*chain_arg)) return *parsed;
785  // Not a known string, so return original string
786  return *chain_arg;
787  }
788  if (fRegTest) return ChainType::REGTEST;
789  if (fSigNet) return ChainType::SIGNET;
790  if (fTestNet) return ChainType::TESTNET;
791  if (fTestNet4) return ChainType::TESTNET4;
792  return ChainType::MAIN;
793 }
794 
795 bool ArgsManager::UseDefaultSection(const std::string& arg) const
796 {
797  return m_network == ChainTypeToString(ChainType::MAIN) || m_network_only_args.count(arg) == 0;
798 }
799 
800 common::SettingsValue ArgsManager::GetSetting(const std::string& arg) const
801 {
802  LOCK(cs_args);
803  return common::GetSetting(
804  m_settings, m_network, SettingName(arg), !UseDefaultSection(arg),
805  /*ignore_nonpersistent=*/false, /*get_chain_type=*/false);
806 }
807 
808 std::vector<common::SettingsValue> ArgsManager::GetSettingsList(const std::string& arg) const
809 {
810  LOCK(cs_args);
811  return common::GetSettingsList(m_settings, m_network, SettingName(arg), !UseDefaultSection(arg));
812 }
813 
815  const std::string& prefix,
816  const std::string& section,
817  const std::map<std::string, std::vector<common::SettingsValue>>& args) const
818 {
819  std::string section_str = section.empty() ? "" : "[" + section + "] ";
820  for (const auto& arg : args) {
821  for (const auto& value : arg.second) {
822  std::optional<unsigned int> flags = GetArgFlags('-' + arg.first);
823  if (flags) {
824  std::string value_str = (*flags & SENSITIVE) ? "****" : value.write();
825  LogPrintf("%s %s%s=%s\n", prefix, section_str, arg.first, value_str);
826  }
827  }
828  }
829 }
830 
832 {
833  LOCK(cs_args);
834  for (const auto& section : m_settings.ro_config) {
835  logArgsPrefix("Config file arg:", section.first, section.second);
836  }
837  for (const auto& setting : m_settings.rw_settings) {
838  LogPrintf("Setting file arg: %s = %s\n", setting.first, setting.second.write());
839  }
840  logArgsPrefix("Command-line arg:", "", m_settings.command_line_options);
841 }
842 
843 namespace common {
844 #ifdef WIN32
845 WinCmdLineArgs::WinCmdLineArgs()
846 {
847  wchar_t** wargv = CommandLineToArgvW(GetCommandLineW(), &argc);
848  std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t> utf8_cvt;
849  argv = new char*[argc];
850  args.resize(argc);
851  for (int i = 0; i < argc; i++) {
852  args[i] = utf8_cvt.to_bytes(wargv[i]);
853  argv[i] = &*args[i].begin();
854  }
855  LocalFree(wargv);
856 }
857 
858 WinCmdLineArgs::~WinCmdLineArgs()
859 {
860  delete[] argv;
861 }
862 
863 std::pair<int, char**> WinCmdLineArgs::get()
864 {
865  return std::make_pair(argc, argv);
866 }
867 #endif
868 } // namespace common
std::optional< common::SettingsValue > InterpretValue(const KeyInfo &key, const std::string *value, unsigned int flags, std::string &error)
Interpret settings value based on registered flags.
Definition: args.cpp:106
static path PathFromString(const std::string &string)
Convert byte string to path object.
Definition: fs.h:174
std::string section
Definition: args.h:72
fs::path GetPathArg(std::string arg, const fs::path &default_value={}) const
Return path argument or default value.
Definition: args.cpp:271
int ret
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: args.cpp:370
OptionsCategory
Definition: args.h:52
bool isBool() const
Definition: univalue.h:82
fs::path AbsPathJoin(const fs::path &base, const fs::path &path)
Helper function for joining two paths.
Definition: fs.cpp:36
fs::path GetConfigFilePath() const
Return config file path (read-only)
Definition: args.cpp:736
assert(!tx.IsCoinBase())
std::variant< ChainType, std::string > GetChainArg() const
Return -regtest/-signet/-testnet/-testnet4/-chain= setting as a ChainType enum if a recognized chain ...
Definition: args.cpp:763
bool get_bool() const
const char *const BITCOIN_SETTINGS_FILENAME
Definition: args.cpp:39
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn&#39;t already have a value.
Definition: args.cpp:537
common::SettingsValue GetSetting(const std::string &arg) const
Get setting value.
Definition: args.cpp:800
bool ReadSettings(const fs::path &path, std::map< std::string, SettingsValue > &values, std::vector< std::string > &errors)
Read settings file.
Definition: settings.cpp:72
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1161
const char * prefix
Definition: rest.cpp:1007
const std::vector< std::string > TEST_OPTIONS_DOC
Definition: args.cpp:686
void AddHiddenArgs(const std::vector< std::string > &args)
Add many hidden arguments.
Definition: args.cpp:584
disallow -nofoo syntax
Definition: args.h:109
void SelectConfigNetwork(const std::string &network)
Select the network in use.
Definition: args.cpp:172
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
bool negated
Definition: args.h:73
const auto cmd
common::SettingsValue GetPersistentSetting(const std::string &name) const
Get current setting from config file or read/write settings file, ignoring nonpersistent command line...
Definition: args.cpp:444
const std::string & get_str() const
static const int optIndent
Definition: args.cpp:672
bool isNum() const
Definition: univalue.h:84
bool ParseParameters(int argc, const char *const argv[], std::string &error)
Definition: args.cpp:178
std::string HelpMessageGroup(const std::string &message)
Format a string to be used as group of options in help messages.
Definition: args.cpp:675
RecursiveMutex cs_args
Definition: args.h:132
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: args.cpp:506
static const int64_t values[]
A selection of numbers that do not trigger int64_t overflow when added/subtracted.
Int getInt() const
Definition: univalue.h:138
void ForceSetArg(const std::string &strArg, const std::string &strValue)
Definition: args.cpp:545
ChainType GetChainType() const
Returns the appropriate chain type from the program arguments.
Definition: args.cpp:749
bool SoftSetArg(const std::string &strArg, const std::string &strValue)
Set an argument if it doesn&#39;t already have a value.
Definition: args.cpp:529
const std::string & getValStr() const
Definition: univalue.h:68
void SetConfigFilePath(fs::path)
Definition: args.cpp:742
std::string m_name
Definition: args.h:82
disable validation
Definition: args.h:104
Definition: args.h:70
std::string GetHelpMessage() const
Get the help string.
Definition: args.cpp:591
bool RenameOver(fs::path src, fs::path dest)
Rename src to dest.
Definition: fs_helpers.cpp:249
std::string HelpMessageOpt(const std::string &option, const std::string &message)
Format a string to be used as option description in help messages.
Definition: args.cpp:679
fs::path GetDataDir(bool net_specific) const
Get data directory path.
Definition: args.cpp:306
fs::path GetDataDirBase() const
Get data directory path.
Definition: args.h:225
Accessor for list of settings that skips negated values when iterated over.
Definition: settings.h:90
CRPCCommand m_command
Definition: interfaces.cpp:533
disallow -foo syntax that doesn&#39;t assign any value
Definition: args.h:110
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: args.cpp:375
bool ReadSettingsFile(std::vector< std::string > *errors=nullptr)
Read settings file.
Definition: args.cpp:401
std::string GetChainTypeString() const
Returns the appropriate chain type string from the program arguments.
Definition: args.cpp:756
void AddCommand(const std::string &cmd, const std::string &help)
Add subcommand.
Definition: args.cpp:551
bool IsArgNegated(const std::string &strArg) const
Return true if the argument was originally passed as a negated option, i.e.
Definition: args.cpp:451
ChainType
Definition: chaintype.h:11
fs::path GetDataDirNet() const
Get data directory path with appended network identifier.
Definition: args.h:232
static std::string PathToString(const path &path)
Convert path object to a byte string.
Definition: fs.h:151
ArgsManager & args
Definition: bitcoind.cpp:270
std::optional< std::string > SettingToString(const common::SettingsValue &value)
Definition: args.cpp:467
SettingsValue GetSetting(const Settings &settings, const std::string &section, const std::string &name, bool ignore_default_section_config, bool ignore_nonpersistent, bool get_chain_type)
Get settings value from combined sources: forced settings, command line arguments, runtime read-write settings, and the read-only config file.
Definition: settings.cpp:146
std::vector< common::SettingsValue > GetSettingsList(const std::string &arg) const
Get list of setting values.
Definition: args.cpp:808
static bool InterpretBool(const std::string &strValue)
Interpret a string argument as a boolean.
Definition: args.cpp:58
bool isFalse() const
Definition: univalue.h:81
#define LOCK(cs)
Definition: sync.h:257
const char * name
Definition: rest.cpp:49
fs::path GetBlocksDirPath() const
Get blocks directory path.
Definition: args.cpp:281
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
Definition: args.cpp:563
std::list< SectionInfo > GetUnrecognizedSections() const
Log warnings for unrecognized section names in the config file.
Definition: args.cpp:155
std::optional< bool > SettingToBool(const common::SettingsValue &value)
Definition: args.cpp:517
bool HasTestOption(const ArgsManager &args, const std::string &test_option)
Checks if a particular test option is present in -test command-line arg options.
Definition: args.cpp:690
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...
std::optional< const Command > GetCommand() const
Get the command and command args (returns std::nullopt if no command provided)
Definition: args.cpp:341
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:190
static void SaveErrors(const std::vector< std::string > errors, std::vector< std::string > *error_out)
Definition: args.cpp:390
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:203
bool isNull() const
Definition: univalue.h:79
bool isTrue() const
Definition: univalue.h:80
Definition: args.cpp:843
ArgsManager gArgs
Definition: args.cpp:41
std::string ToLower(std::string_view str)
Returns the lowercase equivalent of the given string.
int flags
Definition: bitcoin-tx.cpp:533
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
Definition: args.cpp:665
std::optional< unsigned int > GetArgFlags(const std::string &name) const
Return Flags for known arg.
Definition: args.cpp:259
bool WriteSettingsFile(std::vector< std::string > *errors=nullptr, bool backup=false) const
Write settings file or backup settings file.
Definition: args.cpp:424
std::string name
Definition: args.h:71
fs::path GetDefaultDataDir()
Definition: args.cpp:698
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Definition: args.cpp:481
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:248
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: args.cpp:456
bool HelpRequested(const ArgsManager &args)
Definition: args.cpp:660
void LogArgs() const
Log the config file options and the command line arguments, useful for troubleshooting.
Definition: args.cpp:831
std::string ChainTypeToString(ChainType chain)
Definition: chaintype.cpp:11
static const int msgIndent
Definition: args.cpp:673
const char *const BITCOIN_CONF_FILENAME
Definition: args.cpp:38
std::optional< ChainType > ChainTypeFromString(std::string_view chain)
Definition: chaintype.cpp:28
bool WriteSettings(const fs::path &path, const std::map< std::string, SettingsValue > &values, std::vector< std::string > &errors)
Write settings file.
Definition: settings.cpp:123
static std::string SettingName(const std::string &arg)
Definition: args.cpp:65
std::optional< int64_t > SettingToInt(const common::SettingsValue &value)
Definition: args.cpp:492
void logArgsPrefix(const std::string &prefix, const std::string &section, const std::map< std::string, std::vector< common::SettingsValue >> &args) const
Definition: args.cpp:814
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
Definition: args.cpp:361
static bool exists(const path &p)
Definition: fs.h:89
void ClearPathCache()
Clear cached directory paths.
Definition: args.cpp:332
#define LogPrintf(...)
Definition: logging.h:274
static const int screenWidth
Definition: args.cpp:671
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:32
static path absolute(const path &p)
Definition: fs.h:82
static RPCHelpMan help()
Definition: server.cpp:143
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: args.cpp:795
#define Assert(val)
Identity function.
Definition: check.h:77
KeyInfo InterpretKey(std::string key)
Parse "name", "section.name", "noname", "section.noname" settings keys.
Definition: args.cpp:78
bool CheckDataDirOption(const ArgsManager &args)
Definition: args.cpp:730
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: args.cpp:135
auto FindKey(Map &&map, Key &&key) -> decltype(&map.at(key))
Map lookup helper.
Definition: settings.h:107