Branch data Line data Source code
1 : : // Copyright (c) 2009-2010 Satoshi Nakamoto
2 : : // Copyright (c) 2009-present 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>
23 : : #include <shellapi.h>
24 : : #include <shlobj.h>
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 : :
39 : : const char * const BITCOIN_CONF_FILENAME = "bitcoin.conf";
40 : : const char * const BITCOIN_SETTINGS_FILENAME = "settings.json";
41 : :
42 : : ArgsManager gArgs;
43 : :
44 : : /**
45 : : * Interpret a string argument as a boolean.
46 : : *
47 : : * The definition of LocaleIndependentAtoi<int>() requires that non-numeric string values
48 : : * like "foo", return 0. This means that if a user unintentionally supplies a
49 : : * non-integer argument here, the return value is always false. This means that
50 : : * -foo=false does what the user probably expects, but -foo=true is well defined
51 : : * but does not do what they probably expected.
52 : : *
53 : : * The return value of LocaleIndependentAtoi<int>(...) is zero when given input not
54 : : * representable as an int.
55 : : *
56 : : * For a more extensive discussion of this topic (and a wide range of opinions
57 : : * on the Right Way to change this code), see PR12713.
58 : : */
59 : 336532 : static bool InterpretBool(const std::string& strValue)
60 : : {
61 [ + + ]: 336532 : if (strValue.empty())
62 : : return true;
63 [ - + ]: 328682 : return (LocaleIndependentAtoi<int>(strValue) != 0);
64 : : }
65 : :
66 : 1401349 : static std::string SettingName(const std::string& arg)
67 : : {
68 [ - + + - : 1402559 : return arg.size() > 0 && arg[0] == '-' ? arg.substr(1) : arg;
+ + ]
69 : : }
70 : :
71 : : /**
72 : : * Parse "name", "section.name", "noname", "section.noname" settings keys.
73 : : *
74 : : * @note Where an option was negated can be later checked using the
75 : : * IsArgNegated() method. One use case for this is to have a way to disable
76 : : * options that are not normally boolean (e.g. using -nodebuglogfile to request
77 : : * that debug log output is not sent to any file at all).
78 : : */
79 : 378556 : KeyInfo InterpretKey(std::string key)
80 : : {
81 [ + + ]: 378556 : KeyInfo result;
82 : : // Split section name from key name for keys like "testnet.foo" or "regtest.bar"
83 : 378556 : size_t option_index = key.find('.');
84 [ + + ]: 378556 : if (option_index != std::string::npos) {
85 [ + - ]: 133172 : result.section = key.substr(0, option_index);
86 [ + - ]: 133172 : key.erase(0, option_index + 1);
87 : : }
88 [ - + + + ]: 378556 : if (key.starts_with("no")) {
89 [ + - ]: 105576 : key.erase(0, 2);
90 : 105576 : result.negated = true;
91 : : }
92 [ + - ]: 378556 : result.name = key;
93 : 378556 : return result;
94 : 0 : }
95 : :
96 : : /**
97 : : * Interpret settings value based on registered flags.
98 : : *
99 : : * @param[in] key key information to know if key was negated
100 : : * @param[in] value string value of setting to be parsed
101 : : * @param[in] flags ArgsManager registered argument flags
102 : : * @param[out] error Error description if settings value is not valid
103 : : *
104 : : * @return parsed settings value if it is valid, otherwise nullopt accompanied
105 : : * by a descriptive error string
106 : : */
107 : 359363 : std::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 [ + + ]: 359363 : if (key.negated) {
112 [ - + ]: 105575 : if (flags & ArgsManager::DISALLOW_NEGATION) {
113 : 0 : error = strprintf("Negating of -%s is meaningless and therefore forbidden", key.name);
114 : 0 : return std::nullopt;
115 : : }
116 : : // Double negatives like -nofoo=0 are supported (but discouraged)
117 [ + + + + ]: 105575 : if (value && !InterpretBool(*value)) {
118 : 11 : LogPrintf("Warning: parsed potentially confusing double-negative -%s=%s\n", key.name, *value);
119 : 11 : return true;
120 : : }
121 : 105564 : return false;
122 : : }
123 [ + + + + ]: 253788 : if (!value && (flags & ArgsManager::DISALLOW_ELISION)) {
124 : 1 : error = strprintf("Can not set -%s with no value. Please specify value with -%s=value.", key.name, key.name);
125 : 1 : return std::nullopt;
126 : : }
127 [ + - ]: 253787 : return value ? *value : "";
128 : : }
129 : :
130 : : // Define default constructor and destructor that are not inline, so code instantiating this class doesn't need to
131 : : // #include class definitions for all members.
132 : : // For example, m_settings has an internal dependency on univalue.
133 : 52052 : ArgsManager::ArgsManager() = default;
134 [ + + ]: 260255 : ArgsManager::~ArgsManager() = default;
135 : :
136 : 49229 : std::set<std::string> ArgsManager::GetUnsuitableSectionOnlyArgs() const
137 : : {
138 [ + - ]: 49229 : std::set<std::string> unsuitables;
139 : :
140 [ + - ]: 49229 : LOCK(cs_args);
141 : :
142 : : // if there's no section selected, don't worry
143 [ - + ]: 49229 : 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 [ + - + + ]: 49229 : if (m_network == ChainTypeToString(ChainType::MAIN)) return std::set<std::string> {};
147 : :
148 [ + + ]: 64269 : for (const auto& arg : m_network_only_args) {
149 [ + - + - : 27448 : if (OnlyHasDefaultSectionSetting(m_settings, m_network, SettingName(arg))) {
+ + ]
150 [ + - ]: 1753 : unsuitables.insert(arg);
151 : : }
152 : : }
153 : 36821 : return unsuitables;
154 : 49229 : }
155 : :
156 : 1740 : std::list<SectionInfo> ArgsManager::GetUnrecognizedSections() const
157 : : {
158 : : // Section names to be recognized in the config file.
159 : 1740 : static const std::set<std::string> available_sections{
160 : : ChainTypeToString(ChainType::REGTEST),
161 : : ChainTypeToString(ChainType::SIGNET),
162 : : ChainTypeToString(ChainType::TESTNET),
163 : : ChainTypeToString(ChainType::TESTNET4),
164 : : ChainTypeToString(ChainType::MAIN),
165 [ + + + - : 9144 : };
- + + + -
- ]
166 : :
167 : 1740 : LOCK(cs_args);
168 [ + - ]: 1740 : std::list<SectionInfo> unrecognized = m_config_sections;
169 : 2856 : unrecognized.remove_if([](const SectionInfo& appeared){ return available_sections.find(appeared.m_name) != available_sections.end(); });
170 [ + - ]: 1740 : return unrecognized;
171 [ + - + - : 2974 : }
+ - + - +
- - - ]
172 : :
173 : 3382 : void ArgsManager::SelectConfigNetwork(const std::string& network)
174 : : {
175 : 3382 : LOCK(cs_args);
176 [ + - + - ]: 6764 : m_network = network;
177 : 3382 : }
178 : :
179 : 51984 : bool ArgsManager::ParseParameters(int argc, const char* const argv[], std::string& error)
180 : : {
181 : 51984 : LOCK(cs_args);
182 : 51984 : m_settings.command_line_options.clear();
183 : :
184 [ + + ]: 201046 : for (int i = 1; i < argc; i++) {
185 [ + - ]: 150872 : 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.starts_with("-psn_")) continue;
193 : : #endif
194 : :
195 [ + + ]: 150872 : if (key == "-") break; //bitcoin-tx using stdin
196 : 150860 : std::optional<std::string> val;
197 : 150860 : size_t is_index = key.find('=');
198 [ + + ]: 150860 : if (is_index != std::string::npos) {
199 [ + - ]: 138006 : val = key.substr(is_index + 1);
200 [ + - ]: 138006 : key.erase(is_index);
201 : : }
202 : : #ifdef WIN32
203 : : key = ToLower(key);
204 : : if (key[0] == '/')
205 : : key[0] = '-';
206 : : #endif
207 : :
208 [ + + ]: 150860 : if (key[0] != '-') {
209 [ + + + - ]: 1788 : if (!m_accept_any_command && m_command.empty()) {
210 : : // The first non-dash arg is a registered command
211 [ + - ]: 40 : std::optional<unsigned int> flags = GetArgFlags(key);
212 [ + + - + ]: 40 : if (!flags || !(*flags & ArgsManager::COMMAND)) {
213 [ + - ]: 4 : error = strprintf("Invalid command '%s'", argv[i]);
214 : 4 : return false;
215 : : }
216 : : }
217 [ + - ]: 1784 : m_command.push_back(key);
218 [ + + ]: 3140 : while (++i < argc) {
219 : : // The remaining args are command args
220 [ + - ]: 1356 : m_command.emplace_back(argv[i]);
221 : : }
222 : 1784 : break;
223 : : }
224 : :
225 : : // Transform --foo to -foo
226 [ - + + - : 149072 : if (key.length() > 1 && key[1] == '-')
+ + ]
227 [ + - ]: 6 : key.erase(0, 1);
228 : :
229 : : // Transform -foo to foo
230 [ + - ]: 149072 : key.erase(0, 1);
231 [ - + + - ]: 298144 : KeyInfo keyinfo = InterpretKey(key);
232 [ + - + - ]: 149072 : 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 [ + + + + ]: 149072 : if (!flags || !keyinfo.section.empty()) {
238 [ + - ]: 9 : error = strprintf("Invalid parameter %s", argv[i]);
239 : 9 : return false;
240 : : }
241 : :
242 [ + + + - ]: 160207 : std::optional<common::SettingsValue> value = InterpretValue(keyinfo, val ? &*val : nullptr, *flags, error);
243 [ + + ]: 149063 : if (!value) return false;
244 : :
245 [ + - + - ]: 149062 : m_settings.command_line_options[keyinfo.name].push_back(*value);
246 : 301729 : }
247 : :
248 : : // we do not allow -includeconf from command line, only -noincludeconf
249 [ + - + + ]: 51970 : if (auto* includes = common::FindKey(m_settings.command_line_options, "includeconf")) {
250 : 5 : const common::SettingsSpan values{*includes};
251 : : // Range may be empty if -noincludeconf was passed
252 [ + - + + ]: 5 : if (!values.empty()) {
253 [ + - + - : 4 : error = "-includeconf cannot be used from commandline; -includeconf=" + values.begin()->write();
+ - ]
254 : 4 : return false; // pick first value as example
255 : : }
256 : : }
257 : : return true;
258 : 51984 : }
259 : :
260 : 415771 : std::optional<unsigned int> ArgsManager::GetArgFlags(const std::string& name) const
261 : : {
262 : 415771 : LOCK(cs_args);
263 [ + + ]: 819560 : for (const auto& arg_map : m_available_args) {
264 : 800496 : const auto search = arg_map.second.find(name);
265 [ + + ]: 800496 : if (search != arg_map.second.end()) {
266 : 396707 : return search->second.m_flags;
267 : : }
268 : : }
269 : 19064 : return std::nullopt;
270 : 415771 : }
271 : :
272 : 29264 : fs::path ArgsManager::GetPathArg(std::string arg, const fs::path& default_value) const
273 : : {
274 [ + + ]: 29264 : if (IsArgNegated(arg)) return fs::path{};
275 [ + - ]: 29254 : std::string path_str = GetArg(arg, "");
276 [ + + + - ]: 42081 : if (path_str.empty()) return default_value;
277 [ + - + - ]: 38481 : fs::path result = fs::PathFromString(path_str).lexically_normal();
278 : : // Remove trailing slash, if present.
279 [ + + + - : 38481 : return result.has_filename() ? result : result.parent_path();
+ - ]
280 : 42081 : }
281 : :
282 : 8257 : fs::path ArgsManager::GetBlocksDirPath() const
283 : : {
284 : 8257 : LOCK(cs_args);
285 : 8257 : 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 [ + + + - ]: 8257 : if (!path.empty()) return path;
290 : :
291 [ + - + - : 1919 : if (IsArgSet("-blocksdir")) {
+ + ]
292 [ + - + - : 12 : path = fs::absolute(GetPathArg("-blocksdir"));
+ - ]
293 [ + - + + ]: 3 : if (!fs::is_directory(path)) {
294 [ + - ]: 1 : path = "";
295 [ + - ]: 1 : return path;
296 : : }
297 : : } else {
298 [ + - ]: 3832 : path = GetDataDirBase();
299 : : }
300 : :
301 [ + - + - ]: 3836 : path /= fs::PathFromString(BaseParams().DataDir());
302 [ + - ]: 1918 : path /= "blocks";
303 [ + - ]: 1918 : fs::create_directories(path);
304 [ + - + - ]: 8257 : return path;
305 : 8257 : }
306 : :
307 : 41180 : fs::path ArgsManager::GetDataDir(bool net_specific) const
308 : : {
309 : 41180 : LOCK(cs_args);
310 [ + + ]: 41180 : fs::path& path = net_specific ? m_cached_network_datadir_path : m_cached_datadir_path;
311 : :
312 : : // Used cached path if available
313 [ + + + - : 48363 : if (!path.empty()) return path;
+ - ]
314 : :
315 [ + - + - ]: 14366 : const fs::path datadir{GetPathArg("-datadir")};
316 [ + + ]: 7183 : if (!datadir.empty()) {
317 [ + - ]: 14356 : path = fs::absolute(datadir);
318 [ + - - + ]: 7178 : if (!fs::is_directory(path)) {
319 [ # # ]: 0 : path = "";
320 [ # # ]: 0 : return path;
321 : : }
322 : : } else {
323 [ + - ]: 15 : path = GetDefaultDataDir();
324 : : }
325 : :
326 [ + + + - : 7183 : if (net_specific && !BaseParams().DataDir().empty()) {
+ + ]
327 [ + - + - ]: 7101 : path /= fs::PathFromString(BaseParams().DataDir());
328 : : }
329 : :
330 [ + - ]: 7183 : return path;
331 : 48363 : }
332 : :
333 : 2819 : void ArgsManager::ClearPathCache()
334 : : {
335 : 2819 : LOCK(cs_args);
336 : :
337 : 2819 : m_cached_datadir_path = fs::path();
338 : 2819 : m_cached_network_datadir_path = fs::path();
339 [ + - ]: 5638 : m_cached_blocks_path = fs::path();
340 : 2819 : }
341 : :
342 : 37 : std::optional<const ArgsManager::Command> ArgsManager::GetCommand() const
343 : : {
344 [ + - ]: 37 : Command ret;
345 [ + - ]: 37 : LOCK(cs_args);
346 [ + + ]: 37 : auto it = m_command.begin();
347 [ + + ]: 37 : if (it == m_command.end()) {
348 : : // No command was passed
349 : 1 : return std::nullopt;
350 : : }
351 [ + - ]: 36 : if (!m_accept_any_command) {
352 : : // The registered command
353 [ + - ]: 36 : ret.command = *(it++);
354 : : }
355 [ + + ]: 46 : while (it != m_command.end()) {
356 : : // The unregistered command and args (if any)
357 [ + - ]: 10 : ret.args.push_back(*(it++));
358 : : }
359 : 36 : return ret;
360 : 74 : }
361 : :
362 : 173036 : std::vector<std::string> ArgsManager::GetArgs(const std::string& strArg) const
363 : : {
364 : 173036 : std::vector<std::string> result;
365 [ + - + + ]: 268385 : for (const common::SettingsValue& value : GetSettingsList(strArg)) {
366 [ - + - - : 286043 : result.push_back(value.isFalse() ? "0" : value.isTrue() ? "1" : value.get_str());
+ + + - +
- - + +
- ]
367 : : }
368 : 173036 : return result;
369 : 0 : }
370 : :
371 : 134331 : bool ArgsManager::IsArgSet(const std::string& strArg) const
372 : : {
373 : 134331 : return !GetSetting(strArg).isNull();
374 : : }
375 : :
376 : 4874 : bool ArgsManager::GetSettingsPath(fs::path* filepath, bool temp, bool backup) const
377 : : {
378 [ + - + - ]: 9748 : fs::path settings = GetPathArg("-settings", BITCOIN_SETTINGS_FILENAME);
379 [ + + ]: 4874 : if (settings.empty()) {
380 : : return false;
381 : : }
382 [ - + ]: 4871 : if (backup) {
383 [ # # ]: 0 : settings += ".bak";
384 : : }
385 [ + + ]: 4871 : if (filepath) {
386 [ + + + - : 25112 : *filepath = fsbridge::AbsPathJoin(GetDataDirNet(), temp ? settings + ".tmp" : settings);
+ - + - +
+ - - ]
387 : : }
388 : : return true;
389 : 4874 : }
390 : :
391 : 4 : static void SaveErrors(const std::vector<std::string> errors, std::vector<std::string>* error_out)
392 : : {
393 [ + + ]: 8 : for (const auto& error : errors) {
394 [ + + ]: 4 : if (error_out) {
395 : 3 : error_out->emplace_back(error);
396 : : } else {
397 : 1 : LogPrintf("%s\n", error);
398 : : }
399 : : }
400 : 4 : }
401 : :
402 : 1124 : bool ArgsManager::ReadSettingsFile(std::vector<std::string>* errors)
403 : : {
404 : 1124 : fs::path path;
405 [ + - + - ]: 1124 : if (!GetSettingsPath(&path, /* temp= */ false)) {
406 : : return true; // Do nothing if settings file disabled.
407 : : }
408 : :
409 [ + - ]: 1124 : LOCK(cs_args);
410 : 1124 : m_settings.rw_settings.clear();
411 : 1124 : std::vector<std::string> read_errors;
412 [ + - + + ]: 1124 : if (!common::ReadSettings(path, m_settings.rw_settings, read_errors)) {
413 [ + - + - ]: 3 : SaveErrors(read_errors, errors);
414 : 3 : return false;
415 : : }
416 [ + + ]: 1258 : for (const auto& setting : m_settings.rw_settings) {
417 [ - + + - ]: 274 : KeyInfo key = InterpretKey(setting.first); // Split setting key into section and argname
418 [ + - + - : 137 : if (!GetArgFlags('-' + key.name)) {
+ + ]
419 [ + - ]: 7 : LogPrintf("Ignoring unknown rw_settings value %s\n", setting.first);
420 : : }
421 : 137 : }
422 : : return true;
423 [ + - ]: 3372 : }
424 : :
425 : 1312 : bool ArgsManager::WriteSettingsFile(std::vector<std::string>* errors, bool backup) const
426 : : {
427 : 1312 : fs::path path, path_tmp;
428 [ + - + - : 1312 : if (!GetSettingsPath(&path, /*temp=*/false, backup) || !GetSettingsPath(&path_tmp, /*temp=*/true, backup)) {
+ - - + ]
429 [ # # ]: 0 : throw std::logic_error("Attempt to write settings file when dynamic settings are disabled.");
430 : : }
431 : :
432 [ + - ]: 1312 : LOCK(cs_args);
433 : 1312 : std::vector<std::string> write_errors;
434 [ + - - + ]: 1312 : if (!common::WriteSettings(path_tmp, m_settings.rw_settings, write_errors)) {
435 [ # # # # ]: 0 : SaveErrors(write_errors, errors);
436 : 0 : return false;
437 : : }
438 [ + - + - : 3936 : if (!RenameOver(path_tmp, path)) {
+ - + + ]
439 [ - + + - : 4 : SaveErrors({strprintf("Failed renaming settings file %s to %s\n", fs::PathToString(path_tmp), fs::PathToString(path))}, errors);
+ - + + -
- ]
440 : 1 : return false;
441 : : }
442 : : return true;
443 [ - + + - : 5250 : }
+ - ]
444 : :
445 : 0 : common::SettingsValue ArgsManager::GetPersistentSetting(const std::string& name) const
446 : : {
447 : 0 : LOCK(cs_args);
448 [ # # # # : 0 : return common::GetSetting(m_settings, m_network, name, !UseDefaultSection("-" + name),
# # ]
449 [ # # ]: 0 : /*ignore_nonpersistent=*/true, /*get_chain_type=*/false);
450 : 0 : }
451 : :
452 : 81841 : bool ArgsManager::IsArgNegated(const std::string& strArg) const
453 : : {
454 : 81841 : return GetSetting(strArg).isFalse();
455 : : }
456 : :
457 : 90795 : std::string ArgsManager::GetArg(const std::string& strArg, const std::string& strDefault) const
458 : : {
459 [ + - ]: 181588 : return GetArg(strArg).value_or(strDefault);
460 : : }
461 : :
462 : 167133 : std::optional<std::string> ArgsManager::GetArg(const std::string& strArg) const
463 : : {
464 : 167133 : const common::SettingsValue value = GetSetting(strArg);
465 [ + + ]: 334264 : return SettingToString(value);
466 : 167133 : }
467 : :
468 : 167133 : std::optional<std::string> SettingToString(const common::SettingsValue& value)
469 : : {
470 [ + + ]: 167133 : if (value.isNull()) return std::nullopt;
471 [ + + ]: 64987 : if (value.isFalse()) return "0";
472 [ + + ]: 53275 : if (value.isTrue()) return "1";
473 [ + + - + ]: 53270 : if (value.isNum()) return value.getValStr();
474 [ - + ]: 106526 : return value.get_str();
475 : : }
476 : :
477 : 0 : std::string SettingToString(const common::SettingsValue& value, const std::string& strDefault)
478 : : {
479 [ # # ]: 0 : return SettingToString(value).value_or(strDefault);
480 : : }
481 : :
482 : 171016 : int64_t ArgsManager::GetIntArg(const std::string& strArg, int64_t nDefault) const
483 : : {
484 [ + + ]: 171016 : return GetIntArg(strArg).value_or(nDefault);
485 : : }
486 : :
487 : 201619 : std::optional<int64_t> ArgsManager::GetIntArg(const std::string& strArg) const
488 : : {
489 : 201619 : const common::SettingsValue value = GetSetting(strArg);
490 [ + + ]: 403235 : return SettingToInt(value);
491 : 201619 : }
492 : :
493 : 201619 : std::optional<int64_t> SettingToInt(const common::SettingsValue& value)
494 : : {
495 [ + + ]: 201619 : if (value.isNull()) return std::nullopt;
496 [ + + ]: 8465 : if (value.isFalse()) return 0;
497 [ + + ]: 8460 : if (value.isTrue()) return 1;
498 [ + + ]: 8457 : if (value.isNum()) return value.getInt<int64_t>();
499 [ - + ]: 8454 : return LocaleIndependentAtoi<int64_t>(value.get_str());
500 : : }
501 : :
502 : 0 : int64_t SettingToInt(const common::SettingsValue& value, int64_t nDefault)
503 : : {
504 [ # # ]: 0 : return SettingToInt(value).value_or(nDefault);
505 : : }
506 : :
507 : 505506 : bool ArgsManager::GetBoolArg(const std::string& strArg, bool fDefault) const
508 : : {
509 [ + + ]: 505506 : return GetBoolArg(strArg).value_or(fDefault);
510 : : }
511 : :
512 : 524399 : std::optional<bool> ArgsManager::GetBoolArg(const std::string& strArg) const
513 : : {
514 : 524399 : const common::SettingsValue value = GetSetting(strArg);
515 [ + + ]: 1048788 : return SettingToBool(value);
516 : 524399 : }
517 : :
518 : 524399 : std::optional<bool> SettingToBool(const common::SettingsValue& value)
519 : : {
520 [ + + ]: 524399 : if (value.isNull()) return std::nullopt;
521 [ + + ]: 225091 : if (value.isBool()) return value.get_bool();
522 : 223510 : return InterpretBool(value.get_str());
523 : : }
524 : :
525 : 0 : bool SettingToBool(const common::SettingsValue& value, bool fDefault)
526 : : {
527 [ # # ]: 0 : return SettingToBool(value).value_or(fDefault);
528 : : }
529 : :
530 : 52137 : bool ArgsManager::SoftSetArg(const std::string& strArg, const std::string& strValue)
531 : : {
532 : 52137 : LOCK(cs_args);
533 [ + - + + ]: 52137 : if (IsArgSet(strArg)) return false;
534 [ + - ]: 1922 : ForceSetArg(strArg, strValue);
535 : : return true;
536 : 52137 : }
537 : :
538 : 4641 : bool ArgsManager::SoftSetBoolArg(const std::string& strArg, bool fValue)
539 : : {
540 [ + + ]: 4641 : if (fValue)
541 [ + - ]: 2221 : return SoftSetArg(strArg, std::string("1"));
542 : : else
543 [ + - ]: 2420 : return SoftSetArg(strArg, std::string("0"));
544 : : }
545 : :
546 : 51311 : void ArgsManager::ForceSetArg(const std::string& strArg, const std::string& strValue)
547 : : {
548 : 51311 : LOCK(cs_args);
549 [ + - + - : 51311 : m_settings.forced_settings[SettingName(strArg)] = strValue;
+ - + - ]
550 : 51311 : }
551 : :
552 : 147 : void ArgsManager::AddCommand(const std::string& cmd, const std::string& help)
553 : : {
554 : 147 : Assert(cmd.find('=') == std::string::npos);
555 : 147 : Assert(cmd.at(0) != '-');
556 : :
557 : 147 : LOCK(cs_args);
558 : 147 : m_accept_any_command = false; // latch to false
559 [ + - ]: 147 : std::map<std::string, Arg>& arg_map = m_available_args[OptionsCategory::COMMANDS];
560 [ + - - + : 294 : auto ret = arg_map.emplace(cmd, Arg{"", help, ArgsManager::COMMAND});
+ - ]
561 [ + - ]: 147 : Assert(ret.second); // Fail on duplicate commands
562 : 147 : }
563 : :
564 : 428915 : void ArgsManager::AddArg(const std::string& name, const std::string& help, unsigned int flags, const OptionsCategory& cat)
565 : : {
566 : 428915 : Assert((flags & ArgsManager::COMMAND) == 0); // use AddCommand
567 : :
568 : : // Split arg name from its help param
569 : 428915 : size_t eq_index = name.find('=');
570 [ + + ]: 428915 : if (eq_index == std::string::npos) {
571 [ - + ]: 222052 : eq_index = name.size();
572 : : }
573 : 428915 : std::string arg_name = name.substr(0, eq_index);
574 : :
575 [ + - ]: 428915 : LOCK(cs_args);
576 [ + - ]: 428915 : std::map<std::string, Arg>& arg_map = m_available_args[cat];
577 [ - + + - : 857830 : auto ret = arg_map.emplace(arg_name, Arg{name.substr(eq_index, name.size() - eq_index), help, flags});
- + + - ]
578 [ - + ]: 428915 : assert(ret.second); // Make sure an insertion actually happened
579 : :
580 [ + + ]: 428915 : if (flags & ArgsManager::NETWORK_ONLY) {
581 [ + - ]: 15301 : m_network_only_args.emplace(arg_name);
582 : : }
583 : 428915 : }
584 : :
585 : 4758 : void ArgsManager::AddHiddenArgs(const std::vector<std::string>& names)
586 : : {
587 [ + + ]: 24930 : for (const std::string& name : names) {
588 [ + - ]: 40344 : AddArg(name, "", ArgsManager::ALLOW_ANY, OptionsCategory::HIDDEN);
589 : : }
590 : 4758 : }
591 : :
592 : 619 : void ArgsManager::ClearArgs()
593 : : {
594 : 619 : LOCK(cs_args);
595 : 619 : m_settings = {};
596 : 619 : m_available_args.clear();
597 [ + - ]: 619 : m_network_only_args.clear();
598 : 619 : }
599 : :
600 : 1058 : void ArgsManager::CheckMultipleCLIArgs() const
601 : : {
602 : 1058 : LOCK(cs_args);
603 : 1058 : std::vector<std::string> found{};
604 : 1058 : auto cmds = m_available_args.find(OptionsCategory::CLI_COMMANDS);
605 [ + - ]: 1058 : if (cmds != m_available_args.end()) {
606 [ + - + + ]: 5290 : for (const auto& [cmd, argspec] : cmds->second) {
607 [ + - + + ]: 4232 : if (IsArgSet(cmd)) {
608 [ + - ]: 42 : found.push_back(cmd);
609 : : }
610 : : }
611 [ - + + + ]: 1058 : if (found.size() > 1) {
612 [ + - + - : 2 : throw std::runtime_error(strprintf("Only one of %s may be specified.", util::Join(found, ", ")));
+ - ]
613 : : }
614 : : }
615 [ + - ]: 2115 : }
616 : :
617 : 1 : std::string ArgsManager::GetHelpMessage() const
618 : : {
619 [ + - ]: 1 : const bool show_debug = GetBoolArg("-help-debug", false);
620 : :
621 [ + - ]: 1 : std::string usage;
622 [ + - ]: 1 : LOCK(cs_args);
623 [ + - ]: 11 : for (const auto& arg_map : m_available_args) {
624 [ + + + + : 11 : switch(arg_map.first) {
+ + + - +
+ + - - -
- + ]
625 : 1 : case OptionsCategory::OPTIONS:
626 [ + - + - ]: 2 : usage += HelpMessageGroup("Options:");
627 : 1 : break;
628 : 1 : case OptionsCategory::CONNECTION:
629 [ + - + - ]: 2 : usage += HelpMessageGroup("Connection options:");
630 : 1 : break;
631 : 1 : case OptionsCategory::ZMQ:
632 [ + - + - ]: 2 : usage += HelpMessageGroup("ZeroMQ notification options:");
633 : 1 : break;
634 : 1 : case OptionsCategory::DEBUG_TEST:
635 [ + - + - ]: 2 : usage += HelpMessageGroup("Debugging/Testing options:");
636 : 1 : break;
637 : 1 : case OptionsCategory::NODE_RELAY:
638 [ + - + - ]: 2 : usage += HelpMessageGroup("Node relay options:");
639 : 1 : break;
640 : 1 : case OptionsCategory::BLOCK_CREATION:
641 [ + - + - ]: 2 : usage += HelpMessageGroup("Block creation options:");
642 : 1 : break;
643 : 1 : case OptionsCategory::RPC:
644 [ + - + - ]: 2 : usage += HelpMessageGroup("RPC server options:");
645 : 1 : break;
646 : 0 : case OptionsCategory::IPC:
647 [ # # # # ]: 0 : usage += HelpMessageGroup("IPC interprocess connection options:");
648 : 0 : break;
649 : 1 : case OptionsCategory::WALLET:
650 [ + - + - ]: 2 : usage += HelpMessageGroup("Wallet options:");
651 : 1 : break;
652 : 1 : case OptionsCategory::WALLET_DEBUG_TEST:
653 [ - + - - : 1 : if (show_debug) usage += HelpMessageGroup("Wallet debugging/testing options:");
- - ]
654 : : break;
655 : 1 : case OptionsCategory::CHAINPARAMS:
656 [ + - + - ]: 2 : usage += HelpMessageGroup("Chain selection options:");
657 : 1 : break;
658 : 0 : case OptionsCategory::GUI:
659 [ # # # # ]: 0 : usage += HelpMessageGroup("UI Options:");
660 : 0 : break;
661 : 0 : case OptionsCategory::COMMANDS:
662 [ # # # # ]: 0 : usage += HelpMessageGroup("Commands:");
663 : 0 : break;
664 : 0 : case OptionsCategory::REGISTER_COMMANDS:
665 [ # # # # ]: 0 : usage += HelpMessageGroup("Register Commands:");
666 : 0 : break;
667 : 0 : case OptionsCategory::CLI_COMMANDS:
668 [ # # # # ]: 0 : usage += HelpMessageGroup("CLI Commands:");
669 : 0 : break;
670 : : default:
671 : : break;
672 : : }
673 : :
674 : : // When we get to the hidden options, stop
675 [ + + ]: 11 : if (arg_map.first == OptionsCategory::HIDDEN) break;
676 : :
677 [ + + ]: 190 : for (const auto& arg : arg_map.second) {
678 [ + - + + ]: 180 : if (show_debug || !(arg.second.m_flags & ArgsManager::DEBUG_ONLY)) {
679 [ + + ]: 139 : std::string name;
680 [ + + ]: 139 : if (arg.second.m_help_param.empty()) {
681 [ + - ]: 57 : name = arg.first;
682 : : } else {
683 [ + - ]: 82 : name = arg.first + arg.second.m_help_param;
684 : : }
685 [ + - ]: 278 : usage += HelpMessageOpt(name, arg.second.m_help_text);
686 : 139 : }
687 : : }
688 : : }
689 [ + - ]: 1 : return usage;
690 : 1 : }
691 : :
692 : 2321 : bool HelpRequested(const ArgsManager& args)
693 : : {
694 [ + - + - : 11603 : return args.IsArgSet("-?") || args.IsArgSet("-h") || args.IsArgSet("-help") || args.IsArgSet("-help-debug");
+ - + - +
- + + + -
+ - + - +
- + - + -
+ + + - -
- - - -
- ]
695 : : }
696 : :
697 : 2982 : void SetupHelpOptions(ArgsManager& args)
698 : : {
699 [ + - + - ]: 5964 : args.AddArg("-help", "Print this help message and exit (also -h or -?)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
700 [ + - ]: 2982 : args.AddHiddenArgs({"-h", "-?"});
701 : 2982 : }
702 : :
703 : : static const int screenWidth = 79;
704 : : static const int optIndent = 2;
705 : : static const int msgIndent = 7;
706 : :
707 : 9 : std::string HelpMessageGroup(const std::string &message) {
708 [ + - ]: 27 : return std::string(message) + std::string("\n\n");
709 : : }
710 : :
711 : 139 : std::string HelpMessageOpt(const std::string &option, const std::string &message) {
712 [ + - + - ]: 278 : return std::string(optIndent,' ') + std::string(option) +
713 [ + - + - : 556 : std::string("\n") + std::string(msgIndent,' ') +
+ - ]
714 [ + - + - ]: 417 : FormatParagraph(message, screenWidth - msgIndent, msgIndent) +
715 [ + - ]: 417 : std::string("\n\n");
716 : : }
717 : :
718 : : const std::vector<std::string> TEST_OPTIONS_DOC{
719 : : "addrman (use deterministic addrman)",
720 : : "reindex_after_failure_noninteractive_yes (When asked for a reindex after failure interactively, simulate as-if answered with 'yes')",
721 : : "bip94 (enforce BIP94 consensus rules)",
722 : : };
723 : :
724 : 4167 : bool HasTestOption(const ArgsManager& args, const std::string& test_option)
725 : : {
726 [ + - ]: 4167 : const auto options = args.GetArgs("-test");
727 [ - + - + : 50004 : return std::any_of(options.begin(), options.end(), [test_option](const auto& option) {
- + + - -
+ + - - +
+ - - + +
- ]
728 [ + + ]: 25 : return option == test_option;
729 : 4167 : });
730 : 4167 : }
731 : :
732 : 1099 : fs::path GetDefaultDataDir()
733 : : {
734 : : // Windows:
735 : : // old: C:\Users\Username\AppData\Roaming\Bitcoin
736 : : // new: C:\Users\Username\AppData\Local\Bitcoin
737 : : // macOS: ~/Library/Application Support/Bitcoin
738 : : // Unix-like: ~/.bitcoin
739 : : #ifdef WIN32
740 : : // Windows
741 : : // Check for existence of datadir in old location and keep it there
742 : : fs::path legacy_path = GetSpecialFolderPath(CSIDL_APPDATA) / "Bitcoin";
743 : : if (fs::exists(legacy_path)) return legacy_path;
744 : :
745 : : // Otherwise, fresh installs can start in the new, "proper" location
746 : : return GetSpecialFolderPath(CSIDL_LOCAL_APPDATA) / "Bitcoin";
747 : : #else
748 : 1099 : fs::path pathRet;
749 : 1099 : char* pszHome = getenv("HOME");
750 [ + - - + ]: 1099 : if (pszHome == nullptr || strlen(pszHome) == 0)
751 [ # # ]: 0 : pathRet = fs::path("/");
752 : : else
753 [ + - ]: 2198 : pathRet = fs::path(pszHome);
754 : : #ifdef __APPLE__
755 : : // macOS
756 : : return pathRet / "Library/Application Support/Bitcoin";
757 : : #else
758 : : // Unix-like
759 [ + - + - ]: 3297 : return pathRet / ".bitcoin";
760 : : #endif
761 : : #endif
762 : 1099 : }
763 : :
764 : 4431 : bool CheckDataDirOption(const ArgsManager& args)
765 : : {
766 [ + - + - ]: 8862 : const fs::path datadir{args.GetPathArg("-datadir")};
767 [ + + + - : 8857 : return datadir.empty() || fs::is_directory(fs::absolute(datadir));
+ - + + ]
768 : 4431 : }
769 : :
770 : 3302 : fs::path ArgsManager::GetConfigFilePath() const
771 : : {
772 : 3302 : LOCK(cs_args);
773 [ + - + - : 3302 : return *Assert(m_config_path);
+ - ]
774 : 3302 : }
775 : :
776 : 1 : void ArgsManager::SetConfigFilePath(fs::path path)
777 : : {
778 : 1 : LOCK(cs_args);
779 [ - + ]: 1 : assert(!m_config_path);
780 [ + - ]: 1 : m_config_path = path;
781 : 1 : }
782 : :
783 : 4076 : ChainType ArgsManager::GetChainType() const
784 : : {
785 : 4076 : std::variant<ChainType, std::string> arg = GetChainArg();
786 [ + - ]: 4076 : if (auto* parsed = std::get_if<ChainType>(&arg)) return *parsed;
787 [ # # # # : 0 : throw std::runtime_error(strprintf("Unknown chain %s.", std::get<std::string>(arg)));
# # ]
788 : 4076 : }
789 : :
790 : 5787 : std::string ArgsManager::GetChainTypeString() const
791 : : {
792 : 5787 : auto arg = GetChainArg();
793 [ + - + - ]: 5600 : if (auto* parsed = std::get_if<ChainType>(&arg)) return ChainTypeToString(*parsed);
794 [ - - - - ]: 5600 : return std::get<std::string>(arg);
795 : 5600 : }
796 : :
797 : 9863 : std::variant<ChainType, std::string> ArgsManager::GetChainArg() const
798 : : {
799 : 49315 : auto get_net = [&](const std::string& arg) {
800 : 39452 : LOCK(cs_args);
801 [ + - + - ]: 78904 : common::SettingsValue value = common::GetSetting(m_settings, /* section= */ "", SettingName(arg),
802 : : /* ignore_default_section_config= */ false,
803 : : /*ignore_nonpersistent=*/false,
804 [ + - ]: 39452 : /* get_chain_type= */ true);
805 [ + + - + : 39452 : return value.isNull() ? false : value.isBool() ? value.get_bool() : InterpretBool(value.get_str());
- - + - +
- ]
806 [ + - ]: 78904 : };
807 : :
808 [ + - ]: 9863 : const bool fRegTest = get_net("-regtest");
809 [ + - ]: 9863 : const bool fSigNet = get_net("-signet");
810 [ + - ]: 9863 : const bool fTestNet = get_net("-testnet");
811 [ + - ]: 9863 : const bool fTestNet4 = get_net("-testnet4");
812 [ + - ]: 9863 : const auto chain_arg = GetArg("-chain");
813 : :
814 [ + + ]: 9863 : if ((int)chain_arg.has_value() + (int)fRegTest + (int)fSigNet + (int)fTestNet + (int)fTestNet4 > 1) {
815 [ + - ]: 187 : throw std::runtime_error("Invalid combination of -regtest, -signet, -testnet, -testnet4 and -chain. Can use at most one.");
816 : : }
817 [ + + ]: 9676 : if (chain_arg) {
818 [ - + + - : 28 : if (auto parsed = ChainTypeFromString(*chain_arg)) return *parsed;
+ - ]
819 : : // Not a known string, so return original string
820 [ # # ]: 0 : return *chain_arg;
821 : : }
822 [ + + ]: 9648 : if (fRegTest) return ChainType::REGTEST;
823 [ + + ]: 1771 : if (fSigNet) return ChainType::SIGNET;
824 [ + + ]: 1644 : if (fTestNet) return ChainType::TESTNET;
825 [ + + ]: 1636 : if (fTestNet4) return ChainType::TESTNET4;
826 : 1298 : return ChainType::MAIN;
827 : 9676 : }
828 : :
829 : 1283138 : bool ArgsManager::UseDefaultSection(const std::string& arg) const
830 : : {
831 [ + + + + ]: 1283138 : return m_network == ChainTypeToString(ChainType::MAIN) || m_network_only_args.count(arg) == 0;
832 : : }
833 : :
834 : 1109349 : common::SettingsValue ArgsManager::GetSetting(const std::string& arg) const
835 : : {
836 : 1109349 : LOCK(cs_args);
837 : 1109349 : return common::GetSetting(
838 [ + - + - ]: 2218698 : m_settings, m_network, SettingName(arg), !UseDefaultSection(arg),
839 [ + - + - ]: 1109349 : /*ignore_nonpersistent=*/false, /*get_chain_type=*/false);
840 : 1109349 : }
841 : :
842 : 173789 : std::vector<common::SettingsValue> ArgsManager::GetSettingsList(const std::string& arg) const
843 : : {
844 : 173789 : LOCK(cs_args);
845 [ + - + - : 347578 : return common::GetSettingsList(m_settings, m_network, SettingName(arg), !UseDefaultSection(arg));
+ - + - ]
846 : 173789 : }
847 : :
848 : 3275 : void ArgsManager::logArgsPrefix(
849 : : const std::string& prefix,
850 : : const std::string& section,
851 : : const std::map<std::string, std::vector<common::SettingsValue>>& args) const
852 : : {
853 [ + + + - ]: 4364 : std::string section_str = section.empty() ? "" : "[" + section + "] ";
854 [ + + ]: 38096 : for (const auto& arg : args) {
855 [ + + ]: 71996 : for (const auto& value : arg.second) {
856 [ + - + - ]: 37175 : std::optional<unsigned int> flags = GetArgFlags('-' + arg.first);
857 [ + - ]: 37175 : if (flags) {
858 [ + + + - : 37175 : std::string value_str = (*flags & SENSITIVE) ? "****" : value.write();
+ - ]
859 [ + - ]: 37175 : LogPrintf("%s %s%s=%s\n", prefix, section_str, arg.first, value_str);
860 : 37175 : }
861 : : }
862 : : }
863 : 3275 : }
864 : :
865 : 1095 : void ArgsManager::LogArgs() const
866 : : {
867 : 1095 : LOCK(cs_args);
868 [ + + ]: 3275 : for (const auto& section : m_settings.ro_config) {
869 [ + - + - ]: 4360 : logArgsPrefix("Config file arg:", section.first, section.second);
870 : : }
871 [ + + ]: 1227 : for (const auto& setting : m_settings.rw_settings) {
872 [ + - + - ]: 264 : LogPrintf("Setting file arg: %s = %s\n", setting.first, setting.second.write());
873 : : }
874 [ + - + - : 2190 : logArgsPrefix("Command-line arg:", "", m_settings.command_line_options);
+ - + - ]
875 : 1095 : }
876 : :
877 : : namespace common {
878 : : #ifdef WIN32
879 : : WinCmdLineArgs::WinCmdLineArgs()
880 : : {
881 : : wchar_t** wargv = CommandLineToArgvW(GetCommandLineW(), &argc);
882 : : std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t> utf8_cvt;
883 : : argv = new char*[argc];
884 : : args.resize(argc);
885 : : for (int i = 0; i < argc; i++) {
886 : : args[i] = utf8_cvt.to_bytes(wargv[i]);
887 : : argv[i] = &*args[i].begin();
888 : : }
889 : : LocalFree(wargv);
890 : : }
891 : :
892 : : WinCmdLineArgs::~WinCmdLineArgs()
893 : : {
894 : : delete[] argv;
895 : : }
896 : :
897 : : std::pair<int, char**> WinCmdLineArgs::get()
898 : : {
899 : : return std::make_pair(argc, argv);
900 : : }
901 : : #endif
902 : : } // namespace common
|