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