/ src / common / args.cpp
args.cpp
  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  
 41  ArgsManager gArgs;
 42  
 43  /**
 44   * Interpret a string argument as a boolean.
 45   *
 46   * The definition of LocaleIndependentAtoi<int>() requires that non-numeric string values
 47   * like "foo", return 0. This means that if a user unintentionally supplies a
 48   * non-integer argument here, the return value is always false. This means that
 49   * -foo=false does what the user probably expects, but -foo=true is well defined
 50   * but does not do what they probably expected.
 51   *
 52   * The return value of LocaleIndependentAtoi<int>(...) is zero when given input not
 53   * representable as an int.
 54   *
 55   * For a more extensive discussion of this topic (and a wide range of opinions
 56   * on the Right Way to change this code), see PR12713.
 57   */
 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  
 70  /**
 71   * Parse "name", "section.name", "noname", "section.noname" settings keys.
 72   *
 73   * @note Where an option was negated can be later checked using the
 74   * IsArgNegated() method. One use case for this is to have a way to disable
 75   * options that are not normally boolean (e.g. using -nodebuglogfile to request
 76   * that debug log output is not sent to any file at all).
 77   */
 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  
 95  /**
 96   * Interpret settings value based on registered flags.
 97   *
 98   * @param[in]   key      key information to know if key was negated
 99   * @param[in]   value    string value of setting to be parsed
100   * @param[in]   flags    ArgsManager registered argument flags
101   * @param[out]  error    Error description if settings value is not valid
102   *
103   * @return parsed settings value if it is valid, otherwise nullopt accompanied
104   * by a descriptive error string
105   */
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) {
111          if (flags & ArgsManager::DISALLOW_NEGATION) {
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{
159          ChainTypeToString(ChainType::REGTEST),
160          ChainTypeToString(ChainType::SIGNET),
161          ChainTypeToString(ChainType::TESTNET),
162          ChainTypeToString(ChainType::MAIN),
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  
280  fs::path ArgsManager::GetBlocksDirPath() const
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";
301      fs::create_directories(path);
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  
331  void ArgsManager::ClearPathCache()
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  
443  common::SettingsValue ArgsManager::GetPersistentSetting(const std::string& name) const
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  
578      if (flags & ArgsManager::NETWORK_ONLY) {
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) {
586          AddArg(name, "", ArgsManager::ALLOW_ANY, OptionsCategory::HIDDEN);
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) {
598              case OptionsCategory::OPTIONS:
599                  usage += HelpMessageGroup("Options:");
600                  break;
601              case OptionsCategory::CONNECTION:
602                  usage += HelpMessageGroup("Connection options:");
603                  break;
604              case OptionsCategory::ZMQ:
605                  usage += HelpMessageGroup("ZeroMQ notification options:");
606                  break;
607              case OptionsCategory::DEBUG_TEST:
608                  usage += HelpMessageGroup("Debugging/Testing options:");
609                  break;
610              case OptionsCategory::NODE_RELAY:
611                  usage += HelpMessageGroup("Node relay options:");
612                  break;
613              case OptionsCategory::BLOCK_CREATION:
614                  usage += HelpMessageGroup("Block creation options:");
615                  break;
616              case OptionsCategory::RPC:
617                  usage += HelpMessageGroup("RPC server options:");
618                  break;
619              case OptionsCategory::WALLET:
620                  usage += HelpMessageGroup("Wallet options:");
621                  break;
622              case OptionsCategory::WALLET_DEBUG_TEST:
623                  if (show_debug) usage += HelpMessageGroup("Wallet debugging/testing options:");
624                  break;
625              case OptionsCategory::CHAINPARAMS:
626                  usage += HelpMessageGroup("Chain selection options:");
627                  break;
628              case OptionsCategory::GUI:
629                  usage += HelpMessageGroup("UI Options:");
630                  break;
631              case OptionsCategory::COMMANDS:
632                  usage += HelpMessageGroup("Commands:");
633                  break;
634              case OptionsCategory::REGISTER_COMMANDS:
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  
659  bool HelpRequested(const ArgsManager& args)
660  {
661      return args.IsArgSet("-?") || args.IsArgSet("-h") || args.IsArgSet("-help") || args.IsArgSet("-help-debug");
662  }
663  
664  void SetupHelpOptions(ArgsManager& args)
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,' ') +
681             FormatParagraph(message, screenWidth - msgIndent, 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  
697  fs::path GetDefaultDataDir()
698  {
699      // Windows: C:\Users\Username\AppData\Roaming\Bitcoin
700      // macOS: ~/Library/Application Support/Bitcoin
701      // Unix-like: ~/.bitcoin
702  #ifdef WIN32
703      // Windows
704      return GetSpecialFolderPath(CSIDL_APPDATA) / "Bitcoin";
705  #else
706      fs::path pathRet;
707      char* pszHome = getenv("HOME");
708      if (pszHome == nullptr || strlen(pszHome) == 0)
709          pathRet = fs::path("/");
710      else
711          pathRet = fs::path(pszHome);
712  #ifdef MAC_OSX
713      // macOS
714      return pathRet / "Library/Application Support/Bitcoin";
715  #else
716      // Unix-like
717      return pathRet / ".bitcoin";
718  #endif
719  #endif
720  }
721  
722  bool CheckDataDirOption(const ArgsManager& args)
723  {
724      const fs::path datadir{args.GetPathArg("-datadir")};
725      return datadir.empty() || fs::is_directory(fs::absolute(datadir));
726  }
727  
728  fs::path ArgsManager::GetConfigFilePath() const
729  {
730      LOCK(cs_args);
731      return *Assert(m_config_path);
732  }
733  
734  void ArgsManager::SetConfigFilePath(fs::path path)
735  {
736      LOCK(cs_args);
737      assert(!m_config_path);
738      m_config_path = path;
739  }
740  
741  ChainType ArgsManager::GetChainType() const
742  {
743      std::variant<ChainType, std::string> arg = GetChainArg();
744      if (auto* parsed = std::get_if<ChainType>(&arg)) return *parsed;
745      throw std::runtime_error(strprintf("Unknown chain %s.", std::get<std::string>(arg)));
746  }
747  
748  std::string ArgsManager::GetChainTypeString() const
749  {
750      auto arg = GetChainArg();
751      if (auto* parsed = std::get_if<ChainType>(&arg)) return ChainTypeToString(*parsed);
752      return std::get<std::string>(arg);
753  }
754  
755  std::variant<ChainType, std::string> ArgsManager::GetChainArg() const
756  {
757      auto get_net = [&](const std::string& arg) {
758          LOCK(cs_args);
759          common::SettingsValue value = common::GetSetting(m_settings, /* section= */ "", SettingName(arg),
760              /* ignore_default_section_config= */ false,
761              /*ignore_nonpersistent=*/false,
762              /* get_chain_type= */ true);
763          return value.isNull() ? false : value.isBool() ? value.get_bool() : InterpretBool(value.get_str());
764      };
765  
766      const bool fRegTest = get_net("-regtest");
767      const bool fSigNet  = get_net("-signet");
768      const bool fTestNet = get_net("-testnet");
769      const auto chain_arg = GetArg("-chain");
770  
771      if ((int)chain_arg.has_value() + (int)fRegTest + (int)fSigNet + (int)fTestNet > 1) {
772          throw std::runtime_error("Invalid combination of -regtest, -signet, -testnet and -chain. Can use at most one.");
773      }
774      if (chain_arg) {
775          if (auto parsed = ChainTypeFromString(*chain_arg)) return *parsed;
776          // Not a known string, so return original string
777          return *chain_arg;
778      }
779      if (fRegTest) return ChainType::REGTEST;
780      if (fSigNet) return ChainType::SIGNET;
781      if (fTestNet) return ChainType::TESTNET;
782      return ChainType::MAIN;
783  }
784  
785  bool ArgsManager::UseDefaultSection(const std::string& arg) const
786  {
787      return m_network == ChainTypeToString(ChainType::MAIN) || m_network_only_args.count(arg) == 0;
788  }
789  
790  common::SettingsValue ArgsManager::GetSetting(const std::string& arg) const
791  {
792      LOCK(cs_args);
793      return common::GetSetting(
794          m_settings, m_network, SettingName(arg), !UseDefaultSection(arg),
795          /*ignore_nonpersistent=*/false, /*get_chain_type=*/false);
796  }
797  
798  std::vector<common::SettingsValue> ArgsManager::GetSettingsList(const std::string& arg) const
799  {
800      LOCK(cs_args);
801      return common::GetSettingsList(m_settings, m_network, SettingName(arg), !UseDefaultSection(arg));
802  }
803  
804  void ArgsManager::logArgsPrefix(
805      const std::string& prefix,
806      const std::string& section,
807      const std::map<std::string, std::vector<common::SettingsValue>>& args) const
808  {
809      std::string section_str = section.empty() ? "" : "[" + section + "] ";
810      for (const auto& arg : args) {
811          for (const auto& value : arg.second) {
812              std::optional<unsigned int> flags = GetArgFlags('-' + arg.first);
813              if (flags) {
814                  std::string value_str = (*flags & SENSITIVE) ? "****" : value.write();
815                  LogPrintf("%s %s%s=%s\n", prefix, section_str, arg.first, value_str);
816              }
817          }
818      }
819  }
820  
821  void ArgsManager::LogArgs() const
822  {
823      LOCK(cs_args);
824      for (const auto& section : m_settings.ro_config) {
825          logArgsPrefix("Config file arg:", section.first, section.second);
826      }
827      for (const auto& setting : m_settings.rw_settings) {
828          LogPrintf("Setting file arg: %s = %s\n", setting.first, setting.second.write());
829      }
830      logArgsPrefix("Command-line arg:", "", m_settings.command_line_options);
831  }
832  
833  namespace common {
834  #ifdef WIN32
835  WinCmdLineArgs::WinCmdLineArgs()
836  {
837      wchar_t** wargv = CommandLineToArgvW(GetCommandLineW(), &argc);
838      std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t> utf8_cvt;
839      argv = new char*[argc];
840      args.resize(argc);
841      for (int i = 0; i < argc; i++) {
842          args[i] = utf8_cvt.to_bytes(wargv[i]);
843          argv[i] = &*args[i].begin();
844      }
845      LocalFree(wargv);
846  }
847  
848  WinCmdLineArgs::~WinCmdLineArgs()
849  {
850      delete[] argv;
851  }
852  
853  std::pair<int, char**> WinCmdLineArgs::get()
854  {
855      return std::make_pair(argc, argv);
856  }
857  #endif
858  } // namespace common