Bitcoin Core  25.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 <logging.h>
10 #include <sync.h>
11 #include <tinyformat.h>
12 #include <univalue.h>
13 #include <util/chaintype.h>
14 #include <util/check.h>
15 #include <util/fs.h>
16 #include <util/fs_helpers.h>
17 #include <util/settings.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 <filesystem>
32 #include <map>
33 #include <optional>
34 #include <stdexcept>
35 #include <string>
36 #include <utility>
37 #include <variant>
38 
39 const char * const BITCOIN_CONF_FILENAME = "bitcoin.conf";
40 const char * const BITCOIN_SETTINGS_FILENAME = "settings.json";
41 
43 
59 static bool InterpretBool(const std::string& strValue)
60 {
61  if (strValue.empty())
62  return true;
63  return (LocaleIndependentAtoi<int>(strValue) != 0);
64 }
65 
66 static std::string SettingName(const std::string& arg)
67 {
68  return arg.size() > 0 && arg[0] == '-' ? arg.substr(1) : arg;
69 }
70 
79 KeyInfo InterpretKey(std::string key)
80 {
81  KeyInfo result;
82  // Split section name from key name for keys like "testnet.foo" or "regtest.bar"
83  size_t option_index = key.find('.');
84  if (option_index != std::string::npos) {
85  result.section = key.substr(0, option_index);
86  key.erase(0, option_index + 1);
87  }
88  if (key.substr(0, 2) == "no") {
89  key.erase(0, 2);
90  result.negated = true;
91  }
92  result.name = key;
93  return result;
94 }
95 
107 std::optional<util::SettingsValue> InterpretValue(const KeyInfo& key, const std::string* value,
108  unsigned int flags, std::string& error)
109 {
110  // Return negated settings as false values.
111  if (key.negated) {
113  error = strprintf("Negating of -%s is meaningless and therefore forbidden", key.name);
114  return std::nullopt;
115  }
116  // Double negatives like -nofoo=0 are supported (but discouraged)
117  if (value && !InterpretBool(*value)) {
118  LogPrintf("Warning: parsed potentially confusing double-negative -%s=%s\n", key.name, *value);
119  return true;
120  }
121  return false;
122  }
123  if (!value && (flags & ArgsManager::DISALLOW_ELISION)) {
124  error = strprintf("Can not set -%s with no value. Please specify value with -%s=value.", key.name, key.name);
125  return std::nullopt;
126  }
127  return value ? *value : "";
128 }
129 
130 // Define default constructor and destructor that are not inline, so code instantiating this class doesn't need to
131 // #include class definitions for all members.
132 // For example, m_settings has an internal dependency on univalue.
133 ArgsManager::ArgsManager() = default;
134 ArgsManager::~ArgsManager() = default;
135 
136 std::set<std::string> ArgsManager::GetUnsuitableSectionOnlyArgs() const
137 {
138  std::set<std::string> unsuitables;
139 
140  LOCK(cs_args);
141 
142  // if there's no section selected, don't worry
143  if (m_network.empty()) return std::set<std::string> {};
144 
145  // if it's okay to use the default section for this network, don't worry
146  if (m_network == ChainTypeToString(ChainType::MAIN)) return std::set<std::string> {};
147 
148  for (const auto& arg : m_network_only_args) {
149  if (OnlyHasDefaultSectionSetting(m_settings, m_network, SettingName(arg))) {
150  unsuitables.insert(arg);
151  }
152  }
153  return unsuitables;
154 }
155 
156 std::list<SectionInfo> ArgsManager::GetUnrecognizedSections() const
157 {
158  // Section names to be recognized in the config file.
159  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.push_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<util::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 = util::FindKey(m_settings.command_line_options, "includeconf")) {
249  const util::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 const 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 util::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 (!util::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 (!util::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 util::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 util::SettingsValue value = GetSetting(strArg);
464  return SettingToString(value);
465 }
466 
467 std::optional<std::string> SettingToString(const util::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 util::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 util::SettingsValue value = GetSetting(strArg);
489  return SettingToInt(value);
490 }
491 
492 std::optional<int64_t> SettingToInt(const util::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 util::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 util::SettingsValue value = GetSetting(strArg);
514  return SettingToBool(value);
515 }
516 
517 std::optional<bool> SettingToBool(const util::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 util::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 
687 {
688  // Windows: C:\Users\Username\AppData\Roaming\Bitcoin
689  // macOS: ~/Library/Application Support/Bitcoin
690  // Unix-like: ~/.bitcoin
691 #ifdef WIN32
692  // Windows
693  return GetSpecialFolderPath(CSIDL_APPDATA) / "Bitcoin";
694 #else
695  fs::path pathRet;
696  char* pszHome = getenv("HOME");
697  if (pszHome == nullptr || strlen(pszHome) == 0)
698  pathRet = fs::path("/");
699  else
700  pathRet = fs::path(pszHome);
701 #ifdef MAC_OSX
702  // macOS
703  return pathRet / "Library/Application Support/Bitcoin";
704 #else
705  // Unix-like
706  return pathRet / ".bitcoin";
707 #endif
708 #endif
709 }
710 
712 {
713  const fs::path datadir{args.GetPathArg("-datadir")};
714  return datadir.empty() || fs::is_directory(fs::absolute(datadir));
715 }
716 
718 {
719  LOCK(cs_args);
720  return *Assert(m_config_path);
721 }
722 
724 {
725  std::variant<ChainType, std::string> arg = GetChainArg();
726  if (auto* parsed = std::get_if<ChainType>(&arg)) return *parsed;
727  throw std::runtime_error(strprintf("Unknown chain %s.", std::get<std::string>(arg)));
728 }
729 
731 {
732  auto arg = GetChainArg();
733  if (auto* parsed = std::get_if<ChainType>(&arg)) return ChainTypeToString(*parsed);
734  return std::get<std::string>(arg);
735 }
736 
737 std::variant<ChainType, std::string> ArgsManager::GetChainArg() const
738 {
739  auto get_net = [&](const std::string& arg) {
740  LOCK(cs_args);
741  util::SettingsValue value = util::GetSetting(m_settings, /* section= */ "", SettingName(arg),
742  /* ignore_default_section_config= */ false,
743  /*ignore_nonpersistent=*/false,
744  /* get_chain_type= */ true);
745  return value.isNull() ? false : value.isBool() ? value.get_bool() : InterpretBool(value.get_str());
746  };
747 
748  const bool fRegTest = get_net("-regtest");
749  const bool fSigNet = get_net("-signet");
750  const bool fTestNet = get_net("-testnet");
751  const auto chain_arg = GetArg("-chain");
752 
753  if ((int)chain_arg.has_value() + (int)fRegTest + (int)fSigNet + (int)fTestNet > 1) {
754  throw std::runtime_error("Invalid combination of -regtest, -signet, -testnet and -chain. Can use at most one.");
755  }
756  if (chain_arg) {
757  if (auto parsed = ChainTypeFromString(*chain_arg)) return *parsed;
758  // Not a known string, so return original string
759  return *chain_arg;
760  }
761  if (fRegTest) return ChainType::REGTEST;
762  if (fSigNet) return ChainType::SIGNET;
763  if (fTestNet) return ChainType::TESTNET;
764  return ChainType::MAIN;
765 }
766 
767 bool ArgsManager::UseDefaultSection(const std::string& arg) const
768 {
769  return m_network == ChainTypeToString(ChainType::MAIN) || m_network_only_args.count(arg) == 0;
770 }
771 
772 util::SettingsValue ArgsManager::GetSetting(const std::string& arg) const
773 {
774  LOCK(cs_args);
775  return util::GetSetting(
776  m_settings, m_network, SettingName(arg), !UseDefaultSection(arg),
777  /*ignore_nonpersistent=*/false, /*get_chain_type=*/false);
778 }
779 
780 std::vector<util::SettingsValue> ArgsManager::GetSettingsList(const std::string& arg) const
781 {
782  LOCK(cs_args);
783  return util::GetSettingsList(m_settings, m_network, SettingName(arg), !UseDefaultSection(arg));
784 }
785 
787  const std::string& prefix,
788  const std::string& section,
789  const std::map<std::string, std::vector<util::SettingsValue>>& args) const
790 {
791  std::string section_str = section.empty() ? "" : "[" + section + "] ";
792  for (const auto& arg : args) {
793  for (const auto& value : arg.second) {
794  std::optional<unsigned int> flags = GetArgFlags('-' + arg.first);
795  if (flags) {
796  std::string value_str = (*flags & SENSITIVE) ? "****" : value.write();
797  LogPrintf("%s %s%s=%s\n", prefix, section_str, arg.first, value_str);
798  }
799  }
800  }
801 }
802 
804 {
805  LOCK(cs_args);
806  for (const auto& section : m_settings.ro_config) {
807  logArgsPrefix("Config file arg:", section.first, section.second);
808  }
809  for (const auto& setting : m_settings.rw_settings) {
810  LogPrintf("Setting file arg: %s = %s\n", setting.first, setting.second.write());
811  }
812  logArgsPrefix("Command-line arg:", "", m_settings.command_line_options);
813 }
814 
815 namespace common {
816 #ifdef WIN32
817 WinCmdLineArgs::WinCmdLineArgs()
818 {
819  wchar_t** wargv = CommandLineToArgvW(GetCommandLineW(), &argc);
820  std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t> utf8_cvt;
821  argv = new char*[argc];
822  args.resize(argc);
823  for (int i = 0; i < argc; i++) {
824  args[i] = utf8_cvt.to_bytes(wargv[i]);
825  argv[i] = &*args[i].begin();
826  }
827  LocalFree(wargv);
828 }
829 
830 WinCmdLineArgs::~WinCmdLineArgs()
831 {
832  delete[] argv;
833 }
834 
835 std::pair<int, char**> WinCmdLineArgs::get()
836 {
837  return std::make_pair(argc, argv);
838 }
839 #endif
840 } // namespace common
bool HelpRequested(const ArgsManager &args)
Definition: args.cpp:660
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
Definition: args.cpp:665
fs::path GetDefaultDataDir()
Definition: args.cpp:686
static const int msgIndent
Definition: args.cpp:673
static void SaveErrors(const std::vector< std::string > errors, std::vector< std::string > *error_out)
Definition: args.cpp:390
const char *const BITCOIN_SETTINGS_FILENAME
Definition: args.cpp:40
std::optional< std::string > SettingToString(const util::SettingsValue &value)
Definition: args.cpp:467
bool CheckDataDirOption(const ArgsManager &args)
Definition: args.cpp:711
static const int screenWidth
Definition: args.cpp:671
ArgsManager gArgs
Definition: args.cpp:42
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: args.cpp:107
std::optional< int64_t > SettingToInt(const util::SettingsValue &value)
Definition: args.cpp:492
static std::string SettingName(const std::string &arg)
Definition: args.cpp:66
std::string HelpMessageGroup(const std::string &message)
Format a string to be used as group of options in help messages.
Definition: args.cpp:675
KeyInfo InterpretKey(std::string key)
Parse "name", "section.name", "noname", "section.noname" settings keys.
Definition: args.cpp:79
const char *const BITCOIN_CONF_FILENAME
Definition: args.cpp:39
static bool InterpretBool(const std::string &strValue)
Interpret a string argument as a boolean.
Definition: args.cpp:59
static const int optIndent
Definition: args.cpp:672
std::optional< bool > SettingToBool(const util::SettingsValue &value)
Definition: args.cpp:517
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
OptionsCategory
Definition: args.h:52
int ret
int flags
Definition: bitcoin-tx.cpp:528
const auto cmd
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:73
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:136
std::optional< const Command > GetCommand() const
Get the command and command args (returns std::nullopt if no command provided)
Definition: args.cpp:341
const fs::path & GetBlocksDirPath() const
Get blocks directory path.
Definition: args.cpp:281
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
std::list< SectionInfo > GetUnrecognizedSections() const
Log warnings for unrecognized section names in the config file.
Definition: args.cpp:156
@ 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
bool ReadSettingsFile(std::vector< std::string > *errors=nullptr)
Read settings file.
Definition: args.cpp:401
ChainType GetChainType() const
Returns the appropriate chain type from the program arguments.
Definition: args.cpp:723
void ForceSetArg(const std::string &strArg, const std::string &strValue)
Definition: args.cpp:545
void logArgsPrefix(const std::string &prefix, const std::string &section, const std::map< std::string, std::vector< util::SettingsValue >> &args) const
Definition: args.cpp:786
std::string GetChainTypeString() const
Returns the appropriate chain type string from the program arguments.
Definition: args.cpp:730
bool ParseParameters(int argc, const char *const argv[], std::string &error)
Definition: args.cpp:178
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
Definition: args.cpp:361
util::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
std::optional< unsigned int > GetArgFlags(const std::string &name) const
Return Flags for known arg.
Definition: args.cpp:259
const fs::path & GetDataDirBase() const
Get data directory path.
Definition: args.h:224
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 SoftSetArg(const std::string &strArg, const std::string &strValue)
Set an argument if it doesn't already have a value.
Definition: args.cpp:529
void SelectConfigNetwork(const std::string &network)
Select the network in use.
Definition: args.cpp:172
std::string GetHelpMessage() const
Get the help string.
Definition: args.cpp:591
void ClearPathCache()
Clear cached directory paths.
Definition: args.cpp:332
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: args.cpp:370
const fs::path & GetDataDirNet() const
Get data directory path with appended network identifier.
Definition: args.h:231
bool WriteSettingsFile(std::vector< std::string > *errors=nullptr, bool backup=false) const
Write settings file or backup settings file.
Definition: args.cpp:424
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Definition: args.cpp:481
const fs::path & GetDataDir(bool net_specific) const
Get data directory path.
Definition: args.cpp:306
fs::path GetConfigFilePath() const
Return config file path (read-only)
Definition: args.cpp:717
void AddCommand(const std::string &cmd, const std::string &help)
Add subcommand.
Definition: args.cpp:551
std::vector< util::SettingsValue > GetSettingsList(const std::string &arg) const
Get list of setting values.
Definition: args.cpp:780
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:737
void LogArgs() const
Log the config file options and the command line arguments, useful for troubleshooting.
Definition: args.cpp:803
RecursiveMutex cs_args
Definition: args.h:132
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:767
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: args.cpp:456
util::SettingsValue GetSetting(const std::string &arg) const
Get setting value.
Definition: args.cpp:772
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn't already have a value.
Definition: args.cpp:537
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: args.cpp:506
void AddHiddenArgs(const std::vector< std::string > &args)
Add many hidden arguments.
Definition: args.cpp:584
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
Definition: args.cpp:563
fs::path GetPathArg(std::string arg, const fs::path &default_value={}) const
Return path argument or default value.
Definition: args.cpp:271
const std::string & get_str() const
bool isTrue() const
Definition: univalue.h:77
bool isNull() const
Definition: univalue.h:76
const std::string & getValStr() const
Definition: univalue.h:65
bool isBool() const
Definition: univalue.h:79
Int getInt() const
Definition: univalue.h:137
bool isNum() const
Definition: univalue.h:81
bool isFalse() const
Definition: univalue.h:78
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:31
bool RenameOver(fs::path src, fs::path dest)
Rename src to dest.
Definition: fs_helpers.cpp:261
bool error(const char *fmt, const Args &... args)
Definition: logging.h:261
#define LogPrintf(...)
Definition: logging.h:236
Definition: args.cpp:815
static path absolute(const path &p)
Definition: fs.h:81
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:188
static std::string PathToString(const path &path)
Convert path object to a byte string.
Definition: fs.h:150
static path PathFromString(const std::string &string)
Convert byte string to path object.
Definition: fs.h:173
fs::path AbsPathJoin(const fs::path &base, const fs::path &path)
Helper function for joining two paths.
Definition: fs.cpp:35
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:185
bool ReadSettings(const fs::path &path, std::map< std::string, SettingsValue > &values, std::vector< std::string > &errors)
Read settings file.
Definition: settings.cpp:64
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:230
bool WriteSettings(const fs::path &path, const std::map< std::string, SettingsValue > &values, std::vector< std::string > &errors)
Write settings file.
Definition: settings.cpp:109
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:128
auto FindKey(Map &&map, Key &&key) -> decltype(&map.at(key))
Map lookup helper.
Definition: settings.h:106
CRPCCommand m_command
Definition: interfaces.cpp:500
ArgsManager args
const char * prefix
Definition: rest.cpp:1004
const char * name
Definition: rest.cpp:45
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:137
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:89
#define LOCK(cs)
Definition: sync.h:258
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1162
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())