Coverage Report

Created: 2026-07-14 18:13

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/bitcoin/src/common/args.cpp
Line
Count
Source
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 <sync.h>
11
#include <tinyformat.h>
12
#include <univalue.h>
13
#include <util/chaintype.h>
14
#include <util/check.h>
15
#include <util/fs.h>
16
#include <util/fs_helpers.h>
17
#include <util/log.h>
18
#include <util/strencodings.h>
19
#include <util/string.h>
20
21
#ifdef WIN32
22
#include <shlobj.h>
23
#endif
24
25
#include <algorithm>
26
#include <cassert>
27
#include <cstdint>
28
#include <cstdlib>
29
#include <cstring>
30
#include <map>
31
#include <optional>
32
#include <stdexcept>
33
#include <string>
34
#include <utility>
35
#include <variant>
36
37
const char * const BITCOIN_CONF_FILENAME = "bitcoin.conf";
38
const char * const BITCOIN_SETTINGS_FILENAME = "settings.json";
39
40
ArgsManager gArgs;
41
42
/**
43
 * Interpret a string argument as a boolean.
44
 *
45
 * The definition of LocaleIndependentAtoi<int>() requires that non-numeric string values
46
 * like "foo", return 0. This means that if a user unintentionally supplies a
47
 * non-integer argument here, the return value is always false. This means that
48
 * -foo=false does what the user probably expects, but -foo=true is well defined
49
 * but does not do what they probably expected.
50
 *
51
 * The return value of LocaleIndependentAtoi<int>(...) is zero when given input not
52
 * representable as an int.
53
 *
54
 * For a more extensive discussion of this topic (and a wide range of opinions
55
 * on the Right Way to change this code), see PR12713.
56
 */
57
static bool InterpretBool(const std::string& strValue)
58
378
{
59
378
    if (strValue.empty())
  Branch (59:9): [True: 135, False: 243]
60
135
        return true;
61
243
    return (LocaleIndependentAtoi<int>(strValue) != 0);
62
378
}
63
64
static std::string SettingName(const std::string& arg)
65
1.09M
{
66
1.09M
    return arg.size() > 0 && arg[0] == '-' ? arg.substr(1) : arg;
  Branch (66:12): [True: 1.09M, False: 0]
  Branch (66:30): [True: 1.09M, False: 81]
67
1.09M
}
68
69
/**
70
 * Parse "name", "section.name", "noname", "section.noname" settings keys.
71
 *
72
 * @note Where an option was negated can be later checked using the
73
 * IsArgNegated() method. One use case for this is to have a way to disable
74
 * options that are not normally boolean (e.g. using -nodebuglogfile to request
75
 * that debug log output is not sent to any file at all).
76
 */
77
KeyInfo InterpretKey(std::string key)
78
675
{
79
675
    KeyInfo result;
80
    // Split section name from key name for keys like "testnet.foo" or "regtest.bar"
81
675
    size_t option_index = key.find('.');
82
675
    if (option_index != std::string::npos) {
  Branch (82:9): [True: 0, False: 675]
83
0
        result.section = key.substr(0, option_index);
84
0
        key.erase(0, option_index + 1);
85
0
    }
86
675
    if (key.starts_with("no")) {
  Branch (86:9): [True: 27, False: 648]
87
27
        key.erase(0, 2);
88
27
        result.negated = true;
89
27
    }
90
675
    result.name = key;
91
675
    return result;
92
675
}
93
94
/**
95
 * Interpret settings value based on registered flags.
96
 *
97
 * @param[in]   key      key information to know if key was negated
98
 * @param[in]   value    string value of setting to be parsed
99
 * @param[in]   flags    ArgsManager registered argument flags
100
 * @param[out]  error    Error description if settings value is not valid
101
 *
102
 * @return parsed settings value if it is valid, otherwise nullopt accompanied
103
 * by a descriptive error string
104
 */
105
std::optional<common::SettingsValue> InterpretValue(const KeyInfo& key, const std::string* value,
106
                                                  unsigned int flags, std::string& error)
107
675
{
108
    // Return negated settings as false values.
109
675
    if (key.negated) {
  Branch (109:9): [True: 27, False: 648]
110
27
        if (flags & ArgsManager::DISALLOW_NEGATION) {
  Branch (110:13): [True: 0, False: 27]
111
0
            error = strprintf("Negating of -%s is meaningless and therefore forbidden", key.name);
112
0
            return std::nullopt;
113
0
        }
114
        // Double negatives like -nofoo=0 are supported (but discouraged)
115
27
        if (value && !InterpretBool(*value)) {
  Branch (115:13): [True: 0, False: 27]
  Branch (115:22): [True: 0, False: 0]
116
0
            LogWarning("Parsed potentially confusing double-negative -%s=%s", key.name, *value);
117
0
            return true;
118
0
        }
119
27
        return false;
120
27
    }
121
648
    if (!value && (flags & ArgsManager::DISALLOW_ELISION)) {
  Branch (121:9): [True: 162, False: 486]
  Branch (121:19): [True: 0, False: 162]
122
0
        error = strprintf("Can not set -%s with no value. Please specify value with -%s=value.", key.name, key.name);
123
0
        return std::nullopt;
124
0
    }
125
648
    return value ? *value : "";
  Branch (125:12): [True: 486, False: 162]
126
648
}
127
128
// Define default constructor and destructor that are not inline, so code instantiating this class doesn't need to
129
// #include class definitions for all members.
130
// For example, m_settings has an internal dependency on univalue.
131
27
ArgsManager::ArgsManager() = default;
132
0
ArgsManager::~ArgsManager() = default;
133
134
std::set<std::string> ArgsManager::GetUnsuitableSectionOnlyArgs() const
135
27
{
136
27
    std::set<std::string> unsuitables;
137
138
27
    LOCK(cs_args);
139
140
    // if there's no section selected, don't worry
141
27
    if (m_network.empty()) return std::set<std::string> {};
  Branch (141:9): [True: 0, False: 27]
142
143
    // if it's okay to use the default section for this network, don't worry
144
27
    if (m_network == ChainTypeToString(ChainType::MAIN)) return std::set<std::string> {};
  Branch (144:9): [True: 0, False: 27]
145
146
216
    for (const auto& arg : m_network_only_args) {
  Branch (146:26): [True: 216, False: 27]
147
216
        if (OnlyHasDefaultSectionSetting(m_settings, m_network, SettingName(arg))) {
  Branch (147:13): [True: 0, False: 216]
148
0
            unsuitables.insert(arg);
149
0
        }
150
216
    }
151
27
    return unsuitables;
152
27
}
153
154
std::list<SectionInfo> ArgsManager::GetUnrecognizedSections() const
155
27
{
156
    // Section names to be recognized in the config file.
157
27
    static const std::set<std::string> available_sections{
158
27
        ChainTypeToString(ChainType::REGTEST),
159
27
        ChainTypeToString(ChainType::SIGNET),
160
27
        ChainTypeToString(ChainType::TESTNET),
161
27
        ChainTypeToString(ChainType::TESTNET4),
162
27
        ChainTypeToString(ChainType::MAIN),
163
27
    };
164
165
27
    LOCK(cs_args);
166
27
    std::list<SectionInfo> unrecognized = m_config_sections;
167
27
    unrecognized.remove_if([](const SectionInfo& appeared){ return available_sections.contains(appeared.m_name); });
168
27
    return unrecognized;
169
27
}
170
171
void ArgsManager::SelectConfigNetwork(const std::string& network)
172
27
{
173
27
    LOCK(cs_args);
174
27
    m_network = network;
175
27
}
176
177
bool ArgsManager::ParseParameters(int argc, const char* const argv[], std::string& error)
178
27
{
179
27
    LOCK(cs_args);
180
27
    m_settings.command_line_options.clear();
181
182
702
    for (int i = 1; i < argc; i++) {
  Branch (182:21): [True: 675, False: 27]
183
675
        std::string key(argv[i]);
184
185
#ifdef __APPLE__
186
        // At the first time when a user gets the "App downloaded from the
187
        // internet" warning, and clicks the Open button, macOS passes
188
        // a unique process serial number (PSN) as -psn_... command-line
189
        // argument, which we filter out.
190
        if (key.starts_with("-psn_")) continue;
191
#endif
192
193
675
        if (key == "-") break; //bitcoin-tx using stdin
  Branch (193:13): [True: 0, False: 675]
194
675
        std::optional<std::string> val;
195
675
        size_t is_index = key.find('=');
196
675
        if (is_index != std::string::npos) {
  Branch (196:13): [True: 486, False: 189]
197
486
            val = key.substr(is_index + 1);
198
486
            key.erase(is_index);
199
486
        }
200
#ifdef WIN32
201
        key = ToLower(key);
202
        if (key[0] == '/')
203
            key[0] = '-';
204
#endif
205
206
675
        if (key[0] != '-') {
  Branch (206:13): [True: 0, False: 675]
207
0
            if (!m_accept_any_command && m_command.empty()) {
  Branch (207:17): [True: 0, False: 0]
  Branch (207:42): [True: 0, False: 0]
208
                // The first non-dash arg is a registered command
209
0
                std::optional<unsigned int> flags = GetArgFlags_(key);
210
0
                if (!flags || !(*flags & ArgsManager::COMMAND)) {
  Branch (210:21): [True: 0, False: 0]
  Branch (210:31): [True: 0, False: 0]
211
0
                    error = strprintf("Invalid command '%s'", argv[i]);
212
0
                    return false;
213
0
                }
214
0
            }
215
0
            m_command.push_back(key);
216
0
            while (++i < argc) {
  Branch (216:20): [True: 0, False: 0]
217
                // The remaining args are command args
218
0
                m_command.emplace_back(argv[i]);
219
0
            }
220
0
            break;
221
0
        }
222
223
        // Transform --foo to -foo
224
675
        if (key.length() > 1 && key[1] == '-')
  Branch (224:13): [True: 675, False: 0]
  Branch (224:33): [True: 0, False: 675]
225
0
            key.erase(0, 1);
226
227
        // Transform -foo to foo
228
675
        key.erase(0, 1);
229
675
        KeyInfo keyinfo = InterpretKey(key);
230
675
        std::optional<unsigned int> flags = GetArgFlags_('-' + keyinfo.name);
231
232
        // Unknown command line options and command line options with dot
233
        // characters (which are returned from InterpretKey with nonempty
234
        // section strings) are not valid.
235
675
        if (!flags || !keyinfo.section.empty()) {
  Branch (235:13): [True: 0, False: 675]
  Branch (235:23): [True: 0, False: 675]
236
0
            error = strprintf("Invalid parameter %s", argv[i]);
237
0
            return false;
238
0
        }
239
240
675
        std::optional<common::SettingsValue> value = InterpretValue(keyinfo, val ? &*val : nullptr, *flags, error);
  Branch (240:78): [True: 486, False: 189]
241
675
        if (!value) return false;
  Branch (241:13): [True: 0, False: 675]
242
243
675
        m_settings.command_line_options[keyinfo.name].push_back(*value);
244
675
    }
245
246
    // we do not allow -includeconf from command line, only -noincludeconf
247
27
    if (auto* includes = common::FindKey(m_settings.command_line_options, "includeconf")) {
  Branch (247:15): [True: 0, False: 27]
248
0
        const common::SettingsSpan values{*includes};
249
        // Range may be empty if -noincludeconf was passed
250
0
        if (!values.empty()) {
  Branch (250:13): [True: 0, False: 0]
251
0
            error = "-includeconf cannot be used from commandline; -includeconf=" + values.begin()->write();
252
0
            return false; // pick first value as example
253
0
        }
254
0
    }
255
27
    return true;
256
27
}
257
258
std::optional<unsigned int> ArgsManager::GetArgFlags_(const std::string& name) const
259
1.35k
{
260
1.35k
    AssertLockHeld(cs_args);
261
4.75k
    for (const auto& arg_map : m_available_args) {
  Branch (261:30): [True: 4.75k, False: 0]
262
4.75k
        const auto search = arg_map.second.find(name);
263
4.75k
        if (search != arg_map.second.end()) {
  Branch (263:13): [True: 1.35k, False: 3.40k]
264
1.35k
            return search->second.m_flags;
265
1.35k
        }
266
4.75k
    }
267
0
    return m_default_flags;
268
1.35k
}
269
270
std::optional<unsigned int> ArgsManager::GetArgFlags(const std::string& name) const
271
0
{
272
0
    LOCK(cs_args);
273
0
    return GetArgFlags_(name);
274
0
}
275
276
void ArgsManager::SetDefaultFlags(std::optional<unsigned int> flags)
277
0
{
278
0
    LOCK(cs_args);
279
0
    m_default_flags = flags;
280
0
}
281
282
fs::path ArgsManager::GetPathArg_(std::string arg, const fs::path& default_value) const
283
300k
{
284
300k
    AssertLockHeld(cs_args);
285
300k
    const auto value = GetSetting_(arg);
286
300k
    if (value.isFalse()) return {};
  Branch (286:9): [True: 0, False: 300k]
287
300k
    std::string path_str = SettingToString(value, "");
288
300k
    if (path_str.empty()) return default_value;
  Branch (288:9): [True: 300k, False: 162]
289
162
    fs::path result = fs::PathFromString(path_str).lexically_normal();
290
    // Remove trailing slash, if present.
291
162
    return result.has_filename() ? result : result.parent_path();
  Branch (291:12): [True: 162, False: 0]
292
300k
}
293
294
fs::path ArgsManager::GetPathArg(std::string arg, const fs::path& default_value) const
295
300k
{
296
300k
    LOCK(cs_args);
297
300k
    return GetPathArg_(std::move(arg), default_value);
298
300k
}
299
300
fs::path ArgsManager::GetBlocksDirPath() const
301
69.1k
{
302
69.1k
    LOCK(cs_args);
303
69.1k
    fs::path& path = m_cached_blocks_path;
304
305
    // Cache the path to avoid calling fs::create_directories on every call of
306
    // this function
307
69.1k
    if (!path.empty()) return path;
  Branch (307:9): [True: 69.1k, False: 27]
308
309
27
    if (!GetSetting_("-blocksdir").isNull()) {
  Branch (309:9): [True: 0, False: 27]
310
0
        path = fs::absolute(GetPathArg_("-blocksdir"));
311
0
        if (!fs::is_directory(path)) {
  Branch (311:13): [True: 0, False: 0]
312
0
            path = "";
313
0
            return path;
314
0
        }
315
27
    } else {
316
27
        path = GetDataDir(/*net_specific=*/false);
317
27
    }
318
319
27
    path /= fs::PathFromString(BaseParams().DataDir());
320
27
    path /= "blocks";
321
27
    fs::create_directories(path);
322
27
    return path;
323
27
}
324
325
81
fs::path ArgsManager::GetDataDirBase() const {
326
81
    LOCK(cs_args);
327
81
    return GetDataDir(/*net_specific=*/false);
328
81
}
329
330
881k
fs::path ArgsManager::GetDataDirNet() const {
331
881k
    LOCK(cs_args);
332
881k
    return GetDataDir(/*net_specific=*/true);
333
881k
}
334
335
fs::path ArgsManager::GetDataDir(bool net_specific) const
336
881k
{
337
881k
    AssertLockHeld(cs_args);
338
881k
    fs::path& path = net_specific ? m_cached_network_datadir_path : m_cached_datadir_path;
  Branch (338:22): [True: 881k, False: 135]
339
340
    // Used cached path if available
341
881k
    if (!path.empty()) return path;
  Branch (341:9): [True: 881k, False: 81]
342
343
81
    const fs::path datadir{GetPathArg_("-datadir")};
344
81
    if (!datadir.empty()) {
  Branch (344:9): [True: 81, False: 0]
345
81
        path = fs::absolute(datadir);
346
81
        if (!fs::is_directory(path)) {
  Branch (346:13): [True: 0, False: 81]
347
0
            path = "";
348
0
            return path;
349
0
        }
350
81
    } else {
351
0
        path = GetDefaultDataDir();
352
0
    }
353
354
81
    if (net_specific && !BaseParams().DataDir().empty()) {
  Branch (354:9): [True: 27, False: 54]
  Branch (354:25): [True: 27, False: 0]
355
27
        path /= fs::PathFromString(BaseParams().DataDir());
356
27
    }
357
358
81
    return path;
359
81
}
360
361
void ArgsManager::ClearPathCache()
362
27
{
363
27
    LOCK(cs_args);
364
365
27
    m_cached_datadir_path = fs::path();
366
27
    m_cached_network_datadir_path = fs::path();
367
27
    m_cached_blocks_path = fs::path();
368
27
}
369
370
std::optional<const ArgsManager::Command> ArgsManager::GetCommand() const
371
0
{
372
0
    Command ret;
373
0
    LOCK(cs_args);
374
0
    auto it = m_command.begin();
375
0
    if (it == m_command.end()) {
  Branch (375:9): [True: 0, False: 0]
376
        // No command was passed
377
0
        return std::nullopt;
378
0
    }
379
0
    if (!m_accept_any_command) {
  Branch (379:9): [True: 0, False: 0]
380
        // The registered command
381
0
        ret.command = *(it++);
382
0
    }
383
0
    while (it != m_command.end()) {
  Branch (383:12): [True: 0, False: 0]
384
        // The unregistered command and args (if any)
385
0
        ret.args.push_back(*(it++));
386
0
    }
387
0
    return ret;
388
0
}
389
390
bool ArgsManager::CheckCommandOptions(const std::string& command, std::vector<std::string>* errors) const
391
0
{
392
0
    LOCK(cs_args);
393
394
0
    auto command_options = m_available_args.find(OptionsCategory::COMMAND_OPTIONS);
395
0
    if (command_options == m_available_args.end()) {
  Branch (395:9): [True: 0, False: 0]
396
        // There are no command-specific options at all, so everything is fine
397
0
        return true;
398
0
    }
399
400
0
    const auto command_args = m_command_args.find(command);
401
0
    auto is_valid_opt = [&](const auto& opt) EXCLUSIVE_LOCKS_REQUIRED(cs_args) -> bool {
402
0
        if (command_args == m_command_args.end()) {
  Branch (402:13): [True: 0, False: 0]
403
            // Caller may not have checked that command actually exists
404
            // before calling this function.  In that case, treat it as
405
            // having no valid command-specific options.
406
0
            return false;
407
0
        } else {
408
0
            return command_args->second.contains(opt);
409
0
        }
410
0
    };
411
412
0
    bool ok = true;
413
0
    for (const auto& [arg, _] : command_options->second) {
  Branch (413:31): [True: 0, False: 0]
414
0
        if (!GetSetting_(arg).isNull() && !is_valid_opt(arg)) {
  Branch (414:13): [True: 0, False: 0]
  Branch (414:13): [True: 0, False: 0]
  Branch (414:43): [True: 0, False: 0]
415
0
            ok = false;
416
0
            if (errors != nullptr) {
  Branch (416:17): [True: 0, False: 0]
417
0
                errors->emplace_back(strprintf("The %s option cannot be used with the '%s' command.", arg, command));
418
0
            }
419
0
        }
420
0
    }
421
0
    return ok;
422
0
}
423
424
std::vector<std::string> ArgsManager::GetArgs(const std::string& strArg) const
425
303k
{
426
303k
    std::vector<std::string> result;
427
303k
    for (const common::SettingsValue& value : GetSettingsList(strArg)) {
  Branch (427:45): [True: 152k, False: 303k]
428
152k
        result.push_back(value.isFalse() ? "0" : value.isTrue() ? "1" : value.get_str());
  Branch (428:26): [True: 0, False: 152k]
  Branch (428:50): [True: 0, False: 152k]
429
152k
    }
430
303k
    return result;
431
303k
}
432
433
bool ArgsManager::IsArgSet(const std::string& strArg) const
434
513
{
435
513
    return !GetSetting(strArg).isNull();
436
513
}
437
438
bool ArgsManager::GetSettingsPath(fs::path* filepath, bool temp, bool backup) const
439
108
{
440
108
    fs::path settings = GetPathArg("-settings", BITCOIN_SETTINGS_FILENAME);
441
108
    if (settings.empty()) {
  Branch (441:9): [True: 0, False: 108]
442
0
        return false;
443
0
    }
444
108
    if (backup) {
  Branch (444:9): [True: 0, False: 108]
445
0
        settings += ".bak";
446
0
    }
447
108
    if (filepath) {
  Branch (447:9): [True: 81, False: 27]
448
81
        *filepath = fsbridge::AbsPathJoin(GetDataDirNet(), temp ? settings + ".tmp" : settings);
  Branch (448:60): [True: 27, False: 54]
449
81
    }
450
108
    return true;
451
108
}
452
453
static void SaveErrors(const std::vector<std::string> errors, std::vector<std::string>* error_out)
454
0
{
455
0
    for (const auto& error : errors) {
  Branch (455:28): [True: 0, False: 0]
456
0
        if (error_out) {
  Branch (456:13): [True: 0, False: 0]
457
0
            error_out->emplace_back(error);
458
0
        } else {
459
0
            LogWarning("%s", error);
460
0
        }
461
0
    }
462
0
}
463
464
bool ArgsManager::ReadSettingsFile(std::vector<std::string>* errors)
465
27
{
466
27
    fs::path path;
467
27
    if (!GetSettingsPath(&path, /* temp= */ false)) {
  Branch (467:9): [True: 0, False: 27]
468
0
        return true; // Do nothing if settings file disabled.
469
0
    }
470
471
27
    LOCK(cs_args);
472
27
    m_settings.rw_settings.clear();
473
27
    std::vector<std::string> read_errors;
474
27
    if (!common::ReadSettings(path, m_settings.rw_settings, read_errors)) {
  Branch (474:9): [True: 0, False: 27]
475
0
        SaveErrors(read_errors, errors);
476
0
        return false;
477
0
    }
478
27
    for (const auto& setting : m_settings.rw_settings) {
  Branch (478:30): [True: 0, False: 27]
479
0
        KeyInfo key = InterpretKey(setting.first); // Split setting key into section and argname
480
0
        if (!GetArgFlags_('-' + key.name)) {
  Branch (480:13): [True: 0, False: 0]
481
0
            LogWarning("Ignoring unknown rw_settings value %s", setting.first);
482
0
        }
483
0
    }
484
27
    return true;
485
27
}
486
487
bool ArgsManager::WriteSettingsFile(std::vector<std::string>* errors, bool backup) const
488
27
{
489
27
    fs::path path, path_tmp;
490
27
    if (!GetSettingsPath(&path, /*temp=*/false, backup) || !GetSettingsPath(&path_tmp, /*temp=*/true, backup)) {
  Branch (490:9): [True: 0, False: 27]
  Branch (490:60): [True: 0, False: 27]
491
0
        throw std::logic_error("Attempt to write settings file when dynamic settings are disabled.");
492
0
    }
493
494
27
    LOCK(cs_args);
495
27
    std::vector<std::string> write_errors;
496
27
    if (!common::WriteSettings(path_tmp, m_settings.rw_settings, write_errors)) {
  Branch (496:9): [True: 0, False: 27]
497
0
        SaveErrors(write_errors, errors);
498
0
        return false;
499
0
    }
500
27
    if (!RenameOver(path_tmp, path)) {
  Branch (500:9): [True: 0, False: 27]
501
0
        SaveErrors({strprintf("Failed renaming settings file %s to %s\n", fs::PathToString(path_tmp), fs::PathToString(path))}, errors);
502
0
        return false;
503
0
    }
504
27
    return true;
505
27
}
506
507
common::SettingsValue ArgsManager::GetPersistentSetting(const std::string& name) const
508
0
{
509
0
    LOCK(cs_args);
510
0
    return common::GetSetting(m_settings, m_network, name, !UseDefaultSection("-" + name),
511
0
        /*ignore_nonpersistent=*/true, /*get_chain_type=*/false);
512
0
}
513
514
bool ArgsManager::IsArgNegated(const std::string& strArg) const
515
135
{
516
135
    return GetSetting(strArg).isFalse();
517
135
}
518
519
std::string ArgsManager::GetArg(const std::string& strArg, const std::string& strDefault) const
520
233
{
521
233
    return GetArg(strArg).value_or(strDefault);
522
233
}
523
524
std::optional<std::string> ArgsManager::GetArg(const std::string& strArg) const
525
692
{
526
692
    const common::SettingsValue value = GetSetting(strArg);
527
692
    return SettingToString(value);
528
692
}
529
530
std::optional<std::string> SettingToString(const common::SettingsValue& value)
531
301k
{
532
301k
    if (value.isNull()) return std::nullopt;
  Branch (532:9): [True: 300k, False: 216]
533
216
    if (value.isFalse()) return "0";
  Branch (533:9): [True: 0, False: 216]
534
216
    if (value.isTrue()) return "1";
  Branch (534:9): [True: 0, False: 216]
535
216
    if (value.isNum()) return value.getValStr();
  Branch (535:9): [True: 0, False: 216]
536
216
    return value.get_str();
537
216
}
538
539
std::string SettingToString(const common::SettingsValue& value, const std::string& strDefault)
540
300k
{
541
300k
    return SettingToString(value).value_or(strDefault);
542
300k
}
543
544
template <std::integral Int>
545
Int ArgsManager::GetArg(const std::string& strArg, Int nDefault) const
546
810
{
547
810
    return GetArg<Int>(strArg).value_or(nDefault);
548
810
}
Unexecuted instantiation: _ZNK11ArgsManager6GetArgITkSt8integralaEET_RKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES1_
Unexecuted instantiation: _ZNK11ArgsManager6GetArgITkSt8integralhEET_RKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES1_
Unexecuted instantiation: _ZNK11ArgsManager6GetArgITkSt8integralsEET_RKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES1_
Unexecuted instantiation: _ZNK11ArgsManager6GetArgITkSt8integraltEET_RKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES1_
_ZNK11ArgsManager6GetArgITkSt8integraliEET_RKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES1_
Line
Count
Source
546
54
{
547
54
    return GetArg<Int>(strArg).value_or(nDefault);
548
54
}
Unexecuted instantiation: _ZNK11ArgsManager6GetArgITkSt8integraljEET_RKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES1_
_ZNK11ArgsManager6GetArgITkSt8integrallEET_RKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES1_
Line
Count
Source
546
756
{
547
756
    return GetArg<Int>(strArg).value_or(nDefault);
548
756
}
Unexecuted instantiation: _ZNK11ArgsManager6GetArgITkSt8integralmEET_RKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES1_
549
550
template <std::integral Int>
551
std::optional<Int> ArgsManager::GetArg(const std::string& strArg) const
552
1.48k
{
553
1.48k
    const common::SettingsValue value = GetSetting(strArg);
554
1.48k
    return SettingTo<Int>(value);
555
1.48k
}
Unexecuted instantiation: _ZNK11ArgsManager6GetArgITkSt8integralaEESt8optionalIT_ERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Unexecuted instantiation: _ZNK11ArgsManager6GetArgITkSt8integralhEESt8optionalIT_ERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Unexecuted instantiation: _ZNK11ArgsManager6GetArgITkSt8integralsEESt8optionalIT_ERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Unexecuted instantiation: _ZNK11ArgsManager6GetArgITkSt8integraltEESt8optionalIT_ERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
_ZNK11ArgsManager6GetArgITkSt8integraliEESt8optionalIT_ERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
552
54
{
553
54
    const common::SettingsValue value = GetSetting(strArg);
554
54
    return SettingTo<Int>(value);
555
54
}
Unexecuted instantiation: _ZNK11ArgsManager6GetArgITkSt8integraljEESt8optionalIT_ERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
_ZNK11ArgsManager6GetArgITkSt8integrallEESt8optionalIT_ERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
552
1.32k
{
553
1.32k
    const common::SettingsValue value = GetSetting(strArg);
554
1.32k
    return SettingTo<Int>(value);
555
1.32k
}
_ZNK11ArgsManager6GetArgITkSt8integralmEESt8optionalIT_ERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
552
108
{
553
108
    const common::SettingsValue value = GetSetting(strArg);
554
108
    return SettingTo<Int>(value);
555
108
}
556
557
template <std::integral Int>
558
std::optional<Int> SettingTo(const common::SettingsValue& value)
559
1.48k
{
560
1.48k
    if (value.isNull()) return std::nullopt;
  Branch (560:9): [True: 0, False: 0]
  Branch (560:9): [True: 0, False: 0]
  Branch (560:9): [True: 0, False: 0]
  Branch (560:9): [True: 0, False: 0]
  Branch (560:9): [True: 27, False: 27]
  Branch (560:9): [True: 0, False: 0]
  Branch (560:9): [True: 1.05k, False: 270]
  Branch (560:9): [True: 108, False: 0]
561
297
    if (value.isFalse()) return 0;
  Branch (561:9): [True: 0, False: 0]
  Branch (561:9): [True: 0, False: 0]
  Branch (561:9): [True: 0, False: 0]
  Branch (561:9): [True: 0, False: 0]
  Branch (561:9): [True: 0, False: 27]
  Branch (561:9): [True: 0, False: 0]
  Branch (561:9): [True: 0, False: 270]
  Branch (561:9): [True: 0, False: 0]
562
297
    if (value.isTrue()) return 1;
  Branch (562:9): [True: 0, False: 0]
  Branch (562:9): [True: 0, False: 0]
  Branch (562:9): [True: 0, False: 0]
  Branch (562:9): [True: 0, False: 0]
  Branch (562:9): [True: 0, False: 27]
  Branch (562:9): [True: 0, False: 0]
  Branch (562:9): [True: 0, False: 270]
  Branch (562:9): [True: 0, False: 0]
563
297
    if (value.isNum()) return value.getInt<Int>();
  Branch (563:9): [True: 0, False: 0]
  Branch (563:9): [True: 0, False: 0]
  Branch (563:9): [True: 0, False: 0]
  Branch (563:9): [True: 0, False: 0]
  Branch (563:9): [True: 0, False: 27]
  Branch (563:9): [True: 0, False: 0]
  Branch (563:9): [True: 0, False: 270]
  Branch (563:9): [True: 0, False: 0]
564
297
    return LocaleIndependentAtoi<Int>(value.get_str());
565
297
}
Unexecuted instantiation: _Z9SettingToITkSt8integralaESt8optionalIT_ERK8UniValue
Unexecuted instantiation: _Z9SettingToITkSt8integralhESt8optionalIT_ERK8UniValue
Unexecuted instantiation: _Z9SettingToITkSt8integralsESt8optionalIT_ERK8UniValue
Unexecuted instantiation: _Z9SettingToITkSt8integraltESt8optionalIT_ERK8UniValue
_Z9SettingToITkSt8integraliESt8optionalIT_ERK8UniValue
Line
Count
Source
559
54
{
560
54
    if (value.isNull()) return std::nullopt;
  Branch (560:9): [True: 27, False: 27]
561
27
    if (value.isFalse()) return 0;
  Branch (561:9): [True: 0, False: 27]
562
27
    if (value.isTrue()) return 1;
  Branch (562:9): [True: 0, False: 27]
563
27
    if (value.isNum()) return value.getInt<Int>();
  Branch (563:9): [True: 0, False: 27]
564
27
    return LocaleIndependentAtoi<Int>(value.get_str());
565
27
}
Unexecuted instantiation: _Z9SettingToITkSt8integraljESt8optionalIT_ERK8UniValue
_Z9SettingToITkSt8integrallESt8optionalIT_ERK8UniValue
Line
Count
Source
559
1.32k
{
560
1.32k
    if (value.isNull()) return std::nullopt;
  Branch (560:9): [True: 1.05k, False: 270]
561
270
    if (value.isFalse()) return 0;
  Branch (561:9): [True: 0, False: 270]
562
270
    if (value.isTrue()) return 1;
  Branch (562:9): [True: 0, False: 270]
563
270
    if (value.isNum()) return value.getInt<Int>();
  Branch (563:9): [True: 0, False: 270]
564
270
    return LocaleIndependentAtoi<Int>(value.get_str());
565
270
}
_Z9SettingToITkSt8integralmESt8optionalIT_ERK8UniValue
Line
Count
Source
559
108
{
560
108
    if (value.isNull()) return std::nullopt;
  Branch (560:9): [True: 108, False: 0]
561
0
    if (value.isFalse()) return 0;
  Branch (561:9): [True: 0, False: 0]
562
0
    if (value.isTrue()) return 1;
  Branch (562:9): [True: 0, False: 0]
563
0
    if (value.isNum()) return value.getInt<Int>();
  Branch (563:9): [True: 0, False: 0]
564
0
    return LocaleIndependentAtoi<Int>(value.get_str());
565
0
}
566
567
template <std::integral Int>
568
Int SettingTo(const common::SettingsValue& value, Int nDefault)
569
0
{
570
0
    return SettingTo<Int>(value).value_or(nDefault);
571
0
}
Unexecuted instantiation: _Z9SettingToITkSt8integralaET_RK8UniValueS0_
Unexecuted instantiation: _Z9SettingToITkSt8integralhET_RK8UniValueS0_
Unexecuted instantiation: _Z9SettingToITkSt8integralsET_RK8UniValueS0_
Unexecuted instantiation: _Z9SettingToITkSt8integraltET_RK8UniValueS0_
Unexecuted instantiation: _Z9SettingToITkSt8integraliET_RK8UniValueS0_
Unexecuted instantiation: _Z9SettingToITkSt8integraljET_RK8UniValueS0_
Unexecuted instantiation: _Z9SettingToITkSt8integrallET_RK8UniValueS0_
Unexecuted instantiation: _Z9SettingToITkSt8integralmET_RK8UniValueS0_
572
573
bool ArgsManager::GetBoolArg(const std::string& strArg, bool fDefault) const
574
489k
{
575
489k
    return GetBoolArg(strArg).value_or(fDefault);
576
489k
}
577
578
std::optional<bool> ArgsManager::GetBoolArg(const std::string& strArg) const
579
490k
{
580
490k
    const common::SettingsValue value = GetSetting(strArg);
581
490k
    return SettingToBool(value);
582
490k
}
583
584
std::optional<bool> SettingToBool(const common::SettingsValue& value)
585
490k
{
586
490k
    if (value.isNull()) return std::nullopt;
  Branch (586:9): [True: 489k, False: 324]
587
324
    if (value.isBool()) return value.get_bool();
  Branch (587:9): [True: 0, False: 324]
588
324
    return InterpretBool(value.get_str());
589
324
}
590
591
bool SettingToBool(const common::SettingsValue& value, bool fDefault)
592
0
{
593
0
    return SettingToBool(value).value_or(fDefault);
594
0
}
595
596
#define INSTANTIATE_INT_TYPE(Type)                                                    \
597
    template Type ArgsManager::GetArg<Type>(const std::string&, Type) const;          \
598
    template std::optional<Type> ArgsManager::GetArg<Type>(const std::string&) const; \
599
    template Type SettingTo<Type>(const common::SettingsValue&, Type);                \
600
    template std::optional<Type> SettingTo<Type>(const common::SettingsValue&)
601
602
INSTANTIATE_INT_TYPE(int8_t);
603
INSTANTIATE_INT_TYPE(uint8_t);
604
INSTANTIATE_INT_TYPE(int16_t);
605
INSTANTIATE_INT_TYPE(uint16_t);
606
INSTANTIATE_INT_TYPE(int32_t);
607
INSTANTIATE_INT_TYPE(uint32_t);
608
INSTANTIATE_INT_TYPE(int64_t);
609
INSTANTIATE_INT_TYPE(uint64_t);
610
611
#undef INSTANTIATE_INT_TYPE
612
613
bool ArgsManager::SoftSetArg(const std::string& strArg, const std::string& strValue)
614
108
{
615
108
    LOCK(cs_args);
616
108
    if (!GetSetting_(strArg).isNull()) return false;
  Branch (616:9): [True: 27, False: 81]
617
81
    m_settings.forced_settings[SettingName(strArg)] = strValue;
618
81
    return true;
619
108
}
620
621
bool ArgsManager::SoftSetBoolArg(const std::string& strArg, bool fValue)
622
108
{
623
108
    if (fValue)
  Branch (623:9): [True: 54, False: 54]
624
54
        return SoftSetArg(strArg, std::string("1"));
625
54
    else
626
54
        return SoftSetArg(strArg, std::string("0"));
627
108
}
628
629
void ArgsManager::ForceSetArg(const std::string& strArg, const std::string& strValue)
630
0
{
631
0
    LOCK(cs_args);
632
0
    m_settings.forced_settings[SettingName(strArg)] = strValue;
633
0
}
634
635
void ArgsManager::AddCommand(const std::string& cmd, const std::string& help, std::set<std::string> options)
636
0
{
637
0
    Assert(cmd.find('=') == std::string::npos);
638
0
    Assert(cmd.at(0) != '-');
639
640
0
    LOCK(cs_args);
641
0
    m_accept_any_command = false; // latch to false
642
0
    std::map<std::string, Arg>& arg_map = m_available_args[OptionsCategory::COMMANDS];
643
0
    auto ret = arg_map.emplace(cmd, Arg{"", help, ArgsManager::COMMAND});
644
0
    if (!options.empty()) {
  Branch (644:9): [True: 0, False: 0]
645
0
        auto& cmdopts = m_available_args[OptionsCategory::COMMAND_OPTIONS];
646
0
        bool command_has_all_options_defined = true;
647
0
        for (const auto& opt : options) {
  Branch (647:30): [True: 0, False: 0]
648
0
            if (!cmdopts.contains(opt)) {
  Branch (648:17): [True: 0, False: 0]
649
0
                command_has_all_options_defined = false;
650
0
            }
651
0
        }
652
0
        Assert(command_has_all_options_defined);
653
654
0
        m_command_args.try_emplace(cmd, std::move(options));
655
0
    }
656
0
    Assert(ret.second); // Fail on duplicate commands
657
0
}
658
659
void ArgsManager::AddArg(const std::string& name, const std::string& help, unsigned int flags, const OptionsCategory& cat)
660
5.21k
{
661
5.21k
    Assert((flags & ArgsManager::COMMAND) == 0); // use AddCommand
662
663
    // Split arg name from its help param
664
5.21k
    size_t eq_index = name.find('=');
665
5.21k
    if (eq_index == std::string::npos) {
  Branch (665:9): [True: 2.37k, False: 2.83k]
666
2.37k
        eq_index = name.size();
667
2.37k
    }
668
5.21k
    std::string arg_name = name.substr(0, eq_index);
669
670
5.21k
    LOCK(cs_args);
671
672
    // Allow duplicates involving HIDDEN — it is used as a placeholder for args
673
    // unavailable in this binary but tolerated for shared config files (see #13441).
674
29.3k
    for (const auto& arg_map : m_available_args) {
  Branch (674:30): [True: 29.3k, False: 5.21k]
675
29.3k
        if (arg_map.first == OptionsCategory::HIDDEN || cat == OptionsCategory::HIDDEN) continue;
  Branch (675:13): [True: 5.15k, False: 24.2k]
  Branch (675:57): [True: 4.83k, False: 19.3k]
676
19.3k
        Assert(!arg_map.second.contains(arg_name));
677
19.3k
    }
678
679
5.21k
    std::map<std::string, Arg>& arg_map = m_available_args[cat];
680
5.21k
    auto ret = arg_map.emplace(arg_name, Arg{name.substr(eq_index, name.size() - eq_index), help, flags});
681
5.21k
    assert(ret.second); // Make sure an insertion actually happened
  Branch (681:5): [True: 5.21k, False: 0]
682
683
5.21k
    if (flags & ArgsManager::NETWORK_ONLY) {
  Branch (683:9): [True: 216, False: 4.99k]
684
216
        m_network_only_args.emplace(arg_name);
685
216
    }
686
5.21k
}
687
688
void ArgsManager::AddHiddenArgs(const std::vector<std::string>& names)
689
54
{
690
540
    for (const std::string& name : names) {
  Branch (690:34): [True: 540, False: 54]
691
540
        AddArg(name, "", ArgsManager::ALLOW_ANY, OptionsCategory::HIDDEN);
692
540
    }
693
54
}
694
695
void ArgsManager::ClearArgs()
696
0
{
697
0
    LOCK(cs_args);
698
0
    m_settings = {};
699
0
    m_available_args.clear();
700
0
    m_command_args.clear();
701
0
    m_network_only_args.clear();
702
0
    m_config_sections.clear();
703
0
}
704
705
void ArgsManager::CheckMultipleCLIArgs() const
706
0
{
707
0
    LOCK(cs_args);
708
0
    std::vector<std::string> found{};
709
0
    auto cmds = m_available_args.find(OptionsCategory::CLI_COMMANDS);
710
0
    if (cmds != m_available_args.end()) {
  Branch (710:9): [True: 0, False: 0]
711
0
        for (const auto& [cmd, argspec] : cmds->second) {
  Branch (711:41): [True: 0, False: 0]
712
0
            if (!GetSetting_(cmd).isNull()) {
  Branch (712:17): [True: 0, False: 0]
713
0
                found.push_back(cmd);
714
0
            }
715
0
        }
716
0
        if (found.size() > 1) {
  Branch (716:13): [True: 0, False: 0]
717
0
            throw std::runtime_error(strprintf("Only one of %s may be specified.", util::Join(found, ", ")));
718
0
        }
719
0
    }
720
0
}
721
722
std::string ArgsManager::GetHelpMessage() const
723
0
{
724
0
    const bool show_debug = GetBoolArg("-help-debug", false);
725
726
0
    std::string usage;
727
0
    LOCK(cs_args);
728
729
0
    const auto command_options = m_available_args.find(OptionsCategory::COMMAND_OPTIONS);
730
0
    const auto for_matching_cmd_opts = [&](const std::set<std::string>& select, auto&& fn) EXCLUSIVE_LOCKS_REQUIRED(cs_args) {
731
0
        if (select.empty()) return;
  Branch (731:13): [True: 0, False: 0]
732
0
        if (command_options == m_available_args.end()) return;
  Branch (732:13): [True: 0, False: 0]
733
0
        for (const auto& [name, info] : command_options->second) {
  Branch (733:39): [True: 0, False: 0]
734
0
            if (!show_debug && (info.m_flags & ArgsManager::DEBUG_ONLY)) continue;
  Branch (734:17): [True: 0, False: 0]
  Branch (734:32): [True: 0, False: 0]
735
0
            if (!select.contains(name)) continue;
  Branch (735:17): [True: 0, False: 0]
736
0
            fn(name, info);
737
0
        }
738
0
    };
739
740
0
    for (const auto& [category, category_args] : m_available_args) {
  Branch (740:48): [True: 0, False: 0]
741
0
        switch(category) {
  Branch (741:16): [True: 0, False: 0]
742
0
            case OptionsCategory::OPTIONS:
  Branch (742:13): [True: 0, False: 0]
743
0
                usage += HelpMessageGroup("Options:");
744
0
                break;
745
0
            case OptionsCategory::CONNECTION:
  Branch (745:13): [True: 0, False: 0]
746
0
                usage += HelpMessageGroup("Connection options:");
747
0
                break;
748
0
            case OptionsCategory::ZMQ:
  Branch (748:13): [True: 0, False: 0]
749
0
                usage += HelpMessageGroup("ZeroMQ notification options:");
750
0
                break;
751
0
            case OptionsCategory::DEBUG_TEST:
  Branch (751:13): [True: 0, False: 0]
752
0
                usage += HelpMessageGroup("Debugging/Testing options:");
753
0
                break;
754
0
            case OptionsCategory::NODE_RELAY:
  Branch (754:13): [True: 0, False: 0]
755
0
                usage += HelpMessageGroup("Node relay options:");
756
0
                break;
757
0
            case OptionsCategory::BLOCK_CREATION:
  Branch (757:13): [True: 0, False: 0]
758
0
                usage += HelpMessageGroup("Block creation options:");
759
0
                break;
760
0
            case OptionsCategory::RPC:
  Branch (760:13): [True: 0, False: 0]
761
0
                usage += HelpMessageGroup("RPC server options:");
762
0
                break;
763
0
            case OptionsCategory::IPC:
  Branch (763:13): [True: 0, False: 0]
764
0
                usage += HelpMessageGroup("IPC interprocess connection options:");
765
0
                break;
766
0
            case OptionsCategory::WALLET:
  Branch (766:13): [True: 0, False: 0]
767
0
                usage += HelpMessageGroup("Wallet options:");
768
0
                break;
769
0
            case OptionsCategory::WALLET_DEBUG_TEST:
  Branch (769:13): [True: 0, False: 0]
770
0
                if (show_debug) usage += HelpMessageGroup("Wallet debugging/testing options:");
  Branch (770:21): [True: 0, False: 0]
771
0
                break;
772
0
            case OptionsCategory::CHAINPARAMS:
  Branch (772:13): [True: 0, False: 0]
773
0
                usage += HelpMessageGroup("Chain selection options:");
774
0
                break;
775
0
            case OptionsCategory::GUI:
  Branch (775:13): [True: 0, False: 0]
776
0
                usage += HelpMessageGroup("UI Options:");
777
0
                break;
778
0
            case OptionsCategory::COMMANDS:
  Branch (778:13): [True: 0, False: 0]
779
0
                usage += HelpMessageGroup("Commands:");
780
0
                break;
781
0
            case OptionsCategory::REGISTER_COMMANDS:
  Branch (781:13): [True: 0, False: 0]
782
0
                usage += HelpMessageGroup("Register Commands:");
783
0
                break;
784
0
            case OptionsCategory::CLI_COMMANDS:
  Branch (784:13): [True: 0, False: 0]
785
0
                usage += HelpMessageGroup("CLI Commands:");
786
0
                break;
787
0
            case OptionsCategory::COMMAND_OPTIONS:
  Branch (787:13): [True: 0, False: 0]
788
0
            case OptionsCategory::HIDDEN:
  Branch (788:13): [True: 0, False: 0]
789
0
                break;
790
0
        } // no default case, so the compiler can warn about missing cases
791
792
0
        if (category == OptionsCategory::COMMAND_OPTIONS) continue;
  Branch (792:13): [True: 0, False: 0]
793
794
        // When we get to the hidden options, stop
795
0
        if (category == OptionsCategory::HIDDEN) break;
  Branch (795:13): [True: 0, False: 0]
796
797
0
        for (const auto& [arg_name, arg_info] : category_args) {
  Branch (797:47): [True: 0, False: 0]
798
0
            if (show_debug || !(arg_info.m_flags & ArgsManager::DEBUG_ONLY)) {
  Branch (798:17): [True: 0, False: 0]
  Branch (798:31): [True: 0, False: 0]
799
0
                usage += HelpMessageOpt(arg_name, arg_info.m_help_param, arg_info.m_help_text);
800
801
0
                if (category == OptionsCategory::COMMANDS) {
  Branch (801:21): [True: 0, False: 0]
802
0
                    const auto cmd_args = m_command_args.find(arg_name);
803
0
                    if (cmd_args == m_command_args.end()) continue;
  Branch (803:25): [True: 0, False: 0]
804
0
                    for_matching_cmd_opts(cmd_args->second, [&](const auto& cmdopt_name, const auto& cmdopt_info) {
805
0
                        usage += HelpMessageOpt(cmdopt_name, cmdopt_info.m_help_param, cmdopt_info.m_help_text, /*subopt=*/true);
806
0
                    });
807
0
                }
808
0
            }
809
0
        }
810
0
    }
811
0
    return usage;
812
0
}
813
814
bool HelpRequested(const ArgsManager& args)
815
27
{
816
27
    return args.IsArgSet("-?") || args.IsArgSet("-h") || args.IsArgSet("-help") || args.IsArgSet("-help-debug");
  Branch (816:12): [True: 0, False: 27]
  Branch (816:35): [True: 0, False: 27]
  Branch (816:58): [True: 0, False: 27]
  Branch (816:84): [True: 0, False: 27]
817
27
}
818
819
void SetupHelpOptions(ArgsManager& args)
820
27
{
821
27
    args.AddArg("-help", "Print this help message and exit (also -h or -?)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
822
27
    args.AddHiddenArgs({"-h", "-?"});
823
27
}
824
825
0
std::string HelpMessageGroup(const std::string &message) {
826
0
    return std::string(message) + std::string("\n\n");
827
0
}
828
829
std::string HelpMessageOpt(std::string_view option, std::string_view help_param, std::string_view message, bool subopt)
830
0
{
831
0
    constexpr int screen_width = 79;
832
0
    int opt_indent = 2;
833
0
    int msg_indent = 7;
834
835
0
    if (subopt) {
  Branch (835:9): [True: 0, False: 0]
836
0
        int bump = msg_indent - opt_indent;
837
0
        opt_indent += bump; // opt_indent now at the old msg_indent level
838
0
        msg_indent += bump; // indent by the same amount
839
0
    }
840
0
    int msg_width = screen_width - msg_indent;
841
842
0
    return strprintf("%*s%s%s\n%*s%s\n\n",
843
0
                     opt_indent, "", option, help_param,
844
0
                     msg_indent, "", FormatParagraph(message, msg_width, msg_indent));
845
0
}
846
847
const std::vector<std::string> TEST_OPTIONS_DOC{
848
    "addrman (use deterministic addrman)",
849
    "reindex_after_failure_noninteractive_yes (When asked for a reindex after failure interactively, simulate as-if answered with 'yes')",
850
    "bip94 (enforce BIP94 consensus rules)",
851
};
852
853
bool HasTestOption(const ArgsManager& args, const std::string& test_option)
854
81
{
855
81
    const auto options = args.GetArgs("-test");
856
81
    return std::any_of(options.begin(), options.end(), [test_option](const auto& option) {
857
0
        return option == test_option;
858
0
    });
859
81
}
860
861
fs::path GetDefaultDataDir()
862
27
{
863
    // Windows:
864
    //   old: C:\Users\Username\AppData\Roaming\Bitcoin
865
    //   new: C:\Users\Username\AppData\Local\Bitcoin
866
    // macOS: ~/Library/Application Support/Bitcoin
867
    // Unix-like: ~/.bitcoin
868
#ifdef WIN32
869
    // Windows
870
    // Check for existence of datadir in old location and keep it there
871
    fs::path legacy_path = GetSpecialFolderPath(CSIDL_APPDATA) / "Bitcoin";
872
    if (fs::exists(legacy_path)) return legacy_path;
873
874
    // Otherwise, fresh installs can start in the new, "proper" location
875
    return GetSpecialFolderPath(CSIDL_LOCAL_APPDATA) / "Bitcoin";
876
#else
877
27
    fs::path pathRet;
878
27
    char* pszHome = getenv("HOME");
879
27
    if (pszHome == nullptr || strlen(pszHome) == 0)
  Branch (879:9): [True: 0, False: 27]
  Branch (879:31): [True: 0, False: 27]
880
0
        pathRet = fs::path("/");
881
27
    else
882
27
        pathRet = fs::path(pszHome);
883
#ifdef __APPLE__
884
    // macOS
885
    return pathRet / "Library/Application Support/Bitcoin";
886
#else
887
    // Unix-like
888
27
    return pathRet / ".bitcoin";
889
27
#endif
890
27
#endif
891
27
}
892
893
bool CheckDataDirOption(const ArgsManager& args)
894
54
{
895
54
    const fs::path datadir{args.GetPathArg("-datadir")};
896
54
    return datadir.empty() || fs::is_directory(fs::absolute(datadir));
  Branch (896:12): [True: 0, False: 54]
  Branch (896:31): [True: 54, False: 0]
897
54
}
898
899
fs::path ArgsManager::GetConfigFilePath() const
900
54
{
901
54
    LOCK(cs_args);
902
54
    return *Assert(m_config_path);
903
54
}
904
905
void ArgsManager::SetConfigFilePath(fs::path path)
906
0
{
907
0
    LOCK(cs_args);
908
0
    assert(!m_config_path);
  Branch (908:5): [True: 0, False: 0]
909
0
    m_config_path = path;
910
0
}
911
912
ChainType ArgsManager::GetChainType() const
913
54
{
914
54
    std::variant<ChainType, std::string> arg = GetChainArg();
915
54
    if (auto* parsed = std::get_if<ChainType>(&arg)) return *parsed;
  Branch (915:15): [True: 54, False: 0]
916
0
    throw std::runtime_error(strprintf("Unknown chain %s.", std::get<std::string>(arg)));
917
54
}
918
919
std::string ArgsManager::GetChainTypeString() const
920
0
{
921
0
    auto arg = GetChainArg();
922
0
    if (auto* parsed = std::get_if<ChainType>(&arg)) return ChainTypeToString(*parsed);
  Branch (922:15): [True: 0, False: 0]
923
0
    return std::get<std::string>(arg);
924
0
}
925
926
std::variant<ChainType, std::string> ArgsManager::GetChainArg() const
927
54
{
928
216
    auto get_net = [&](const std::string& arg) {
929
216
        LOCK(cs_args);
930
216
        common::SettingsValue value = common::GetSetting(m_settings, /* section= */ "", SettingName(arg),
931
216
            /* ignore_default_section_config= */ false,
932
216
            /*ignore_nonpersistent=*/false,
933
216
            /* get_chain_type= */ true);
934
216
        return value.isNull() ? false : value.isBool() ? value.get_bool() : InterpretBool(value.get_str());
  Branch (934:16): [True: 162, False: 54]
  Branch (934:41): [True: 0, False: 54]
935
216
    };
936
937
54
    const bool fRegTest = get_net("-regtest");
938
54
    const bool fSigNet  = get_net("-signet");
939
54
    const bool fTestNet = get_net("-testnet");
940
54
    const bool fTestNet4 = get_net("-testnet4");
941
54
    const auto chain_arg = GetArg("-chain");
942
943
54
    if ((int)chain_arg.has_value() + (int)fRegTest + (int)fSigNet + (int)fTestNet + (int)fTestNet4 > 1) {
  Branch (943:9): [True: 0, False: 54]
944
0
        throw std::runtime_error("Invalid combination of -regtest, -signet, -testnet, -testnet4 and -chain. Can use at most one.");
945
0
    }
946
54
    if (chain_arg) {
  Branch (946:9): [True: 0, False: 54]
947
0
        if (auto parsed = ChainTypeFromString(*chain_arg)) return *parsed;
  Branch (947:18): [True: 0, False: 0]
948
        // Not a known string, so return original string
949
0
        return *chain_arg;
950
0
    }
951
54
    if (fRegTest) return ChainType::REGTEST;
  Branch (951:9): [True: 54, False: 0]
952
0
    if (fSigNet) return ChainType::SIGNET;
  Branch (952:9): [True: 0, False: 0]
953
0
    if (fTestNet) return ChainType::TESTNET;
  Branch (953:9): [True: 0, False: 0]
954
0
    if (fTestNet4) return ChainType::TESTNET4;
  Branch (954:9): [True: 0, False: 0]
955
0
    return ChainType::MAIN;
956
0
}
957
958
bool ArgsManager::UseDefaultSection(const std::string& arg) const
959
1.09M
{
960
1.09M
    AssertLockHeld(cs_args);
961
1.09M
    return m_network == ChainTypeToString(ChainType::MAIN) || !m_network_only_args.contains(arg);
  Branch (961:12): [True: 18.4E, False: 1.09M]
  Branch (961:63): [True: 945k, False: 151k]
962
1.09M
}
963
964
common::SettingsValue ArgsManager::GetSetting_(const std::string& arg) const
965
793k
{
966
793k
    AssertLockHeld(cs_args);
967
793k
    return common::GetSetting(
968
793k
        m_settings, m_network, SettingName(arg), !UseDefaultSection(arg),
969
793k
        /*ignore_nonpersistent=*/false, /*get_chain_type=*/false);
970
793k
}
971
972
common::SettingsValue ArgsManager::GetSetting(const std::string& arg) const
973
492k
{
974
492k
    LOCK(cs_args);
975
492k
    return GetSetting_(arg);
976
492k
}
977
978
std::vector<common::SettingsValue> ArgsManager::GetSettingsList(const std::string& arg) const
979
303k
{
980
303k
    LOCK(cs_args);
981
303k
    return common::GetSettingsList(m_settings, m_network, SettingName(arg), !UseDefaultSection(arg));
982
303k
}
983
984
void ArgsManager::logArgsPrefix(
985
    const std::string& prefix,
986
    const std::string& section,
987
    const std::map<std::string, std::vector<common::SettingsValue>>& args) const
988
27
{
989
27
    AssertLockHeld(cs_args);
990
27
    std::string section_str = section.empty() ? "" : "[" + section + "] ";
  Branch (990:31): [True: 27, False: 0]
991
594
    for (const auto& arg : args) {
  Branch (991:26): [True: 594, False: 27]
992
675
        for (const auto& value : arg.second) {
  Branch (992:32): [True: 675, False: 594]
993
675
            std::optional<unsigned int> flags = GetArgFlags_('-' + arg.first);
994
675
            if (flags) {
  Branch (994:17): [True: 675, False: 0]
995
675
                std::string value_str = (*flags & SENSITIVE) ? "****" : value.write();
  Branch (995:41): [True: 0, False: 675]
996
675
                LogInfo("%s %s%s=%s\n", prefix, section_str, arg.first, value_str);
997
675
            }
998
675
        }
999
594
    }
1000
27
}
1001
1002
void ArgsManager::LogArgs() const
1003
27
{
1004
27
    LOCK(cs_args);
1005
27
    for (const auto& section : m_settings.ro_config) {
  Branch (1005:30): [True: 0, False: 27]
1006
0
        logArgsPrefix("Config file arg:", section.first, section.second);
1007
0
    }
1008
27
    for (const auto& setting : m_settings.rw_settings) {
  Branch (1008:30): [True: 0, False: 27]
1009
0
        LogInfo("Setting file arg: %s = %s\n", setting.first, setting.second.write());
1010
0
    }
1011
27
    logArgsPrefix("Command-line arg:", "", m_settings.command_line_options);
1012
27
}