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