LCOV - code coverage report
Current view: top level - src/util - system.cpp (source / functions) Hit Total Coverage
Test: coverage.lcov Lines: 710 796 89.2 %
Date: 2021-06-29 14:35:33 Functions: 74 77 96.1 %
Legend: Modified by patch:
Lines: hit not hit | Branches: + taken - not taken # not executed

Not modified by patch:
Lines: hit not hit | Branches: + taken - not taken # not executed
Branches: 289 352 82.1 %

           Branch data     Line data    Source code
#       1                 :            : // Copyright (c) 2009-2010 Satoshi Nakamoto
#       2                 :            : // Copyright (c) 2009-2020 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 <util/system.h>
#       7                 :            : 
#       8                 :            : #ifdef ENABLE_EXTERNAL_SIGNER
#       9                 :            : #include <boost/process.hpp>
#      10                 :            : #endif // ENABLE_EXTERNAL_SIGNER
#      11                 :            : 
#      12                 :            : #include <chainparamsbase.h>
#      13                 :            : #include <sync.h>
#      14                 :            : #include <util/check.h>
#      15                 :            : #include <util/getuniquepath.h>
#      16                 :            : #include <util/strencodings.h>
#      17                 :            : #include <util/string.h>
#      18                 :            : #include <util/translation.h>
#      19                 :            : 
#      20                 :            : 
#      21                 :            : #if (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__))
#      22                 :            : #include <pthread.h>
#      23                 :            : #include <pthread_np.h>
#      24                 :            : #endif
#      25                 :            : 
#      26                 :            : #ifndef WIN32
#      27                 :            : // for posix_fallocate, in configure.ac we check if it is present after this
#      28                 :            : #ifdef __linux__
#      29                 :            : 
#      30                 :            : #ifdef _POSIX_C_SOURCE
#      31                 :            : #undef _POSIX_C_SOURCE
#      32                 :            : #endif
#      33                 :            : 
#      34                 :            : #define _POSIX_C_SOURCE 200112L
#      35                 :            : 
#      36                 :            : #endif // __linux__
#      37                 :            : 
#      38                 :            : #include <algorithm>
#      39                 :            : #include <cassert>
#      40                 :            : #include <fcntl.h>
#      41                 :            : #include <sched.h>
#      42                 :            : #include <sys/resource.h>
#      43                 :            : #include <sys/stat.h>
#      44                 :            : 
#      45                 :            : #else
#      46                 :            : 
#      47                 :            : #ifdef _MSC_VER
#      48                 :            : #pragma warning(disable:4786)
#      49                 :            : #pragma warning(disable:4804)
#      50                 :            : #pragma warning(disable:4805)
#      51                 :            : #pragma warning(disable:4717)
#      52                 :            : #endif
#      53                 :            : 
#      54                 :            : #ifndef NOMINMAX
#      55                 :            : #define NOMINMAX
#      56                 :            : #endif
#      57                 :            : #include <codecvt>
#      58                 :            : 
#      59                 :            : #include <io.h> /* for _commit */
#      60                 :            : #include <shellapi.h>
#      61                 :            : #include <shlobj.h>
#      62                 :            : #endif
#      63                 :            : 
#      64                 :            : #ifdef HAVE_MALLOPT_ARENA_MAX
#      65                 :            : #include <malloc.h>
#      66                 :            : #endif
#      67                 :            : 
#      68                 :            : #include <boost/algorithm/string/replace.hpp>
#      69                 :            : #include <thread>
#      70                 :            : #include <typeinfo>
#      71                 :            : #include <univalue.h>
#      72                 :            : 
#      73                 :            : // Application startup time (used for uptime calculation)
#      74                 :            : const int64_t nStartupTime = GetTime();
#      75                 :            : 
#      76                 :            : const char * const BITCOIN_CONF_FILENAME = "bitcoin.conf";
#      77                 :            : const char * const BITCOIN_SETTINGS_FILENAME = "settings.json";
#      78                 :            : 
#      79                 :            : ArgsManager gArgs;
#      80                 :            : 
#      81                 :            : /** Mutex to protect dir_locks. */
#      82                 :            : static Mutex cs_dir_locks;
#      83                 :            : /** A map that contains all the currently held directory locks. After
#      84                 :            :  * successful locking, these will be held here until the global destructor
#      85                 :            :  * cleans them up and thus automatically unlocks them, or ReleaseDirectoryLocks
#      86                 :            :  * is called.
#      87                 :            :  */
#      88                 :            : static std::map<std::string, std::unique_ptr<fsbridge::FileLock>> dir_locks GUARDED_BY(cs_dir_locks);
#      89                 :            : 
#      90                 :            : bool LockDirectory(const fs::path& directory, const std::string lockfile_name, bool probe_only)
#      91                 :       1942 : {
#      92                 :       1942 :     LOCK(cs_dir_locks);
#      93                 :       1942 :     fs::path pathLockFile = directory / lockfile_name;
#      94                 :            : 
#      95                 :            :     // If a lock for this directory already exists in the map, don't try to re-lock it
#      96         [ +  + ]:       1942 :     if (dir_locks.count(pathLockFile.string())) {
#      97                 :          2 :         return true;
#      98                 :          2 :     }
#      99                 :            : 
#     100                 :            :     // Create empty lock file if it doesn't exist.
#     101                 :       1940 :     FILE* file = fsbridge::fopen(pathLockFile, "a");
#     102         [ +  + ]:       1940 :     if (file) fclose(file);
#     103                 :       1940 :     auto lock = std::make_unique<fsbridge::FileLock>(pathLockFile);
#     104         [ +  + ]:       1940 :     if (!lock->TryLock()) {
#     105                 :         10 :         return error("Error while attempting to lock directory %s: %s", directory.string(), lock->GetReason());
#     106                 :         10 :     }
#     107         [ +  + ]:       1930 :     if (!probe_only) {
#     108                 :            :         // Lock successful and we're not just probing, put it into the map
#     109                 :       1263 :         dir_locks.emplace(pathLockFile.string(), std::move(lock));
#     110                 :       1263 :     }
#     111                 :       1930 :     return true;
#     112                 :       1930 : }
#     113                 :            : 
#     114                 :            : void UnlockDirectory(const fs::path& directory, const std::string& lockfile_name)
#     115                 :        608 : {
#     116                 :        608 :     LOCK(cs_dir_locks);
#     117                 :        608 :     dir_locks.erase((directory / lockfile_name).string());
#     118                 :        608 : }
#     119                 :            : 
#     120                 :            : void ReleaseDirectoryLocks()
#     121                 :          3 : {
#     122                 :          3 :     LOCK(cs_dir_locks);
#     123                 :          3 :     dir_locks.clear();
#     124                 :          3 : }
#     125                 :            : 
#     126                 :            : bool DirIsWritable(const fs::path& directory)
#     127                 :       1330 : {
#     128                 :       1330 :     fs::path tmpFile = GetUniquePath(directory);
#     129                 :            : 
#     130                 :       1330 :     FILE* file = fsbridge::fopen(tmpFile, "a");
#     131         [ +  + ]:       1330 :     if (!file) return false;
#     132                 :            : 
#     133                 :       1329 :     fclose(file);
#     134                 :       1329 :     remove(tmpFile);
#     135                 :            : 
#     136                 :       1329 :     return true;
#     137                 :       1329 : }
#     138                 :            : 
#     139                 :            : bool CheckDiskSpace(const fs::path& dir, uint64_t additional_bytes)
#     140                 :       5177 : {
#     141                 :       5177 :     constexpr uint64_t min_disk_space = 52428800; // 50 MiB
#     142                 :            : 
#     143                 :       5177 :     uint64_t free_bytes_available = fs::space(dir).available;
#     144                 :       5177 :     return free_bytes_available >= min_disk_space + additional_bytes;
#     145                 :       5177 : }
#     146                 :            : 
#     147                 :          0 : std::streampos GetFileSize(const char* path, std::streamsize max) {
#     148                 :          0 :     std::ifstream file(path, std::ios::binary);
#     149                 :          0 :     file.ignore(max);
#     150                 :          0 :     return file.gcount();
#     151                 :          0 : }
#     152                 :            : 
#     153                 :            : /**
#     154                 :            :  * Interpret a string argument as a boolean.
#     155                 :            :  *
#     156                 :            :  * The definition of atoi() requires that non-numeric string values like "foo",
#     157                 :            :  * return 0. This means that if a user unintentionally supplies a non-integer
#     158                 :            :  * argument here, the return value is always false. This means that -foo=false
#     159                 :            :  * does what the user probably expects, but -foo=true is well defined but does
#     160                 :            :  * not do what they probably expected.
#     161                 :            :  *
#     162                 :            :  * The return value of atoi() is undefined when given input not representable as
#     163                 :            :  * an int. On most systems this means string value between "-2147483648" and
#     164                 :            :  * "2147483647" are well defined (this method will return true). Setting
#     165                 :            :  * -txindex=2147483648 on most systems, however, is probably undefined.
#     166                 :            :  *
#     167                 :            :  * For a more extensive discussion of this topic (and a wide range of opinions
#     168                 :            :  * on the Right Way to change this code), see PR12713.
#     169                 :            :  */
#     170                 :            : static bool InterpretBool(const std::string& strValue)
#     171                 :     144370 : {
#     172         [ +  + ]:     144370 :     if (strValue.empty())
#     173                 :       8146 :         return true;
#     174                 :     136224 :     return (atoi(strValue) != 0);
#     175                 :     136224 : }
#     176                 :            : 
#     177                 :            : static std::string SettingName(const std::string& arg)
#     178                 :    2380249 : {
#     179 [ +  - ][ +  + ]:    2380249 :     return arg.size() > 0 && arg[0] == '-' ? arg.substr(1) : arg;
#     180                 :    2380249 : }
#     181                 :            : 
#     182                 :            : /**
#     183                 :            :  * Interpret -nofoo as if the user supplied -foo=0.
#     184                 :            :  *
#     185                 :            :  * This method also tracks when the -no form was supplied, and if so,
#     186                 :            :  * checks whether there was a double-negative (-nofoo=0 -> -foo=1).
#     187                 :            :  *
#     188                 :            :  * If there was not a double negative, it removes the "no" from the key
#     189                 :            :  * and returns false.
#     190                 :            :  *
#     191                 :            :  * If there was a double negative, it removes "no" from the key, and
#     192                 :            :  * returns true.
#     193                 :            :  *
#     194                 :            :  * If there was no "no", it returns the string value untouched.
#     195                 :            :  *
#     196                 :            :  * Where an option was negated can be later checked using the
#     197                 :            :  * IsArgNegated() method. One use case for this is to have a way to disable
#     198                 :            :  * options that are not normally boolean (e.g. using -nodebuglogfile to request
#     199                 :            :  * that debug log output is not sent to any file at all).
#     200                 :            :  */
#     201                 :            : 
#     202                 :            : static util::SettingsValue InterpretOption(std::string& section, std::string& key, const std::string& value)
#     203                 :     388233 : {
#     204                 :            :     // Split section name from key name for keys like "testnet.foo" or "regtest.bar"
#     205                 :     388233 :     size_t option_index = key.find('.');
#     206         [ +  + ]:     388233 :     if (option_index != std::string::npos) {
#     207                 :     123161 :         section = key.substr(0, option_index);
#     208                 :     123161 :         key.erase(0, option_index + 1);
#     209                 :     123161 :     }
#     210         [ +  + ]:     388233 :     if (key.substr(0, 2) == "no") {
#     211                 :     117703 :         key.erase(0, 2);
#     212                 :            :         // Double negatives like -nofoo=0 are supported (but discouraged)
#     213         [ +  + ]:     117703 :         if (!InterpretBool(value)) {
#     214                 :         16 :             LogPrintf("Warning: parsed potentially confusing double-negative -%s=%s\n", key, value);
#     215                 :         16 :             return true;
#     216                 :         16 :         }
#     217                 :     117687 :         return false;
#     218                 :     117687 :     }
#     219                 :     270530 :     return value;
#     220                 :     270530 : }
#     221                 :            : 
#     222                 :            : /**
#     223                 :            :  * Check settings value validity according to flags.
#     224                 :            :  *
#     225                 :            :  * TODO: Add more meaningful error checks here in the future
#     226                 :            :  * See "here's how the flags are meant to behave" in
#     227                 :            :  * https://github.com/bitcoin/bitcoin/pull/16097#issuecomment-514627823
#     228                 :            :  */
#     229                 :            : static bool CheckValid(const std::string& key, const util::SettingsValue& val, unsigned int flags, std::string& error)
#     230                 :     378611 : {
#     231 [ +  + ][ -  + ]:     378611 :     if (val.isBool() && !(flags & ArgsManager::ALLOW_BOOL)) {
#     232                 :          0 :         error = strprintf("Negating of -%s is meaningless and therefore forbidden", key);
#     233                 :          0 :         return false;
#     234                 :          0 :     }
#     235                 :     378611 :     return true;
#     236                 :     378611 : }
#     237                 :            : 
#     238                 :            : namespace {
#     239                 :            : fs::path StripRedundantLastElementsOfPath(const fs::path& path)
#     240                 :       6817 : {
#     241                 :       6817 :     auto result = path;
#     242         [ +  + ]:       6829 :     while (result.filename().string() == ".") {
#     243                 :         12 :         result = result.parent_path();
#     244                 :         12 :     }
#     245                 :            : 
#     246                 :       6817 :     assert(fs::equivalent(result, path));
#     247                 :       6817 :     return result;
#     248                 :       6817 : }
#     249                 :            : } // namespace
#     250                 :            : 
#     251                 :            : // Define default constructor and destructor that are not inline, so code instantiating this class doesn't need to
#     252                 :            : // #include class definitions for all members.
#     253                 :            : // For example, m_settings has an internal dependency on univalue.
#     254                 :      58561 : ArgsManager::ArgsManager() {}
#     255                 :      57133 : ArgsManager::~ArgsManager() {}
#     256                 :            : 
#     257                 :            : const std::set<std::string> ArgsManager::GetUnsuitableSectionOnlyArgs() const
#     258                 :      54940 : {
#     259                 :      54940 :     std::set<std::string> unsuitables;
#     260                 :            : 
#     261                 :      54940 :     LOCK(cs_args);
#     262                 :            : 
#     263                 :            :     // if there's no section selected, don't worry
#     264         [ -  + ]:      54940 :     if (m_network.empty()) return std::set<std::string> {};
#     265                 :            : 
#     266                 :            :     // if it's okay to use the default section for this network, don't worry
#     267         [ +  + ]:      54940 :     if (m_network == CBaseChainParams::MAIN) return std::set<std::string> {};
#     268                 :            : 
#     269         [ +  + ]:      36338 :     for (const auto& arg : m_network_only_args) {
#     270         [ +  + ]:      23584 :         if (OnlyHasDefaultSectionSetting(m_settings, m_network, SettingName(arg))) {
#     271                 :       1693 :             unsuitables.insert(arg);
#     272                 :       1693 :         }
#     273                 :      23584 :     }
#     274                 :      36338 :     return unsuitables;
#     275                 :      36338 : }
#     276                 :            : 
#     277                 :            : const std::list<SectionInfo> ArgsManager::GetUnrecognizedSections() const
#     278                 :       1515 : {
#     279                 :            :     // Section names to be recognized in the config file.
#     280                 :       1515 :     static const std::set<std::string> available_sections{
#     281                 :       1515 :         CBaseChainParams::REGTEST,
#     282                 :       1515 :         CBaseChainParams::SIGNET,
#     283                 :       1515 :         CBaseChainParams::TESTNET,
#     284                 :       1515 :         CBaseChainParams::MAIN
#     285                 :       1515 :     };
#     286                 :            : 
#     287                 :       1515 :     LOCK(cs_args);
#     288                 :       1515 :     std::list<SectionInfo> unrecognized = m_config_sections;
#     289                 :       1515 :     unrecognized.remove_if([](const SectionInfo& appeared){ return available_sections.find(appeared.m_name) != available_sections.end(); });
#     290                 :       1515 :     return unrecognized;
#     291                 :       1515 : }
#     292                 :            : 
#     293                 :            : void ArgsManager::SelectConfigNetwork(const std::string& network)
#     294                 :       3105 : {
#     295                 :       3105 :     LOCK(cs_args);
#     296                 :       3105 :     m_network = network;
#     297                 :       3105 : }
#     298                 :            : 
#     299                 :            : bool ArgsManager::ParseParameters(int argc, const char* const argv[], std::string& error)
#     300                 :      58627 : {
#     301                 :      58627 :     LOCK(cs_args);
#     302                 :      58627 :     m_settings.command_line_options.clear();
#     303                 :            : 
#     304         [ +  + ]:     214354 :     for (int i = 1; i < argc; i++) {
#     305                 :     156459 :         std::string key(argv[i]);
#     306                 :            : 
#     307                 :            : #ifdef MAC_OSX
#     308                 :            :         // At the first time when a user gets the "App downloaded from the
#     309                 :            :         // internet" warning, and clicks the Open button, macOS passes
#     310                 :            :         // a unique process serial number (PSN) as -psn_... command-line
#     311                 :            :         // argument, which we filter out.
#     312                 :            :         if (key.substr(0, 5) == "-psn_") continue;
#     313                 :            : #endif
#     314                 :            : 
#     315         [ -  + ]:     156459 :         if (key == "-") break; //bitcoin-tx using stdin
#     316                 :     156459 :         std::string val;
#     317                 :     156459 :         size_t is_index = key.find('=');
#     318         [ +  + ]:     156459 :         if (is_index != std::string::npos) {
#     319                 :     149286 :             val = key.substr(is_index + 1);
#     320                 :     149286 :             key.erase(is_index);
#     321                 :     149286 :         }
#     322                 :            : #ifdef WIN32
#     323                 :            :         key = ToLower(key);
#     324                 :            :         if (key[0] == '/')
#     325                 :            :             key[0] = '-';
#     326                 :            : #endif
#     327                 :            : 
#     328         [ +  + ]:     156459 :         if (key[0] != '-') {
#     329 [ +  + ][ +  - ]:        721 :             if (!m_accept_any_command && m_command.empty()) {
#     330                 :            :                 // The first non-dash arg is a registered command
#     331                 :         59 :                 std::optional<unsigned int> flags = GetArgFlags(key);
#     332 [ +  + ][ -  + ]:         59 :                 if (!flags || !(*flags & ArgsManager::COMMAND)) {
#     333                 :          4 :                     error = strprintf("Invalid command '%s'", argv[i]);
#     334                 :          4 :                     return false;
#     335                 :          4 :                 }
#     336                 :        717 :             }
#     337                 :        717 :             m_command.push_back(key);
#     338         [ +  + ]:       1319 :             while (++i < argc) {
#     339                 :            :                 // The remaining args are command args
#     340                 :        602 :                 m_command.push_back(argv[i]);
#     341                 :        602 :             }
#     342                 :        717 :             break;
#     343                 :        717 :         }
#     344                 :            : 
#     345                 :            :         // Transform --foo to -foo
#     346 [ +  - ][ +  + ]:     155738 :         if (key.length() > 1 && key[1] == '-')
#     347                 :         12 :             key.erase(0, 1);
#     348                 :            : 
#     349                 :            :         // Transform -foo to foo
#     350                 :     155738 :         key.erase(0, 1);
#     351                 :     155738 :         std::string section;
#     352                 :     155738 :         util::SettingsValue value = InterpretOption(section, key, val);
#     353                 :     155738 :         std::optional<unsigned int> flags = GetArgFlags('-' + key);
#     354                 :            : 
#     355                 :            :         // Unknown command line options and command line options with dot
#     356                 :            :         // characters (which are returned from InterpretOption with nonempty
#     357                 :            :         // section strings) are not valid.
#     358 [ +  + ][ +  + ]:     155738 :         if (!flags || !section.empty()) {
#     359                 :         11 :             error = strprintf("Invalid parameter %s", argv[i]);
#     360                 :         11 :             return false;
#     361                 :         11 :         }
#     362                 :            : 
#     363         [ -  + ]:     155727 :         if (!CheckValid(key, value, *flags, error)) return false;
#     364                 :            : 
#     365                 :     155727 :         m_settings.command_line_options[key].push_back(value);
#     366                 :     155727 :     }
#     367                 :            : 
#     368                 :            :     // we do not allow -includeconf from command line
#     369         [ +  + ]:      58627 :     if (auto* includes = util::FindKey(m_settings.command_line_options, "includeconf")) {
#     370                 :          2 :         const auto& include{*util::SettingsSpan(*includes).begin()}; // pick first value as example
#     371                 :          2 :         error = "-includeconf cannot be used from commandline; -includeconf=" + include.write();
#     372                 :          2 :         return false;
#     373                 :          2 :     }
#     374                 :      58610 :     return true;
#     375                 :      58610 : }
#     376                 :            : 
#     377                 :            : std::optional<unsigned int> ArgsManager::GetArgFlags(const std::string& name) const
#     378                 :     404843 : {
#     379                 :     404843 :     LOCK(cs_args);
#     380         [ +  + ]:     570210 :     for (const auto& arg_map : m_available_args) {
#     381                 :     570210 :         const auto search = arg_map.second.find(name);
#     382         [ +  + ]:     570210 :         if (search != arg_map.second.end()) {
#     383                 :     395399 :             return search->second.m_flags;
#     384                 :     395399 :         }
#     385                 :     570210 :     }
#     386                 :     404843 :     return std::nullopt;
#     387                 :     404843 : }
#     388                 :            : 
#     389                 :            : const fs::path& ArgsManager::GetBlocksDirPath() const
#     390                 :     410413 : {
#     391                 :     410413 :     LOCK(cs_args);
#     392                 :     410413 :     fs::path& path = m_cached_blocks_path;
#     393                 :            : 
#     394                 :            :     // Cache the path to avoid calling fs::create_directories on every call of
#     395                 :            :     // this function
#     396         [ +  + ]:     410413 :     if (!path.empty()) return path;
#     397                 :            : 
#     398         [ +  + ]:       1515 :     if (IsArgSet("-blocksdir")) {
#     399                 :          2 :         path = fs::system_complete(GetArg("-blocksdir", ""));
#     400         [ +  + ]:          2 :         if (!fs::is_directory(path)) {
#     401                 :          1 :             path = "";
#     402                 :          1 :             return path;
#     403                 :          1 :         }
#     404                 :       1513 :     } else {
#     405                 :       1513 :         path = GetDataDirBase();
#     406                 :       1513 :     }
#     407                 :            : 
#     408                 :       1515 :     path /= BaseParams().DataDir();
#     409                 :       1514 :     path /= "blocks";
#     410                 :       1514 :     fs::create_directories(path);
#     411                 :       1514 :     path = StripRedundantLastElementsOfPath(path);
#     412                 :       1514 :     return path;
#     413                 :       1515 : }
#     414                 :            : 
#     415                 :            : const fs::path& ArgsManager::GetDataDir(bool net_specific) const
#     416                 :      29339 : {
#     417                 :      29339 :     LOCK(cs_args);
#     418         [ +  + ]:      29339 :     fs::path& path = net_specific ? m_cached_network_datadir_path : m_cached_datadir_path;
#     419                 :            : 
#     420                 :            :     // Cache the path to avoid calling fs::create_directories on every call of
#     421                 :            :     // this function
#     422         [ +  + ]:      29339 :     if (!path.empty()) return path;
#     423                 :            : 
#     424                 :       5303 :     std::string datadir = GetArg("-datadir", "");
#     425         [ +  - ]:       5303 :     if (!datadir.empty()) {
#     426                 :       5303 :         path = fs::system_complete(datadir);
#     427         [ -  + ]:       5303 :         if (!fs::is_directory(path)) {
#     428                 :          0 :             path = "";
#     429                 :          0 :             return path;
#     430                 :          0 :         }
#     431                 :          0 :     } else {
#     432                 :          0 :         path = GetDefaultDataDir();
#     433                 :          0 :     }
#     434         [ +  + ]:       5303 :     if (net_specific)
#     435                 :       2241 :         path /= BaseParams().DataDir();
#     436                 :            : 
#     437         [ +  + ]:       5303 :     if (fs::create_directories(path)) {
#     438                 :            :         // This is the first run, create wallets subdirectory too
#     439                 :        285 :         fs::create_directories(path / "wallets");
#     440                 :        285 :     }
#     441                 :            : 
#     442                 :       5303 :     path = StripRedundantLastElementsOfPath(path);
#     443                 :       5303 :     return path;
#     444                 :       5303 : }
#     445                 :            : 
#     446                 :            : void ArgsManager::ClearPathCache()
#     447                 :       2201 : {
#     448                 :       2201 :     LOCK(cs_args);
#     449                 :            : 
#     450                 :       2201 :     m_cached_datadir_path = fs::path();
#     451                 :       2201 :     m_cached_network_datadir_path = fs::path();
#     452                 :       2201 :     m_cached_blocks_path = fs::path();
#     453                 :       2201 : }
#     454                 :            : 
#     455                 :            : std::optional<const ArgsManager::Command> ArgsManager::GetCommand() const
#     456                 :         57 : {
#     457                 :         57 :     Command ret;
#     458                 :         57 :     LOCK(cs_args);
#     459                 :         57 :     auto it = m_command.begin();
#     460         [ +  + ]:         57 :     if (it == m_command.end()) {
#     461                 :            :         // No command was passed
#     462                 :          2 :         return std::nullopt;
#     463                 :          2 :     }
#     464         [ +  - ]:         55 :     if (!m_accept_any_command) {
#     465                 :            :         // The registered command
#     466                 :         55 :         ret.command = *(it++);
#     467                 :         55 :     }
#     468         [ +  + ]:         57 :     while (it != m_command.end()) {
#     469                 :            :         // The unregistered command and args (if any)
#     470                 :          2 :         ret.args.push_back(*(it++));
#     471                 :          2 :     }
#     472                 :         55 :     return ret;
#     473                 :         55 : }
#     474                 :            : 
#     475                 :            : std::vector<std::string> ArgsManager::GetArgs(const std::string& strArg) const
#     476                 :      74786 : {
#     477                 :      74786 :     std::vector<std::string> result;
#     478         [ +  + ]:      96214 :     for (const util::SettingsValue& value : GetSettingsList(strArg)) {
#     479 [ -  + ][ +  + ]:      96214 :         result.push_back(value.isFalse() ? "0" : value.isTrue() ? "1" : value.get_str());
#     480                 :      96214 :     }
#     481                 :      74786 :     return result;
#     482                 :      74786 : }
#     483                 :            : 
#     484                 :            : bool ArgsManager::IsArgSet(const std::string& strArg) const
#     485                 :     194424 : {
#     486                 :     194424 :     return !GetSetting(strArg).isNull();
#     487                 :     194424 : }
#     488                 :            : 
#     489                 :            : bool ArgsManager::InitSettings(std::string& error)
#     490                 :        671 : {
#     491         [ +  + ]:        671 :     if (!GetSettingsPath()) {
#     492                 :          2 :         return true; // Do nothing if settings file disabled.
#     493                 :          2 :     }
#     494                 :            : 
#     495                 :        669 :     std::vector<std::string> errors;
#     496         [ +  + ]:        669 :     if (!ReadSettingsFile(&errors)) {
#     497                 :          3 :         error = strprintf("Failed loading settings file:\n- %s\n", Join(errors, "\n- "));
#     498                 :          3 :         return false;
#     499                 :          3 :     }
#     500         [ -  + ]:        666 :     if (!WriteSettingsFile(&errors)) {
#     501                 :          0 :         error = strprintf("Failed saving settings file:\n- %s\n", Join(errors, "\n- "));
#     502                 :          0 :         return false;
#     503                 :          0 :     }
#     504                 :        666 :     return true;
#     505                 :        666 : }
#     506                 :            : 
#     507                 :            : bool ArgsManager::GetSettingsPath(fs::path* filepath, bool temp) const
#     508                 :       3160 : {
#     509         [ +  + ]:       3160 :     if (IsArgNegated("-settings")) {
#     510                 :          2 :         return false;
#     511                 :          2 :     }
#     512         [ +  + ]:       3158 :     if (filepath) {
#     513                 :       2489 :         std::string settings = GetArg("-settings", BITCOIN_SETTINGS_FILENAME);
#     514         [ +  + ]:       2489 :         *filepath = fsbridge::AbsPathJoin(GetDataDirNet(), temp ? settings + ".tmp" : settings);
#     515                 :       2489 :     }
#     516                 :       3158 :     return true;
#     517                 :       3158 : }
#     518                 :            : 
#     519                 :            : static void SaveErrors(const std::vector<std::string> errors, std::vector<std::string>* error_out)
#     520                 :          5 : {
#     521         [ +  + ]:          5 :     for (const auto& error : errors) {
#     522         [ +  + ]:          5 :         if (error_out) {
#     523                 :          3 :             error_out->emplace_back(error);
#     524                 :          3 :         } else {
#     525                 :          2 :             LogPrintf("%s\n", error);
#     526                 :          2 :         }
#     527                 :          5 :     }
#     528                 :          5 : }
#     529                 :            : 
#     530                 :            : bool ArgsManager::ReadSettingsFile(std::vector<std::string>* errors)
#     531                 :        671 : {
#     532                 :        671 :     fs::path path;
#     533         [ -  + ]:        671 :     if (!GetSettingsPath(&path, /* temp= */ false)) {
#     534                 :          0 :         return true; // Do nothing if settings file disabled.
#     535                 :          0 :     }
#     536                 :            : 
#     537                 :        671 :     LOCK(cs_args);
#     538                 :        671 :     m_settings.rw_settings.clear();
#     539                 :        671 :     std::vector<std::string> read_errors;
#     540         [ +  + ]:        671 :     if (!util::ReadSettings(path, m_settings.rw_settings, read_errors)) {
#     541                 :          3 :         SaveErrors(read_errors, errors);
#     542                 :          3 :         return false;
#     543                 :          3 :     }
#     544         [ +  + ]:        668 :     for (const auto& setting : m_settings.rw_settings) {
#     545                 :        188 :         std::string section;
#     546                 :        188 :         std::string key = setting.first;
#     547                 :        188 :         (void)InterpretOption(section, key, /* value */ {}); // Split setting key into section and argname
#     548         [ +  + ]:        188 :         if (!GetArgFlags('-' + key)) {
#     549                 :          8 :             LogPrintf("Ignoring unknown rw_settings value %s\n", setting.first);
#     550                 :          8 :         }
#     551                 :        188 :     }
#     552                 :        668 :     return true;
#     553                 :        668 : }
#     554                 :            : 
#     555                 :            : bool ArgsManager::WriteSettingsFile(std::vector<std::string>* errors) const
#     556                 :        909 : {
#     557                 :        909 :     fs::path path, path_tmp;
#     558 [ -  + ][ -  + ]:        909 :     if (!GetSettingsPath(&path, /* temp= */ false) || !GetSettingsPath(&path_tmp, /* temp= */ true)) {
#     559                 :          0 :         throw std::logic_error("Attempt to write settings file when dynamic settings are disabled.");
#     560                 :          0 :     }
#     561                 :            : 
#     562                 :        909 :     LOCK(cs_args);
#     563                 :        909 :     std::vector<std::string> write_errors;
#     564         [ -  + ]:        909 :     if (!util::WriteSettings(path_tmp, m_settings.rw_settings, write_errors)) {
#     565                 :          0 :         SaveErrors(write_errors, errors);
#     566                 :          0 :         return false;
#     567                 :          0 :     }
#     568         [ +  + ]:        909 :     if (!RenameOver(path_tmp, path)) {
#     569                 :          2 :         SaveErrors({strprintf("Failed renaming settings file %s to %s\n", path_tmp.string(), path.string())}, errors);
#     570                 :          2 :         return false;
#     571                 :          2 :     }
#     572                 :        907 :     return true;
#     573                 :        907 : }
#     574                 :            : 
#     575                 :            : bool ArgsManager::IsArgNegated(const std::string& strArg) const
#     576                 :      58134 : {
#     577                 :      58134 :     return GetSetting(strArg).isFalse();
#     578                 :      58134 : }
#     579                 :            : 
#     580                 :            : std::string ArgsManager::GetArg(const std::string& strArg, const std::string& strDefault) const
#     581                 :     250776 : {
#     582                 :     250776 :     const util::SettingsValue value = GetSetting(strArg);
#     583 [ +  + ][ +  + ]:     250776 :     return value.isNull() ? strDefault : value.isFalse() ? "0" : value.isTrue() ? "1" : value.get_str();
#                 [ +  + ]
#     584                 :     250776 : }
#     585                 :            : 
#     586                 :            : int64_t ArgsManager::GetArg(const std::string& strArg, int64_t nDefault) const
#     587                 :    1054026 : {
#     588                 :    1054026 :     const util::SettingsValue value = GetSetting(strArg);
#     589 [ +  + ][ +  + ]:    1054026 :     return value.isNull() ? nDefault : value.isFalse() ? 0 : value.isTrue() ? 1 : value.isNum() ? value.get_int64() : atoi64(value.get_str());
#         [ +  + ][ -  + ]
#     590                 :    1054026 : }
#     591                 :            : 
#     592                 :            : bool ArgsManager::GetBoolArg(const std::string& strArg, bool fDefault) const
#     593                 :     642690 : {
#     594                 :     642690 :     const util::SettingsValue value = GetSetting(strArg);
#     595 [ +  + ][ +  + ]:     642690 :     return value.isNull() ? fDefault : value.isBool() ? value.get_bool() : InterpretBool(value.get_str());
#     596                 :     642690 : }
#     597                 :            : 
#     598                 :            : bool ArgsManager::SoftSetArg(const std::string& strArg, const std::string& strValue)
#     599                 :      54795 : {
#     600                 :      54795 :     LOCK(cs_args);
#     601         [ +  + ]:      54795 :     if (IsArgSet(strArg)) return false;
#     602                 :       1428 :     ForceSetArg(strArg, strValue);
#     603                 :       1428 :     return true;
#     604                 :       1428 : }
#     605                 :            : 
#     606                 :            : bool ArgsManager::SoftSetBoolArg(const std::string& strArg, bool fValue)
#     607                 :       1369 : {
#     608         [ +  + ]:       1369 :     if (fValue)
#     609                 :       1337 :         return SoftSetArg(strArg, std::string("1"));
#     610                 :         32 :     else
#     611                 :         32 :         return SoftSetArg(strArg, std::string("0"));
#     612                 :       1369 : }
#     613                 :            : 
#     614                 :            : void ArgsManager::ForceSetArg(const std::string& strArg, const std::string& strValue)
#     615                 :      56632 : {
#     616                 :      56632 :     LOCK(cs_args);
#     617                 :      56632 :     m_settings.forced_settings[SettingName(strArg)] = strValue;
#     618                 :      56632 : }
#     619                 :            : 
#     620                 :            : void ArgsManager::AddCommand(const std::string& cmd, const std::string& help, const OptionsCategory& cat)
#     621                 :        315 : {
#     622                 :        315 :     Assert(cmd.find('=') == std::string::npos);
#     623                 :        315 :     Assert(cmd.at(0) != '-');
#     624                 :            : 
#     625                 :        315 :     LOCK(cs_args);
#     626                 :        315 :     m_accept_any_command = false; // latch to false
#     627                 :        315 :     std::map<std::string, Arg>& arg_map = m_available_args[cat];
#     628                 :        315 :     auto ret = arg_map.emplace(cmd, Arg{"", help, ArgsManager::COMMAND});
#     629                 :        315 :     Assert(ret.second); // Fail on duplicate commands
#     630                 :        315 : }
#     631                 :            : 
#     632                 :            : void ArgsManager::AddArg(const std::string& name, const std::string& help, unsigned int flags, const OptionsCategory& cat)
#     633                 :     358497 : {
#     634                 :     358497 :     Assert((flags & ArgsManager::COMMAND) == 0); // use AddCommand
#     635                 :            : 
#     636                 :            :     // Split arg name from its help param
#     637                 :     358497 :     size_t eq_index = name.find('=');
#     638         [ +  + ]:     358497 :     if (eq_index == std::string::npos) {
#     639                 :     196305 :         eq_index = name.size();
#     640                 :     196305 :     }
#     641                 :     358497 :     std::string arg_name = name.substr(0, eq_index);
#     642                 :            : 
#     643                 :     358497 :     LOCK(cs_args);
#     644                 :     358497 :     std::map<std::string, Arg>& arg_map = m_available_args[cat];
#     645                 :     358497 :     auto ret = arg_map.emplace(arg_name, Arg{name.substr(eq_index, name.size() - eq_index), help, flags});
#     646                 :     358497 :     assert(ret.second); // Make sure an insertion actually happened
#     647                 :            : 
#     648         [ +  + ]:     358497 :     if (flags & ArgsManager::NETWORK_ONLY) {
#     649                 :      13025 :         m_network_only_args.emplace(arg_name);
#     650                 :      13025 :     }
#     651                 :     358497 : }
#     652                 :            : 
#     653                 :            : void ArgsManager::AddHiddenArgs(const std::vector<std::string>& names)
#     654                 :       6881 : {
#     655         [ +  + ]:      35266 :     for (const std::string& name : names) {
#     656                 :      35266 :         AddArg(name, "", ArgsManager::ALLOW_ANY, OptionsCategory::HIDDEN);
#     657                 :      35266 :     }
#     658                 :       6881 : }
#     659                 :            : 
#     660                 :            : std::string ArgsManager::GetHelpMessage() const
#     661                 :          1 : {
#     662                 :          1 :     const bool show_debug = GetBoolArg("-help-debug", false);
#     663                 :            : 
#     664                 :          1 :     std::string usage = "";
#     665                 :          1 :     LOCK(cs_args);
#     666         [ +  - ]:         10 :     for (const auto& arg_map : m_available_args) {
#     667                 :         10 :         switch(arg_map.first) {
#     668         [ +  + ]:          1 :             case OptionsCategory::OPTIONS:
#     669                 :          1 :                 usage += HelpMessageGroup("Options:");
#     670                 :          1 :                 break;
#     671         [ +  + ]:          1 :             case OptionsCategory::CONNECTION:
#     672                 :          1 :                 usage += HelpMessageGroup("Connection options:");
#     673                 :          1 :                 break;
#     674         [ -  + ]:          0 :             case OptionsCategory::ZMQ:
#     675                 :          0 :                 usage += HelpMessageGroup("ZeroMQ notification options:");
#     676                 :          0 :                 break;
#     677         [ +  + ]:          1 :             case OptionsCategory::DEBUG_TEST:
#     678                 :          1 :                 usage += HelpMessageGroup("Debugging/Testing options:");
#     679                 :          1 :                 break;
#     680         [ +  + ]:          1 :             case OptionsCategory::NODE_RELAY:
#     681                 :          1 :                 usage += HelpMessageGroup("Node relay options:");
#     682                 :          1 :                 break;
#     683         [ +  + ]:          1 :             case OptionsCategory::BLOCK_CREATION:
#     684                 :          1 :                 usage += HelpMessageGroup("Block creation options:");
#     685                 :          1 :                 break;
#     686         [ +  + ]:          1 :             case OptionsCategory::RPC:
#     687                 :          1 :                 usage += HelpMessageGroup("RPC server options:");
#     688                 :          1 :                 break;
#     689         [ +  + ]:          1 :             case OptionsCategory::WALLET:
#     690                 :          1 :                 usage += HelpMessageGroup("Wallet options:");
#     691                 :          1 :                 break;
#     692         [ +  + ]:          1 :             case OptionsCategory::WALLET_DEBUG_TEST:
#     693         [ -  + ]:          1 :                 if (show_debug) usage += HelpMessageGroup("Wallet debugging/testing options:");
#     694                 :          1 :                 break;
#     695         [ +  + ]:          1 :             case OptionsCategory::CHAINPARAMS:
#     696                 :          1 :                 usage += HelpMessageGroup("Chain selection options:");
#     697                 :          1 :                 break;
#     698         [ -  + ]:          0 :             case OptionsCategory::GUI:
#     699                 :          0 :                 usage += HelpMessageGroup("UI Options:");
#     700                 :          0 :                 break;
#     701         [ -  + ]:          0 :             case OptionsCategory::COMMANDS:
#     702                 :          0 :                 usage += HelpMessageGroup("Commands:");
#     703                 :          0 :                 break;
#     704         [ -  + ]:          0 :             case OptionsCategory::REGISTER_COMMANDS:
#     705                 :          0 :                 usage += HelpMessageGroup("Register Commands:");
#     706                 :          0 :                 break;
#     707         [ +  + ]:          1 :             default:
#     708                 :          1 :                 break;
#     709                 :         10 :         }
#     710                 :            : 
#     711                 :            :         // When we get to the hidden options, stop
#     712         [ +  + ]:         10 :         if (arg_map.first == OptionsCategory::HIDDEN) break;
#     713                 :            : 
#     714         [ +  + ]:        159 :         for (const auto& arg : arg_map.second) {
#     715 [ -  + ][ +  + ]:        159 :             if (show_debug || !(arg.second.m_flags & ArgsManager::DEBUG_ONLY)) {
#     716                 :        122 :                 std::string name;
#     717         [ +  + ]:        122 :                 if (arg.second.m_help_param.empty()) {
#     718                 :         54 :                     name = arg.first;
#     719                 :         68 :                 } else {
#     720                 :         68 :                     name = arg.first + arg.second.m_help_param;
#     721                 :         68 :                 }
#     722                 :        122 :                 usage += HelpMessageOpt(name, arg.second.m_help_text);
#     723                 :        122 :             }
#     724                 :        159 :         }
#     725                 :          9 :     }
#     726                 :          1 :     return usage;
#     727                 :          1 : }
#     728                 :            : 
#     729                 :            : bool HelpRequested(const ArgsManager& args)
#     730                 :       1412 : {
#     731 [ -  + ][ +  + ]:       1412 :     return args.IsArgSet("-?") || args.IsArgSet("-h") || args.IsArgSet("-help") || args.IsArgSet("-help-debug");
#         [ -  + ][ -  + ]
#     732                 :       1412 : }
#     733                 :            : 
#     734                 :            : void SetupHelpOptions(ArgsManager& args)
#     735                 :       2273 : {
#     736                 :       2273 :     args.AddArg("-?", "Print this help message and exit", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#     737                 :       2273 :     args.AddHiddenArgs({"-h", "-help"});
#     738                 :       2273 : }
#     739                 :            : 
#     740                 :            : static const int screenWidth = 79;
#     741                 :            : static const int optIndent = 2;
#     742                 :            : static const int msgIndent = 7;
#     743                 :            : 
#     744                 :          8 : std::string HelpMessageGroup(const std::string &message) {
#     745                 :          8 :     return std::string(message) + std::string("\n\n");
#     746                 :          8 : }
#     747                 :            : 
#     748                 :        122 : std::string HelpMessageOpt(const std::string &option, const std::string &message) {
#     749                 :        122 :     return std::string(optIndent,' ') + std::string(option) +
#     750                 :        122 :            std::string("\n") + std::string(msgIndent,' ') +
#     751                 :        122 :            FormatParagraph(message, screenWidth - msgIndent, msgIndent) +
#     752                 :        122 :            std::string("\n\n");
#     753                 :        122 : }
#     754                 :            : 
#     755                 :            : static std::string FormatException(const std::exception* pex, const char* pszThread)
#     756                 :          0 : {
#     757                 :            : #ifdef WIN32
#     758                 :            :     char pszModule[MAX_PATH] = "";
#     759                 :            :     GetModuleFileNameA(nullptr, pszModule, sizeof(pszModule));
#     760                 :            : #else
#     761                 :          0 :     const char* pszModule = "bitcoin";
#     762                 :          0 : #endif
#     763         [ #  # ]:          0 :     if (pex)
#     764                 :          0 :         return strprintf(
#     765                 :          0 :             "EXCEPTION: %s       \n%s       \n%s in %s       \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
#     766                 :          0 :     else
#     767                 :          0 :         return strprintf(
#     768                 :          0 :             "UNKNOWN EXCEPTION       \n%s in %s       \n", pszModule, pszThread);
#     769                 :          0 : }
#     770                 :            : 
#     771                 :            : void PrintExceptionContinue(const std::exception* pex, const char* pszThread)
#     772                 :          0 : {
#     773                 :          0 :     std::string message = FormatException(pex, pszThread);
#     774                 :          0 :     LogPrintf("\n\n************************\n%s\n", message);
#     775                 :          0 :     tfm::format(std::cerr, "\n\n************************\n%s\n", message);
#     776                 :          0 : }
#     777                 :            : 
#     778                 :            : fs::path GetDefaultDataDir()
#     779                 :        661 : {
#     780                 :            :     // Windows: C:\Users\Username\AppData\Roaming\Bitcoin
#     781                 :            :     // macOS: ~/Library/Application Support/Bitcoin
#     782                 :            :     // Unix-like: ~/.bitcoin
#     783                 :            : #ifdef WIN32
#     784                 :            :     // Windows
#     785                 :            :     return GetSpecialFolderPath(CSIDL_APPDATA) / "Bitcoin";
#     786                 :            : #else
#     787                 :        661 :     fs::path pathRet;
#     788                 :        661 :     char* pszHome = getenv("HOME");
#     789 [ -  + ][ -  + ]:        661 :     if (pszHome == nullptr || strlen(pszHome) == 0)
#     790                 :          0 :         pathRet = fs::path("/");
#     791                 :        661 :     else
#     792                 :        661 :         pathRet = fs::path(pszHome);
#     793                 :            : #ifdef MAC_OSX
#     794                 :            :     // macOS
#     795                 :            :     return pathRet / "Library/Application Support/Bitcoin";
#     796                 :            : #else
#     797                 :            :     // Unix-like
#     798                 :        661 :     return pathRet / ".bitcoin";
#     799                 :        661 : #endif
#     800                 :        661 : #endif
#     801                 :        661 : }
#     802                 :            : 
#     803                 :            : bool CheckDataDirOption()
#     804                 :       2754 : {
#     805                 :       2754 :     std::string datadir = gArgs.GetArg("-datadir", "");
#     806 [ +  + ][ +  + ]:       2754 :     return datadir.empty() || fs::is_directory(fs::system_complete(datadir));
#     807                 :       2754 : }
#     808                 :            : 
#     809                 :            : fs::path GetConfigFile(const std::string& confPath)
#     810                 :       2036 : {
#     811                 :       2036 :     return AbsPathForConfigVal(fs::path(confPath), false);
#     812                 :       2036 : }
#     813                 :            : 
#     814                 :            : static bool GetConfigOptions(std::istream& stream, const std::string& filepath, std::string& error, std::vector<std::pair<std::string, std::string>>& options, std::list<SectionInfo>& sections)
#     815                 :      57561 : {
#     816                 :      57561 :     std::string str, prefix;
#     817                 :      57561 :     std::string::size_type pos;
#     818                 :      57561 :     int linenr = 1;
#     819         [ +  + ]:     291253 :     while (std::getline(stream, str)) {
#     820                 :     233697 :         bool used_hash = false;
#     821         [ +  + ]:     233697 :         if ((pos = str.find('#')) != std::string::npos) {
#     822                 :          3 :             str = str.substr(0, pos);
#     823                 :          3 :             used_hash = true;
#     824                 :          3 :         }
#     825                 :     233697 :         const static std::string pattern = " \t\r\n";
#     826                 :     233697 :         str = TrimString(str, pattern);
#     827         [ +  + ]:     233697 :         if (!str.empty()) {
#     828 [ +  + ][ +  + ]:     233694 :             if (*str.begin() == '[' && *str.rbegin() == ']') {
#                 [ +  - ]
#     829                 :       1376 :                 const std::string section = str.substr(1, str.size() - 2);
#     830                 :       1376 :                 sections.emplace_back(SectionInfo{section, filepath, linenr});
#     831                 :       1376 :                 prefix = section + '.';
#     832         [ +  + ]:     232318 :             } else if (*str.begin() == '-') {
#     833                 :          1 :                 error = strprintf("parse error on line %i: %s, options in configuration file must be specified without leading -", linenr, str);
#     834                 :          1 :                 return false;
#     835         [ +  + ]:     232317 :             } else if ((pos = str.find('=')) != std::string::npos) {
#     836                 :     232316 :                 std::string name = prefix + TrimString(str.substr(0, pos), pattern);
#     837                 :     232316 :                 std::string value = TrimString(str.substr(pos + 1), pattern);
#     838 [ +  + ][ +  - ]:     232316 :                 if (used_hash && name.find("rpcpassword") != std::string::npos) {
#     839                 :          3 :                     error = strprintf("parse error on line %i, using # in rpcpassword can be ambiguous and should be avoided", linenr);
#     840                 :          3 :                     return false;
#     841                 :          3 :                 }
#     842                 :     232313 :                 options.emplace_back(name, value);
#     843 [ +  + ][ +  + ]:     232313 :                 if ((pos = name.rfind('.')) != std::string::npos && prefix.length() <= pos) {
#     844                 :     102819 :                     sections.emplace_back(SectionInfo{name.substr(0, pos), filepath, linenr});
#     845                 :     102819 :                 }
#     846                 :     232313 :             } else {
#     847                 :          1 :                 error = strprintf("parse error on line %i: %s", linenr, str);
#     848 [ +  - ][ +  - ]:          1 :                 if (str.size() >= 2 && str.substr(0, 2) == "no") {
#                 [ +  - ]
#     849                 :          1 :                     error += strprintf(", if you intended to specify a negated option, use %s=1 instead", str);
#     850                 :          1 :                 }
#     851                 :          1 :                 return false;
#     852                 :          1 :             }
#     853                 :     233692 :         }
#     854                 :     233692 :         ++linenr;
#     855                 :     233692 :     }
#     856                 :      57561 :     return true;
#     857                 :      57561 : }
#     858                 :            : 
#     859                 :            : bool ArgsManager::ReadConfigStream(std::istream& stream, const std::string& filepath, std::string& error, bool ignore_invalid_keys)
#     860                 :      57561 : {
#     861                 :      57561 :     LOCK(cs_args);
#     862                 :      57561 :     std::vector<std::pair<std::string, std::string>> options;
#     863         [ +  + ]:      57561 :     if (!GetConfigOptions(stream, filepath, error, options, m_config_sections)) {
#     864                 :          5 :         return false;
#     865                 :          5 :     }
#     866         [ +  + ]:     232307 :     for (const std::pair<std::string, std::string>& option : options) {
#     867                 :     232307 :         std::string section;
#     868                 :     232307 :         std::string key = option.first;
#     869                 :     232307 :         util::SettingsValue value = InterpretOption(section, key, option.second);
#     870                 :     232307 :         std::optional<unsigned int> flags = GetArgFlags('-' + key);
#     871         [ +  + ]:     232307 :         if (flags) {
#     872         [ -  + ]:     222884 :             if (!CheckValid(key, value, *flags, error)) {
#     873                 :          0 :                 return false;
#     874                 :          0 :             }
#     875                 :     222884 :             m_settings.ro_config[section][key].push_back(value);
#     876                 :     222884 :         } else {
#     877         [ +  - ]:       9423 :             if (ignore_invalid_keys) {
#     878                 :       9423 :                 LogPrintf("Ignoring unknown configuration value %s\n", option.first);
#     879                 :       9423 :             } else {
#     880                 :          0 :                 error = strprintf("Invalid configuration value %s", option.first);
#     881                 :          0 :                 return false;
#     882                 :          0 :             }
#     883                 :       9423 :         }
#     884                 :     232307 :     }
#     885                 :      57556 :     return true;
#     886                 :      57556 : }
#     887                 :            : 
#     888                 :            : bool ArgsManager::ReadConfigFiles(std::string& error, bool ignore_invalid_keys)
#     889                 :       1351 : {
#     890                 :       1351 :     {
#     891                 :       1351 :         LOCK(cs_args);
#     892                 :       1351 :         m_settings.ro_config.clear();
#     893                 :       1351 :         m_config_sections.clear();
#     894                 :       1351 :     }
#     895                 :            : 
#     896                 :       1351 :     const std::string confPath = GetArg("-conf", BITCOIN_CONF_FILENAME);
#     897                 :       1351 :     fsbridge::ifstream stream(GetConfigFile(confPath));
#     898                 :            : 
#     899                 :            :     // ok to not have a config file
#     900         [ +  - ]:       1351 :     if (stream.good()) {
#     901         [ -  + ]:       1351 :         if (!ReadConfigStream(stream, confPath, error, ignore_invalid_keys)) {
#     902                 :          0 :             return false;
#     903                 :          0 :         }
#     904                 :            :         // `-includeconf` cannot be included in the command line arguments except
#     905                 :            :         // as `-noincludeconf` (which indicates that no included conf file should be used).
#     906                 :       1351 :         bool use_conf_file{true};
#     907                 :       1351 :         {
#     908                 :       1351 :             LOCK(cs_args);
#     909         [ -  + ]:       1351 :             if (auto* includes = util::FindKey(m_settings.command_line_options, "includeconf")) {
#     910                 :            :                 // ParseParameters() fails if a non-negated -includeconf is passed on the command-line
#     911                 :          0 :                 assert(util::SettingsSpan(*includes).last_negated());
#     912                 :          0 :                 use_conf_file = false;
#     913                 :          0 :             }
#     914                 :       1351 :         }
#     915         [ +  - ]:       1351 :         if (use_conf_file) {
#     916                 :       1351 :             std::string chain_id = GetChainName();
#     917                 :       1351 :             std::vector<std::string> conf_file_names;
#     918                 :            : 
#     919                 :       5392 :             auto add_includes = [&](const std::string& network, size_t skip = 0) {
#     920                 :       5392 :                 size_t num_values = 0;
#     921                 :       5392 :                 LOCK(cs_args);
#     922         [ +  + ]:       5392 :                 if (auto* section = util::FindKey(m_settings.ro_config, network)) {
#     923         [ +  + ]:       5390 :                     if (auto* values = util::FindKey(*section, "includeconf")) {
#     924         [ +  + ]:         53 :                         for (size_t i = std::max(skip, util::SettingsSpan(*values).negated()); i < values->size(); ++i) {
#     925                 :         24 :                             conf_file_names.push_back((*values)[i].get_str());
#     926                 :         24 :                         }
#     927                 :         29 :                         num_values = values->size();
#     928                 :         29 :                     }
#     929                 :       5390 :                 }
#     930                 :       5392 :                 return num_values;
#     931                 :       5392 :             };
#     932                 :            : 
#     933                 :            :             // We haven't set m_network yet (that happens in SelectParams()), so manually check
#     934                 :            :             // for network.includeconf args.
#     935                 :       1351 :             const size_t chain_includes = add_includes(chain_id);
#     936                 :       1351 :             const size_t default_includes = add_includes({});
#     937                 :            : 
#     938         [ +  + ]:       1351 :             for (const std::string& conf_file_name : conf_file_names) {
#     939                 :         23 :                 fsbridge::ifstream conf_file_stream(GetConfigFile(conf_file_name));
#     940         [ +  + ]:         23 :                 if (conf_file_stream.good()) {
#     941         [ +  + ]:         22 :                     if (!ReadConfigStream(conf_file_stream, conf_file_name, error, ignore_invalid_keys)) {
#     942                 :          5 :                         return false;
#     943                 :          5 :                     }
#     944                 :         17 :                     LogPrintf("Included configuration file %s\n", conf_file_name);
#     945                 :         17 :                 } else {
#     946                 :          1 :                     error = "Failed to include configuration file " + conf_file_name;
#     947                 :          1 :                     return false;
#     948                 :          1 :                 }
#     949                 :         23 :             }
#     950                 :            : 
#     951                 :            :             // Warn about recursive -includeconf
#     952                 :       1351 :             conf_file_names.clear();
#     953                 :       1345 :             add_includes(chain_id, /* skip= */ chain_includes);
#     954                 :       1345 :             add_includes({}, /* skip= */ default_includes);
#     955                 :       1345 :             std::string chain_id_final = GetChainName();
#     956         [ -  + ]:       1345 :             if (chain_id_final != chain_id) {
#     957                 :            :                 // Also warn about recursive includeconf for the chain that was specified in one of the includeconfs
#     958                 :          0 :                 add_includes(chain_id_final);
#     959                 :          0 :             }
#     960         [ +  + ]:       1345 :             for (const std::string& conf_file_name : conf_file_names) {
#     961                 :          1 :                 tfm::format(std::cerr, "warning: -includeconf cannot be used from included files; ignoring -includeconf=%s\n", conf_file_name);
#     962                 :          1 :             }
#     963                 :       1345 :         }
#     964                 :       1351 :     }
#     965                 :            : 
#     966                 :            :     // If datadir is changed in .conf file:
#     967                 :       1351 :     gArgs.ClearPathCache();
#     968         [ +  + ]:       1345 :     if (!CheckDataDirOption()) {
#     969                 :          1 :         error = strprintf("specified data directory \"%s\" does not exist.", GetArg("-datadir", ""));
#     970                 :          1 :         return false;
#     971                 :          1 :     }
#     972                 :       1344 :     return true;
#     973                 :       1344 : }
#     974                 :            : 
#     975                 :            : std::string ArgsManager::GetChainName() const
#     976                 :       8381 : {
#     977                 :      25143 :     auto get_net = [&](const std::string& arg) {
#     978                 :      25143 :         LOCK(cs_args);
#     979                 :      25143 :         util::SettingsValue value = util::GetSetting(m_settings, /* section= */ "", SettingName(arg),
#     980                 :      25143 :             /* ignore_default_section_config= */ false,
#     981                 :      25143 :             /* get_chain_name= */ true);
#     982 [ +  + ][ -  + ]:      25143 :         return value.isNull() ? false : value.isBool() ? value.get_bool() : InterpretBool(value.get_str());
#     983                 :      25143 :     };
#     984                 :            : 
#     985                 :       8381 :     const bool fRegTest = get_net("-regtest");
#     986                 :       8381 :     const bool fSigNet  = get_net("-signet");
#     987                 :       8381 :     const bool fTestNet = get_net("-testnet");
#     988                 :       8381 :     const bool is_chain_arg_set = IsArgSet("-chain");
#     989                 :            : 
#     990         [ +  + ]:       8381 :     if ((int)is_chain_arg_set + (int)fRegTest + (int)fSigNet + (int)fTestNet > 1) {
#     991                 :        374 :         throw std::runtime_error("Invalid combination of -regtest, -signet, -testnet and -chain. Can use at most one.");
#     992                 :        374 :     }
#     993         [ +  + ]:       8007 :     if (fRegTest)
#     994                 :       5310 :         return CBaseChainParams::REGTEST;
#     995         [ +  + ]:       2697 :     if (fSigNet) {
#     996                 :         28 :         return CBaseChainParams::SIGNET;
#     997                 :         28 :     }
#     998         [ +  + ]:       2669 :     if (fTestNet)
#     999                 :        672 :         return CBaseChainParams::TESTNET;
#    1000                 :            : 
#    1001                 :       1997 :     return GetArg("-chain", CBaseChainParams::MAIN);
#    1002                 :       1997 : }
#    1003                 :            : 
#    1004                 :            : bool ArgsManager::UseDefaultSection(const std::string& arg) const
#    1005                 :    2274890 : {
#    1006 [ +  + ][ +  + ]:    2274890 :     return m_network == CBaseChainParams::MAIN || m_network_only_args.count(arg) == 0;
#    1007                 :    2274890 : }
#    1008                 :            : 
#    1009                 :            : util::SettingsValue ArgsManager::GetSetting(const std::string& arg) const
#    1010                 :    2200074 : {
#    1011                 :    2200074 :     LOCK(cs_args);
#    1012                 :    2200074 :     return util::GetSetting(
#    1013                 :    2200074 :         m_settings, m_network, SettingName(arg), !UseDefaultSection(arg), /* get_chain_name= */ false);
#    1014                 :    2200074 : }
#    1015                 :            : 
#    1016                 :            : std::vector<util::SettingsValue> ArgsManager::GetSettingsList(const std::string& arg) const
#    1017                 :      74812 : {
#    1018                 :      74812 :     LOCK(cs_args);
#    1019                 :      74812 :     return util::GetSettingsList(m_settings, m_network, SettingName(arg), !UseDefaultSection(arg));
#    1020                 :      74812 : }
#    1021                 :            : 
#    1022                 :            : void ArgsManager::logArgsPrefix(
#    1023                 :            :     const std::string& prefix,
#    1024                 :            :     const std::string& section,
#    1025                 :            :     const std::map<std::string, std::vector<util::SettingsValue>>& args) const
#    1026                 :       1986 : {
#    1027         [ +  + ]:       1986 :     std::string section_str = section.empty() ? "" : "[" + section + "] ";
#    1028         [ +  + ]:      15846 :     for (const auto& arg : args) {
#    1029         [ +  + ]:      16551 :         for (const auto& value : arg.second) {
#    1030                 :      16551 :             std::optional<unsigned int> flags = GetArgFlags('-' + arg.first);
#    1031         [ +  - ]:      16551 :             if (flags) {
#    1032         [ +  + ]:      16551 :                 std::string value_str = (*flags & SENSITIVE) ? "****" : value.write();
#    1033                 :      16551 :                 LogPrintf("%s %s%s=%s\n", prefix, section_str, arg.first, value_str);
#    1034                 :      16551 :             }
#    1035                 :      16551 :         }
#    1036                 :      15846 :     }
#    1037                 :       1986 : }
#    1038                 :            : 
#    1039                 :            : void ArgsManager::LogArgs() const
#    1040                 :        663 : {
#    1041                 :        663 :     LOCK(cs_args);
#    1042         [ +  + ]:       1323 :     for (const auto& section : m_settings.ro_config) {
#    1043                 :       1323 :         logArgsPrefix("Config file arg:", section.first, section.second);
#    1044                 :       1323 :     }
#    1045         [ +  + ]:        663 :     for (const auto& setting : m_settings.rw_settings) {
#    1046                 :        186 :         LogPrintf("Setting file arg: %s = %s\n", setting.first, setting.second.write());
#    1047                 :        186 :     }
#    1048                 :        663 :     logArgsPrefix("Command-line arg:", "", m_settings.command_line_options);
#    1049                 :        663 : }
#    1050                 :            : 
#    1051                 :            : bool RenameOver(fs::path src, fs::path dest)
#    1052                 :       4367 : {
#    1053                 :            : #ifdef WIN32
#    1054                 :            :     return MoveFileExW(src.wstring().c_str(), dest.wstring().c_str(),
#    1055                 :            :                        MOVEFILE_REPLACE_EXISTING) != 0;
#    1056                 :            : #else
#    1057                 :       4367 :     int rc = std::rename(src.string().c_str(), dest.string().c_str());
#    1058                 :       4367 :     return (rc == 0);
#    1059                 :       4367 : #endif /* WIN32 */
#    1060                 :       4367 : }
#    1061                 :            : 
#    1062                 :            : /**
#    1063                 :            :  * Ignores exceptions thrown by Boost's create_directories if the requested directory exists.
#    1064                 :            :  * Specifically handles case where path p exists, but it wasn't possible for the user to
#    1065                 :            :  * write to the parent directory.
#    1066                 :            :  */
#    1067                 :            : bool TryCreateDirectories(const fs::path& p)
#    1068                 :       2810 : {
#    1069                 :       2810 :     try
#    1070                 :       2810 :     {
#    1071                 :       2810 :         return fs::create_directories(p);
#    1072                 :       2810 :     } catch (const fs::filesystem_error&) {
#    1073 [ +  - ][ #  # ]:          3 :         if (!fs::exists(p) || !fs::is_directory(p))
#    1074                 :          3 :             throw;
#    1075                 :          0 :     }
#    1076                 :            : 
#    1077                 :            :     // create_directories didn't create the directory, it had to have existed already
#    1078                 :          0 :     return false;
#    1079                 :          0 : }
#    1080                 :            : 
#    1081                 :            : bool FileCommit(FILE *file)
#    1082                 :       6034 : {
#    1083         [ -  + ]:       6034 :     if (fflush(file) != 0) { // harmless if redundantly called
#    1084                 :          0 :         LogPrintf("%s: fflush failed: %d\n", __func__, errno);
#    1085                 :          0 :         return false;
#    1086                 :          0 :     }
#    1087                 :            : #ifdef WIN32
#    1088                 :            :     HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
#    1089                 :            :     if (FlushFileBuffers(hFile) == 0) {
#    1090                 :            :         LogPrintf("%s: FlushFileBuffers failed: %d\n", __func__, GetLastError());
#    1091                 :            :         return false;
#    1092                 :            :     }
#    1093                 :            : #elif defined(MAC_OSX) && defined(F_FULLFSYNC)
#    1094                 :            :     if (fcntl(fileno(file), F_FULLFSYNC, 0) == -1) { // Manpage says "value other than -1" is returned on success
#    1095                 :            :         LogPrintf("%s: fcntl F_FULLFSYNC failed: %d\n", __func__, errno);
#    1096                 :            :         return false;
#    1097                 :            :     }
#    1098                 :            : #elif HAVE_FDATASYNC
#    1099 [ -  + ][ #  # ]:       6034 :     if (fdatasync(fileno(file)) != 0 && errno != EINVAL) { // Ignore EINVAL for filesystems that don't support sync
#    1100                 :          0 :         LogPrintf("%s: fdatasync failed: %d\n", __func__, errno);
#    1101                 :          0 :         return false;
#    1102                 :          0 :     }
#    1103                 :            : #else
#    1104                 :            :     if (fsync(fileno(file)) != 0 && errno != EINVAL) {
#    1105                 :            :         LogPrintf("%s: fsync failed: %d\n", __func__, errno);
#    1106                 :            :         return false;
#    1107                 :            :     }
#    1108                 :            : #endif
#    1109                 :       6034 :     return true;
#    1110                 :       6034 : }
#    1111                 :            : 
#    1112                 :            : void DirectoryCommit(const fs::path &dirname)
#    1113                 :       3212 : {
#    1114                 :       3212 : #ifndef WIN32
#    1115                 :       3212 :     FILE* file = fsbridge::fopen(dirname, "r");
#    1116         [ +  - ]:       3212 :     if (file) {
#    1117                 :       3212 :         fsync(fileno(file));
#    1118                 :       3212 :         fclose(file);
#    1119                 :       3212 :     }
#    1120                 :       3212 : #endif
#    1121                 :       3212 : }
#    1122                 :            : 
#    1123                 :         34 : bool TruncateFile(FILE *file, unsigned int length) {
#    1124                 :            : #if defined(WIN32)
#    1125                 :            :     return _chsize(_fileno(file), length) == 0;
#    1126                 :            : #else
#    1127                 :         34 :     return ftruncate(fileno(file), length) == 0;
#    1128                 :         34 : #endif
#    1129                 :         34 : }
#    1130                 :            : 
#    1131                 :            : /**
#    1132                 :            :  * this function tries to raise the file descriptor limit to the requested number.
#    1133                 :            :  * It returns the actual file descriptor limit (which may be more or less than nMinFD)
#    1134                 :            :  */
#    1135                 :       1514 : int RaiseFileDescriptorLimit(int nMinFD) {
#    1136                 :            : #if defined(WIN32)
#    1137                 :            :     return 2048;
#    1138                 :            : #else
#    1139                 :       1514 :     struct rlimit limitFD;
#    1140         [ +  - ]:       1514 :     if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) {
#    1141         [ -  + ]:       1514 :         if (limitFD.rlim_cur < (rlim_t)nMinFD) {
#    1142                 :          0 :             limitFD.rlim_cur = nMinFD;
#    1143         [ #  # ]:          0 :             if (limitFD.rlim_cur > limitFD.rlim_max)
#    1144                 :          0 :                 limitFD.rlim_cur = limitFD.rlim_max;
#    1145                 :          0 :             setrlimit(RLIMIT_NOFILE, &limitFD);
#    1146                 :          0 :             getrlimit(RLIMIT_NOFILE, &limitFD);
#    1147                 :          0 :         }
#    1148                 :       1514 :         return limitFD.rlim_cur;
#    1149                 :       1514 :     }
#    1150                 :          0 :     return nMinFD; // getrlimit failed, assume it's fine
#    1151                 :          0 : #endif
#    1152                 :          0 : }
#    1153                 :            : 
#    1154                 :            : /**
#    1155                 :            :  * this function tries to make a particular range of a file allocated (corresponding to disk space)
#    1156                 :            :  * it is advisory, and the range specified in the arguments will never contain live data
#    1157                 :            :  */
#    1158                 :        768 : void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length) {
#    1159                 :            : #if defined(WIN32)
#    1160                 :            :     // Windows-specific version
#    1161                 :            :     HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
#    1162                 :            :     LARGE_INTEGER nFileSize;
#    1163                 :            :     int64_t nEndPos = (int64_t)offset + length;
#    1164                 :            :     nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF;
#    1165                 :            :     nFileSize.u.HighPart = nEndPos >> 32;
#    1166                 :            :     SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN);
#    1167                 :            :     SetEndOfFile(hFile);
#    1168                 :            : #elif defined(MAC_OSX)
#    1169                 :            :     // OSX specific version
#    1170                 :            :     // NOTE: Contrary to other OS versions, the OSX version assumes that
#    1171                 :            :     // NOTE: offset is the size of the file.
#    1172                 :            :     fstore_t fst;
#    1173                 :            :     fst.fst_flags = F_ALLOCATECONTIG;
#    1174                 :            :     fst.fst_posmode = F_PEOFPOSMODE;
#    1175                 :            :     fst.fst_offset = 0;
#    1176                 :            :     fst.fst_length = length; // mac os fst_length takes the # of free bytes to allocate, not desired file size
#    1177                 :            :     fst.fst_bytesalloc = 0;
#    1178                 :            :     if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) {
#    1179                 :            :         fst.fst_flags = F_ALLOCATEALL;
#    1180                 :            :         fcntl(fileno(file), F_PREALLOCATE, &fst);
#    1181                 :            :     }
#    1182                 :            :     ftruncate(fileno(file), static_cast<off_t>(offset) + length);
#    1183                 :            : #else
#    1184                 :        768 :     #if defined(HAVE_POSIX_FALLOCATE)
#    1185                 :            :     // Version using posix_fallocate
#    1186                 :        768 :     off_t nEndPos = (off_t)offset + length;
#    1187         [ -  + ]:        768 :     if (0 == posix_fallocate(fileno(file), 0, nEndPos)) return;
#    1188                 :        768 :     #endif
#    1189                 :            :     // Fallback version
#    1190                 :            :     // TODO: just write one byte per block
#    1191                 :        768 :     static const char buf[65536] = {};
#    1192         [ -  + ]:        768 :     if (fseek(file, offset, SEEK_SET)) {
#    1193                 :          0 :         return;
#    1194                 :          0 :     }
#    1195         [ +  + ]:     125175 :     while (length > 0) {
#    1196                 :     124407 :         unsigned int now = 65536;
#    1197         [ +  + ]:     124407 :         if (length < now)
#    1198                 :         95 :             now = length;
#    1199                 :     124407 :         fwrite(buf, 1, now, file); // allowed to fail; this function is advisory anyway
#    1200                 :     124407 :         length -= now;
#    1201                 :     124407 :     }
#    1202                 :        768 : #endif
#    1203                 :        768 : }
#    1204                 :            : 
#    1205                 :            : #ifdef WIN32
#    1206                 :            : fs::path GetSpecialFolderPath(int nFolder, bool fCreate)
#    1207                 :            : {
#    1208                 :            :     WCHAR pszPath[MAX_PATH] = L"";
#    1209                 :            : 
#    1210                 :            :     if(SHGetSpecialFolderPathW(nullptr, pszPath, nFolder, fCreate))
#    1211                 :            :     {
#    1212                 :            :         return fs::path(pszPath);
#    1213                 :            :     }
#    1214                 :            : 
#    1215                 :            :     LogPrintf("SHGetSpecialFolderPathW() failed, could not obtain requested path.\n");
#    1216                 :            :     return fs::path("");
#    1217                 :            : }
#    1218                 :            : #endif
#    1219                 :            : 
#    1220                 :            : #ifndef WIN32
#    1221                 :            : std::string ShellEscape(const std::string& arg)
#    1222                 :         26 : {
#    1223                 :         26 :     std::string escaped = arg;
#    1224                 :         26 :     boost::replace_all(escaped, "'", "'\"'\"'");
#    1225                 :         26 :     return "'" + escaped + "'";
#    1226                 :         26 : }
#    1227                 :            : #endif
#    1228                 :            : 
#    1229                 :            : #if HAVE_SYSTEM
#    1230                 :            : void runCommand(const std::string& strCommand)
#    1231                 :        140 : {
#    1232         [ -  + ]:        140 :     if (strCommand.empty()) return;
#    1233                 :        140 : #ifndef WIN32
#    1234                 :        140 :     int nErr = ::system(strCommand.c_str());
#    1235                 :            : #else
#    1236                 :            :     int nErr = ::_wsystem(std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>,wchar_t>().from_bytes(strCommand).c_str());
#    1237                 :            : #endif
#    1238         [ -  + ]:        140 :     if (nErr)
#    1239                 :        140 :         LogPrintf("runCommand error: system(%s) returned %d\n", strCommand, nErr);
#    1240                 :        140 : }
#    1241                 :            : #endif
#    1242                 :            : 
#    1243                 :            : #ifdef ENABLE_EXTERNAL_SIGNER
#    1244                 :            : UniValue RunCommandParseJSON(const std::string& str_command, const std::string& str_std_in)
#    1245                 :            : {
#    1246                 :            :     namespace bp = boost::process;
#    1247                 :            : 
#    1248                 :            :     UniValue result_json;
#    1249                 :            :     bp::opstream stdin_stream;
#    1250                 :            :     bp::ipstream stdout_stream;
#    1251                 :            :     bp::ipstream stderr_stream;
#    1252                 :            : 
#    1253                 :            :     if (str_command.empty()) return UniValue::VNULL;
#    1254                 :            : 
#    1255                 :            :     bp::child c(
#    1256                 :            :         str_command,
#    1257                 :            :         bp::std_out > stdout_stream,
#    1258                 :            :         bp::std_err > stderr_stream,
#    1259                 :            :         bp::std_in < stdin_stream
#    1260                 :            :     );
#    1261                 :            :     if (!str_std_in.empty()) {
#    1262                 :            :         stdin_stream << str_std_in << std::endl;
#    1263                 :            :     }
#    1264                 :            :     stdin_stream.pipe().close();
#    1265                 :            : 
#    1266                 :            :     std::string result;
#    1267                 :            :     std::string error;
#    1268                 :            :     std::getline(stdout_stream, result);
#    1269                 :            :     std::getline(stderr_stream, error);
#    1270                 :            : 
#    1271                 :            :     c.wait();
#    1272                 :            :     const int n_error = c.exit_code();
#    1273                 :            :     if (n_error) throw std::runtime_error(strprintf("RunCommandParseJSON error: process(%s) returned %d: %s\n", str_command, n_error, error));
#    1274                 :            :     if (!result_json.read(result)) throw std::runtime_error("Unable to parse JSON: " + result);
#    1275                 :            : 
#    1276                 :            :     return result_json;
#    1277                 :            : }
#    1278                 :            : #endif // ENABLE_EXTERNAL_SIGNER
#    1279                 :            : 
#    1280                 :            : void SetupEnvironment()
#    1281                 :       2273 : {
#    1282                 :            : #ifdef HAVE_MALLOPT_ARENA_MAX
#    1283                 :            :     // glibc-specific: On 32-bit systems set the number of arenas to 1.
#    1284                 :            :     // By default, since glibc 2.10, the C library will create up to two heap
#    1285                 :            :     // arenas per core. This is known to cause excessive virtual address space
#    1286                 :            :     // usage in our usage. Work around it by setting the maximum number of
#    1287                 :            :     // arenas to 1.
#    1288                 :            :     if (sizeof(void*) == 4) {
#    1289                 :            :         mallopt(M_ARENA_MAX, 1);
#    1290                 :            :     }
#    1291                 :            : #endif
#    1292                 :            :     // On most POSIX systems (e.g. Linux, but not BSD) the environment's locale
#    1293                 :            :     // may be invalid, in which case the "C.UTF-8" locale is used as fallback.
#    1294                 :            : #if !defined(WIN32) && !defined(MAC_OSX) && !defined(__FreeBSD__) && !defined(__OpenBSD__)
#    1295                 :            :     try {
#    1296                 :            :         std::locale(""); // Raises a runtime error if current locale is invalid
#    1297                 :            :     } catch (const std::runtime_error&) {
#    1298                 :            :         setenv("LC_ALL", "C.UTF-8", 1);
#    1299                 :            :     }
#    1300                 :            : #elif defined(WIN32)
#    1301                 :            :     // Set the default input/output charset is utf-8
#    1302                 :            :     SetConsoleCP(CP_UTF8);
#    1303                 :            :     SetConsoleOutputCP(CP_UTF8);
#    1304                 :            : #endif
#    1305                 :            :     // The path locale is lazy initialized and to avoid deinitialization errors
#    1306                 :            :     // in multithreading environments, it is set explicitly by the main thread.
#    1307                 :            :     // A dummy locale is used to extract the internal default locale, used by
#    1308                 :            :     // fs::path, which is then used to explicitly imbue the path.
#    1309                 :       2273 :     std::locale loc = fs::path::imbue(std::locale::classic());
#    1310                 :       2273 : #ifndef WIN32
#    1311                 :       2273 :     fs::path::imbue(loc);
#    1312                 :            : #else
#    1313                 :            :     fs::path::imbue(std::locale(loc, new std::codecvt_utf8_utf16<wchar_t>()));
#    1314                 :            : #endif
#    1315                 :       2273 : }
#    1316                 :            : 
#    1317                 :            : bool SetupNetworking()
#    1318                 :       2190 : {
#    1319                 :            : #ifdef WIN32
#    1320                 :            :     // Initialize Windows Sockets
#    1321                 :            :     WSADATA wsadata;
#    1322                 :            :     int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
#    1323                 :            :     if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2)
#    1324                 :            :         return false;
#    1325                 :            : #endif
#    1326                 :       2190 :     return true;
#    1327                 :       2190 : }
#    1328                 :            : 
#    1329                 :            : int GetNumCores()
#    1330                 :       2192 : {
#    1331                 :       2192 :     return std::thread::hardware_concurrency();
#    1332                 :       2192 : }
#    1333                 :            : 
#    1334                 :            : std::string CopyrightHolders(const std::string& strPrefix)
#    1335                 :          1 : {
#    1336                 :          1 :     const auto copyright_devs = strprintf(_(COPYRIGHT_HOLDERS).translated, COPYRIGHT_HOLDERS_SUBSTITUTION);
#    1337                 :          1 :     std::string strCopyrightHolders = strPrefix + copyright_devs;
#    1338                 :            : 
#    1339                 :            :     // Make sure Bitcoin Core copyright is not removed by accident
#    1340         [ -  + ]:          1 :     if (copyright_devs.find("Bitcoin Core") == std::string::npos) {
#    1341                 :          0 :         strCopyrightHolders += "\n" + strPrefix + "The Bitcoin Core developers";
#    1342                 :          0 :     }
#    1343                 :          1 :     return strCopyrightHolders;
#    1344                 :          1 : }
#    1345                 :            : 
#    1346                 :            : // Obtain the application startup time (used for uptime calculation)
#    1347                 :            : int64_t GetStartupTime()
#    1348                 :          1 : {
#    1349                 :          1 :     return nStartupTime;
#    1350                 :          1 : }
#    1351                 :            : 
#    1352                 :            : fs::path AbsPathForConfigVal(const fs::path& path, bool net_specific)
#    1353                 :       7544 : {
#    1354         [ +  + ]:       7544 :     if (path.is_absolute()) {
#    1355                 :         28 :         return path;
#    1356                 :         28 :     }
#    1357         [ +  + ]:       7516 :     return fsbridge::AbsPathJoin(net_specific ? gArgs.GetDataDirNet() : gArgs.GetDataDirBase(), path);
#    1358                 :       7516 : }
#    1359                 :            : 
#    1360                 :            : void ScheduleBatchPriority()
#    1361                 :        621 : {
#    1362                 :            : #ifdef SCHED_BATCH
#    1363                 :            :     const static sched_param param{};
#    1364                 :            :     const int rc = pthread_setschedparam(pthread_self(), SCHED_BATCH, &param);
#    1365                 :            :     if (rc != 0) {
#    1366                 :            :         LogPrintf("Failed to pthread_setschedparam: %s\n", strerror(rc));
#    1367                 :            :     }
#    1368                 :            : #endif
#    1369                 :        621 : }
#    1370                 :            : 
#    1371                 :            : namespace util {
#    1372                 :            : #ifdef WIN32
#    1373                 :            : WinCmdLineArgs::WinCmdLineArgs()
#    1374                 :            : {
#    1375                 :            :     wchar_t** wargv = CommandLineToArgvW(GetCommandLineW(), &argc);
#    1376                 :            :     std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t> utf8_cvt;
#    1377                 :            :     argv = new char*[argc];
#    1378                 :            :     args.resize(argc);
#    1379                 :            :     for (int i = 0; i < argc; i++) {
#    1380                 :            :         args[i] = utf8_cvt.to_bytes(wargv[i]);
#    1381                 :            :         argv[i] = &*args[i].begin();
#    1382                 :            :     }
#    1383                 :            :     LocalFree(wargv);
#    1384                 :            : }
#    1385                 :            : 
#    1386                 :            : WinCmdLineArgs::~WinCmdLineArgs()
#    1387                 :            : {
#    1388                 :            :     delete[] argv;
#    1389                 :            : }
#    1390                 :            : 
#    1391                 :            : std::pair<int, char**> WinCmdLineArgs::get()
#    1392                 :            : {
#    1393                 :            :     return std::make_pair(argc, argv);
#    1394                 :            : }
#    1395                 :            : #endif
#    1396                 :            : } // namespace util

Generated by: LCOV version 1.14