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