Branch data Line data Source code
1 : : // Copyright (c) 2009-2010 Satoshi Nakamoto
2 : : // Copyright (c) 2009-2022 The Bitcoin Core developers
3 : : // Distributed under the MIT software license, see the accompanying
4 : : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 : :
6 : : #include <common/args.h>
7 : :
8 : : #include <chainparamsbase.h>
9 : : #include <common/settings.h>
10 : : #include <logging.h>
11 : : #include <sync.h>
12 : : #include <tinyformat.h>
13 : : #include <univalue.h>
14 : : #include <util/chaintype.h>
15 : : #include <util/check.h>
16 : : #include <util/fs.h>
17 : : #include <util/fs_helpers.h>
18 : : #include <util/strencodings.h>
19 : :
20 : : #ifdef WIN32
21 : : #include <codecvt> /* for codecvt_utf8_utf16 */
22 : : #include <shellapi.h> /* for CommandLineToArgvW */
23 : : #include <shlobj.h> /* for CSIDL_APPDATA */
24 : : #endif
25 : :
26 : : #include <algorithm>
27 : : #include <cassert>
28 : : #include <cstdint>
29 : : #include <cstdlib>
30 : : #include <cstring>
31 : : #include <map>
32 : : #include <optional>
33 : : #include <stdexcept>
34 : : #include <string>
35 : : #include <utility>
36 : : #include <variant>
37 : :
38 : : const char * const BITCOIN_CONF_FILENAME = "bitcoin.conf";
39 : : const char * const BITCOIN_SETTINGS_FILENAME = "settings.json";
40 : :
41 : : ArgsManager gArgs;
42 : :
43 : : /**
44 : : * Interpret a string argument as a boolean.
45 : : *
46 : : * The definition of LocaleIndependentAtoi<int>() requires that non-numeric string values
47 : : * like "foo", return 0. This means that if a user unintentionally supplies a
48 : : * non-integer argument here, the return value is always false. This means that
49 : : * -foo=false does what the user probably expects, but -foo=true is well defined
50 : : * but does not do what they probably expected.
51 : : *
52 : : * The return value of LocaleIndependentAtoi<int>(...) is zero when given input not
53 : : * representable as an int.
54 : : *
55 : : * For a more extensive discussion of this topic (and a wide range of opinions
56 : : * on the Right Way to change this code), see PR12713.
57 : : */
58 : 107887 : static bool InterpretBool(const std::string& strValue)
59 : : {
60 [ + + ]: 107887 : if (strValue.empty())
61 : : return true;
62 : 105995 : return (LocaleIndependentAtoi<int>(strValue) != 0);
63 : : }
64 : :
65 : 366501 : static std::string SettingName(const std::string& arg)
66 : : {
67 [ + - + + ]: 366501 : return arg.size() > 0 && arg[0] == '-' ? arg.substr(1) : arg;
68 : : }
69 : :
70 : : /**
71 : : * Parse "name", "section.name", "noname", "section.noname" settings keys.
72 : : *
73 : : * @note Where an option was negated can be later checked using the
74 : : * IsArgNegated() method. One use case for this is to have a way to disable
75 : : * options that are not normally boolean (e.g. using -nodebuglogfile to request
76 : : * that debug log output is not sent to any file at all).
77 : : */
78 : 314773 : KeyInfo InterpretKey(std::string key)
79 : : {
80 [ + + ]: 314773 : KeyInfo result;
81 : : // Split section name from key name for keys like "testnet.foo" or "regtest.bar"
82 : 314773 : size_t option_index = key.find('.');
83 [ + + ]: 314773 : if (option_index != std::string::npos) {
84 [ + - ]: 91409 : result.section = key.substr(0, option_index);
85 [ + - ]: 91409 : key.erase(0, option_index + 1);
86 : : }
87 [ + - + + ]: 314773 : if (key.substr(0, 2) == "no") {
88 [ + - ]: 103295 : key.erase(0, 2);
89 : 103295 : result.negated = true;
90 : : }
91 [ + - ]: 314773 : result.name = key;
92 : 314773 : return result;
93 : 0 : }
94 : :
95 : : /**
96 : : * Interpret settings value based on registered flags.
97 : : *
98 : : * @param[in] key key information to know if key was negated
99 : : * @param[in] value string value of setting to be parsed
100 : : * @param[in] flags ArgsManager registered argument flags
101 : : * @param[out] error Error description if settings value is not valid
102 : : *
103 : : * @return parsed settings value if it is valid, otherwise nullopt accompanied
104 : : * by a descriptive error string
105 : : */
106 : 314770 : std::optional<common::SettingsValue> InterpretValue(const KeyInfo& key, const std::string* value,
107 : : unsigned int flags, std::string& error)
108 : : {
109 : : // Return negated settings as false values.
110 [ + + ]: 314770 : if (key.negated) {
111 [ - + ]: 103295 : if (flags & ArgsManager::DISALLOW_NEGATION) {
112 : 0 : error = strprintf("Negating of -%s is meaningless and therefore forbidden", key.name);
113 : 0 : return std::nullopt;
114 : : }
115 : : // Double negatives like -nofoo=0 are supported (but discouraged)
116 [ + + + + ]: 103295 : if (value && !InterpretBool(*value)) {
117 : 7 : LogPrintf("Warning: parsed potentially confusing double-negative -%s=%s\n", key.name, *value);
118 : 7 : return true;
119 : : }
120 : 103288 : return false;
121 : : }
122 [ + + - + ]: 211475 : if (!value && (flags & ArgsManager::DISALLOW_ELISION)) {
123 : 0 : error = strprintf("Can not set -%s with no value. Please specify value with -%s=value.", key.name, key.name);
124 : 0 : return std::nullopt;
125 : : }
126 : 422950 : return value ? *value : "";
127 : : }
128 : :
129 : : // Define default constructor and destructor that are not inline, so code instantiating this class doesn't need to
130 : : // #include class definitions for all members.
131 : : // For example, m_settings has an internal dependency on univalue.
132 : 49743 : ArgsManager::ArgsManager() = default;
133 [ - + ]: 248710 : ArgsManager::~ArgsManager() = default;
134 : :
135 : 48071 : std::set<std::string> ArgsManager::GetUnsuitableSectionOnlyArgs() const
136 : : {
137 [ + - ]: 48071 : std::set<std::string> unsuitables;
138 : :
139 [ + - ]: 48071 : LOCK(cs_args);
140 : :
141 : : // if there's no section selected, don't worry
142 [ - + ]: 48071 : if (m_network.empty()) return std::set<std::string> {};
143 : :
144 : : // if it's okay to use the default section for this network, don't worry
145 [ + - + + ]: 48071 : if (m_network == ChainTypeToString(ChainType::MAIN)) return std::set<std::string> {};
146 : :
147 [ + + ]: 54180 : for (const auto& arg : m_network_only_args) {
148 [ + - + - : 18480 : if (OnlyHasDefaultSectionSetting(m_settings, m_network, SettingName(arg))) {
+ + ]
149 [ + - ]: 1752 : unsuitables.insert(arg);
150 : : }
151 : : }
152 : 35700 : return unsuitables;
153 : 48071 : }
154 : :
155 : 583 : std::list<SectionInfo> ArgsManager::GetUnrecognizedSections() const
156 : : {
157 : : // Section names to be recognized in the config file.
158 : 583 : static const std::set<std::string> available_sections{
159 : : ChainTypeToString(ChainType::REGTEST),
160 : : ChainTypeToString(ChainType::SIGNET),
161 : : ChainTypeToString(ChainType::TESTNET),
162 : : ChainTypeToString(ChainType::TESTNET4),
163 : : ChainTypeToString(ChainType::MAIN),
164 [ + + + - : 1183 : };
- + + + -
- ]
165 : :
166 : 583 : LOCK(cs_args);
167 [ + - ]: 583 : std::list<SectionInfo> unrecognized = m_config_sections;
168 : 583 : unrecognized.remove_if([](const SectionInfo& appeared){ return available_sections.find(appeared.m_name) != available_sections.end(); });
169 [ + - ]: 583 : return unrecognized;
170 [ + - + - : 683 : }
+ - + - +
- - - ]
171 : :
172 : 1113 : void ArgsManager::SelectConfigNetwork(const std::string& network)
173 : : {
174 : 1113 : LOCK(cs_args);
175 [ + - + - ]: 2226 : m_network = network;
176 : 1113 : }
177 : :
178 : 49688 : bool ArgsManager::ParseParameters(int argc, const char* const argv[], std::string& error)
179 : : {
180 : 49688 : LOCK(cs_args);
181 : 49688 : m_settings.command_line_options.clear();
182 : :
183 [ + + ]: 179180 : for (int i = 1; i < argc; i++) {
184 [ + - ]: 130180 : std::string key(argv[i]);
185 : :
186 : : #ifdef MAC_OSX
187 : : // At the first time when a user gets the "App downloaded from the
188 : : // internet" warning, and clicks the Open button, macOS passes
189 : : // a unique process serial number (PSN) as -psn_... command-line
190 : : // argument, which we filter out.
191 : : if (key.substr(0, 5) == "-psn_") continue;
192 : : #endif
193 : :
194 [ + + ]: 130180 : if (key == "-") break; //bitcoin-tx using stdin
195 : 130168 : std::optional<std::string> val;
196 : 130168 : size_t is_index = key.find('=');
197 [ + + ]: 130168 : if (is_index != std::string::npos) {
198 [ + - ]: 127079 : val = key.substr(is_index + 1);
199 [ + - ]: 127079 : key.erase(is_index);
200 : : }
201 : : #ifdef WIN32
202 : : key = ToLower(key);
203 : : if (key[0] == '/')
204 : : key[0] = '-';
205 : : #endif
206 : :
207 [ + + ]: 130168 : if (key[0] != '-') {
208 [ + + + - ]: 674 : if (!m_accept_any_command && m_command.empty()) {
209 : : // The first non-dash arg is a registered command
210 [ + - ]: 5 : std::optional<unsigned int> flags = GetArgFlags(key);
211 [ + + - + ]: 5 : if (!flags || !(*flags & ArgsManager::COMMAND)) {
212 [ + - ]: 2 : error = strprintf("Invalid command '%s'", argv[i]);
213 : 2 : return false;
214 : : }
215 : : }
216 [ + - ]: 672 : m_command.push_back(key);
217 [ + + ]: 775 : while (++i < argc) {
218 : : // The remaining args are command args
219 [ + - ]: 103 : m_command.emplace_back(argv[i]);
220 : : }
221 : 672 : break;
222 : : }
223 : :
224 : : // Transform --foo to -foo
225 [ + - + + ]: 129494 : if (key.length() > 1 && key[1] == '-')
226 [ + - ]: 6 : key.erase(0, 1);
227 : :
228 : : // Transform -foo to foo
229 [ + - ]: 129494 : key.erase(0, 1);
230 [ + - + - ]: 129494 : KeyInfo keyinfo = InterpretKey(key);
231 [ + - + - ]: 129494 : std::optional<unsigned int> flags = GetArgFlags('-' + keyinfo.name);
232 : :
233 : : // Unknown command line options and command line options with dot
234 : : // characters (which are returned from InterpretKey with nonempty
235 : : // section strings) are not valid.
236 [ + + + + ]: 129494 : if (!flags || !keyinfo.section.empty()) {
237 [ + - ]: 2 : error = strprintf("Invalid parameter %s", argv[i]);
238 : 2 : return false;
239 : : }
240 : :
241 [ + + + - ]: 131986 : std::optional<common::SettingsValue> value = InterpretValue(keyinfo, val ? &*val : nullptr, *flags, error);
242 [ - + ]: 129492 : if (!value) return false;
243 : :
244 [ + - + - ]: 129492 : m_settings.command_line_options[keyinfo.name].push_back(*value);
245 : 260346 : }
246 : :
247 : : // we do not allow -includeconf from command line, only -noincludeconf
248 [ + - + + ]: 49684 : if (auto* includes = common::FindKey(m_settings.command_line_options, "includeconf")) {
249 : 3 : const common::SettingsSpan values{*includes};
250 : : // Range may be empty if -noincludeconf was passed
251 [ + - + + ]: 3 : if (!values.empty()) {
252 [ + - + - : 2 : error = "-includeconf cannot be used from commandline; -includeconf=" + values.begin()->write();
+ - ]
253 : 2 : return false; // pick first value as example
254 : : }
255 : : }
256 : : return true;
257 : 49688 : }
258 : :
259 : 314782 : std::optional<unsigned int> ArgsManager::GetArgFlags(const std::string& name) const
260 : : {
261 : 314782 : LOCK(cs_args);
262 [ + + ]: 338137 : for (const auto& arg_map : m_available_args) {
263 : 338133 : const auto search = arg_map.second.find(name);
264 [ + + ]: 338133 : if (search != arg_map.second.end()) {
265 : 314778 : return search->second.m_flags;
266 : : }
267 : : }
268 : 4 : return std::nullopt;
269 : 314782 : }
270 : :
271 : 2196 : fs::path ArgsManager::GetPathArg(std::string arg, const fs::path& default_value) const
272 : : {
273 [ + + ]: 2196 : if (IsArgNegated(arg)) return fs::path{};
274 [ + - ]: 2195 : std::string path_str = GetArg(arg, "");
275 [ + + + - ]: 3778 : if (path_str.empty()) return default_value;
276 [ + - + - ]: 4749 : fs::path result = fs::PathFromString(path_str).lexically_normal();
277 : : // Remove trailing slash, if present.
278 [ + + + - : 4749 : return result.has_filename() ? result : result.parent_path();
+ - ]
279 : 3778 : }
280 : :
281 : 1337 : fs::path ArgsManager::GetBlocksDirPath() const
282 : : {
283 : 1337 : LOCK(cs_args);
284 : 1337 : fs::path& path = m_cached_blocks_path;
285 : :
286 : : // Cache the path to avoid calling fs::create_directories on every call of
287 : : // this function
288 [ + + + - ]: 1337 : if (!path.empty()) return path;
289 : :
290 [ + - + - : 751 : if (IsArgSet("-blocksdir")) {
- + ]
291 [ # # # # : 0 : path = fs::absolute(GetPathArg("-blocksdir"));
# # ]
292 [ # # # # ]: 0 : if (!fs::is_directory(path)) {
293 [ # # ]: 0 : path = "";
294 [ # # ]: 0 : return path;
295 : : }
296 : : } else {
297 [ + - ]: 1502 : path = GetDataDirBase();
298 : : }
299 : :
300 [ + - + - ]: 1502 : path /= fs::PathFromString(BaseParams().DataDir());
301 [ + - ]: 751 : path /= "blocks";
302 [ + - ]: 751 : fs::create_directories(path);
303 [ + - + - ]: 1337 : return path;
304 : 1337 : }
305 : :
306 : 2537 : fs::path ArgsManager::GetDataDir(bool net_specific) const
307 : : {
308 : 2537 : LOCK(cs_args);
309 [ + + ]: 2537 : fs::path& path = net_specific ? m_cached_network_datadir_path : m_cached_datadir_path;
310 : :
311 : : // Used cached path if available
312 [ + + + - : 4088 : if (!path.empty()) return path;
+ - ]
313 : :
314 [ + - + - ]: 3102 : const fs::path datadir{GetPathArg("-datadir")};
315 [ + - ]: 1551 : if (!datadir.empty()) {
316 [ + - ]: 3102 : path = fs::absolute(datadir);
317 [ + - - + ]: 1551 : if (!fs::is_directory(path)) {
318 [ # # ]: 0 : path = "";
319 [ # # ]: 0 : return path;
320 : : }
321 : : } else {
322 [ # # ]: 0 : path = GetDefaultDataDir();
323 : : }
324 : :
325 [ + + + - : 1551 : if (net_specific && !BaseParams().DataDir().empty()) {
+ + ]
326 [ + - + - ]: 504 : path /= fs::PathFromString(BaseParams().DataDir());
327 : : }
328 : :
329 [ + - ]: 1551 : return path;
330 : 4088 : }
331 : :
332 : 587 : void ArgsManager::ClearPathCache()
333 : : {
334 : 587 : LOCK(cs_args);
335 : :
336 : 587 : m_cached_datadir_path = fs::path();
337 : 587 : m_cached_network_datadir_path = fs::path();
338 [ + - ]: 1174 : m_cached_blocks_path = fs::path();
339 : 587 : }
340 : :
341 : 3 : std::optional<const ArgsManager::Command> ArgsManager::GetCommand() const
342 : : {
343 [ + - ]: 3 : Command ret;
344 [ + - ]: 3 : LOCK(cs_args);
345 [ - + ]: 3 : auto it = m_command.begin();
346 [ - + ]: 3 : if (it == m_command.end()) {
347 : : // No command was passed
348 : 0 : return std::nullopt;
349 : : }
350 [ + - ]: 3 : if (!m_accept_any_command) {
351 : : // The registered command
352 [ + - ]: 3 : ret.command = *(it++);
353 : : }
354 [ + + ]: 6 : while (it != m_command.end()) {
355 : : // The unregistered command and args (if any)
356 [ + - ]: 3 : ret.args.push_back(*(it++));
357 : : }
358 : 3 : return ret;
359 : 6 : }
360 : :
361 : 51516 : std::vector<std::string> ArgsManager::GetArgs(const std::string& strArg) const
362 : : {
363 : 51516 : std::vector<std::string> result;
364 [ + - + + ]: 128997 : for (const common::SettingsValue& value : GetSettingsList(strArg)) {
365 [ - + - - : 154962 : result.push_back(value.isFalse() ? "0" : value.isTrue() ? "1" : value.get_str());
+ + + - +
- + - +
- ]
366 : 51516 : }
367 : 51516 : return result;
368 : 0 : }
369 : :
370 : 102258 : bool ArgsManager::IsArgSet(const std::string& strArg) const
371 : : {
372 : 102258 : return !GetSetting(strArg).isNull();
373 : : }
374 : :
375 : 25 : bool ArgsManager::GetSettingsPath(fs::path* filepath, bool temp, bool backup) const
376 : : {
377 [ + - + - ]: 50 : fs::path settings = GetPathArg("-settings", BITCOIN_SETTINGS_FILENAME);
378 [ + - ]: 25 : if (settings.empty()) {
379 : : return false;
380 : : }
381 [ - + ]: 25 : if (backup) {
382 [ # # ]: 0 : settings += ".bak";
383 : : }
384 [ + - ]: 25 : if (filepath) {
385 [ + + + - : 174 : *filepath = fsbridge::AbsPathJoin(GetDataDirNet(), temp ? settings + ".tmp" : settings);
+ - + - +
+ - - ]
386 : : }
387 : : return true;
388 : 25 : }
389 : :
390 : 1 : static void SaveErrors(const std::vector<std::string> errors, std::vector<std::string>* error_out)
391 : : {
392 [ + + ]: 2 : for (const auto& error : errors) {
393 [ - + ]: 1 : if (error_out) {
394 : 0 : error_out->emplace_back(error);
395 : : } else {
396 : 1 : LogPrintf("%s\n", error);
397 : : }
398 : : }
399 : 1 : }
400 : :
401 : 1 : bool ArgsManager::ReadSettingsFile(std::vector<std::string>* errors)
402 : : {
403 : 1 : fs::path path;
404 [ + - + - ]: 1 : if (!GetSettingsPath(&path, /* temp= */ false)) {
405 : : return true; // Do nothing if settings file disabled.
406 : : }
407 : :
408 [ + - ]: 1 : LOCK(cs_args);
409 : 1 : m_settings.rw_settings.clear();
410 : 1 : std::vector<std::string> read_errors;
411 [ + - - + ]: 1 : if (!common::ReadSettings(path, m_settings.rw_settings, read_errors)) {
412 [ # # # # ]: 0 : SaveErrors(read_errors, errors);
413 : 0 : return false;
414 : : }
415 [ + + ]: 2 : for (const auto& setting : m_settings.rw_settings) {
416 [ + - + - ]: 1 : KeyInfo key = InterpretKey(setting.first); // Split setting key into section and argname
417 [ + - + - : 1 : if (!GetArgFlags('-' + key.name)) {
+ - ]
418 [ + - ]: 1 : LogPrintf("Ignoring unknown rw_settings value %s\n", setting.first);
419 : : }
420 : 1 : }
421 : : return true;
422 [ + - ]: 3 : }
423 : :
424 : 12 : bool ArgsManager::WriteSettingsFile(std::vector<std::string>* errors, bool backup) const
425 : : {
426 : 12 : fs::path path, path_tmp;
427 [ + - + - : 12 : if (!GetSettingsPath(&path, /*temp=*/false, backup) || !GetSettingsPath(&path_tmp, /*temp=*/true, backup)) {
+ - - + ]
428 [ # # ]: 0 : throw std::logic_error("Attempt to write settings file when dynamic settings are disabled.");
429 : : }
430 : :
431 [ + - ]: 12 : LOCK(cs_args);
432 : 12 : std::vector<std::string> write_errors;
433 [ + - - + ]: 12 : if (!common::WriteSettings(path_tmp, m_settings.rw_settings, write_errors)) {
434 [ # # # # ]: 0 : SaveErrors(write_errors, errors);
435 : 0 : return false;
436 : : }
437 [ + - + - : 36 : if (!RenameOver(path_tmp, path)) {
+ - + + ]
438 [ + - + - : 4 : SaveErrors({strprintf("Failed renaming settings file %s to %s\n", fs::PathToString(path_tmp), fs::PathToString(path))}, errors);
+ - + + -
- ]
439 : 1 : return false;
440 : : }
441 : : return true;
442 [ + - + - : 50 : }
+ - ]
443 : :
444 : 0 : common::SettingsValue ArgsManager::GetPersistentSetting(const std::string& name) const
445 : : {
446 : 0 : LOCK(cs_args);
447 [ # # # # : 0 : return common::GetSetting(m_settings, m_network, name, !UseDefaultSection("-" + name),
# # ]
448 [ # # ]: 0 : /*ignore_nonpersistent=*/true, /*get_chain_type=*/false);
449 : 0 : }
450 : :
451 : 50284 : bool ArgsManager::IsArgNegated(const std::string& strArg) const
452 : : {
453 : 50284 : return GetSetting(strArg).isFalse();
454 : : }
455 : :
456 : 50365 : std::string ArgsManager::GetArg(const std::string& strArg, const std::string& strDefault) const
457 : : {
458 [ + - ]: 100728 : return GetArg(strArg).value_or(strDefault);
459 : : }
460 : :
461 : 53627 : std::optional<std::string> ArgsManager::GetArg(const std::string& strArg) const
462 : : {
463 : 53627 : const common::SettingsValue value = GetSetting(strArg);
464 [ + + ]: 107252 : return SettingToString(value);
465 : 53627 : }
466 : :
467 : 53627 : std::optional<std::string> SettingToString(const common::SettingsValue& value)
468 : : {
469 [ + + ]: 53627 : if (value.isNull()) return std::nullopt;
470 [ + + ]: 48765 : if (value.isFalse()) return "0";
471 [ + + ]: 37054 : if (value.isTrue()) return "1";
472 [ + + ]: 37046 : if (value.isNum()) return value.getValStr();
473 : 37043 : return value.get_str();
474 : : }
475 : :
476 : 0 : std::string SettingToString(const common::SettingsValue& value, const std::string& strDefault)
477 : : {
478 [ # # ]: 0 : return SettingToString(value).value_or(strDefault);
479 : : }
480 : :
481 : 13316 : int64_t ArgsManager::GetIntArg(const std::string& strArg, int64_t nDefault) const
482 : : {
483 [ + + ]: 13316 : return GetIntArg(strArg).value_or(nDefault);
484 : : }
485 : :
486 : 17317 : std::optional<int64_t> ArgsManager::GetIntArg(const std::string& strArg) const
487 : : {
488 : 17317 : const common::SettingsValue value = GetSetting(strArg);
489 [ + + ]: 34631 : return SettingToInt(value);
490 : 17317 : }
491 : :
492 : 17317 : std::optional<int64_t> SettingToInt(const common::SettingsValue& value)
493 : : {
494 [ + + ]: 17317 : if (value.isNull()) return std::nullopt;
495 [ + + ]: 120 : if (value.isFalse()) return 0;
496 [ + + ]: 115 : if (value.isTrue()) return 1;
497 [ + + ]: 112 : if (value.isNum()) return value.getInt<int64_t>();
498 : 109 : return LocaleIndependentAtoi<int64_t>(value.get_str());
499 : : }
500 : :
501 : 0 : int64_t SettingToInt(const common::SettingsValue& value, int64_t nDefault)
502 : : {
503 [ # # ]: 0 : return SettingToInt(value).value_or(nDefault);
504 : : }
505 : :
506 : 11011 : bool ArgsManager::GetBoolArg(const std::string& strArg, bool fDefault) const
507 : : {
508 [ + + ]: 11011 : return GetBoolArg(strArg).value_or(fDefault);
509 : : }
510 : :
511 : 15228 : std::optional<bool> ArgsManager::GetBoolArg(const std::string& strArg) const
512 : : {
513 : 15228 : const common::SettingsValue value = GetSetting(strArg);
514 [ + + ]: 30446 : return SettingToBool(value);
515 : 15228 : }
516 : :
517 : 15228 : std::optional<bool> SettingToBool(const common::SettingsValue& value)
518 : : {
519 [ + + ]: 15228 : if (value.isNull()) return std::nullopt;
520 [ + + ]: 2619 : if (value.isBool()) return value.get_bool();
521 : 2576 : return InterpretBool(value.get_str());
522 : : }
523 : :
524 : 0 : bool SettingToBool(const common::SettingsValue& value, bool fDefault)
525 : : {
526 [ # # ]: 0 : return SettingToBool(value).value_or(fDefault);
527 : : }
528 : :
529 : 47489 : bool ArgsManager::SoftSetArg(const std::string& strArg, const std::string& strValue)
530 : : {
531 : 47489 : LOCK(cs_args);
532 [ + - + + ]: 47489 : if (IsArgSet(strArg)) return false;
533 [ + - ]: 785 : ForceSetArg(strArg, strValue);
534 : : return true;
535 : 47489 : }
536 : :
537 : 0 : bool ArgsManager::SoftSetBoolArg(const std::string& strArg, bool fValue)
538 : : {
539 [ # # ]: 0 : if (fValue)
540 [ # # ]: 0 : return SoftSetArg(strArg, std::string("1"));
541 : : else
542 [ # # ]: 0 : return SoftSetArg(strArg, std::string("0"));
543 : : }
544 : :
545 : 49468 : void ArgsManager::ForceSetArg(const std::string& strArg, const std::string& strValue)
546 : : {
547 : 49468 : LOCK(cs_args);
548 [ + - + - : 49468 : m_settings.forced_settings[SettingName(strArg)] = strValue;
+ - + - ]
549 : 49468 : }
550 : :
551 : 5 : void ArgsManager::AddCommand(const std::string& cmd, const std::string& help)
552 : : {
553 : 5 : Assert(cmd.find('=') == std::string::npos);
554 : 5 : Assert(cmd.at(0) != '-');
555 : :
556 : 5 : LOCK(cs_args);
557 : 5 : m_accept_any_command = false; // latch to false
558 [ + - ]: 5 : std::map<std::string, Arg>& arg_map = m_available_args[OptionsCategory::COMMANDS];
559 [ + - + - : 5 : auto ret = arg_map.emplace(cmd, Arg{"", help, ArgsManager::COMMAND});
+ - ]
560 [ + - ]: 5 : Assert(ret.second); // Fail on duplicate commands
561 : 5 : }
562 : :
563 : 167590 : void ArgsManager::AddArg(const std::string& name, const std::string& help, unsigned int flags, const OptionsCategory& cat)
564 : : {
565 : 167590 : Assert((flags & ArgsManager::COMMAND) == 0); // use AddCommand
566 : :
567 : : // Split arg name from its help param
568 : 167590 : size_t eq_index = name.find('=');
569 [ + + ]: 167590 : if (eq_index == std::string::npos) {
570 : 103528 : eq_index = name.size();
571 : : }
572 : 167590 : std::string arg_name = name.substr(0, eq_index);
573 : :
574 [ + - ]: 167590 : LOCK(cs_args);
575 [ + - ]: 167590 : std::map<std::string, Arg>& arg_map = m_available_args[cat];
576 [ + - + - : 167590 : auto ret = arg_map.emplace(arg_name, Arg{name.substr(eq_index, name.size() - eq_index), help, flags});
+ - ]
577 [ - + ]: 167590 : assert(ret.second); // Make sure an insertion actually happened
578 : :
579 [ + + ]: 167590 : if (flags & ArgsManager::NETWORK_ONLY) {
580 [ + - ]: 4664 : m_network_only_args.emplace(arg_name);
581 : : }
582 : 167590 : }
583 : :
584 : 1269 : void ArgsManager::AddHiddenArgs(const std::vector<std::string>& names)
585 : : {
586 [ + + ]: 7888 : for (const std::string& name : names) {
587 [ + - ]: 13238 : AddArg(name, "", ArgsManager::ALLOW_ANY, OptionsCategory::HIDDEN);
588 : : }
589 : 1269 : }
590 : :
591 : 0 : std::string ArgsManager::GetHelpMessage() const
592 : : {
593 [ # # ]: 0 : const bool show_debug = GetBoolArg("-help-debug", false);
594 : :
595 [ # # ]: 0 : std::string usage;
596 [ # # ]: 0 : LOCK(cs_args);
597 [ # # ]: 0 : for (const auto& arg_map : m_available_args) {
598 [ # # # # : 0 : switch(arg_map.first) {
# # # # #
# # # #
# ]
599 : 0 : case OptionsCategory::OPTIONS:
600 [ # # # # ]: 0 : usage += HelpMessageGroup("Options:");
601 : 0 : break;
602 : 0 : case OptionsCategory::CONNECTION:
603 [ # # # # ]: 0 : usage += HelpMessageGroup("Connection options:");
604 : 0 : break;
605 : 0 : case OptionsCategory::ZMQ:
606 [ # # # # ]: 0 : usage += HelpMessageGroup("ZeroMQ notification options:");
607 : 0 : break;
608 : 0 : case OptionsCategory::DEBUG_TEST:
609 [ # # # # ]: 0 : usage += HelpMessageGroup("Debugging/Testing options:");
610 : 0 : break;
611 : 0 : case OptionsCategory::NODE_RELAY:
612 [ # # # # ]: 0 : usage += HelpMessageGroup("Node relay options:");
613 : 0 : break;
614 : 0 : case OptionsCategory::BLOCK_CREATION:
615 [ # # # # ]: 0 : usage += HelpMessageGroup("Block creation options:");
616 : 0 : break;
617 : 0 : case OptionsCategory::RPC:
618 [ # # # # ]: 0 : usage += HelpMessageGroup("RPC server options:");
619 : 0 : break;
620 : 0 : case OptionsCategory::WALLET:
621 [ # # # # ]: 0 : usage += HelpMessageGroup("Wallet options:");
622 : 0 : break;
623 : 0 : case OptionsCategory::WALLET_DEBUG_TEST:
624 [ # # # # : 0 : if (show_debug) usage += HelpMessageGroup("Wallet debugging/testing options:");
# # ]
625 : : break;
626 : 0 : case OptionsCategory::CHAINPARAMS:
627 [ # # # # ]: 0 : usage += HelpMessageGroup("Chain selection options:");
628 : 0 : break;
629 : 0 : case OptionsCategory::GUI:
630 [ # # # # ]: 0 : usage += HelpMessageGroup("UI Options:");
631 : 0 : break;
632 : 0 : case OptionsCategory::COMMANDS:
633 [ # # # # ]: 0 : usage += HelpMessageGroup("Commands:");
634 : 0 : break;
635 : 0 : case OptionsCategory::REGISTER_COMMANDS:
636 [ # # # # ]: 0 : usage += HelpMessageGroup("Register Commands:");
637 : 0 : break;
638 : : default:
639 : : break;
640 : : }
641 : :
642 : : // When we get to the hidden options, stop
643 [ # # ]: 0 : if (arg_map.first == OptionsCategory::HIDDEN) break;
644 : :
645 [ # # ]: 0 : for (const auto& arg : arg_map.second) {
646 [ # # # # ]: 0 : if (show_debug || !(arg.second.m_flags & ArgsManager::DEBUG_ONLY)) {
647 [ # # ]: 0 : std::string name;
648 [ # # ]: 0 : if (arg.second.m_help_param.empty()) {
649 [ # # ]: 0 : name = arg.first;
650 : : } else {
651 [ # # ]: 0 : name = arg.first + arg.second.m_help_param;
652 : : }
653 [ # # ]: 0 : usage += HelpMessageOpt(name, arg.second.m_help_text);
654 : 0 : }
655 : : }
656 : : }
657 [ # # ]: 0 : return usage;
658 : 0 : }
659 : :
660 : 101 : bool HelpRequested(const ArgsManager& args)
661 : : {
662 [ + - + - : 505 : return args.IsArgSet("-?") || args.IsArgSet("-h") || args.IsArgSet("-help") || args.IsArgSet("-help-debug");
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - -
- - - -
- ]
663 : : }
664 : :
665 : 686 : void SetupHelpOptions(ArgsManager& args)
666 : : {
667 [ + - + - ]: 1372 : args.AddArg("-?", "Print this help message and exit", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
668 [ + - ]: 686 : args.AddHiddenArgs({"-h", "-help"});
669 : 686 : }
670 : :
671 : : static const int screenWidth = 79;
672 : : static const int optIndent = 2;
673 : : static const int msgIndent = 7;
674 : :
675 : 0 : std::string HelpMessageGroup(const std::string &message) {
676 [ # # # # ]: 0 : return std::string(message) + std::string("\n\n");
677 : : }
678 : :
679 : 0 : std::string HelpMessageOpt(const std::string &option, const std::string &message) {
680 [ # # # # ]: 0 : return std::string(optIndent,' ') + std::string(option) +
681 [ # # # # : 0 : std::string("\n") + std::string(msgIndent,' ') +
# # ]
682 [ # # # # ]: 0 : FormatParagraph(message, screenWidth - msgIndent, msgIndent) +
683 [ # # ]: 0 : std::string("\n\n");
684 : : }
685 : :
686 : : const std::vector<std::string> TEST_OPTIONS_DOC{
687 : : "addrman (use deterministic addrman)",
688 : : };
689 : :
690 : 0 : bool HasTestOption(const ArgsManager& args, const std::string& test_option)
691 : : {
692 [ # # ]: 0 : const auto options = args.GetArgs("-test");
693 [ # # # # : 0 : return std::any_of(options.begin(), options.end(), [test_option](const auto& option) {
# # ]
694 [ # # # # : 0 : return option == test_option;
# # # # #
# # # #
# ]
695 : 0 : });
696 : 0 : }
697 : :
698 : 0 : fs::path GetDefaultDataDir()
699 : : {
700 : : // Windows:
701 : : // old: C:\Users\Username\AppData\Roaming\Bitcoin
702 : : // new: C:\Users\Username\AppData\Local\Bitcoin
703 : : // macOS: ~/Library/Application Support/Bitcoin
704 : : // Unix-like: ~/.bitcoin
705 : : #ifdef WIN32
706 : : // Windows
707 : : // Check for existence of datadir in old location and keep it there
708 : : fs::path legacy_path = GetSpecialFolderPath(CSIDL_APPDATA) / "Bitcoin";
709 : : if (fs::exists(legacy_path)) return legacy_path;
710 : :
711 : : // Otherwise, fresh installs can start in the new, "proper" location
712 : : return GetSpecialFolderPath(CSIDL_LOCAL_APPDATA) / "Bitcoin";
713 : : #else
714 : 0 : fs::path pathRet;
715 : 0 : char* pszHome = getenv("HOME");
716 [ # # # # ]: 0 : if (pszHome == nullptr || strlen(pszHome) == 0)
717 [ # # ]: 0 : pathRet = fs::path("/");
718 : : else
719 [ # # ]: 0 : pathRet = fs::path(pszHome);
720 : : #ifdef MAC_OSX
721 : : // macOS
722 : : return pathRet / "Library/Application Support/Bitcoin";
723 : : #else
724 : : // Unix-like
725 [ # # # # ]: 0 : return pathRet / ".bitcoin";
726 : : #endif
727 : : #endif
728 : 0 : }
729 : :
730 : 0 : bool CheckDataDirOption(const ArgsManager& args)
731 : : {
732 [ # # # # ]: 0 : const fs::path datadir{args.GetPathArg("-datadir")};
733 [ # # # # : 0 : return datadir.empty() || fs::is_directory(fs::absolute(datadir));
# # # # ]
734 : 0 : }
735 : :
736 : 0 : fs::path ArgsManager::GetConfigFilePath() const
737 : : {
738 : 0 : LOCK(cs_args);
739 [ # # # # : 0 : return *Assert(m_config_path);
# # ]
740 : 0 : }
741 : :
742 : 0 : void ArgsManager::SetConfigFilePath(fs::path path)
743 : : {
744 : 0 : LOCK(cs_args);
745 [ # # ]: 0 : assert(!m_config_path);
746 [ # # ]: 0 : m_config_path = path;
747 : 0 : }
748 : :
749 : 684 : ChainType ArgsManager::GetChainType() const
750 : : {
751 : 684 : std::variant<ChainType, std::string> arg = GetChainArg();
752 [ + - ]: 684 : if (auto* parsed = std::get_if<ChainType>(&arg)) return *parsed;
753 [ # # # # : 0 : throw std::runtime_error(strprintf("Unknown chain %s.", std::get<std::string>(arg)));
# # ]
754 : 684 : }
755 : :
756 : 1386 : std::string ArgsManager::GetChainTypeString() const
757 : : {
758 : 1386 : auto arg = GetChainArg();
759 [ + - + - ]: 1199 : if (auto* parsed = std::get_if<ChainType>(&arg)) return ChainTypeToString(*parsed);
760 [ # # # # ]: 0 : return std::get<std::string>(arg);
761 : 1199 : }
762 : :
763 : 2070 : std::variant<ChainType, std::string> ArgsManager::GetChainArg() const
764 : : {
765 : 10350 : auto get_net = [&](const std::string& arg) {
766 : 8280 : LOCK(cs_args);
767 [ + - + - ]: 16560 : common::SettingsValue value = common::GetSetting(m_settings, /* section= */ "", SettingName(arg),
768 : : /* ignore_default_section_config= */ false,
769 : : /*ignore_nonpersistent=*/false,
770 [ + - ]: 8280 : /* get_chain_type= */ true);
771 [ + + - + : 8280 : return value.isNull() ? false : value.isBool() ? value.get_bool() : InterpretBool(value.get_str());
- - + - +
- ]
772 [ + - ]: 16560 : };
773 : :
774 [ + - ]: 2070 : const bool fRegTest = get_net("-regtest");
775 [ + - ]: 2070 : const bool fSigNet = get_net("-signet");
776 [ + - ]: 2070 : const bool fTestNet = get_net("-testnet");
777 [ + - ]: 2070 : const bool fTestNet4 = get_net("-testnet4");
778 [ + - ]: 2070 : const auto chain_arg = GetArg("-chain");
779 : :
780 [ + + ]: 2070 : if ((int)chain_arg.has_value() + (int)fRegTest + (int)fSigNet + (int)fTestNet + (int)fTestNet4 > 1) {
781 [ + - ]: 187 : throw std::runtime_error("Invalid combination of -regtest, -signet, -testnet, -testnet4 and -chain. Can use at most one.");
782 : : }
783 [ - + ]: 1883 : if (chain_arg) {
784 [ # # # # ]: 0 : if (auto parsed = ChainTypeFromString(*chain_arg)) return *parsed;
785 : : // Not a known string, so return original string
786 [ # # ]: 0 : return *chain_arg;
787 : : }
788 [ + + ]: 1883 : if (fRegTest) return ChainType::REGTEST;
789 [ - + ]: 1560 : if (fSigNet) return ChainType::SIGNET;
790 [ + + ]: 1560 : if (fTestNet) return ChainType::TESTNET;
791 [ + + ]: 1230 : if (fTestNet4) return ChainType::TESTNET4;
792 : 1229 : return ChainType::MAIN;
793 : 1883 : }
794 : :
795 : 290273 : bool ArgsManager::UseDefaultSection(const std::string& arg) const
796 : : {
797 [ + + + + ]: 290273 : return m_network == ChainTypeToString(ChainType::MAIN) || m_network_only_args.count(arg) == 0;
798 : : }
799 : :
800 : 238740 : common::SettingsValue ArgsManager::GetSetting(const std::string& arg) const
801 : : {
802 : 238740 : LOCK(cs_args);
803 : 238740 : return common::GetSetting(
804 [ + - + - ]: 477480 : m_settings, m_network, SettingName(arg), !UseDefaultSection(arg),
805 [ + - + - ]: 238740 : /*ignore_nonpersistent=*/false, /*get_chain_type=*/false);
806 : 238740 : }
807 : :
808 : 51533 : std::vector<common::SettingsValue> ArgsManager::GetSettingsList(const std::string& arg) const
809 : : {
810 : 51533 : LOCK(cs_args);
811 [ + - + - : 103066 : return common::GetSettingsList(m_settings, m_network, SettingName(arg), !UseDefaultSection(arg));
+ - + - ]
812 : 51533 : }
813 : :
814 : 1 : void ArgsManager::logArgsPrefix(
815 : : const std::string& prefix,
816 : : const std::string& section,
817 : : const std::map<std::string, std::vector<common::SettingsValue>>& args) const
818 : : {
819 [ + - - - ]: 1 : std::string section_str = section.empty() ? "" : "[" + section + "] ";
820 [ + + ]: 5 : for (const auto& arg : args) {
821 [ + + ]: 8 : for (const auto& value : arg.second) {
822 [ + - + - ]: 4 : std::optional<unsigned int> flags = GetArgFlags('-' + arg.first);
823 [ + - ]: 4 : if (flags) {
824 [ + + + - : 4 : std::string value_str = (*flags & SENSITIVE) ? "****" : value.write();
+ - ]
825 [ + - ]: 4 : LogPrintf("%s %s%s=%s\n", prefix, section_str, arg.first, value_str);
826 : 4 : }
827 : : }
828 : : }
829 : 1 : }
830 : :
831 : 1 : void ArgsManager::LogArgs() const
832 : : {
833 : 1 : LOCK(cs_args);
834 [ - + ]: 1 : for (const auto& section : m_settings.ro_config) {
835 [ # # # # ]: 0 : logArgsPrefix("Config file arg:", section.first, section.second);
836 : : }
837 [ - + ]: 1 : for (const auto& setting : m_settings.rw_settings) {
838 [ # # # # ]: 0 : LogPrintf("Setting file arg: %s = %s\n", setting.first, setting.second.write());
839 : : }
840 [ + - + - : 2 : logArgsPrefix("Command-line arg:", "", m_settings.command_line_options);
+ - + - ]
841 : 1 : }
842 : :
843 : : namespace common {
844 : : #ifdef WIN32
845 : : WinCmdLineArgs::WinCmdLineArgs()
846 : : {
847 : : wchar_t** wargv = CommandLineToArgvW(GetCommandLineW(), &argc);
848 : : std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t> utf8_cvt;
849 : : argv = new char*[argc];
850 : : args.resize(argc);
851 : : for (int i = 0; i < argc; i++) {
852 : : args[i] = utf8_cvt.to_bytes(wargv[i]);
853 : : argv[i] = &*args[i].begin();
854 : : }
855 : : LocalFree(wargv);
856 : : }
857 : :
858 : : WinCmdLineArgs::~WinCmdLineArgs()
859 : : {
860 : : delete[] argv;
861 : : }
862 : :
863 : : std::pair<int, char**> WinCmdLineArgs::get()
864 : : {
865 : : return std::make_pair(argc, argv);
866 : : }
867 : : #endif
868 : : } // namespace common
|