LCOV - code coverage report
Current view: top level - src - init.cpp (source / functions) Hit Total Coverage
Test: coverage.lcov Lines: 930 1159 80.2 %
Date: 2021-06-29 14:35:33 Functions: 30 34 88.2 %
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: 346 492 70.3 %

           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                 :            : #if defined(HAVE_CONFIG_H)
#       7                 :            : #include <config/bitcoin-config.h>
#       8                 :            : #endif
#       9                 :            : 
#      10                 :            : #include <init.h>
#      11                 :            : 
#      12                 :            : #include <addrman.h>
#      13                 :            : #include <amount.h>
#      14                 :            : #include <banman.h>
#      15                 :            : #include <blockfilter.h>
#      16                 :            : #include <chain.h>
#      17                 :            : #include <chainparams.h>
#      18                 :            : #include <compat/sanity.h>
#      19                 :            : #include <fs.h>
#      20                 :            : #include <hash.h>
#      21                 :            : #include <httprpc.h>
#      22                 :            : #include <httpserver.h>
#      23                 :            : #include <index/blockfilterindex.h>
#      24                 :            : #include <index/coinstatsindex.h>
#      25                 :            : #include <index/txindex.h>
#      26                 :            : #include <init/common.h>
#      27                 :            : #include <interfaces/chain.h>
#      28                 :            : #include <interfaces/node.h>
#      29                 :            : #include <mapport.h>
#      30                 :            : #include <miner.h>
#      31                 :            : #include <net.h>
#      32                 :            : #include <net_permissions.h>
#      33                 :            : #include <net_processing.h>
#      34                 :            : #include <netbase.h>
#      35                 :            : #include <node/blockstorage.h>
#      36                 :            : #include <node/context.h>
#      37                 :            : #include <node/ui_interface.h>
#      38                 :            : #include <policy/feerate.h>
#      39                 :            : #include <policy/fees.h>
#      40                 :            : #include <policy/policy.h>
#      41                 :            : #include <policy/settings.h>
#      42                 :            : #include <protocol.h>
#      43                 :            : #include <rpc/blockchain.h>
#      44                 :            : #include <rpc/register.h>
#      45                 :            : #include <rpc/server.h>
#      46                 :            : #include <rpc/util.h>
#      47                 :            : #include <scheduler.h>
#      48                 :            : #include <script/sigcache.h>
#      49                 :            : #include <script/standard.h>
#      50                 :            : #include <shutdown.h>
#      51                 :            : #include <sync.h>
#      52                 :            : #include <timedata.h>
#      53                 :            : #include <torcontrol.h>
#      54                 :            : #include <txdb.h>
#      55                 :            : #include <txmempool.h>
#      56                 :            : #include <txorphanage.h>
#      57                 :            : #include <util/asmap.h>
#      58                 :            : #include <util/check.h>
#      59                 :            : #include <util/moneystr.h>
#      60                 :            : #include <util/string.h>
#      61                 :            : #include <util/system.h>
#      62                 :            : #include <util/thread.h>
#      63                 :            : #include <util/threadnames.h>
#      64                 :            : #include <util/translation.h>
#      65                 :            : #include <validation.h>
#      66                 :            : #include <validationinterface.h>
#      67                 :            : #include <walletinitinterface.h>
#      68                 :            : 
#      69                 :            : #include <functional>
#      70                 :            : #include <set>
#      71                 :            : #include <stdint.h>
#      72                 :            : #include <stdio.h>
#      73                 :            : #include <thread>
#      74                 :            : #include <vector>
#      75                 :            : 
#      76                 :            : #ifndef WIN32
#      77                 :            : #include <attributes.h>
#      78                 :            : #include <cerrno>
#      79                 :            : #include <signal.h>
#      80                 :            : #include <sys/stat.h>
#      81                 :            : #endif
#      82                 :            : 
#      83                 :            : #include <boost/algorithm/string/replace.hpp>
#      84                 :            : #include <boost/signals2/signal.hpp>
#      85                 :            : 
#      86                 :            : #if ENABLE_ZMQ
#      87                 :            : #include <zmq/zmqabstractnotifier.h>
#      88                 :            : #include <zmq/zmqnotificationinterface.h>
#      89                 :            : #include <zmq/zmqrpc.h>
#      90                 :            : #endif
#      91                 :            : 
#      92                 :            : static const bool DEFAULT_PROXYRANDOMIZE = true;
#      93                 :            : static const bool DEFAULT_REST_ENABLE = false;
#      94                 :            : 
#      95                 :            : #ifdef WIN32
#      96                 :            : // Win32 LevelDB doesn't use filedescriptors, and the ones used for
#      97                 :            : // accessing block files don't count towards the fd_set size limit
#      98                 :            : // anyway.
#      99                 :            : #define MIN_CORE_FILEDESCRIPTORS 0
#     100                 :            : #else
#     101                 :       6056 : #define MIN_CORE_FILEDESCRIPTORS 150
#     102                 :            : #endif
#     103                 :            : 
#     104                 :            : static const char* DEFAULT_ASMAP_FILENAME="ip_asn.map";
#     105                 :            : 
#     106                 :            : /**
#     107                 :            :  * The PID file facilities.
#     108                 :            :  */
#     109                 :            : static const char* BITCOIN_PID_FILENAME = "bitcoind.pid";
#     110                 :            : 
#     111                 :            : static fs::path GetPidFile(const ArgsManager& args)
#     112                 :       1326 : {
#     113                 :       1326 :     return AbsPathForConfigVal(fs::path(args.GetArg("-pid", BITCOIN_PID_FILENAME)));
#     114                 :       1326 : }
#     115                 :            : 
#     116                 :            : [[nodiscard]] static bool CreatePidFile(const ArgsManager& args)
#     117                 :        663 : {
#     118                 :        663 :     fsbridge::ofstream file{GetPidFile(args)};
#     119         [ +  - ]:        663 :     if (file) {
#     120                 :            : #ifdef WIN32
#     121                 :            :         tfm::format(file, "%d\n", GetCurrentProcessId());
#     122                 :            : #else
#     123                 :        663 :         tfm::format(file, "%d\n", getpid());
#     124                 :        663 : #endif
#     125                 :        663 :         return true;
#     126                 :        663 :     } else {
#     127                 :          0 :         return InitError(strprintf(_("Unable to create the PID file '%s': %s"), GetPidFile(args).string(), std::strerror(errno)));
#     128                 :          0 :     }
#     129                 :        663 : }
#     130                 :            : 
#     131                 :            : //////////////////////////////////////////////////////////////////////////////
#     132                 :            : //
#     133                 :            : // Shutdown
#     134                 :            : //
#     135                 :            : 
#     136                 :            : //
#     137                 :            : // Thread management and startup/shutdown:
#     138                 :            : //
#     139                 :            : // The network-processing threads are all part of a thread group
#     140                 :            : // created by AppInit() or the Qt main() function.
#     141                 :            : //
#     142                 :            : // A clean exit happens when StartShutdown() or the SIGTERM
#     143                 :            : // signal handler sets ShutdownRequested(), which makes main thread's
#     144                 :            : // WaitForShutdown() interrupts the thread group.
#     145                 :            : // And then, WaitForShutdown() makes all other on-going threads
#     146                 :            : // in the thread group join the main thread.
#     147                 :            : // Shutdown() is then called to clean up database connections, and stop other
#     148                 :            : // threads that should only be stopped after the main network-processing
#     149                 :            : // threads have exited.
#     150                 :            : //
#     151                 :            : // Shutdown for Qt is very similar, only it uses a QTimer to detect
#     152                 :            : // ShutdownRequested() getting set, and then does the normal Qt
#     153                 :            : // shutdown thing.
#     154                 :            : //
#     155                 :            : 
#     156                 :            : void Interrupt(NodeContext& node)
#     157                 :        663 : {
#     158                 :        663 :     InterruptHTTPServer();
#     159                 :        663 :     InterruptHTTPRPC();
#     160                 :        663 :     InterruptRPC();
#     161                 :        663 :     InterruptREST();
#     162                 :        663 :     InterruptTorControl();
#     163                 :        663 :     InterruptMapPort();
#     164         [ +  + ]:        663 :     if (node.connman)
#     165                 :        635 :         node.connman->Interrupt();
#     166         [ +  + ]:        663 :     if (g_txindex) {
#     167                 :          9 :         g_txindex->Interrupt();
#     168                 :          9 :     }
#     169                 :        663 :     ForEachBlockFilterIndex([](BlockFilterIndex& index) { index.Interrupt(); });
#     170         [ +  + ]:        663 :     if (g_coin_stats_index) {
#     171                 :          4 :         g_coin_stats_index->Interrupt();
#     172                 :          4 :     }
#     173                 :        663 : }
#     174                 :            : 
#     175                 :            : void Shutdown(NodeContext& node)
#     176                 :        663 : {
#     177                 :        663 :     static Mutex g_shutdown_mutex;
#     178                 :        663 :     TRY_LOCK(g_shutdown_mutex, lock_shutdown);
#     179         [ -  + ]:        663 :     if (!lock_shutdown) return;
#     180                 :        663 :     LogPrintf("%s: In progress...\n", __func__);
#     181                 :        663 :     Assert(node.args);
#     182                 :            : 
#     183                 :            :     /// Note: Shutdown() must be able to handle cases in which initialization failed part of the way,
#     184                 :            :     /// for example if the data directory was found to be locked.
#     185                 :            :     /// Be sure that anything that writes files or flushes caches only does this if the respective
#     186                 :            :     /// module was initialized.
#     187                 :        663 :     util::ThreadRename("shutoff");
#     188         [ +  + ]:        663 :     if (node.mempool) node.mempool->AddTransactionsUpdated(1);
#     189                 :            : 
#     190                 :        663 :     StopHTTPRPC();
#     191                 :        663 :     StopREST();
#     192                 :        663 :     StopRPC();
#     193                 :        663 :     StopHTTPServer();
#     194         [ +  + ]:        663 :     for (const auto& client : node.chain_clients) {
#     195                 :        657 :         client->flush();
#     196                 :        657 :     }
#     197                 :        663 :     StopMapPort();
#     198                 :            : 
#     199                 :            :     // Because these depend on each-other, we make sure that neither can be
#     200                 :            :     // using the other before destroying them.
#     201         [ +  + ]:        663 :     if (node.peerman) UnregisterValidationInterface(node.peerman.get());
#     202         [ +  + ]:        663 :     if (node.connman) node.connman->Stop();
#     203                 :            : 
#     204                 :        663 :     StopTorControl();
#     205                 :            : 
#     206                 :            :     // After everything has been shut down, but before things get flushed, stop the
#     207                 :            :     // CScheduler/checkqueue, scheduler and load block thread.
#     208         [ +  + ]:        663 :     if (node.scheduler) node.scheduler->stop();
#     209 [ +  + ][ +  + ]:        663 :     if (node.chainman && node.chainman->m_load_block.joinable()) node.chainman->m_load_block.join();
#     210                 :        663 :     StopScriptCheckWorkerThreads();
#     211                 :            : 
#     212                 :            :     // After the threads that potentially access these pointers have been stopped,
#     213                 :            :     // destruct and reset all to nullptr.
#     214                 :        663 :     node.peerman.reset();
#     215                 :        663 :     node.connman.reset();
#     216                 :        663 :     node.banman.reset();
#     217                 :        663 :     node.addrman.reset();
#     218                 :            : 
#     219 [ +  + ][ +  + ]:        663 :     if (node.mempool && node.mempool->IsLoaded() && node.args->GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
#         [ +  + ][ +  + ]
#     220                 :        615 :         DumpMempool(*node.mempool);
#     221                 :        615 :     }
#     222                 :            : 
#     223                 :            :     // Drop transactions we were still watching, and record fee estimations.
#     224         [ +  + ]:        663 :     if (node.fee_estimator) node.fee_estimator->Flush();
#     225                 :            : 
#     226                 :            :     // FlushStateToDisk generates a ChainStateFlushed callback, which we should avoid missing
#     227         [ +  + ]:        663 :     if (node.chainman) {
#     228                 :        635 :         LOCK(cs_main);
#     229         [ +  + ]:        635 :         for (CChainState* chainstate : node.chainman->GetAll()) {
#     230         [ +  - ]:        626 :             if (chainstate->CanFlushToDisk()) {
#     231                 :        626 :                 chainstate->ForceFlushStateToDisk();
#     232                 :        626 :             }
#     233                 :        626 :         }
#     234                 :        635 :     }
#     235                 :            : 
#     236                 :            :     // After there are no more peers/RPC left to give us new data which may generate
#     237                 :            :     // CValidationInterface callbacks, flush them...
#     238                 :        663 :     GetMainSignals().FlushBackgroundCallbacks();
#     239                 :            : 
#     240                 :            :     // Stop and delete all indexes only after flushing background callbacks.
#     241         [ +  + ]:        663 :     if (g_txindex) {
#     242                 :          9 :         g_txindex->Stop();
#     243                 :          9 :         g_txindex.reset();
#     244                 :          9 :     }
#     245         [ +  + ]:        663 :     if (g_coin_stats_index) {
#     246                 :          4 :         g_coin_stats_index->Stop();
#     247                 :          4 :         g_coin_stats_index.reset();
#     248                 :          4 :     }
#     249                 :        663 :     ForEachBlockFilterIndex([](BlockFilterIndex& index) { index.Stop(); });
#     250                 :        663 :     DestroyAllBlockFilterIndexes();
#     251                 :            : 
#     252                 :            :     // Any future callbacks will be dropped. This should absolutely be safe - if
#     253                 :            :     // missing a callback results in an unrecoverable situation, unclean shutdown
#     254                 :            :     // would too. The only reason to do the above flushes is to let the wallet catch
#     255                 :            :     // up with our current chain to avoid any strange pruning edge cases and make
#     256                 :            :     // next startup faster by avoiding rescan.
#     257                 :            : 
#     258         [ +  + ]:        663 :     if (node.chainman) {
#     259                 :        635 :         LOCK(cs_main);
#     260         [ +  + ]:        635 :         for (CChainState* chainstate : node.chainman->GetAll()) {
#     261         [ +  - ]:        626 :             if (chainstate->CanFlushToDisk()) {
#     262                 :        626 :                 chainstate->ForceFlushStateToDisk();
#     263                 :        626 :                 chainstate->ResetCoinsViews();
#     264                 :        626 :             }
#     265                 :        626 :         }
#     266                 :        635 :         pblocktree.reset();
#     267                 :        635 :     }
#     268         [ +  + ]:        663 :     for (const auto& client : node.chain_clients) {
#     269                 :        657 :         client->stop();
#     270                 :        657 :     }
#     271                 :            : 
#     272                 :            : #if ENABLE_ZMQ
#     273                 :            :     if (g_zmq_notification_interface) {
#     274                 :            :         UnregisterValidationInterface(g_zmq_notification_interface);
#     275                 :            :         delete g_zmq_notification_interface;
#     276                 :            :         g_zmq_notification_interface = nullptr;
#     277                 :            :     }
#     278                 :            : #endif
#     279                 :            : 
#     280                 :        663 :     node.chain_clients.clear();
#     281                 :        663 :     UnregisterAllValidationInterfaces();
#     282                 :        663 :     GetMainSignals().UnregisterBackgroundSignalScheduler();
#     283                 :        663 :     init::UnsetGlobals();
#     284                 :        663 :     node.mempool.reset();
#     285                 :        663 :     node.fee_estimator.reset();
#     286                 :        663 :     node.chainman = nullptr;
#     287                 :        663 :     node.scheduler.reset();
#     288                 :            : 
#     289                 :        663 :     try {
#     290         [ -  + ]:        663 :         if (!fs::remove(GetPidFile(*node.args))) {
#     291                 :          0 :             LogPrintf("%s: Unable to remove PID file: File does not exist\n", __func__);
#     292                 :          0 :         }
#     293                 :        663 :     } catch (const fs::filesystem_error& e) {
#     294                 :          0 :         LogPrintf("%s: Unable to remove PID file: %s\n", __func__, fsbridge::get_filesystem_error_message(e));
#     295                 :          0 :     }
#     296                 :            : 
#     297                 :        663 :     node.args = nullptr;
#     298                 :        663 :     LogPrintf("%s: done\n", __func__);
#     299                 :        663 : }
#     300                 :            : 
#     301                 :            : /**
#     302                 :            :  * Signal handlers are very limited in what they are allowed to do.
#     303                 :            :  * The execution context the handler is invoked in is not guaranteed,
#     304                 :            :  * so we restrict handler operations to just touching variables:
#     305                 :            :  */
#     306                 :            : #ifndef WIN32
#     307                 :            : static void HandleSIGTERM(int)
#     308                 :          0 : {
#     309                 :          0 :     StartShutdown();
#     310                 :          0 : }
#     311                 :            : 
#     312                 :            : static void HandleSIGHUP(int)
#     313                 :          0 : {
#     314                 :          0 :     LogInstance().m_reopen_file = true;
#     315                 :          0 : }
#     316                 :            : #else
#     317                 :            : static BOOL WINAPI consoleCtrlHandler(DWORD dwCtrlType)
#     318                 :            : {
#     319                 :            :     StartShutdown();
#     320                 :            :     Sleep(INFINITE);
#     321                 :            :     return true;
#     322                 :            : }
#     323                 :            : #endif
#     324                 :            : 
#     325                 :            : #ifndef WIN32
#     326                 :            : static void registerSignalHandler(int signal, void(*handler)(int))
#     327                 :       2004 : {
#     328                 :       2004 :     struct sigaction sa;
#     329                 :       2004 :     sa.sa_handler = handler;
#     330                 :       2004 :     sigemptyset(&sa.sa_mask);
#     331                 :       2004 :     sa.sa_flags = 0;
#     332                 :       2004 :     sigaction(signal, &sa, nullptr);
#     333                 :       2004 : }
#     334                 :            : #endif
#     335                 :            : 
#     336                 :            : static boost::signals2::connection rpc_notify_block_change_connection;
#     337                 :            : static void OnRPCStarted()
#     338                 :        659 : {
#     339                 :        659 :     rpc_notify_block_change_connection = uiInterface.NotifyBlockTip_connect(std::bind(RPCNotifyBlockChange, std::placeholders::_2));
#     340                 :        659 : }
#     341                 :            : 
#     342                 :            : static void OnRPCStopped()
#     343                 :        659 : {
#     344                 :        659 :     rpc_notify_block_change_connection.disconnect();
#     345                 :        659 :     RPCNotifyBlockChange(nullptr);
#     346                 :        659 :     g_best_block_cv.notify_all();
#     347         [ +  - ]:        659 :     LogPrint(BCLog::RPC, "RPC stopped.\n");
#     348                 :        659 : }
#     349                 :            : 
#     350                 :            : void SetupServerArgs(NodeContext& node)
#     351                 :       1536 : {
#     352                 :       1536 :     assert(!node.args);
#     353                 :       1536 :     node.args = &gArgs;
#     354                 :       1536 :     ArgsManager& argsman = *node.args;
#     355                 :            : 
#     356                 :       1536 :     SetupHelpOptions(argsman);
#     357                 :       1536 :     argsman.AddArg("-help-debug", "Print help message with debugging options and exit", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST); // server-only for now
#     358                 :            : 
#     359                 :       1536 :     init::AddLoggingArgs(argsman);
#     360                 :            : 
#     361                 :       1536 :     const auto defaultBaseParams = CreateBaseChainParams(CBaseChainParams::MAIN);
#     362                 :       1536 :     const auto testnetBaseParams = CreateBaseChainParams(CBaseChainParams::TESTNET);
#     363                 :       1536 :     const auto signetBaseParams = CreateBaseChainParams(CBaseChainParams::SIGNET);
#     364                 :       1536 :     const auto regtestBaseParams = CreateBaseChainParams(CBaseChainParams::REGTEST);
#     365                 :       1536 :     const auto defaultChainParams = CreateChainParams(argsman, CBaseChainParams::MAIN);
#     366                 :       1536 :     const auto testnetChainParams = CreateChainParams(argsman, CBaseChainParams::TESTNET);
#     367                 :       1536 :     const auto signetChainParams = CreateChainParams(argsman, CBaseChainParams::SIGNET);
#     368                 :       1536 :     const auto regtestChainParams = CreateChainParams(argsman, CBaseChainParams::REGTEST);
#     369                 :            : 
#     370                 :            :     // Hidden Options
#     371                 :       1536 :     std::vector<std::string> hidden_args = {
#     372                 :       1536 :         "-dbcrashratio", "-forcecompactdb",
#     373                 :            :         // GUI args. These will be overwritten by SetupUIArgs for the GUI
#     374                 :       1536 :         "-choosedatadir", "-lang=<lang>", "-min", "-resetguisettings", "-splash", "-uiplatform"};
#     375                 :            : 
#     376                 :       1536 :     argsman.AddArg("-version", "Print version and exit", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#     377                 :       1536 : #if HAVE_SYSTEM
#     378                 :       1536 :     argsman.AddArg("-alertnotify=<cmd>", "Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#     379                 :       1536 : #endif
#     380                 :       1536 :     argsman.AddArg("-assumevalid=<hex>", strprintf("If this block is in the chain assume that it and its ancestors are valid and potentially skip their script verification (0 to verify all, default: %s, testnet: %s, signet: %s)", defaultChainParams->GetConsensus().defaultAssumeValid.GetHex(), testnetChainParams->GetConsensus().defaultAssumeValid.GetHex(), signetChainParams->GetConsensus().defaultAssumeValid.GetHex()), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#     381                 :       1536 :     argsman.AddArg("-blocksdir=<dir>", "Specify directory to hold blocks subdirectory for *.dat files (default: <datadir>)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#     382                 :       1536 :     argsman.AddArg("-fastprune", "Use smaller block files and lower minimum prune height for testing purposes", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
#     383                 :       1536 : #if HAVE_SYSTEM
#     384                 :       1536 :     argsman.AddArg("-blocknotify=<cmd>", "Execute command when the best block changes (%s in cmd is replaced by block hash)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#     385                 :       1536 : #endif
#     386                 :       1536 :     argsman.AddArg("-blockreconstructionextratxn=<n>", strprintf("Extra transactions to keep in memory for compact block reconstructions (default: %u)", DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#     387                 :       1536 :     argsman.AddArg("-blocksonly", strprintf("Whether to reject transactions from network peers. Automatic broadcast and rebroadcast of any transactions from inbound peers is disabled, unless the peer has the 'forcerelay' permission. RPC transactions are not affected. (default: %u)", DEFAULT_BLOCKSONLY), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#     388                 :       1536 :     argsman.AddArg("-coinstatsindex", strprintf("Maintain coinstats index used by the gettxoutsetinfo RPC (default: %u)", DEFAULT_COINSTATSINDEX), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#     389                 :       1536 :     argsman.AddArg("-conf=<file>", strprintf("Specify path to read-only configuration file. Relative paths will be prefixed by datadir location. (default: %s)", BITCOIN_CONF_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#     390                 :       1536 :     argsman.AddArg("-datadir=<dir>", "Specify data directory", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#     391                 :       1536 :     argsman.AddArg("-dbbatchsize", strprintf("Maximum database write batch size in bytes (default: %u)", nDefaultDbBatchSize), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::OPTIONS);
#     392                 :       1536 :     argsman.AddArg("-dbcache=<n>", strprintf("Maximum database cache size <n> MiB (%d to %d, default: %d). In addition, unused mempool memory is shared for this cache (see -maxmempool).", nMinDbCache, nMaxDbCache, nDefaultDbCache), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#     393                 :       1536 :     argsman.AddArg("-includeconf=<file>", "Specify additional configuration file, relative to the -datadir path (only useable from configuration file, not command line)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#     394                 :       1536 :     argsman.AddArg("-loadblock=<file>", "Imports blocks from external file on startup", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#     395                 :       1536 :     argsman.AddArg("-maxmempool=<n>", strprintf("Keep the transaction memory pool below <n> megabytes (default: %u)", DEFAULT_MAX_MEMPOOL_SIZE), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#     396                 :       1536 :     argsman.AddArg("-maxorphantx=<n>", strprintf("Keep at most <n> unconnectable transactions in memory (default: %u)", DEFAULT_MAX_ORPHAN_TRANSACTIONS), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#     397                 :       1536 :     argsman.AddArg("-mempoolexpiry=<n>", strprintf("Do not keep transactions in the mempool longer than <n> hours (default: %u)", DEFAULT_MEMPOOL_EXPIRY), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#     398                 :       1536 :     argsman.AddArg("-minimumchainwork=<hex>", strprintf("Minimum work assumed to exist on a valid chain in hex (default: %s, testnet: %s, signet: %s)", defaultChainParams->GetConsensus().nMinimumChainWork.GetHex(), testnetChainParams->GetConsensus().nMinimumChainWork.GetHex(), signetChainParams->GetConsensus().nMinimumChainWork.GetHex()), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::OPTIONS);
#     399                 :       1536 :     argsman.AddArg("-par=<n>", strprintf("Set the number of script verification threads (%u to %d, 0 = auto, <0 = leave that many cores free, default: %d)",
#     400                 :       1536 :         -GetNumCores(), MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#     401                 :       1536 :     argsman.AddArg("-persistmempool", strprintf("Whether to save the mempool on shutdown and load on restart (default: %u)", DEFAULT_PERSIST_MEMPOOL), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#     402                 :       1536 :     argsman.AddArg("-pid=<file>", strprintf("Specify pid file. Relative paths will be prefixed by a net-specific datadir location. (default: %s)", BITCOIN_PID_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#     403                 :       1536 :     argsman.AddArg("-prune=<n>", strprintf("Reduce storage requirements by enabling pruning (deleting) of old blocks. This allows the pruneblockchain RPC to be called to delete specific blocks, and enables automatic pruning of old blocks if a target size in MiB is provided. This mode is incompatible with -txindex, -coinstatsindex and -rescan. "
#     404                 :       1536 :             "Warning: Reverting this setting requires re-downloading the entire blockchain. "
#     405                 :       1536 :             "(default: 0 = disable pruning blocks, 1 = allow manual pruning via RPC, >=%u = automatically prune block files to stay under the specified target size in MiB)", MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#     406                 :       1536 :     argsman.AddArg("-reindex", "Rebuild chain state and block index from the blk*.dat files on disk", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#     407                 :       1536 :     argsman.AddArg("-reindex-chainstate", "Rebuild chain state from the currently indexed blocks. When in pruning mode or if blocks on disk might be corrupted, use full -reindex instead.", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#     408                 :       1536 :     argsman.AddArg("-settings=<file>", strprintf("Specify path to dynamic settings data file. Can be disabled with -nosettings. File is written at runtime and not meant to be edited by users (use %s instead for custom settings). Relative paths will be prefixed by datadir location. (default: %s)", BITCOIN_CONF_FILENAME, BITCOIN_SETTINGS_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#     409                 :       1536 : #if HAVE_SYSTEM
#     410                 :       1536 :     argsman.AddArg("-startupnotify=<cmd>", "Execute command on startup.", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#     411                 :       1536 : #endif
#     412                 :       1536 : #ifndef WIN32
#     413                 :       1536 :     argsman.AddArg("-sysperms", "Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#     414                 :            : #else
#     415                 :            :     hidden_args.emplace_back("-sysperms");
#     416                 :            : #endif
#     417                 :       1536 :     argsman.AddArg("-txindex", strprintf("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)", DEFAULT_TXINDEX), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#     418                 :       1536 :     argsman.AddArg("-blockfilterindex=<type>",
#     419                 :       1536 :                  strprintf("Maintain an index of compact filters by block (default: %s, values: %s).", DEFAULT_BLOCKFILTERINDEX, ListBlockFilterTypes()) +
#     420                 :       1536 :                  " If <type> is not supplied or if <type> = 1, indexes for all known types are enabled.",
#     421                 :       1536 :                  ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#     422                 :            : 
#     423                 :       1536 :     argsman.AddArg("-addnode=<ip>", strprintf("Add a node to connect to and attempt to keep the connection open (see the addnode RPC help for more info). This option can be specified multiple times to add multiple nodes; connections are limited to %u at a time and are counted separately from the -maxconnections limit.", MAX_ADDNODE_CONNECTIONS), ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::CONNECTION);
#     424                 :       1536 :     argsman.AddArg("-asmap=<file>", strprintf("Specify asn mapping used for bucketing of the peers (default: %s). Relative paths will be prefixed by the net-specific datadir location.", DEFAULT_ASMAP_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
#     425                 :       1536 :     argsman.AddArg("-bantime=<n>", strprintf("Default duration (in seconds) of manually configured bans (default: %u)", DEFAULT_MISBEHAVING_BANTIME), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
#     426                 :       1536 :     argsman.AddArg("-bind=<addr>[:<port>][=onion]", strprintf("Bind to given address and always listen on it (default: 0.0.0.0). Use [host]:port notation for IPv6. Append =onion to tag any incoming connections to that address and port as incoming Tor connections (default: 127.0.0.1:%u=onion, testnet: 127.0.0.1:%u=onion, signet: 127.0.0.1:%u=onion, regtest: 127.0.0.1:%u=onion)", defaultBaseParams->OnionServiceTargetPort(), testnetBaseParams->OnionServiceTargetPort(), signetBaseParams->OnionServiceTargetPort(), regtestBaseParams->OnionServiceTargetPort()), ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::CONNECTION);
#     427                 :       1536 :     argsman.AddArg("-connect=<ip>", "Connect only to the specified node; -noconnect disables automatic connections (the rules for this peer are the same as for -addnode). This option can be specified multiple times to connect to multiple nodes.", ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::CONNECTION);
#     428                 :       1536 :     argsman.AddArg("-discover", "Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
#     429                 :       1536 :     argsman.AddArg("-dns", strprintf("Allow DNS lookups for -addnode, -seednode and -connect (default: %u)", DEFAULT_NAME_LOOKUP), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
#     430                 :       1536 :     argsman.AddArg("-dnsseed", strprintf("Query for peer addresses via DNS lookup, if low on addresses (default: %u unless -connect used)", DEFAULT_DNSSEED), ArgsManager::ALLOW_BOOL, OptionsCategory::CONNECTION);
#     431                 :       1536 :     argsman.AddArg("-externalip=<ip>", "Specify your own public address", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
#     432                 :       1536 :     argsman.AddArg("-fixedseeds", strprintf("Allow fixed seeds if DNS seeds don't provide peers (default: %u)", DEFAULT_FIXEDSEEDS), ArgsManager::ALLOW_BOOL, OptionsCategory::CONNECTION);
#     433                 :       1536 :     argsman.AddArg("-forcednsseed", strprintf("Always query for peer addresses via DNS lookup (default: %u)", DEFAULT_FORCEDNSSEED), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
#     434                 :       1536 :     argsman.AddArg("-listen", "Accept connections from outside (default: 1 if no -proxy or -connect)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
#     435                 :       1536 :     argsman.AddArg("-listenonion", strprintf("Automatically create Tor onion service (default: %d)", DEFAULT_LISTEN_ONION), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
#     436                 :       1536 :     argsman.AddArg("-maxconnections=<n>", strprintf("Maintain at most <n> connections to peers (default: %u). This limit does not apply to connections manually added via -addnode or the addnode RPC, which have a separate limit of %u.", DEFAULT_MAX_PEER_CONNECTIONS, MAX_ADDNODE_CONNECTIONS), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
#     437                 :       1536 :     argsman.AddArg("-maxreceivebuffer=<n>", strprintf("Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)", DEFAULT_MAXRECEIVEBUFFER), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
#     438                 :       1536 :     argsman.AddArg("-maxsendbuffer=<n>", strprintf("Maximum per-connection send buffer, <n>*1000 bytes (default: %u)", DEFAULT_MAXSENDBUFFER), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
#     439                 :       1536 :     argsman.AddArg("-maxtimeadjustment", strprintf("Maximum allowed median peer time offset adjustment. Local perspective of time may be influenced by peers forward or backward by this amount. (default: %u seconds)", DEFAULT_MAX_TIME_ADJUSTMENT), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
#     440                 :       1536 :     argsman.AddArg("-maxuploadtarget=<n>", strprintf("Tries to keep outbound traffic under the given target (in MiB per 24h). Limit does not apply to peers with 'download' permission. 0 = no limit (default: %d)", DEFAULT_MAX_UPLOAD_TARGET), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
#     441                 :       1536 :     argsman.AddArg("-onion=<ip:port>", "Use separate SOCKS5 proxy to reach peers via Tor onion services, set -noonion to disable (default: -proxy)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
#     442                 :       1536 :     argsman.AddArg("-i2psam=<ip:port>", "I2P SAM proxy to reach I2P peers and accept I2P connections (default: none)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
#     443                 :       1536 :     argsman.AddArg("-i2pacceptincoming", "If set and -i2psam is also set then incoming I2P connections are accepted via the SAM proxy. If this is not set but -i2psam is set then only outgoing connections will be made to the I2P network. Ignored if -i2psam is not set. Listening for incoming I2P connections is done through the SAM proxy, not by binding to a local address and port (default: 1)", ArgsManager::ALLOW_BOOL, OptionsCategory::CONNECTION);
#     444                 :       1536 :     argsman.AddArg("-onlynet=<net>", "Make outgoing connections only through network <net> (" + Join(GetNetworkNames(), ", ") + "). Incoming connections are not affected by this option. This option can be specified multiple times to allow multiple networks. Warning: if it is used with non-onion networks and the -onion or -proxy option is set, then outbound onion connections will still be made; use -noonion or -onion=0 to disable outbound onion connections in this case.", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
#     445                 :       1536 :     argsman.AddArg("-peerbloomfilters", strprintf("Support filtering of blocks and transaction with bloom filters (default: %u)", DEFAULT_PEERBLOOMFILTERS), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
#     446                 :       1536 :     argsman.AddArg("-peerblockfilters", strprintf("Serve compact block filters to peers per BIP 157 (default: %u)", DEFAULT_PEERBLOCKFILTERS), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
#     447                 :       1536 :     argsman.AddArg("-permitbaremultisig", strprintf("Relay non-P2SH multisig (default: %u)", DEFAULT_PERMIT_BAREMULTISIG), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
#     448                 :       1536 :     argsman.AddArg("-port=<port>", strprintf("Listen for connections on <port>. Nodes not using the default ports (default: %u, testnet: %u, signet: %u, regtest: %u) are unlikely to get incoming connections.", defaultChainParams->GetDefaultPort(), testnetChainParams->GetDefaultPort(), signetChainParams->GetDefaultPort(), regtestChainParams->GetDefaultPort()), ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::CONNECTION);
#     449                 :       1536 :     argsman.AddArg("-proxy=<ip:port>", "Connect through SOCKS5 proxy, set -noproxy to disable (default: disabled)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
#     450                 :       1536 :     argsman.AddArg("-proxyrandomize", strprintf("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)", DEFAULT_PROXYRANDOMIZE), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
#     451                 :       1536 :     argsman.AddArg("-seednode=<ip>", "Connect to a node to retrieve peer addresses, and disconnect. This option can be specified multiple times to connect to multiple nodes.", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
#     452                 :       1536 :     argsman.AddArg("-networkactive", "Enable all P2P network activity (default: 1). Can be changed by the setnetworkactive RPC command", ArgsManager::ALLOW_BOOL, OptionsCategory::CONNECTION);
#     453                 :       1536 :     argsman.AddArg("-timeout=<n>", strprintf("Specify socket connection timeout in milliseconds. If an initial attempt to connect is unsuccessful after this amount of time, drop it (minimum: 1, default: %d)", DEFAULT_CONNECT_TIMEOUT), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
#     454                 :       1536 :     argsman.AddArg("-peertimeout=<n>", strprintf("Specify a p2p connection timeout delay in seconds. After connecting to a peer, wait this amount of time before considering disconnection based on inactivity (minimum: 1, default: %d)", DEFAULT_PEER_CONNECT_TIMEOUT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::CONNECTION);
#     455                 :       1536 :     argsman.AddArg("-torcontrol=<ip>:<port>", strprintf("Tor control port to use if onion listening enabled (default: %s)", DEFAULT_TOR_CONTROL), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
#     456                 :       1536 :     argsman.AddArg("-torpassword=<pass>", "Tor control port password (default: empty)", ArgsManager::ALLOW_ANY | ArgsManager::SENSITIVE, OptionsCategory::CONNECTION);
#     457                 :       1536 : #ifdef USE_UPNP
#     458                 :            : #if USE_UPNP
#     459                 :            :     argsman.AddArg("-upnp", "Use UPnP to map the listening port (default: 1 when listening and no -proxy)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
#     460                 :            : #else
#     461                 :       1536 :     argsman.AddArg("-upnp", strprintf("Use UPnP to map the listening port (default: %u)", 0), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
#     462                 :       1536 : #endif
#     463                 :            : #else
#     464                 :            :     hidden_args.emplace_back("-upnp");
#     465                 :            : #endif
#     466                 :       1536 : #ifdef USE_NATPMP
#     467                 :       1536 :     argsman.AddArg("-natpmp", strprintf("Use NAT-PMP to map the listening port (default: %s)", DEFAULT_NATPMP ? "1 when listening and no -proxy" : "0"), ArgsManager::ALLOW_BOOL, OptionsCategory::CONNECTION);
#     468                 :            : #else
#     469                 :            :     hidden_args.emplace_back("-natpmp");
#     470                 :            : #endif // USE_NATPMP
#     471                 :       1536 :     argsman.AddArg("-whitebind=<[permissions@]addr>", "Bind to the given address and add permission flags to the peers connecting to it. "
#     472                 :       1536 :         "Use [host]:port notation for IPv6. Allowed permissions: " + Join(NET_PERMISSIONS_DOC, ", ") + ". "
#     473                 :       1536 :         "Specify multiple permissions separated by commas (default: download,noban,mempool,relay). Can be specified multiple times.", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
#     474                 :            : 
#     475                 :       1536 :     argsman.AddArg("-whitelist=<[permissions@]IP address or network>", "Add permission flags to the peers connecting from the given IP address (e.g. 1.2.3.4) or "
#     476                 :       1536 :         "CIDR-notated network (e.g. 1.2.3.0/24). Uses the same permissions as "
#     477                 :       1536 :         "-whitebind. Can be specified multiple times." , ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
#     478                 :            : 
#     479                 :       1536 :     g_wallet_init_interface.AddWalletOptions(argsman);
#     480                 :            : 
#     481                 :            : #if ENABLE_ZMQ
#     482                 :            :     argsman.AddArg("-zmqpubhashblock=<address>", "Enable publish hash block in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
#     483                 :            :     argsman.AddArg("-zmqpubhashtx=<address>", "Enable publish hash transaction in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
#     484                 :            :     argsman.AddArg("-zmqpubrawblock=<address>", "Enable publish raw block in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
#     485                 :            :     argsman.AddArg("-zmqpubrawtx=<address>", "Enable publish raw transaction in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
#     486                 :            :     argsman.AddArg("-zmqpubsequence=<address>", "Enable publish hash block and tx sequence in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
#     487                 :            :     argsman.AddArg("-zmqpubhashblockhwm=<n>", strprintf("Set publish hash block outbound message high water mark (default: %d)", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM), ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
#     488                 :            :     argsman.AddArg("-zmqpubhashtxhwm=<n>", strprintf("Set publish hash transaction outbound message high water mark (default: %d)", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM), ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
#     489                 :            :     argsman.AddArg("-zmqpubrawblockhwm=<n>", strprintf("Set publish raw block outbound message high water mark (default: %d)", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM), ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
#     490                 :            :     argsman.AddArg("-zmqpubrawtxhwm=<n>", strprintf("Set publish raw transaction outbound message high water mark (default: %d)", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM), ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
#     491                 :            :     argsman.AddArg("-zmqpubsequencehwm=<n>", strprintf("Set publish hash sequence message high water mark (default: %d)", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM), ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
#     492                 :            : #else
#     493                 :       1536 :     hidden_args.emplace_back("-zmqpubhashblock=<address>");
#     494                 :       1536 :     hidden_args.emplace_back("-zmqpubhashtx=<address>");
#     495                 :       1536 :     hidden_args.emplace_back("-zmqpubrawblock=<address>");
#     496                 :       1536 :     hidden_args.emplace_back("-zmqpubrawtx=<address>");
#     497                 :       1536 :     hidden_args.emplace_back("-zmqpubsequence=<n>");
#     498                 :       1536 :     hidden_args.emplace_back("-zmqpubhashblockhwm=<n>");
#     499                 :       1536 :     hidden_args.emplace_back("-zmqpubhashtxhwm=<n>");
#     500                 :       1536 :     hidden_args.emplace_back("-zmqpubrawblockhwm=<n>");
#     501                 :       1536 :     hidden_args.emplace_back("-zmqpubrawtxhwm=<n>");
#     502                 :       1536 :     hidden_args.emplace_back("-zmqpubsequencehwm=<n>");
#     503                 :       1536 : #endif
#     504                 :            : 
#     505                 :       1536 :     argsman.AddArg("-checkblocks=<n>", strprintf("How many blocks to check at startup (default: %u, 0 = all)", DEFAULT_CHECKBLOCKS), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
#     506                 :       1536 :     argsman.AddArg("-checklevel=<n>", strprintf("How thorough the block verification of -checkblocks is: %s (0-4, default: %u)", Join(CHECKLEVEL_DOC, ", "), DEFAULT_CHECKLEVEL), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
#     507                 :       1536 :     argsman.AddArg("-checkblockindex", strprintf("Do a consistency check for the block tree, chainstate, and other validation data structures occasionally. (default: %u, regtest: %u)", defaultChainParams->DefaultConsistencyChecks(), regtestChainParams->DefaultConsistencyChecks()), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
#     508                 :       1536 :     argsman.AddArg("-checkmempool=<n>", strprintf("Run checks every <n> transactions (default: %u, regtest: %u)", defaultChainParams->DefaultConsistencyChecks(), regtestChainParams->DefaultConsistencyChecks()), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
#     509                 :       1536 :     argsman.AddArg("-checkpoints", strprintf("Enable rejection of any forks from the known historical chain until block %s (default: %u)", defaultChainParams->Checkpoints().GetHeight(), DEFAULT_CHECKPOINTS_ENABLED), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
#     510                 :       1536 :     argsman.AddArg("-deprecatedrpc=<method>", "Allows deprecated RPC method(s) to be used", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
#     511                 :       1536 :     argsman.AddArg("-stopafterblockimport", strprintf("Stop running after importing blocks from disk (default: %u)", DEFAULT_STOPAFTERBLOCKIMPORT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
#     512                 :       1536 :     argsman.AddArg("-stopatheight", strprintf("Stop running after reaching the given height in the main chain (default: %u)", DEFAULT_STOPATHEIGHT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
#     513                 :       1536 :     argsman.AddArg("-limitancestorcount=<n>", strprintf("Do not accept transactions if number of in-mempool ancestors is <n> or more (default: %u)", DEFAULT_ANCESTOR_LIMIT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
#     514                 :       1536 :     argsman.AddArg("-limitancestorsize=<n>", strprintf("Do not accept transactions whose size with all in-mempool ancestors exceeds <n> kilobytes (default: %u)", DEFAULT_ANCESTOR_SIZE_LIMIT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
#     515                 :       1536 :     argsman.AddArg("-limitdescendantcount=<n>", strprintf("Do not accept transactions if any ancestor would have <n> or more in-mempool descendants (default: %u)", DEFAULT_DESCENDANT_LIMIT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
#     516                 :       1536 :     argsman.AddArg("-limitdescendantsize=<n>", strprintf("Do not accept transactions if any ancestor would have more than <n> kilobytes of in-mempool descendants (default: %u).", DEFAULT_DESCENDANT_SIZE_LIMIT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
#     517                 :       1536 :     argsman.AddArg("-addrmantest", "Allows to test address relay on localhost", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
#     518                 :       1536 :     argsman.AddArg("-capturemessages", "Capture all P2P messages to disk", ArgsManager::ALLOW_BOOL | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
#     519                 :       1536 :     argsman.AddArg("-mocktime=<n>", "Replace actual time with " + UNIX_EPOCH_TIME + " (default: 0)", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
#     520                 :       1536 :     argsman.AddArg("-maxsigcachesize=<n>", strprintf("Limit sum of signature cache and script execution cache sizes to <n> MiB (default: %u)", DEFAULT_MAX_SIG_CACHE_SIZE), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
#     521                 :       1536 :     argsman.AddArg("-maxtipage=<n>", strprintf("Maximum tip age in seconds to consider node in initial block download (default: %u)", DEFAULT_MAX_TIP_AGE), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
#     522                 :       1536 :     argsman.AddArg("-printpriority", strprintf("Log transaction fee rate in " + CURRENCY_UNIT + "/kvB when mining blocks (default: %u)", DEFAULT_PRINTPRIORITY), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
#     523                 :       1536 :     argsman.AddArg("-uacomment=<cmt>", "Append comment to the user agent string", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
#     524                 :            : 
#     525                 :       1536 :     SetupChainParamsBaseOptions(argsman);
#     526                 :            : 
#     527                 :       1536 :     argsman.AddArg("-acceptnonstdtxn", strprintf("Relay and mine \"non-standard\" transactions (%sdefault: %u)", "testnet/regtest only; ", !testnetChainParams->RequireStandard()), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::NODE_RELAY);
#     528                 :       1536 :     argsman.AddArg("-incrementalrelayfee=<amt>", strprintf("Fee rate (in %s/kvB) used to define cost of relay, used for mempool limiting and BIP 125 replacement. (default: %s)", CURRENCY_UNIT, FormatMoney(DEFAULT_INCREMENTAL_RELAY_FEE)), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::NODE_RELAY);
#     529                 :       1536 :     argsman.AddArg("-dustrelayfee=<amt>", strprintf("Fee rate (in %s/kvB) used to define dust, the value of an output such that it will cost more than its value in fees at this fee rate to spend it. (default: %s)", CURRENCY_UNIT, FormatMoney(DUST_RELAY_TX_FEE)), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::NODE_RELAY);
#     530                 :       1536 :     argsman.AddArg("-bytespersigop", strprintf("Equivalent bytes per sigop in transactions for relay and mining (default: %u)", DEFAULT_BYTES_PER_SIGOP), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
#     531                 :       1536 :     argsman.AddArg("-datacarrier", strprintf("Relay and mine data carrier transactions (default: %u)", DEFAULT_ACCEPT_DATACARRIER), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
#     532                 :       1536 :     argsman.AddArg("-datacarriersize", strprintf("Maximum size of data in data carrier transactions we relay and mine (default: %u)", MAX_OP_RETURN_RELAY), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
#     533                 :       1536 :     argsman.AddArg("-minrelaytxfee=<amt>", strprintf("Fees (in %s/kvB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)",
#     534                 :       1536 :         CURRENCY_UNIT, FormatMoney(DEFAULT_MIN_RELAY_TX_FEE)), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
#     535                 :       1536 :     argsman.AddArg("-whitelistforcerelay", strprintf("Add 'forcerelay' permission to whitelisted inbound peers with default permissions. This will relay transactions even if the transactions were already in the mempool. (default: %d)", DEFAULT_WHITELISTFORCERELAY), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
#     536                 :       1536 :     argsman.AddArg("-whitelistrelay", strprintf("Add 'relay' permission to whitelisted inbound peers with default permissions. This will accept relayed transactions even when not relaying transactions (default: %d)", DEFAULT_WHITELISTRELAY), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
#     537                 :            : 
#     538                 :            : 
#     539                 :       1536 :     argsman.AddArg("-blockmaxweight=<n>", strprintf("Set maximum BIP141 block weight (default: %d)", DEFAULT_BLOCK_MAX_WEIGHT), ArgsManager::ALLOW_ANY, OptionsCategory::BLOCK_CREATION);
#     540                 :       1536 :     argsman.AddArg("-blockmintxfee=<amt>", strprintf("Set lowest fee rate (in %s/kvB) for transactions to be included in block creation. (default: %s)", CURRENCY_UNIT, FormatMoney(DEFAULT_BLOCK_MIN_TX_FEE)), ArgsManager::ALLOW_ANY, OptionsCategory::BLOCK_CREATION);
#     541                 :       1536 :     argsman.AddArg("-blockversion=<n>", "Override block version to test forking scenarios", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::BLOCK_CREATION);
#     542                 :            : 
#     543                 :       1536 :     argsman.AddArg("-rest", strprintf("Accept public REST requests (default: %u)", DEFAULT_REST_ENABLE), ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
#     544                 :       1536 :     argsman.AddArg("-rpcallowip=<ip>", "Allow JSON-RPC connections from specified source. Valid for <ip> are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times", ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
#     545                 :       1536 :     argsman.AddArg("-rpcauth=<userpw>", "Username and HMAC-SHA-256 hashed password for JSON-RPC connections. The field <userpw> comes in the format: <USERNAME>:<SALT>$<HASH>. A canonical python script is included in share/rpcauth. The client then connects normally using the rpcuser=<USERNAME>/rpcpassword=<PASSWORD> pair of arguments. This option can be specified multiple times", ArgsManager::ALLOW_ANY | ArgsManager::SENSITIVE, OptionsCategory::RPC);
#     546                 :       1536 :     argsman.AddArg("-rpcbind=<addr>[:port]", "Bind to given address to listen for JSON-RPC connections. Do not expose the RPC server to untrusted networks such as the public internet! This option is ignored unless -rpcallowip is also passed. Port is optional and overrides -rpcport. Use [host]:port notation for IPv6. This option can be specified multiple times (default: 127.0.0.1 and ::1 i.e., localhost)", ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY | ArgsManager::SENSITIVE, OptionsCategory::RPC);
#     547                 :       1536 :     argsman.AddArg("-rpccookiefile=<loc>", "Location of the auth cookie. Relative paths will be prefixed by a net-specific datadir location. (default: data dir)", ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
#     548                 :       1536 :     argsman.AddArg("-rpcpassword=<pw>", "Password for JSON-RPC connections", ArgsManager::ALLOW_ANY | ArgsManager::SENSITIVE, OptionsCategory::RPC);
#     549                 :       1536 :     argsman.AddArg("-rpcport=<port>", strprintf("Listen for JSON-RPC connections on <port> (default: %u, testnet: %u, signet: %u, regtest: %u)", defaultBaseParams->RPCPort(), testnetBaseParams->RPCPort(), signetBaseParams->RPCPort(), regtestBaseParams->RPCPort()), ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::RPC);
#     550                 :       1536 :     argsman.AddArg("-rpcserialversion", strprintf("Sets the serialization of raw transaction or block hex returned in non-verbose mode, non-segwit(0) or segwit(1) (default: %d)", DEFAULT_RPC_SERIALIZE_VERSION), ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
#     551                 :       1536 :     argsman.AddArg("-rpcservertimeout=<n>", strprintf("Timeout during HTTP requests (default: %d)", DEFAULT_HTTP_SERVER_TIMEOUT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::RPC);
#     552                 :       1536 :     argsman.AddArg("-rpcthreads=<n>", strprintf("Set the number of threads to service RPC calls (default: %d)", DEFAULT_HTTP_THREADS), ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
#     553                 :       1536 :     argsman.AddArg("-rpcuser=<user>", "Username for JSON-RPC connections", ArgsManager::ALLOW_ANY | ArgsManager::SENSITIVE, OptionsCategory::RPC);
#     554                 :       1536 :     argsman.AddArg("-rpcwhitelist=<whitelist>", "Set a whitelist to filter incoming RPC calls for a specific user. The field <whitelist> comes in the format: <USERNAME>:<rpc 1>,<rpc 2>,...,<rpc n>. If multiple whitelists are set for a given user, they are set-intersected. See -rpcwhitelistdefault documentation for information on default whitelist behavior.", ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
#     555                 :       1536 :     argsman.AddArg("-rpcwhitelistdefault", "Sets default behavior for rpc whitelisting. Unless rpcwhitelistdefault is set to 0, if any -rpcwhitelist is set, the rpc server acts as if all rpc users are subject to empty-unless-otherwise-specified whitelists. If rpcwhitelistdefault is set to 1 and no -rpcwhitelist is set, rpc server acts as if all rpc users are subject to empty whitelists.", ArgsManager::ALLOW_BOOL, OptionsCategory::RPC);
#     556                 :       1536 :     argsman.AddArg("-rpcworkqueue=<n>", strprintf("Set the depth of the work queue to service RPC calls (default: %d)", DEFAULT_HTTP_WORKQUEUE), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::RPC);
#     557                 :       1536 :     argsman.AddArg("-server", "Accept command line and JSON-RPC commands", ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
#     558                 :            : 
#     559                 :       1536 : #if HAVE_DECL_FORK
#     560                 :       1536 :     argsman.AddArg("-daemon", strprintf("Run in the background as a daemon and accept commands (default: %d)", DEFAULT_DAEMON), ArgsManager::ALLOW_BOOL, OptionsCategory::OPTIONS);
#     561                 :       1536 :     argsman.AddArg("-daemonwait", strprintf("Wait for initialization to be finished before exiting. This implies -daemon (default: %d)", DEFAULT_DAEMONWAIT), ArgsManager::ALLOW_BOOL, OptionsCategory::OPTIONS);
#     562                 :            : #else
#     563                 :            :     hidden_args.emplace_back("-daemon");
#     564                 :            :     hidden_args.emplace_back("-daemonwait");
#     565                 :            : #endif
#     566                 :            : 
#     567                 :            :     // Add the hidden options
#     568                 :       1536 :     argsman.AddHiddenArgs(hidden_args);
#     569                 :       1536 : }
#     570                 :            : 
#     571                 :            : std::string LicenseInfo()
#     572                 :          1 : {
#     573                 :          1 :     const std::string URL_SOURCE_CODE = "<https://github.com/bitcoin/bitcoin>";
#     574                 :            : 
#     575                 :          1 :     return CopyrightHolders(strprintf(_("Copyright (C) %i-%i").translated, 2009, COPYRIGHT_YEAR) + " ") + "\n" +
#     576                 :          1 :            "\n" +
#     577                 :          1 :            strprintf(_("Please contribute if you find %s useful. "
#     578                 :          1 :                        "Visit %s for further information about the software.").translated,
#     579                 :          1 :                PACKAGE_NAME, "<" PACKAGE_URL ">") +
#     580                 :          1 :            "\n" +
#     581                 :          1 :            strprintf(_("The source code is available from %s.").translated,
#     582                 :          1 :                URL_SOURCE_CODE) +
#     583                 :          1 :            "\n" +
#     584                 :          1 :            "\n" +
#     585                 :          1 :            _("This is experimental software.").translated + "\n" +
#     586                 :          1 :            strprintf(_("Distributed under the MIT software license, see the accompanying file %s or %s").translated, "COPYING", "<https://opensource.org/licenses/MIT>") +
#     587                 :          1 :            "\n";
#     588                 :          1 : }
#     589                 :            : 
#     590                 :            : static bool fHaveGenesis = false;
#     591                 :            : static Mutex g_genesis_wait_mutex;
#     592                 :            : static std::condition_variable g_genesis_wait_cv;
#     593                 :            : 
#     594                 :            : static void BlockNotifyGenesisWait(const CBlockIndex* pBlockIndex)
#     595                 :        248 : {
#     596         [ +  - ]:        248 :     if (pBlockIndex != nullptr) {
#     597                 :        248 :         {
#     598                 :        248 :             LOCK(g_genesis_wait_mutex);
#     599                 :        248 :             fHaveGenesis = true;
#     600                 :        248 :         }
#     601                 :        248 :         g_genesis_wait_cv.notify_all();
#     602                 :        248 :     }
#     603                 :        248 : }
#     604                 :            : 
#     605                 :            : #if HAVE_SYSTEM
#     606                 :            : static void StartupNotify(const ArgsManager& args)
#     607                 :        618 : {
#     608                 :        618 :     std::string cmd = args.GetArg("-startupnotify", "");
#     609         [ -  + ]:        618 :     if (!cmd.empty()) {
#     610                 :          0 :         std::thread t(runCommand, cmd);
#     611                 :          0 :         t.detach(); // thread runs free
#     612                 :          0 :     }
#     613                 :        618 : }
#     614                 :            : #endif
#     615                 :            : 
#     616                 :            : static bool AppInitServers(NodeContext& node)
#     617                 :        659 : {
#     618                 :        659 :     const ArgsManager& args = *Assert(node.args);
#     619                 :        659 :     RPCServer::OnStarted(&OnRPCStarted);
#     620                 :        659 :     RPCServer::OnStopped(&OnRPCStopped);
#     621         [ -  + ]:        659 :     if (!InitHTTPServer())
#     622                 :          0 :         return false;
#     623                 :        659 :     StartRPC();
#     624                 :        659 :     node.rpc_interruption_point = RpcInterruptionPoint;
#     625         [ +  + ]:        659 :     if (!StartHTTPRPC(&node))
#     626                 :          3 :         return false;
#     627         [ +  + ]:        656 :     if (args.GetBoolArg("-rest", DEFAULT_REST_ENABLE)) StartREST(&node);
#     628                 :        656 :     StartHTTPServer();
#     629                 :        656 :     return true;
#     630                 :        656 : }
#     631                 :            : 
#     632                 :            : // Parameter interaction based on rules
#     633                 :            : void InitParameterInteraction(ArgsManager& args)
#     634                 :        668 : {
#     635                 :            :     // when specifying an explicit binding address, you want to listen on it
#     636                 :            :     // even when -connect or -proxy is specified
#     637         [ +  + ]:        668 :     if (args.IsArgSet("-bind")) {
#     638         [ +  + ]:        664 :         if (args.SoftSetBoolArg("-listen", true))
#     639                 :        664 :             LogPrintf("%s: parameter interaction: -bind set -> setting -listen=1\n", __func__);
#     640                 :        664 :     }
#     641         [ +  + ]:        668 :     if (args.IsArgSet("-whitebind")) {
#     642         [ +  + ]:          2 :         if (args.SoftSetBoolArg("-listen", true))
#     643                 :          2 :             LogPrintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__);
#     644                 :          2 :     }
#     645                 :            : 
#     646         [ +  + ]:        668 :     if (args.IsArgSet("-connect")) {
#     647                 :            :         // when only connecting to trusted nodes, do not seed via DNS, or listen by default
#     648         [ -  + ]:          1 :         if (args.SoftSetBoolArg("-dnsseed", false))
#     649                 :          1 :             LogPrintf("%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__);
#     650         [ -  + ]:          1 :         if (args.SoftSetBoolArg("-listen", false))
#     651                 :          1 :             LogPrintf("%s: parameter interaction: -connect set -> setting -listen=0\n", __func__);
#     652                 :          1 :     }
#     653                 :            : 
#     654         [ +  + ]:        668 :     if (args.IsArgSet("-proxy")) {
#     655                 :            :         // to protect privacy, do not listen by default if a default proxy server is specified
#     656         [ -  + ]:          5 :         if (args.SoftSetBoolArg("-listen", false))
#     657                 :          5 :             LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__);
#     658                 :            :         // to protect privacy, do not map ports when a proxy is set. The user may still specify -listen=1
#     659                 :            :         // to listen locally, so don't rely on this happening through -listen below.
#     660         [ -  + ]:          5 :         if (args.SoftSetBoolArg("-upnp", false))
#     661                 :          5 :             LogPrintf("%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__);
#     662         [ -  + ]:          5 :         if (args.SoftSetBoolArg("-natpmp", false)) {
#     663                 :          0 :             LogPrintf("%s: parameter interaction: -proxy set -> setting -natpmp=0\n", __func__);
#     664                 :          0 :         }
#     665                 :            :         // to protect privacy, do not discover addresses by default
#     666         [ -  + ]:          5 :         if (args.SoftSetBoolArg("-discover", false))
#     667                 :          5 :             LogPrintf("%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__);
#     668                 :          5 :     }
#     669                 :            : 
#     670         [ -  + ]:        668 :     if (!args.GetBoolArg("-listen", DEFAULT_LISTEN)) {
#     671                 :            :         // do not map ports or try to retrieve public IP when not listening (pointless)
#     672         [ #  # ]:          0 :         if (args.SoftSetBoolArg("-upnp", false))
#     673                 :          0 :             LogPrintf("%s: parameter interaction: -listen=0 -> setting -upnp=0\n", __func__);
#     674         [ #  # ]:          0 :         if (args.SoftSetBoolArg("-natpmp", false)) {
#     675                 :          0 :             LogPrintf("%s: parameter interaction: -listen=0 -> setting -natpmp=0\n", __func__);
#     676                 :          0 :         }
#     677         [ #  # ]:          0 :         if (args.SoftSetBoolArg("-discover", false))
#     678                 :          0 :             LogPrintf("%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__);
#     679         [ #  # ]:          0 :         if (args.SoftSetBoolArg("-listenonion", false))
#     680                 :          0 :             LogPrintf("%s: parameter interaction: -listen=0 -> setting -listenonion=0\n", __func__);
#     681         [ #  # ]:          0 :         if (args.SoftSetBoolArg("-i2pacceptincoming", false)) {
#     682                 :          0 :             LogPrintf("%s: parameter interaction: -listen=0 -> setting -i2pacceptincoming=0\n", __func__);
#     683                 :          0 :         }
#     684                 :          0 :     }
#     685                 :            : 
#     686         [ -  + ]:        668 :     if (args.IsArgSet("-externalip")) {
#     687                 :            :         // if an explicit public IP is specified, do not try to find others
#     688         [ #  # ]:          0 :         if (args.SoftSetBoolArg("-discover", false))
#     689                 :          0 :             LogPrintf("%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__);
#     690                 :          0 :     }
#     691                 :            : 
#     692                 :            :     // disable whitelistrelay in blocksonly mode
#     693         [ +  + ]:        668 :     if (args.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)) {
#     694         [ +  - ]:          5 :         if (args.SoftSetBoolArg("-whitelistrelay", false))
#     695                 :          5 :             LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -whitelistrelay=0\n", __func__);
#     696                 :          5 :     }
#     697                 :            : 
#     698                 :            :     // Forcing relay from whitelisted hosts implies we will accept relays from them in the first place.
#     699         [ +  + ]:        668 :     if (args.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
#     700         [ +  - ]:          3 :         if (args.SoftSetBoolArg("-whitelistrelay", true))
#     701                 :          3 :             LogPrintf("%s: parameter interaction: -whitelistforcerelay=1 -> setting -whitelistrelay=1\n", __func__);
#     702                 :          3 :     }
#     703                 :        668 : }
#     704                 :            : 
#     705                 :            : /**
#     706                 :            :  * Initialize global loggers.
#     707                 :            :  *
#     708                 :            :  * Note that this is called very early in the process lifetime, so you should be
#     709                 :            :  * careful about what global state you rely on here.
#     710                 :            :  */
#     711                 :            : void InitLogging(const ArgsManager& args)
#     712                 :       1516 : {
#     713                 :       1516 :     init::SetLoggingOptions(args);
#     714                 :       1516 :     init::LogPackageVersion();
#     715                 :       1516 : }
#     716                 :            : 
#     717                 :            : namespace { // Variables internal to initialization process only
#     718                 :            : 
#     719                 :            : int nMaxConnections;
#     720                 :            : int nUserMaxConnections;
#     721                 :            : int nFD;
#     722                 :            : ServiceFlags nLocalServices = ServiceFlags(NODE_NETWORK | NODE_NETWORK_LIMITED);
#     723                 :            : int64_t peer_connect_timeout;
#     724                 :            : std::set<BlockFilterType> g_enabled_filter_types;
#     725                 :            : 
#     726                 :            : } // namespace
#     727                 :            : 
#     728                 :            : [[noreturn]] static void new_handler_terminate()
#     729                 :          0 : {
#     730                 :            :     // Rather than throwing std::bad-alloc if allocation fails, terminate
#     731                 :            :     // immediately to (try to) avoid chain corruption.
#     732                 :            :     // Since LogPrintf may itself allocate memory, set the handler directly
#     733                 :            :     // to terminate first.
#     734                 :          0 :     std::set_new_handler(std::terminate);
#     735                 :          0 :     LogPrintf("Error: Out of memory. Terminating.\n");
#     736                 :            : 
#     737                 :            :     // The log was successful, terminate now.
#     738                 :          0 :     std::terminate();
#     739                 :          0 : };
#     740                 :            : 
#     741                 :            : bool AppInitBasicSetup(const ArgsManager& args)
#     742                 :        668 : {
#     743                 :            :     // ********************************************************* Step 1: setup
#     744                 :            : #ifdef _MSC_VER
#     745                 :            :     // Turn off Microsoft heap dump noise
#     746                 :            :     _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
#     747                 :            :     _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, 0));
#     748                 :            :     // Disable confusing "helpful" text message on abort, Ctrl-C
#     749                 :            :     _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
#     750                 :            : #endif
#     751                 :            : #ifdef WIN32
#     752                 :            :     // Enable heap terminate-on-corruption
#     753                 :            :     HeapSetInformation(nullptr, HeapEnableTerminationOnCorruption, nullptr, 0);
#     754                 :            : #endif
#     755         [ -  + ]:        668 :     if (!InitShutdownState()) {
#     756                 :          0 :         return InitError(Untranslated("Initializing wait-for-shutdown state failed."));
#     757                 :          0 :     }
#     758                 :            : 
#     759         [ -  + ]:        668 :     if (!SetupNetworking()) {
#     760                 :          0 :         return InitError(Untranslated("Initializing networking failed."));
#     761                 :          0 :     }
#     762                 :            : 
#     763                 :        668 : #ifndef WIN32
#     764         [ +  - ]:        668 :     if (!args.GetBoolArg("-sysperms", false)) {
#     765                 :        668 :         umask(077);
#     766                 :        668 :     }
#     767                 :            : 
#     768                 :            :     // Clean shutdown on SIGTERM
#     769                 :        668 :     registerSignalHandler(SIGTERM, HandleSIGTERM);
#     770                 :        668 :     registerSignalHandler(SIGINT, HandleSIGTERM);
#     771                 :            : 
#     772                 :            :     // Reopen debug.log on SIGHUP
#     773                 :        668 :     registerSignalHandler(SIGHUP, HandleSIGHUP);
#     774                 :            : 
#     775                 :            :     // Ignore SIGPIPE, otherwise it will bring the daemon down if the client closes unexpectedly
#     776                 :        668 :     signal(SIGPIPE, SIG_IGN);
#     777                 :            : #else
#     778                 :            :     SetConsoleCtrlHandler(consoleCtrlHandler, true);
#     779                 :            : #endif
#     780                 :            : 
#     781                 :        668 :     std::set_new_handler(new_handler_terminate);
#     782                 :            : 
#     783                 :        668 :     return true;
#     784                 :        668 : }
#     785                 :            : 
#     786                 :            : bool AppInitParameterInteraction(const ArgsManager& args)
#     787                 :       1516 : {
#     788                 :       1516 :     const CChainParams& chainparams = Params();
#     789                 :            :     // ********************************************************* Step 2: parameter interactions
#     790                 :            : 
#     791                 :            :     // also see: InitParameterInteraction()
#     792                 :            : 
#     793                 :            :     // Error if network-specific options (-addnode, -connect, etc) are
#     794                 :            :     // specified in default section of config file, but not overridden
#     795                 :            :     // on the command line or in this network's section of the config file.
#     796                 :       1516 :     std::string network = args.GetChainName();
#     797         [ +  + ]:       1516 :     if (network == CBaseChainParams::SIGNET) {
#     798                 :          7 :         LogPrintf("Signet derived magic (message start): %s\n", HexStr(chainparams.MessageStart()));
#     799                 :          7 :     }
#     800                 :       1516 :     bilingual_str errors;
#     801         [ +  + ]:       1516 :     for (const auto& arg : args.GetUnsuitableSectionOnlyArgs()) {
#     802                 :          1 :         errors += strprintf(_("Config setting for %s only applied on %s network when in [%s] section.") + Untranslated("\n"), arg, network, network);
#     803                 :          1 :     }
#     804                 :            : 
#     805         [ +  + ]:       1516 :     if (!errors.empty()) {
#     806                 :          1 :         return InitError(errors);
#     807                 :          1 :     }
#     808                 :            : 
#     809                 :            :     // Warn if unrecognized section name are present in the config file.
#     810                 :       1515 :     bilingual_str warnings;
#     811         [ +  + ]:       1515 :     for (const auto& section : args.GetUnrecognizedSections()) {
#     812                 :          2 :         warnings += strprintf(Untranslated("%s:%i ") + _("Section [%s] is not recognized.") + Untranslated("\n"), section.m_file, section.m_line, section.m_name);
#     813                 :          2 :     }
#     814                 :            : 
#     815         [ +  + ]:       1515 :     if (!warnings.empty()) {
#     816                 :          1 :         InitWarning(warnings);
#     817                 :          1 :     }
#     818                 :            : 
#     819         [ +  + ]:       1515 :     if (!fs::is_directory(gArgs.GetBlocksDirPath())) {
#     820                 :          1 :         return InitError(strprintf(_("Specified blocks directory \"%s\" does not exist."), args.GetArg("-blocksdir", "")));
#     821                 :          1 :     }
#     822                 :            : 
#     823                 :            :     // parse and validate enabled filter types
#     824                 :       1514 :     std::string blockfilterindex_value = args.GetArg("-blockfilterindex", DEFAULT_BLOCKFILTERINDEX);
#     825 [ +  + ][ +  + ]:       1514 :     if (blockfilterindex_value == "" || blockfilterindex_value == "1") {
#     826                 :          7 :         g_enabled_filter_types = AllBlockFilterTypes();
#     827         [ -  + ]:       1507 :     } else if (blockfilterindex_value != "0") {
#     828                 :          0 :         const std::vector<std::string> names = args.GetArgs("-blockfilterindex");
#     829         [ #  # ]:          0 :         for (const auto& name : names) {
#     830                 :          0 :             BlockFilterType filter_type;
#     831         [ #  # ]:          0 :             if (!BlockFilterTypeByName(name, filter_type)) {
#     832                 :          0 :                 return InitError(strprintf(_("Unknown -blockfilterindex value %s."), name));
#     833                 :          0 :             }
#     834                 :          0 :             g_enabled_filter_types.insert(filter_type);
#     835                 :          0 :         }
#     836                 :          0 :     }
#     837                 :            : 
#     838                 :            :     // Signal NODE_COMPACT_FILTERS if peerblockfilters and basic filters index are both enabled.
#     839         [ +  + ]:       1514 :     if (args.GetBoolArg("-peerblockfilters", DEFAULT_PEERBLOCKFILTERS)) {
#     840         [ -  + ]:          1 :         if (g_enabled_filter_types.count(BlockFilterType::BASIC) != 1) {
#     841                 :          0 :             return InitError(_("Cannot set -peerblockfilters without -blockfilterindex."));
#     842                 :          0 :         }
#     843                 :            : 
#     844                 :          1 :         nLocalServices = ServiceFlags(nLocalServices | NODE_COMPACT_FILTERS);
#     845                 :          1 :     }
#     846                 :            : 
#     847                 :            :     // if using block pruning, then disallow txindex and coinstatsindex
#     848         [ +  + ]:       1514 :     if (args.GetArg("-prune", 0)) {
#     849         [ -  + ]:          9 :         if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX))
#     850                 :          0 :             return InitError(_("Prune mode is incompatible with -txindex."));
#     851         [ -  + ]:          9 :         if (args.GetBoolArg("-coinstatsindex", DEFAULT_COINSTATSINDEX))
#     852                 :          0 :             return InitError(_("Prune mode is incompatible with -coinstatsindex."));
#     853                 :       1514 :     }
#     854                 :            : 
#     855                 :            :     // -bind and -whitebind can't be set when not listening
#     856                 :       1514 :     size_t nUserBind = args.GetArgs("-bind").size() + args.GetArgs("-whitebind").size();
#     857 [ +  + ][ -  + ]:       1514 :     if (nUserBind != 0 && !args.GetBoolArg("-listen", DEFAULT_LISTEN)) {
#                 [ -  + ]
#     858                 :          0 :         return InitError(Untranslated("Cannot set -bind or -whitebind together with -listen=0"));
#     859                 :          0 :     }
#     860                 :            : 
#     861                 :            :     // Make sure enough file descriptors are available
#     862                 :       1514 :     int nBind = std::max(nUserBind, size_t(1));
#     863                 :       1514 :     nUserMaxConnections = args.GetArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
#     864                 :       1514 :     nMaxConnections = std::max(nUserMaxConnections, 0);
#     865                 :            : 
#     866                 :            :     // Trim requested connection counts, to fit into system limitations
#     867                 :            :     // <int> in std::min<int>(...) to work around FreeBSD compilation issue described in #2695
#     868                 :       1514 :     nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS + MAX_ADDNODE_CONNECTIONS + nBind + NUM_FDS_MESSAGE_CAPTURE);
#     869                 :            : 
#     870                 :            : #ifdef USE_POLL
#     871                 :            :     int fd_max = nFD;
#     872                 :            : #else
#     873                 :       1514 :     int fd_max = FD_SETSIZE;
#     874                 :       1514 : #endif
#     875                 :       1514 :     nMaxConnections = std::max(std::min<int>(nMaxConnections, fd_max - nBind - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS - NUM_FDS_MESSAGE_CAPTURE), 0);
#     876         [ -  + ]:       1514 :     if (nFD < MIN_CORE_FILEDESCRIPTORS)
#     877                 :       1514 :         return InitError(_("Not enough file descriptors available."));
#     878                 :       1514 :     nMaxConnections = std::min(nFD - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS - NUM_FDS_MESSAGE_CAPTURE, nMaxConnections);
#     879                 :            : 
#     880         [ -  + ]:       1514 :     if (nMaxConnections < nUserMaxConnections)
#     881                 :          0 :         InitWarning(strprintf(_("Reducing -maxconnections from %d to %d, because of system limitations."), nUserMaxConnections, nMaxConnections));
#     882                 :            : 
#     883                 :            :     // ********************************************************* Step 3: parameter-to-internal-flags
#     884                 :       1514 :     init::SetLoggingCategories(args);
#     885                 :            : 
#     886                 :       1514 :     fCheckBlockIndex = args.GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks());
#     887                 :       1514 :     fCheckpointsEnabled = args.GetBoolArg("-checkpoints", DEFAULT_CHECKPOINTS_ENABLED);
#     888                 :            : 
#     889                 :       1514 :     hashAssumeValid = uint256S(args.GetArg("-assumevalid", chainparams.GetConsensus().defaultAssumeValid.GetHex()));
#     890         [ +  + ]:       1514 :     if (!hashAssumeValid.IsNull())
#     891                 :       1514 :         LogPrintf("Assuming ancestors of block %s have valid signatures.\n", hashAssumeValid.GetHex());
#     892                 :       1514 :     else
#     893                 :       1514 :         LogPrintf("Validating signatures for all blocks.\n");
#     894                 :            : 
#     895         [ +  + ]:       1514 :     if (args.IsArgSet("-minimumchainwork")) {
#     896                 :          3 :         const std::string minChainWorkStr = args.GetArg("-minimumchainwork", "");
#     897         [ -  + ]:          3 :         if (!IsHexNumber(minChainWorkStr)) {
#     898                 :          0 :             return InitError(strprintf(Untranslated("Invalid non-hex (%s) minimum chain work value specified"), minChainWorkStr));
#     899                 :          0 :         }
#     900                 :          3 :         nMinimumChainWork = UintToArith256(uint256S(minChainWorkStr));
#     901                 :       1511 :     } else {
#     902                 :       1511 :         nMinimumChainWork = UintToArith256(chainparams.GetConsensus().nMinimumChainWork);
#     903                 :       1511 :     }
#     904                 :       1514 :     LogPrintf("Setting nMinimumChainWork=%s\n", nMinimumChainWork.GetHex());
#     905         [ -  + ]:       1514 :     if (nMinimumChainWork < UintToArith256(chainparams.GetConsensus().nMinimumChainWork)) {
#     906                 :          0 :         LogPrintf("Warning: nMinimumChainWork set below default value of %s\n", chainparams.GetConsensus().nMinimumChainWork.GetHex());
#     907                 :          0 :     }
#     908                 :            : 
#     909                 :            :     // mempool limits
#     910                 :       1514 :     int64_t nMempoolSizeMax = args.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
#     911                 :       1514 :     int64_t nMempoolSizeMin = args.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000 * 40;
#     912 [ -  + ][ -  + ]:       1514 :     if (nMempoolSizeMax < 0 || nMempoolSizeMax < nMempoolSizeMin)
#     913                 :          0 :         return InitError(strprintf(_("-maxmempool must be at least %d MB"), std::ceil(nMempoolSizeMin / 1000000.0)));
#     914                 :            :     // incremental relay fee sets the minimum feerate increase necessary for BIP 125 replacement in the mempool
#     915                 :            :     // and the amount the mempool min fee increases above the feerate of txs evicted due to mempool limiting.
#     916         [ -  + ]:       1514 :     if (args.IsArgSet("-incrementalrelayfee")) {
#     917                 :          0 :         CAmount n = 0;
#     918         [ #  # ]:          0 :         if (!ParseMoney(args.GetArg("-incrementalrelayfee", ""), n))
#     919                 :          0 :             return InitError(AmountErrMsg("incrementalrelayfee", args.GetArg("-incrementalrelayfee", "")));
#     920                 :          0 :         incrementalRelayFee = CFeeRate(n);
#     921                 :          0 :     }
#     922                 :            : 
#     923                 :            :     // block pruning; get the amount of disk space (in MiB) to allot for block & undo files
#     924                 :       1514 :     int64_t nPruneArg = args.GetArg("-prune", 0);
#     925         [ -  + ]:       1514 :     if (nPruneArg < 0) {
#     926                 :          0 :         return InitError(_("Prune cannot be configured with a negative value."));
#     927                 :          0 :     }
#     928                 :       1514 :     nPruneTarget = (uint64_t) nPruneArg * 1024 * 1024;
#     929         [ +  + ]:       1514 :     if (nPruneArg == 1) {  // manual pruning: -prune=1
#     930                 :          7 :         LogPrintf("Block pruning enabled.  Use RPC call pruneblockchain(height) to manually prune block and undo files.\n");
#     931                 :          7 :         nPruneTarget = std::numeric_limits<uint64_t>::max();
#     932                 :          7 :         fPruneMode = true;
#     933         [ +  + ]:       1507 :     } else if (nPruneTarget) {
#     934         [ -  + ]:          2 :         if (nPruneTarget < MIN_DISK_SPACE_FOR_BLOCK_FILES) {
#     935                 :          0 :             return InitError(strprintf(_("Prune configured below the minimum of %d MiB.  Please use a higher number."), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
#     936                 :          0 :         }
#     937                 :          2 :         LogPrintf("Prune configured to target %u MiB on disk for block and undo files.\n", nPruneTarget / 1024 / 1024);
#     938                 :          2 :         fPruneMode = true;
#     939                 :          2 :     }
#     940                 :            : 
#     941                 :       1514 :     nConnectTimeout = args.GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT);
#     942         [ -  + ]:       1514 :     if (nConnectTimeout <= 0) {
#     943                 :          0 :         nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
#     944                 :          0 :     }
#     945                 :            : 
#     946                 :       1514 :     peer_connect_timeout = args.GetArg("-peertimeout", DEFAULT_PEER_CONNECT_TIMEOUT);
#     947         [ -  + ]:       1514 :     if (peer_connect_timeout <= 0) {
#     948                 :          0 :         return InitError(Untranslated("peertimeout cannot be configured with a negative value."));
#     949                 :          0 :     }
#     950                 :            : 
#     951         [ +  + ]:       1514 :     if (args.IsArgSet("-minrelaytxfee")) {
#     952                 :         17 :         CAmount n = 0;
#     953         [ -  + ]:         17 :         if (!ParseMoney(args.GetArg("-minrelaytxfee", ""), n)) {
#     954                 :          0 :             return InitError(AmountErrMsg("minrelaytxfee", args.GetArg("-minrelaytxfee", "")));
#     955                 :          0 :         }
#     956                 :            :         // High fee check is done afterward in CWallet::Create()
#     957                 :         17 :         ::minRelayTxFee = CFeeRate(n);
#     958         [ -  + ]:       1497 :     } else if (incrementalRelayFee > ::minRelayTxFee) {
#     959                 :            :         // Allow only setting incrementalRelayFee to control both
#     960                 :          0 :         ::minRelayTxFee = incrementalRelayFee;
#     961                 :          0 :         LogPrintf("Increasing minrelaytxfee to %s to match incrementalrelayfee\n",::minRelayTxFee.ToString());
#     962                 :          0 :     }
#     963                 :            : 
#     964                 :            :     // Sanity check argument for min fee for including tx in block
#     965                 :            :     // TODO: Harmonize which arguments need sanity checking and where that happens
#     966         [ -  + ]:       1514 :     if (args.IsArgSet("-blockmintxfee")) {
#     967                 :          0 :         CAmount n = 0;
#     968         [ #  # ]:          0 :         if (!ParseMoney(args.GetArg("-blockmintxfee", ""), n))
#     969                 :          0 :             return InitError(AmountErrMsg("blockmintxfee", args.GetArg("-blockmintxfee", "")));
#     970                 :       1514 :     }
#     971                 :            : 
#     972                 :            :     // Feerate used to define dust.  Shouldn't be changed lightly as old
#     973                 :            :     // implementations may inadvertently create non-standard transactions
#     974         [ -  + ]:       1514 :     if (args.IsArgSet("-dustrelayfee")) {
#     975                 :          0 :         CAmount n = 0;
#     976         [ #  # ]:          0 :         if (!ParseMoney(args.GetArg("-dustrelayfee", ""), n))
#     977                 :          0 :             return InitError(AmountErrMsg("dustrelayfee", args.GetArg("-dustrelayfee", "")));
#     978                 :          0 :         dustRelayFee = CFeeRate(n);
#     979                 :          0 :     }
#     980                 :            : 
#     981                 :       1514 :     fRequireStandard = !args.GetBoolArg("-acceptnonstdtxn", !chainparams.RequireStandard());
#     982 [ +  + ][ +  + ]:       1514 :     if (!chainparams.IsTestChain() && !fRequireStandard) {
#     983                 :          1 :         return InitError(strprintf(Untranslated("acceptnonstdtxn is not currently supported for %s chain"), chainparams.NetworkIDString()));
#     984                 :          1 :     }
#     985                 :       1513 :     nBytesPerSigOp = args.GetArg("-bytespersigop", nBytesPerSigOp);
#     986                 :            : 
#     987         [ -  + ]:       1513 :     if (!g_wallet_init_interface.ParameterInteraction()) return false;
#     988                 :            : 
#     989                 :       1513 :     fIsBareMultisigStd = args.GetBoolArg("-permitbaremultisig", DEFAULT_PERMIT_BAREMULTISIG);
#     990                 :       1513 :     fAcceptDatacarrier = args.GetBoolArg("-datacarrier", DEFAULT_ACCEPT_DATACARRIER);
#     991                 :       1513 :     nMaxDatacarrierBytes = args.GetArg("-datacarriersize", nMaxDatacarrierBytes);
#     992                 :            : 
#     993                 :            :     // Option to startup with mocktime set (used for regression testing):
#     994                 :       1513 :     SetMockTime(args.GetArg("-mocktime", 0)); // SetMockTime(0) is a no-op
#     995                 :            : 
#     996         [ +  + ]:       1513 :     if (args.GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS))
#     997                 :          1 :         nLocalServices = ServiceFlags(nLocalServices | NODE_BLOOM);
#     998                 :            : 
#     999         [ -  + ]:       1513 :     if (args.GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) < 0)
#    1000                 :          0 :         return InitError(Untranslated("rpcserialversion must be non-negative."));
#    1001                 :            : 
#    1002         [ -  + ]:       1513 :     if (args.GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) > 1)
#    1003                 :          0 :         return InitError(Untranslated("Unknown rpcserialversion requested."));
#    1004                 :            : 
#    1005                 :       1513 :     nMaxTipAge = args.GetArg("-maxtipage", DEFAULT_MAX_TIP_AGE);
#    1006                 :            : 
#    1007 [ +  + ][ +  + ]:       1513 :     if (args.IsArgSet("-proxy") && args.GetArg("-proxy", "").empty()) {
#                 [ +  + ]
#    1008                 :          1 :         return InitError(_("No proxy server specified. Use -proxy=<ip> or -proxy=<ip:port>."));
#    1009                 :          1 :     }
#    1010                 :            : 
#    1011                 :       1512 :     return true;
#    1012                 :       1512 : }
#    1013                 :            : 
#    1014                 :            : static bool LockDataDirectory(bool probeOnly)
#    1015                 :       1327 : {
#    1016                 :            :     // Make sure only a single Bitcoin process is using the data directory.
#    1017                 :       1327 :     fs::path datadir = gArgs.GetDataDirNet();
#    1018         [ -  + ]:       1327 :     if (!DirIsWritable(datadir)) {
#    1019                 :          0 :         return InitError(strprintf(_("Cannot write to data directory '%s'; check permissions."), datadir.string()));
#    1020                 :          0 :     }
#    1021         [ +  + ]:       1327 :     if (!LockDirectory(datadir, ".lock", probeOnly)) {
#    1022                 :          1 :         return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running."), datadir.string(), PACKAGE_NAME));
#    1023                 :          1 :     }
#    1024                 :       1326 :     return true;
#    1025                 :       1326 : }
#    1026                 :            : 
#    1027                 :            : bool AppInitSanityChecks()
#    1028                 :        664 : {
#    1029                 :            :     // ********************************************************* Step 4: sanity checks
#    1030                 :            : 
#    1031                 :        664 :     init::SetGlobals();
#    1032                 :            : 
#    1033         [ -  + ]:        664 :     if (!init::SanityChecks()) {
#    1034                 :          0 :         return InitError(strprintf(_("Initialization sanity check failed. %s is shutting down."), PACKAGE_NAME));
#    1035                 :          0 :     }
#    1036                 :            : 
#    1037                 :            :     // Probe the data directory lock to give an early error message, if possible
#    1038                 :            :     // We cannot hold the data directory lock here, as the forking for daemon() hasn't yet happened,
#    1039                 :            :     // and a fork will cause weird behavior to it.
#    1040                 :        664 :     return LockDataDirectory(true);
#    1041                 :        664 : }
#    1042                 :            : 
#    1043                 :            : bool AppInitLockDataDirectory()
#    1044                 :        663 : {
#    1045                 :            :     // After daemonization get the data directory lock again and hold on to it until exit
#    1046                 :            :     // This creates a slight window for a race condition to happen, however this condition is harmless: it
#    1047                 :            :     // will at most make us exit without printing a message to console.
#    1048         [ -  + ]:        663 :     if (!LockDataDirectory(false)) {
#    1049                 :            :         // Detailed error printed inside LockDataDirectory
#    1050                 :          0 :         return false;
#    1051                 :          0 :     }
#    1052                 :        663 :     return true;
#    1053                 :        663 : }
#    1054                 :            : 
#    1055                 :            : bool AppInitInterfaces(NodeContext& node)
#    1056                 :        663 : {
#    1057                 :        663 :     node.chain = interfaces::MakeChain(node);
#    1058                 :            :     // Create client interfaces for wallets that are supposed to be loaded
#    1059                 :            :     // according to -wallet and -disablewallet options. This only constructs
#    1060                 :            :     // the interfaces, it doesn't load wallet data. Wallets actually get loaded
#    1061                 :            :     // when load() and start() interface methods are called below.
#    1062                 :        663 :     g_wallet_init_interface.Construct(node);
#    1063                 :        663 :     return true;
#    1064                 :        663 : }
#    1065                 :            : 
#    1066                 :            : bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
#    1067                 :        663 : {
#    1068                 :        663 :     const ArgsManager& args = *Assert(node.args);
#    1069                 :        663 :     const CChainParams& chainparams = Params();
#    1070                 :            :     // ********************************************************* Step 4a: application initialization
#    1071         [ -  + ]:        663 :     if (!CreatePidFile(args)) {
#    1072                 :            :         // Detailed error printed inside CreatePidFile().
#    1073                 :          0 :         return false;
#    1074                 :          0 :     }
#    1075         [ +  + ]:        663 :     if (!init::StartLogging(args)) {
#    1076                 :            :         // Detailed error printed inside StartLogging().
#    1077                 :          2 :         return false;
#    1078                 :          2 :     }
#    1079                 :            : 
#    1080                 :        661 :     LogPrintf("Using at most %i automatic connections (%i file descriptors available)\n", nMaxConnections, nFD);
#    1081                 :            : 
#    1082                 :            :     // Warn about relative -datadir path.
#    1083 [ -  + ][ +  - ]:        661 :     if (args.IsArgSet("-datadir") && !fs::path(args.GetArg("-datadir", "")).is_absolute()) {
#                 [ -  + ]
#    1084                 :          0 :         LogPrintf("Warning: relative datadir option '%s' specified, which will be interpreted relative to the " /* Continued */
#    1085                 :          0 :                   "current working directory '%s'. This is fragile, because if bitcoin is started in the future "
#    1086                 :          0 :                   "from a different location, it will be unable to locate the current data files. There could "
#    1087                 :          0 :                   "also be data loss if bitcoin is started while in a temporary directory.\n",
#    1088                 :          0 :                   args.GetArg("-datadir", ""), fs::current_path().string());
#    1089                 :          0 :     }
#    1090                 :            : 
#    1091                 :        661 :     InitSignatureCache();
#    1092                 :        661 :     InitScriptExecutionCache();
#    1093                 :            : 
#    1094                 :        661 :     int script_threads = args.GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
#    1095         [ +  + ]:        661 :     if (script_threads <= 0) {
#    1096                 :            :         // -par=0 means autodetect (number of cores - 1 script threads)
#    1097                 :            :         // -par=-n means "leave n cores free" (number of cores - n - 1 script threads)
#    1098                 :        656 :         script_threads += GetNumCores();
#    1099                 :        656 :     }
#    1100                 :            : 
#    1101                 :            :     // Subtract 1 because the main thread counts towards the par threads
#    1102                 :        661 :     script_threads = std::max(script_threads - 1, 0);
#    1103                 :            : 
#    1104                 :            :     // Number of script-checking threads <= MAX_SCRIPTCHECK_THREADS
#    1105                 :        661 :     script_threads = std::min(script_threads, MAX_SCRIPTCHECK_THREADS);
#    1106                 :            : 
#    1107                 :        661 :     LogPrintf("Script verification uses %d additional threads\n", script_threads);
#    1108         [ +  + ]:        661 :     if (script_threads >= 1) {
#    1109                 :        656 :         g_parallel_script_checks = true;
#    1110                 :        656 :         StartScriptCheckWorkerThreads(script_threads);
#    1111                 :        656 :     }
#    1112                 :            : 
#    1113                 :        661 :     assert(!node.scheduler);
#    1114                 :        661 :     node.scheduler = std::make_unique<CScheduler>();
#    1115                 :            : 
#    1116                 :            :     // Start the lightweight task scheduler thread
#    1117                 :        661 :     node.scheduler->m_service_thread = std::thread(util::TraceThread, "scheduler", [&] { node.scheduler->serviceQueue(); });
#    1118                 :            : 
#    1119                 :            :     // Gather some entropy once per minute.
#    1120                 :        661 :     node.scheduler->scheduleEvery([]{
#    1121                 :        136 :         RandAddPeriodic();
#    1122                 :        136 :     }, std::chrono::minutes{1});
#    1123                 :            : 
#    1124                 :        661 :     GetMainSignals().RegisterBackgroundSignalScheduler(*node.scheduler);
#    1125                 :            : 
#    1126                 :            :     /* Register RPC commands regardless of -server setting so they will be
#    1127                 :            :      * available in the GUI RPC console even if external calls are disabled.
#    1128                 :            :      */
#    1129                 :        661 :     RegisterAllCoreRPCCommands(tableRPC);
#    1130         [ +  + ]:        661 :     for (const auto& client : node.chain_clients) {
#    1131                 :        655 :         client->registerRpcs();
#    1132                 :        655 :     }
#    1133                 :            : #if ENABLE_ZMQ
#    1134                 :            :     RegisterZMQRPCCommands(tableRPC);
#    1135                 :            : #endif
#    1136                 :            : 
#    1137                 :            :     /* Start the RPC server already.  It will be started in "warmup" mode
#    1138                 :            :      * and not really process calls already (but it will signify connections
#    1139                 :            :      * that the server is there and will be ready later).  Warmup mode will
#    1140                 :            :      * be disabled when initialisation is finished.
#    1141                 :            :      */
#    1142         [ +  + ]:        661 :     if (args.GetBoolArg("-server", false)) {
#    1143                 :        659 :         uiInterface.InitMessage_connect(SetRPCWarmupStatus);
#    1144         [ +  + ]:        659 :         if (!AppInitServers(node))
#    1145                 :          3 :             return InitError(_("Unable to start HTTP server. See debug log for details."));
#    1146                 :        658 :     }
#    1147                 :            : 
#    1148                 :            :     // ********************************************************* Step 5: verify wallet database integrity
#    1149         [ +  + ]:        658 :     for (const auto& client : node.chain_clients) {
#    1150         [ +  + ]:        652 :         if (!client->verify()) {
#    1151                 :         23 :             return false;
#    1152                 :         23 :         }
#    1153                 :        652 :     }
#    1154                 :            : 
#    1155                 :            :     // ********************************************************* Step 6: network initialization
#    1156                 :            :     // Note that we absolutely cannot open any actual connections
#    1157                 :            :     // until the very end ("start node") as the UTXO/block state
#    1158                 :            :     // is not yet setup and may end up being set up twice if we
#    1159                 :            :     // need to reindex later.
#    1160                 :            : 
#    1161                 :        658 :     fListen = args.GetBoolArg("-listen", DEFAULT_LISTEN);
#    1162                 :        635 :     fDiscover = args.GetBoolArg("-discover", true);
#    1163                 :        635 :     const bool ignores_incoming_txs{args.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)};
#    1164                 :            : 
#    1165                 :        635 :     assert(!node.addrman);
#    1166                 :        635 :     node.addrman = std::make_unique<CAddrMan>();
#    1167                 :        635 :     assert(!node.banman);
#    1168                 :        635 :     node.banman = std::make_unique<BanMan>(gArgs.GetDataDirNet() / "banlist.dat", &uiInterface, args.GetArg("-bantime", DEFAULT_MISBEHAVING_BANTIME));
#    1169                 :        635 :     assert(!node.connman);
#    1170                 :        635 :     node.connman = std::make_unique<CConnman>(GetRand(std::numeric_limits<uint64_t>::max()), GetRand(std::numeric_limits<uint64_t>::max()), *node.addrman, args.GetBoolArg("-networkactive", true));
#    1171                 :            : 
#    1172                 :        635 :     assert(!node.fee_estimator);
#    1173                 :            :     // Don't initialize fee estimation with old data if we don't relay transactions,
#    1174                 :            :     // as they would never get updated.
#    1175         [ +  + ]:        635 :     if (!ignores_incoming_txs) node.fee_estimator = std::make_unique<CBlockPolicyEstimator>();
#    1176                 :            : 
#    1177                 :        635 :     assert(!node.mempool);
#    1178         [ +  + ]:        635 :     int check_ratio = std::min<int>(std::max<int>(args.GetArg("-checkmempool", chainparams.DefaultConsistencyChecks() ? 1 : 0), 0), 1000000);
#    1179                 :        635 :     node.mempool = std::make_unique<CTxMemPool>(node.fee_estimator.get(), check_ratio);
#    1180                 :            : 
#    1181                 :        635 :     assert(!node.chainman);
#    1182                 :        635 :     node.chainman = &g_chainman;
#    1183                 :        635 :     ChainstateManager& chainman = *Assert(node.chainman);
#    1184                 :            : 
#    1185                 :        635 :     assert(!node.peerman);
#    1186                 :        635 :     node.peerman = PeerManager::make(chainparams, *node.connman, *node.addrman, node.banman.get(),
#    1187                 :        635 :                                      *node.scheduler, chainman, *node.mempool, ignores_incoming_txs);
#    1188                 :        635 :     RegisterValidationInterface(node.peerman.get());
#    1189                 :            : 
#    1190                 :            :     // sanitize comments per BIP-0014, format user agent and check total size
#    1191                 :        635 :     std::vector<std::string> uacomments;
#    1192         [ +  + ]:        650 :     for (const std::string& cmt : args.GetArgs("-uacomment")) {
#    1193         [ +  + ]:        650 :         if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT))
#    1194                 :          6 :             return InitError(strprintf(_("User Agent comment (%s) contains unsafe characters."), cmt));
#    1195                 :        644 :         uacomments.push_back(cmt);
#    1196                 :        644 :     }
#    1197                 :        635 :     strSubVersion = FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, uacomments);
#    1198         [ +  + ]:        629 :     if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
#    1199                 :          1 :         return InitError(strprintf(_("Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments."),
#    1200                 :          1 :             strSubVersion.size(), MAX_SUBVERSION_LENGTH));
#    1201                 :          1 :     }
#    1202                 :            : 
#    1203         [ -  + ]:        628 :     if (args.IsArgSet("-onlynet")) {
#    1204                 :          0 :         std::set<enum Network> nets;
#    1205         [ #  # ]:          0 :         for (const std::string& snet : args.GetArgs("-onlynet")) {
#    1206                 :          0 :             enum Network net = ParseNetwork(snet);
#    1207         [ #  # ]:          0 :             if (net == NET_UNROUTABLE)
#    1208                 :          0 :                 return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet));
#    1209                 :          0 :             nets.insert(net);
#    1210                 :          0 :         }
#    1211         [ #  # ]:          0 :         for (int n = 0; n < NET_MAX; n++) {
#    1212                 :          0 :             enum Network net = (enum Network)n;
#    1213         [ #  # ]:          0 :             if (!nets.count(net))
#    1214                 :          0 :                 SetReachable(net, false);
#    1215                 :          0 :         }
#    1216                 :          0 :     }
#    1217                 :            : 
#    1218                 :            :     // Check for host lookup allowed before parsing any network related parameters
#    1219                 :        628 :     fNameLookup = args.GetBoolArg("-dns", DEFAULT_NAME_LOOKUP);
#    1220                 :            : 
#    1221                 :        628 :     bool proxyRandomize = args.GetBoolArg("-proxyrandomize", DEFAULT_PROXYRANDOMIZE);
#    1222                 :            :     // -proxy sets a proxy for all outgoing network traffic
#    1223                 :            :     // -noproxy (or -proxy=0) as well as the empty string can be used to not set a proxy, this is the default
#    1224                 :        628 :     std::string proxyArg = args.GetArg("-proxy", "");
#    1225                 :        628 :     SetReachable(NET_ONION, false);
#    1226 [ +  + ][ +  - ]:        628 :     if (proxyArg != "" && proxyArg != "0") {
#    1227                 :          4 :         CService proxyAddr;
#    1228         [ -  + ]:          4 :         if (!Lookup(proxyArg, proxyAddr, 9050, fNameLookup)) {
#    1229                 :          0 :             return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg));
#    1230                 :          0 :         }
#    1231                 :            : 
#    1232                 :          4 :         proxyType addrProxy = proxyType(proxyAddr, proxyRandomize);
#    1233         [ -  + ]:          4 :         if (!addrProxy.IsValid())
#    1234                 :          0 :             return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg));
#    1235                 :            : 
#    1236                 :          4 :         SetProxy(NET_IPV4, addrProxy);
#    1237                 :          4 :         SetProxy(NET_IPV6, addrProxy);
#    1238                 :          4 :         SetProxy(NET_ONION, addrProxy);
#    1239                 :          4 :         SetNameProxy(addrProxy);
#    1240                 :          4 :         SetReachable(NET_ONION, true); // by default, -proxy sets onion as reachable, unless -noonion later
#    1241                 :          4 :     }
#    1242                 :            : 
#    1243                 :            :     // -onion can be used to set only a proxy for .onion, or override normal proxy for .onion addresses
#    1244                 :            :     // -noonion (or -onion=0) disables connecting to .onion entirely
#    1245                 :            :     // An empty string is used to not override the onion proxy (in which case it defaults to -proxy set above, or none)
#    1246                 :        628 :     std::string onionArg = args.GetArg("-onion", "");
#    1247         [ +  + ]:        628 :     if (onionArg != "") {
#    1248         [ +  + ]:          2 :         if (onionArg == "0") { // Handle -noonion/-onion=0
#    1249                 :          1 :             SetReachable(NET_ONION, false);
#    1250                 :          1 :         } else {
#    1251                 :          1 :             CService onionProxy;
#    1252         [ -  + ]:          1 :             if (!Lookup(onionArg, onionProxy, 9050, fNameLookup)) {
#    1253                 :          0 :                 return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg));
#    1254                 :          0 :             }
#    1255                 :          1 :             proxyType addrOnion = proxyType(onionProxy, proxyRandomize);
#    1256         [ -  + ]:          1 :             if (!addrOnion.IsValid())
#    1257                 :          0 :                 return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg));
#    1258                 :          1 :             SetProxy(NET_ONION, addrOnion);
#    1259                 :          1 :             SetReachable(NET_ONION, true);
#    1260                 :          1 :         }
#    1261                 :          2 :     }
#    1262                 :            : 
#    1263         [ -  + ]:        628 :     for (const std::string& strAddr : args.GetArgs("-externalip")) {
#    1264                 :          0 :         CService addrLocal;
#    1265 [ #  # ][ #  # ]:          0 :         if (Lookup(strAddr, addrLocal, GetListenPort(), fNameLookup) && addrLocal.IsValid())
#                 [ #  # ]
#    1266                 :          0 :             AddLocal(addrLocal, LOCAL_MANUAL);
#    1267                 :          0 :         else
#    1268                 :          0 :             return InitError(ResolveErrMsg("externalip", strAddr));
#    1269                 :          0 :     }
#    1270                 :            : 
#    1271                 :            :     // Read asmap file if configured
#    1272         [ +  + ]:        628 :     if (args.IsArgSet("-asmap")) {
#    1273                 :          6 :         fs::path asmap_path = fs::path(args.GetArg("-asmap", ""));
#    1274         [ +  + ]:          6 :         if (asmap_path.empty()) {
#    1275                 :          4 :             asmap_path = DEFAULT_ASMAP_FILENAME;
#    1276                 :          4 :         }
#    1277         [ +  + ]:          6 :         if (!asmap_path.is_absolute()) {
#    1278                 :          5 :             asmap_path = gArgs.GetDataDirNet() / asmap_path;
#    1279                 :          5 :         }
#    1280         [ +  + ]:          6 :         if (!fs::exists(asmap_path)) {
#    1281                 :          1 :             InitError(strprintf(_("Could not find asmap file %s"), asmap_path));
#    1282                 :          1 :             return false;
#    1283                 :          1 :         }
#    1284                 :          5 :         std::vector<bool> asmap = CAddrMan::DecodeAsmap(asmap_path);
#    1285         [ +  + ]:          5 :         if (asmap.size() == 0) {
#    1286                 :          1 :             InitError(strprintf(_("Could not parse asmap file %s"), asmap_path));
#    1287                 :          1 :             return false;
#    1288                 :          1 :         }
#    1289                 :          4 :         const uint256 asmap_version = SerializeHash(asmap);
#    1290                 :          4 :         node.connman->SetAsmap(std::move(asmap));
#    1291                 :          4 :         LogPrintf("Using asmap version %s for IP bucketing\n", asmap_version.ToString());
#    1292                 :        622 :     } else {
#    1293                 :        622 :         LogPrintf("Using /16 prefix for IP bucketing\n");
#    1294                 :        622 :     }
#    1295                 :            : 
#    1296                 :            : #if ENABLE_ZMQ
#    1297                 :            :     g_zmq_notification_interface = CZMQNotificationInterface::Create();
#    1298                 :            : 
#    1299                 :            :     if (g_zmq_notification_interface) {
#    1300                 :            :         RegisterValidationInterface(g_zmq_notification_interface);
#    1301                 :            :     }
#    1302                 :            : #endif
#    1303                 :            : 
#    1304                 :            :     // ********************************************************* Step 7: load block chain
#    1305                 :            : 
#    1306                 :        628 :     fReindex = args.GetBoolArg("-reindex", false);
#    1307                 :        626 :     bool fReindexChainState = args.GetBoolArg("-reindex-chainstate", false);
#    1308                 :            : 
#    1309                 :            :     // cache size calculations
#    1310                 :        626 :     int64_t nTotalCache = (args.GetArg("-dbcache", nDefaultDbCache) << 20);
#    1311                 :        626 :     nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache
#    1312                 :        626 :     nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greater than nMaxDbcache
#    1313                 :        626 :     int64_t nBlockTreeDBCache = std::min(nTotalCache / 8, nMaxBlockDBCache << 20);
#    1314                 :        626 :     nTotalCache -= nBlockTreeDBCache;
#    1315         [ +  + ]:        626 :     int64_t nTxIndexCache = std::min(nTotalCache / 8, args.GetBoolArg("-txindex", DEFAULT_TXINDEX) ? nMaxTxIndexCache << 20 : 0);
#    1316                 :        626 :     nTotalCache -= nTxIndexCache;
#    1317                 :        626 :     int64_t filter_index_cache = 0;
#    1318         [ +  + ]:        626 :     if (!g_enabled_filter_types.empty()) {
#    1319                 :          7 :         size_t n_indexes = g_enabled_filter_types.size();
#    1320                 :          7 :         int64_t max_cache = std::min(nTotalCache / 8, max_filter_index_cache << 20);
#    1321                 :          7 :         filter_index_cache = max_cache / n_indexes;
#    1322                 :          7 :         nTotalCache -= filter_index_cache * n_indexes;
#    1323                 :          7 :     }
#    1324                 :        626 :     int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23)); // use 25%-50% of the remainder for disk cache
#    1325                 :        626 :     nCoinDBCache = std::min(nCoinDBCache, nMaxCoinsDBCache << 20); // cap total coins db cache
#    1326                 :        626 :     nTotalCache -= nCoinDBCache;
#    1327                 :        626 :     int64_t nCoinCacheUsage = nTotalCache; // the rest goes to in-memory cache
#    1328                 :        626 :     int64_t nMempoolSizeMax = args.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
#    1329                 :        626 :     LogPrintf("Cache configuration:\n");
#    1330                 :        626 :     LogPrintf("* Using %.1f MiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024));
#    1331         [ +  + ]:        626 :     if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
#    1332                 :          9 :         LogPrintf("* Using %.1f MiB for transaction index database\n", nTxIndexCache * (1.0 / 1024 / 1024));
#    1333                 :          9 :     }
#    1334         [ +  + ]:        626 :     for (BlockFilterType filter_type : g_enabled_filter_types) {
#    1335                 :          7 :         LogPrintf("* Using %.1f MiB for %s block filter index database\n",
#    1336                 :          7 :                   filter_index_cache * (1.0 / 1024 / 1024), BlockFilterTypeName(filter_type));
#    1337                 :          7 :     }
#    1338                 :        626 :     LogPrintf("* Using %.1f MiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024));
#    1339                 :        626 :     LogPrintf("* Using %.1f MiB for in-memory UTXO set (plus up to %.1f MiB of unused mempool space)\n", nCoinCacheUsage * (1.0 / 1024 / 1024), nMempoolSizeMax * (1.0 / 1024 / 1024));
#    1340                 :            : 
#    1341                 :        626 :     bool fLoaded = false;
#    1342 [ +  + ][ +  - ]:       1250 :     while (!fLoaded && !ShutdownRequested()) {
#    1343                 :        626 :         const bool fReset = fReindex;
#    1344                 :       1251 :         auto is_coinsview_empty = [&](CChainState* chainstate) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
#    1345 [ +  + ][ +  + ]:       1251 :             return fReset || fReindexChainState || chainstate->CoinsTip().GetBestBlock().IsNull();
#                 [ +  + ]
#    1346                 :       1251 :         };
#    1347                 :        626 :         bilingual_str strLoadError;
#    1348                 :            : 
#    1349                 :        626 :         uiInterface.InitMessage(_("Loading block index…").translated);
#    1350                 :            : 
#    1351                 :        626 :         do {
#    1352                 :        626 :             const int64_t load_block_index_start_time = GetTimeMillis();
#    1353                 :        626 :             try {
#    1354                 :        626 :                 LOCK(cs_main);
#    1355                 :        626 :                 chainman.InitializeChainstate(*Assert(node.mempool));
#    1356                 :        626 :                 chainman.m_total_coinstip_cache = nCoinCacheUsage;
#    1357                 :        626 :                 chainman.m_total_coinsdb_cache = nCoinDBCache;
#    1358                 :            : 
#    1359                 :        626 :                 UnloadBlockIndex(node.mempool.get(), chainman);
#    1360                 :            : 
#    1361                 :            :                 // new CBlockTreeDB tries to delete the existing file, which
#    1362                 :            :                 // fails if it's still open from the previous loop. Close it first:
#    1363                 :        626 :                 pblocktree.reset();
#    1364                 :        626 :                 pblocktree.reset(new CBlockTreeDB(nBlockTreeDBCache, false, fReset));
#    1365                 :            : 
#    1366         [ +  + ]:        626 :                 if (fReset) {
#    1367                 :         10 :                     pblocktree->WriteReindexing(true);
#    1368                 :            :                     //If we're reindexing in prune mode, wipe away unusable block files and all undo data files
#    1369         [ +  + ]:         10 :                     if (fPruneMode)
#    1370                 :          1 :                         CleanupBlockRevFiles();
#    1371                 :         10 :                 }
#    1372                 :            : 
#    1373         [ -  + ]:        626 :                 if (ShutdownRequested()) break;
#    1374                 :            : 
#    1375                 :            :                 // LoadBlockIndex will load fHavePruned if we've ever removed a
#    1376                 :            :                 // block file from disk.
#    1377                 :            :                 // Note that it also sets fReindex based on the disk flag!
#    1378                 :            :                 // From here on out fReindex and fReset mean something different!
#    1379         [ -  + ]:        626 :                 if (!chainman.LoadBlockIndex(chainparams)) {
#    1380         [ #  # ]:          0 :                     if (ShutdownRequested()) break;
#    1381                 :          0 :                     strLoadError = _("Error loading block database");
#    1382                 :          0 :                     break;
#    1383                 :          0 :                 }
#    1384                 :            : 
#    1385                 :            :                 // If the loaded chain has a wrong genesis, bail out immediately
#    1386                 :            :                 // (we're likely using a testnet datadir, or the other way around).
#    1387         [ +  + ]:        626 :                 if (!chainman.BlockIndex().empty() &&
#    1388         [ -  + ]:        626 :                         !g_chainman.m_blockman.LookupBlockIndex(chainparams.GetConsensus().hashGenesisBlock)) {
#    1389                 :          0 :                     return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
#    1390                 :          0 :                 }
#    1391                 :            : 
#    1392                 :            :                 // Check for changed -prune state.  What we are concerned about is a user who has pruned blocks
#    1393                 :            :                 // in the past, but is now trying to run unpruned.
#    1394 [ +  + ][ -  + ]:        626 :                 if (fHavePruned && !fPruneMode) {
#    1395                 :          0 :                     strLoadError = _("You need to rebuild the database using -reindex to go back to unpruned mode.  This will redownload the entire blockchain");
#    1396                 :          0 :                     break;
#    1397                 :          0 :                 }
#    1398                 :            : 
#    1399                 :            :                 // At this point blocktree args are consistent with what's on disk.
#    1400                 :            :                 // If we're not mid-reindex (based on disk + args), add a genesis block on disk
#    1401                 :            :                 // (otherwise we use the one already on disk).
#    1402                 :            :                 // This is called again in ThreadImport after the reindex completes.
#    1403 [ +  + ][ -  + ]:        626 :                 if (!fReindex && !::ChainstateActive().LoadGenesisBlock(chainparams)) {
#    1404                 :          0 :                     strLoadError = _("Error initializing block database");
#    1405                 :          0 :                     break;
#    1406                 :          0 :                 }
#    1407                 :            : 
#    1408                 :            :                 // At this point we're either in reindex or we've loaded a useful
#    1409                 :            :                 // block tree into BlockIndex()!
#    1410                 :            : 
#    1411                 :        626 :                 bool failed_chainstate_init = false;
#    1412                 :            : 
#    1413         [ +  + ]:        626 :                 for (CChainState* chainstate : chainman.GetAll()) {
#    1414                 :        626 :                     chainstate->InitCoinsDB(
#    1415                 :        626 :                         /* cache_size_bytes */ nCoinDBCache,
#    1416                 :        626 :                         /* in_memory */ false,
#    1417 [ +  + ][ +  + ]:        626 :                         /* should_wipe */ fReset || fReindexChainState);
#    1418                 :            : 
#    1419                 :        626 :                     chainstate->CoinsErrorCatcher().AddReadErrCallback([]() {
#    1420                 :          0 :                         uiInterface.ThreadSafeMessageBox(
#    1421                 :          0 :                             _("Error reading from database, shutting down."),
#    1422                 :          0 :                             "", CClientUIInterface::MSG_ERROR);
#    1423                 :          0 :                     });
#    1424                 :            : 
#    1425                 :            :                     // If necessary, upgrade from older database format.
#    1426                 :            :                     // This is a no-op if we cleared the coinsviewdb with -reindex or -reindex-chainstate
#    1427         [ -  + ]:        626 :                     if (!chainstate->CoinsDB().Upgrade()) {
#    1428                 :          0 :                         strLoadError = _("Error upgrading chainstate database");
#    1429                 :          0 :                         failed_chainstate_init = true;
#    1430                 :          0 :                         break;
#    1431                 :          0 :                     }
#    1432                 :            : 
#    1433                 :            :                     // ReplayBlocks is a no-op if we cleared the coinsviewdb with -reindex or -reindex-chainstate
#    1434         [ -  + ]:        626 :                     if (!chainstate->ReplayBlocks(chainparams)) {
#    1435                 :          0 :                         strLoadError = _("Unable to replay blocks. You will need to rebuild the database using -reindex-chainstate.");
#    1436                 :          0 :                         failed_chainstate_init = true;
#    1437                 :          0 :                         break;
#    1438                 :          0 :                     }
#    1439                 :            : 
#    1440                 :            :                     // The on-disk coinsdb is now in a good state, create the cache
#    1441                 :        626 :                     chainstate->InitCoinsCache(nCoinCacheUsage);
#    1442                 :        626 :                     assert(chainstate->CanFlushToDisk());
#    1443                 :            : 
#    1444         [ +  + ]:        626 :                     if (!is_coinsview_empty(chainstate)) {
#    1445                 :            :                         // LoadChainTip initializes the chain based on CoinsTip()'s best block
#    1446         [ -  + ]:        378 :                         if (!chainstate->LoadChainTip(chainparams)) {
#    1447                 :          0 :                             strLoadError = _("Error initializing block database");
#    1448                 :          0 :                             failed_chainstate_init = true;
#    1449                 :          0 :                             break; // out of the per-chainstate loop
#    1450                 :          0 :                         }
#    1451                 :        378 :                         assert(chainstate->m_chain.Tip() != nullptr);
#    1452                 :        378 :                     }
#    1453                 :        626 :                 }
#    1454                 :            : 
#    1455         [ -  + ]:        626 :                 if (failed_chainstate_init) {
#    1456                 :          0 :                     break; // out of the chainstate activation do-while
#    1457                 :          0 :                 }
#    1458                 :          0 :             } catch (const std::exception& e) {
#    1459                 :          0 :                 LogPrintf("%s\n", e.what());
#    1460                 :          0 :                 strLoadError = _("Error opening block database");
#    1461                 :          0 :                 break;
#    1462                 :          0 :             }
#    1463                 :            : 
#    1464         [ +  + ]:        626 :             if (!fReset) {
#    1465                 :        616 :                 LOCK(cs_main);
#    1466                 :        616 :                 auto chainstates{chainman.GetAll()};
#    1467         [ +  + ]:        616 :                 if (std::any_of(chainstates.begin(), chainstates.end(),
#    1468                 :        616 :                                 [&chainparams](const CChainState* cs) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { return cs->NeedsRedownload(chainparams); })) {
#    1469                 :          1 :                     strLoadError = strprintf(_("Witness data for blocks after height %d requires validation. Please restart with -reindex."),
#    1470                 :          1 :                                              chainparams.GetConsensus().SegwitHeight);
#    1471                 :          1 :                     break;
#    1472                 :          1 :                 }
#    1473                 :        625 :             }
#    1474                 :            : 
#    1475                 :        625 :             bool failed_verification = false;
#    1476                 :            : 
#    1477                 :        625 :             try {
#    1478                 :        625 :                 LOCK(cs_main);
#    1479                 :            : 
#    1480         [ +  + ]:        625 :                 for (CChainState* chainstate : chainman.GetAll()) {
#    1481         [ +  + ]:        625 :                     if (!is_coinsview_empty(chainstate)) {
#    1482                 :        377 :                         uiInterface.InitMessage(_("Verifying blocks…").translated);
#    1483 [ +  + ][ -  + ]:        377 :                         if (fHavePruned && args.GetArg("-checkblocks", DEFAULT_CHECKBLOCKS) > MIN_BLOCKS_TO_KEEP) {
#                 [ -  + ]
#    1484                 :          0 :                             LogPrintf("Prune: pruned datadir may not have more than %d blocks; only checking available blocks\n",
#    1485                 :          0 :                                 MIN_BLOCKS_TO_KEEP);
#    1486                 :          0 :                         }
#    1487                 :            : 
#    1488                 :        377 :                         const CBlockIndex* tip = chainstate->m_chain.Tip();
#    1489                 :        377 :                         RPCNotifyBlockChange(tip);
#    1490 [ +  - ][ -  + ]:        377 :                         if (tip && tip->nTime > GetAdjustedTime() + 2 * 60 * 60) {
#    1491                 :          0 :                             strLoadError = _("The block database contains a block which appears to be from the future. "
#    1492                 :          0 :                                     "This may be due to your computer's date and time being set incorrectly. "
#    1493                 :          0 :                                     "Only rebuild the block database if you are sure that your computer's date and time are correct");
#    1494                 :          0 :                             failed_verification = true;
#    1495                 :          0 :                             break;
#    1496                 :          0 :                         }
#    1497                 :            : 
#    1498         [ +  + ]:        377 :                         if (!CVerifyDB().VerifyDB(
#    1499                 :        377 :                                 *chainstate, chainparams, chainstate->CoinsDB(),
#    1500                 :        377 :                                 args.GetArg("-checklevel", DEFAULT_CHECKLEVEL),
#    1501                 :        377 :                                 args.GetArg("-checkblocks", DEFAULT_CHECKBLOCKS))) {
#    1502                 :          1 :                             strLoadError = _("Corrupted block database detected");
#    1503                 :          1 :                             failed_verification = true;
#    1504                 :          1 :                             break;
#    1505                 :          1 :                         }
#    1506                 :        377 :                     }
#    1507                 :        625 :                 }
#    1508                 :        625 :             } catch (const std::exception& e) {
#    1509                 :          0 :                 LogPrintf("%s\n", e.what());
#    1510                 :          0 :                 strLoadError = _("Error opening block database");
#    1511                 :          0 :                 failed_verification = true;
#    1512                 :          0 :                 break;
#    1513                 :          0 :             }
#    1514                 :            : 
#    1515         [ +  + ]:        625 :             if (!failed_verification) {
#    1516                 :        624 :                 fLoaded = true;
#    1517                 :        624 :                 LogPrintf(" block index %15dms\n", GetTimeMillis() - load_block_index_start_time);
#    1518                 :        624 :             }
#    1519                 :        625 :         } while(false);
#    1520                 :            : 
#    1521 [ +  + ][ +  - ]:        626 :         if (!fLoaded && !ShutdownRequested()) {
#    1522                 :            :             // first suggest a reindex
#    1523         [ +  - ]:          2 :             if (!fReset) {
#    1524                 :          2 :                 bool fRet = uiInterface.ThreadSafeQuestion(
#    1525                 :          2 :                     strLoadError + Untranslated(".\n\n") + _("Do you want to rebuild the block database now?"),
#    1526                 :          2 :                     strLoadError.original + ".\nPlease restart with -reindex or -reindex-chainstate to recover.",
#    1527                 :          2 :                     "", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
#    1528         [ -  + ]:          2 :                 if (fRet) {
#    1529                 :          0 :                     fReindex = true;
#    1530                 :          0 :                     AbortShutdown();
#    1531                 :          2 :                 } else {
#    1532                 :          2 :                     LogPrintf("Aborted block database rebuild. Exiting.\n");
#    1533                 :          2 :                     return false;
#    1534                 :          2 :                 }
#    1535                 :          0 :             } else {
#    1536                 :          0 :                 return InitError(strLoadError);
#    1537                 :          0 :             }
#    1538                 :          2 :         }
#    1539                 :        626 :     }
#    1540                 :            : 
#    1541                 :            :     // As LoadBlockIndex can take several minutes, it's possible the user
#    1542                 :            :     // requested to kill the GUI during the last operation. If so, exit.
#    1543                 :            :     // As the program has not fully started yet, Shutdown() is possibly overkill.
#    1544         [ -  + ]:        626 :     if (ShutdownRequested()) {
#    1545                 :          0 :         LogPrintf("Shutdown requested. Exiting.\n");
#    1546                 :          0 :         return false;
#    1547                 :          0 :     }
#    1548                 :            : 
#    1549                 :            :     // ********************************************************* Step 8: start indexers
#    1550         [ +  + ]:        624 :     if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
#    1551                 :          9 :         g_txindex = std::make_unique<TxIndex>(nTxIndexCache, false, fReindex);
#    1552         [ -  + ]:          9 :         if (!g_txindex->Start()) {
#    1553                 :          0 :             return false;
#    1554                 :          0 :         }
#    1555                 :        624 :     }
#    1556                 :            : 
#    1557         [ +  + ]:        624 :     for (const auto& filter_type : g_enabled_filter_types) {
#    1558                 :          7 :         InitBlockFilterIndex(filter_type, filter_index_cache, false, fReindex);
#    1559         [ +  + ]:          7 :         if (!GetBlockFilterIndex(filter_type)->Start()) {
#    1560                 :          1 :             return false;
#    1561                 :          1 :         }
#    1562                 :          7 :     }
#    1563                 :            : 
#    1564         [ +  + ]:        624 :     if (args.GetBoolArg("-coinstatsindex", DEFAULT_COINSTATSINDEX)) {
#    1565                 :          4 :         g_coin_stats_index = std::make_unique<CoinStatsIndex>(/* cache size */ 0, false, fReindex);
#    1566         [ -  + ]:          4 :         if (!g_coin_stats_index->Start()) {
#    1567                 :          0 :             return false;
#    1568                 :          0 :         }
#    1569                 :        623 :     }
#    1570                 :            : 
#    1571                 :            :     // ********************************************************* Step 9: load wallet
#    1572         [ +  + ]:        623 :     for (const auto& client : node.chain_clients) {
#    1573         [ +  + ]:        617 :         if (!client->load()) {
#    1574                 :          2 :             return false;
#    1575                 :          2 :         }
#    1576                 :        617 :     }
#    1577                 :            : 
#    1578                 :            :     // ********************************************************* Step 10: data directory maintenance
#    1579                 :            : 
#    1580                 :            :     // if pruning, unset the service bit and perform the initial blockstore prune
#    1581                 :            :     // after any wallet rescanning has taken place.
#    1582         [ +  + ]:        623 :     if (fPruneMode) {
#    1583                 :          8 :         LogPrintf("Unsetting NODE_NETWORK on prune mode\n");
#    1584                 :          8 :         nLocalServices = ServiceFlags(nLocalServices & ~NODE_NETWORK);
#    1585         [ +  + ]:          8 :         if (!fReindex) {
#    1586                 :          7 :             LOCK(cs_main);
#    1587         [ +  + ]:          7 :             for (CChainState* chainstate : chainman.GetAll()) {
#    1588                 :          7 :                 uiInterface.InitMessage(_("Pruning blockstore…").translated);
#    1589                 :          7 :                 chainstate->PruneAndFlush();
#    1590                 :          7 :             }
#    1591                 :          7 :         }
#    1592                 :          8 :     }
#    1593                 :            : 
#    1594         [ +  + ]:        621 :     if (chainparams.GetConsensus().SegwitHeight != std::numeric_limits<int>::max()) {
#    1595                 :            :         // Advertise witness capabilities.
#    1596                 :            :         // The option to not set NODE_WITNESS is only used in the tests and should be removed.
#    1597                 :        620 :         nLocalServices = ServiceFlags(nLocalServices | NODE_WITNESS);
#    1598                 :        620 :     }
#    1599                 :            : 
#    1600                 :            :     // ********************************************************* Step 11: import blocks
#    1601                 :            : 
#    1602         [ -  + ]:        621 :     if (!CheckDiskSpace(gArgs.GetDataDirNet())) {
#    1603                 :          0 :         InitError(strprintf(_("Error: Disk space is low for %s"), gArgs.GetDataDirNet()));
#    1604                 :          0 :         return false;
#    1605                 :          0 :     }
#    1606         [ -  + ]:        621 :     if (!CheckDiskSpace(gArgs.GetBlocksDirPath())) {
#    1607                 :          0 :         InitError(strprintf(_("Error: Disk space is low for %s"), gArgs.GetBlocksDirPath()));
#    1608                 :          0 :         return false;
#    1609                 :          0 :     }
#    1610                 :            : 
#    1611                 :            :     // Either install a handler to notify us when genesis activates, or set fHaveGenesis directly.
#    1612                 :            :     // No locking, as this happens before any background thread is started.
#    1613                 :        621 :     boost::signals2::connection block_notify_genesis_wait_connection;
#    1614         [ +  + ]:        621 :     if (::ChainActive().Tip() == nullptr) {
#    1615                 :        248 :         block_notify_genesis_wait_connection = uiInterface.NotifyBlockTip_connect(std::bind(BlockNotifyGenesisWait, std::placeholders::_2));
#    1616                 :        373 :     } else {
#    1617                 :        373 :         fHaveGenesis = true;
#    1618                 :        373 :     }
#    1619                 :            : 
#    1620                 :        621 : #if HAVE_SYSTEM
#    1621                 :        621 :     const std::string block_notify = args.GetArg("-blocknotify", "");
#    1622         [ +  + ]:        621 :     if (!block_notify.empty()) {
#    1623                 :        113 :         uiInterface.NotifyBlockTip_connect([block_notify](SynchronizationState sync_state, const CBlockIndex* pBlockIndex) {
#    1624 [ +  + ][ -  + ]:        113 :             if (sync_state != SynchronizationState::POST_INIT || !pBlockIndex) return;
#    1625                 :        112 :             std::string command = block_notify;
#    1626                 :        112 :             boost::replace_all(command, "%s", pBlockIndex->GetBlockHash().GetHex());
#    1627                 :        112 :             std::thread t(runCommand, command);
#    1628                 :        112 :             t.detach(); // thread runs free
#    1629                 :        112 :         });
#    1630                 :          1 :     }
#    1631                 :        621 : #endif
#    1632                 :            : 
#    1633                 :        621 :     std::vector<fs::path> vImportFiles;
#    1634         [ +  + ]:        621 :     for (const std::string& strFile : args.GetArgs("-loadblock")) {
#    1635                 :          1 :         vImportFiles.push_back(strFile);
#    1636                 :          1 :     }
#    1637                 :            : 
#    1638                 :        621 :     chainman.m_load_block = std::thread(&util::TraceThread, "loadblk", [=, &chainman, &args] {
#    1639                 :        621 :         ThreadImport(chainman, vImportFiles, args);
#    1640                 :        621 :     });
#    1641                 :            : 
#    1642                 :            :     // Wait for genesis block to be processed
#    1643                 :        621 :     {
#    1644                 :        621 :         WAIT_LOCK(g_genesis_wait_mutex, lock);
#    1645                 :            :         // We previously could hang here if StartShutdown() is called prior to
#    1646                 :            :         // ThreadImport getting started, so instead we just wait on a timer to
#    1647                 :            :         // check ShutdownRequested() regularly.
#    1648 [ +  + ][ +  - ]:        869 :         while (!fHaveGenesis && !ShutdownRequested()) {
#    1649                 :        248 :             g_genesis_wait_cv.wait_for(lock, std::chrono::milliseconds(500));
#    1650                 :        248 :         }
#    1651                 :        621 :         block_notify_genesis_wait_connection.disconnect();
#    1652                 :        621 :     }
#    1653                 :            : 
#    1654         [ -  + ]:        621 :     if (ShutdownRequested()) {
#    1655                 :          0 :         return false;
#    1656                 :          0 :     }
#    1657                 :            : 
#    1658                 :            :     // ********************************************************* Step 12: start node
#    1659                 :            : 
#    1660                 :        621 :     int chain_active_height;
#    1661                 :            : 
#    1662                 :            :     //// debug print
#    1663                 :        621 :     {
#    1664                 :        621 :         LOCK(cs_main);
#    1665                 :        621 :         LogPrintf("block tree size = %u\n", chainman.BlockIndex().size());
#    1666                 :        621 :         chain_active_height = chainman.ActiveChain().Height();
#    1667         [ -  + ]:        621 :         if (tip_info) {
#    1668                 :          0 :             tip_info->block_height = chain_active_height;
#    1669         [ #  # ]:          0 :             tip_info->block_time = chainman.ActiveChain().Tip() ? chainman.ActiveChain().Tip()->GetBlockTime() : Params().GenesisBlock().GetBlockTime();
#    1670                 :          0 :             tip_info->verification_progress = GuessVerificationProgress(Params().TxData(), chainman.ActiveChain().Tip());
#    1671                 :          0 :         }
#    1672 [ -  + ][ #  # ]:        621 :         if (tip_info && ::pindexBestHeader) {
#    1673                 :          0 :             tip_info->header_height = ::pindexBestHeader->nHeight;
#    1674                 :          0 :             tip_info->header_time = ::pindexBestHeader->GetBlockTime();
#    1675                 :          0 :         }
#    1676                 :        621 :     }
#    1677                 :        621 :     LogPrintf("nBestHeight = %d\n", chain_active_height);
#    1678         [ +  - ]:        621 :     if (node.peerman) node.peerman->SetBestHeight(chain_active_height);
#    1679                 :            : 
#    1680                 :        621 :     Discover();
#    1681                 :            : 
#    1682                 :            :     // Map ports with UPnP or NAT-PMP.
#    1683                 :        621 :     StartMapPort(args.GetBoolArg("-upnp", DEFAULT_UPNP), gArgs.GetBoolArg("-natpmp", DEFAULT_NATPMP));
#    1684                 :            : 
#    1685                 :        621 :     CConnman::Options connOptions;
#    1686                 :        621 :     connOptions.nLocalServices = nLocalServices;
#    1687                 :        621 :     connOptions.nMaxConnections = nMaxConnections;
#    1688                 :        621 :     connOptions.m_max_outbound_full_relay = std::min(MAX_OUTBOUND_FULL_RELAY_CONNECTIONS, connOptions.nMaxConnections);
#    1689                 :        621 :     connOptions.m_max_outbound_block_relay = std::min(MAX_BLOCK_RELAY_ONLY_CONNECTIONS, connOptions.nMaxConnections-connOptions.m_max_outbound_full_relay);
#    1690                 :        621 :     connOptions.nMaxAddnode = MAX_ADDNODE_CONNECTIONS;
#    1691                 :        621 :     connOptions.nMaxFeeler = MAX_FEELER_CONNECTIONS;
#    1692                 :        621 :     connOptions.uiInterface = &uiInterface;
#    1693                 :        621 :     connOptions.m_banman = node.banman.get();
#    1694                 :        621 :     connOptions.m_msgproc = node.peerman.get();
#    1695                 :        621 :     connOptions.nSendBufferMaxSize = 1000 * args.GetArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER);
#    1696                 :        621 :     connOptions.nReceiveFloodSize = 1000 * args.GetArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER);
#    1697                 :        621 :     connOptions.m_added_nodes = args.GetArgs("-addnode");
#    1698                 :            : 
#    1699                 :        621 :     connOptions.nMaxOutboundLimit = 1024 * 1024 * args.GetArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET);
#    1700                 :        621 :     connOptions.m_peer_connect_timeout = peer_connect_timeout;
#    1701                 :            : 
#    1702         [ +  + ]:        621 :     for (const std::string& bind_arg : args.GetArgs("-bind")) {
#    1703                 :        619 :         CService bind_addr;
#    1704                 :        619 :         const size_t index = bind_arg.rfind('=');
#    1705         [ +  - ]:        619 :         if (index == std::string::npos) {
#    1706         [ +  - ]:        619 :             if (Lookup(bind_arg, bind_addr, GetListenPort(), false)) {
#    1707                 :        619 :                 connOptions.vBinds.push_back(bind_addr);
#    1708                 :        619 :                 continue;
#    1709                 :        619 :             }
#    1710                 :          0 :         } else {
#    1711                 :          0 :             const std::string network_type = bind_arg.substr(index + 1);
#    1712         [ #  # ]:          0 :             if (network_type == "onion") {
#    1713                 :          0 :                 const std::string truncated_bind_arg = bind_arg.substr(0, index);
#    1714         [ #  # ]:          0 :                 if (Lookup(truncated_bind_arg, bind_addr, BaseParams().OnionServiceTargetPort(), false)) {
#    1715                 :          0 :                     connOptions.onion_binds.push_back(bind_addr);
#    1716                 :          0 :                     continue;
#    1717                 :          0 :                 }
#    1718                 :          0 :             }
#    1719                 :          0 :         }
#    1720                 :          0 :         return InitError(ResolveErrMsg("bind", bind_arg));
#    1721                 :          0 :     }
#    1722                 :            : 
#    1723         [ +  - ]:        621 :     if (connOptions.onion_binds.empty()) {
#    1724                 :        621 :         connOptions.onion_binds.push_back(DefaultOnionServiceTarget());
#    1725                 :        621 :     }
#    1726                 :            : 
#    1727         [ -  + ]:        621 :     if (args.GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION)) {
#    1728                 :          0 :         const auto bind_addr = connOptions.onion_binds.front();
#    1729         [ #  # ]:          0 :         if (connOptions.onion_binds.size() > 1) {
#    1730                 :          0 :             InitWarning(strprintf(_("More than one onion bind address is provided. Using %s for the automatically created Tor onion service."), bind_addr.ToStringIPPort()));
#    1731                 :          0 :         }
#    1732                 :          0 :         StartTorControl(bind_addr);
#    1733                 :          0 :     }
#    1734                 :            : 
#    1735         [ +  + ]:        621 :     for (const std::string& strBind : args.GetArgs("-whitebind")) {
#    1736                 :          2 :         NetWhitebindPermissions whitebind;
#    1737                 :          2 :         bilingual_str error;
#    1738         [ +  + ]:          2 :         if (!NetWhitebindPermissions::TryParse(strBind, whitebind, error)) return InitError(error);
#    1739                 :          1 :         connOptions.vWhiteBinds.push_back(whitebind);
#    1740                 :          1 :     }
#    1741                 :            : 
#    1742         [ +  + ]:        621 :     for (const auto& net : args.GetArgs("-whitelist")) {
#    1743                 :         84 :         NetWhitelistPermissions subnet;
#    1744                 :         84 :         bilingual_str error;
#    1745         [ +  + ]:         84 :         if (!NetWhitelistPermissions::TryParse(net, subnet, error)) return InitError(error);
#    1746                 :         82 :         connOptions.vWhitelistedRange.push_back(subnet);
#    1747                 :         82 :     }
#    1748                 :            : 
#    1749                 :        620 :     connOptions.vSeedNodes = args.GetArgs("-seednode");
#    1750                 :            : 
#    1751                 :            :     // Initiate outbound connections unless connect=0
#    1752                 :        618 :     connOptions.m_use_addrman_outgoing = !args.IsArgSet("-connect");
#    1753         [ +  + ]:        618 :     if (!connOptions.m_use_addrman_outgoing) {
#    1754                 :          1 :         const auto connect = args.GetArgs("-connect");
#    1755 [ -  + ][ +  - ]:          1 :         if (connect.size() != 1 || connect[0] != "0") {
#    1756                 :          1 :             connOptions.m_specified_outgoing = connect;
#    1757                 :          1 :         }
#    1758                 :          1 :     }
#    1759                 :            : 
#    1760                 :        618 :     const std::string& i2psam_arg = args.GetArg("-i2psam", "");
#    1761         [ +  + ]:        618 :     if (!i2psam_arg.empty()) {
#    1762                 :          2 :         CService addr;
#    1763 [ -  + ][ -  + ]:          2 :         if (!Lookup(i2psam_arg, addr, 7656, fNameLookup) || !addr.IsValid()) {
#                 [ -  + ]
#    1764                 :          0 :             return InitError(strprintf(_("Invalid -i2psam address or hostname: '%s'"), i2psam_arg));
#    1765                 :          0 :         }
#    1766                 :          2 :         SetReachable(NET_I2P, true);
#    1767                 :          2 :         SetProxy(NET_I2P, proxyType{addr});
#    1768                 :        616 :     } else {
#    1769                 :        616 :         SetReachable(NET_I2P, false);
#    1770                 :        616 :     }
#    1771                 :            : 
#    1772                 :        618 :     connOptions.m_i2p_accept_incoming = args.GetBoolArg("-i2pacceptincoming", true);
#    1773                 :            : 
#    1774         [ -  + ]:        618 :     if (!node.connman->Start(*node.scheduler, connOptions)) {
#    1775                 :          0 :         return false;
#    1776                 :          0 :     }
#    1777                 :            : 
#    1778                 :            :     // ********************************************************* Step 13: finished
#    1779                 :            : 
#    1780                 :        618 :     SetRPCWarmupFinished();
#    1781                 :        618 :     uiInterface.InitMessage(_("Done loading").translated);
#    1782                 :            : 
#    1783         [ +  + ]:        618 :     for (const auto& client : node.chain_clients) {
#    1784                 :        612 :         client->start(*node.scheduler);
#    1785                 :        612 :     }
#    1786                 :            : 
#    1787                 :        618 :     BanMan* banman = node.banman.get();
#    1788                 :        618 :     node.scheduler->scheduleEvery([banman]{
#    1789                 :          6 :         banman->DumpBanlist();
#    1790                 :          6 :     }, DUMP_BANS_INTERVAL);
#    1791                 :            : 
#    1792                 :        618 : #if HAVE_SYSTEM
#    1793                 :        618 :     StartupNotify(args);
#    1794                 :        618 : #endif
#    1795                 :            : 
#    1796                 :        618 :     return true;
#    1797                 :        618 : }

Generated by: LCOV version 1.14