init.cpp raw

   1  // Copyright (c) 2009-2010 Satoshi Nakamoto
   2  // Copyright (c) 2009-2022 The Limenka developers
   3  // Distributed under the MIT software license, see the accompanying
   4  // file COPYING or http://www.opensource.org/licenses/mit-license.php.
   5  
   6  #include <limenka-build-config.h> // IWYU pragma: keep
   7  
   8  #include <init.h>
   9  
  10  #include <kernel/checks.h>
  11  
  12  #include <addrman.h>
  13  #include <banman.h>
  14  #include <blockfilter.h>
  15  #include <chain.h>
  16  #include <chainparams.h>
  17  #include <chainparamsbase.h>
  18  #include <clientversion.h>
  19  #include <common/args.h>
  20  #include <common/pcp.h>
  21  #include <common/system.h>
  22  #include <consensus/amount.h>
  23  #include <consensus/consensus.h>
  24  #include <dbwrapper.h>
  25  #include <deploymentstatus.h>
  26  #include <hash.h>
  27  #include <httprpc.h>
  28  #include <httpserver.h>
  29  #include <index/blockfilterindex.h>
  30  #include <index/coinstatsindex.h>
  31  #include <index/txindex.h>
  32  #include <init/common.h>
  33  #include <interfaces/chain.h>
  34  #include <interfaces/init.h>
  35  #include <interfaces/ipc.h>
  36  #include <interfaces/mining.h>
  37  #include <interfaces/node.h>
  38  #include <ipc/exception.h>
  39  #include <kernel/caches.h>
  40  #include <kernel/chainparams.h>
  41  #include <kernel/context.h>
  42  #include <kernel/warning.h>
  43  #include <key.h>
  44  #include <logging.h>
  45  #include <mapport.h>
  46  #include <net.h>
  47  #include <net_permissions.h>
  48  #include <net_processing.h>
  49  #include <netbase.h>
  50  #include <netgroup.h>
  51  #include <node/blockmanager_args.h>
  52  #include <node/blockstorage.h>
  53  #include <node/caches.h>
  54  #include <node/dbcache.h>
  55  #include <node/chainstate.h>
  56  #include <node/chainstatemanager_args.h>
  57  #include <node/context.h>
  58  #include <node/interface_ui.h>
  59  #include <node/kernel_notifications.h>
  60  #include <node/mempool_args.h>
  61  #include <node/mempool_persist.h>
  62  #include <node/mempool_persist_args.h>
  63  #include <node/mempoolbridge.h>
  64  #include <node/miner.h>
  65  #include <node/peerman_args.h>
  66  #include <policy/feerate.h>
  67  #include <policy/fees.h>
  68  #include <policy/fees_args.h>
  69  #include <policy/policy.h>
  70  #include <policy/settings.h>
  71  #include <protocol.h>
  72  #include <rpc/blockchain.h>
  73  #include <rpc/register.h>
  74  #include <rpc/server.h>
  75  #include <rpc/util.h>
  76  #include <scheduler.h>
  77  #include <script/sigcache.h>
  78  #include <stats/stats.h>
  79  #include <sync.h>
  80  #include <torcontrol.h>
  81  #include <txdb.h>
  82  #include <txmempool.h>
  83  #include <util/asmap.h>
  84  #include <util/batchpriority.h>
  85  #include <util/chaintype.h>
  86  #include <util/check.h>
  87  #include <util/fs.h>
  88  #include <util/fs_helpers.h>
  89  #include <util/mempressure.h>
  90  #include <util/moneystr.h>
  91  #include <util/overflow.h>
  92  #include <util/result.h>
  93  #include <util/signalinterrupt.h>
  94  #include <util/strencodings.h>
  95  #include <util/string.h>
  96  #include <util/syserror.h>
  97  #include <util/thread.h>
  98  #include <util/threadnames.h>
  99  #include <util/time.h>
 100  #include <util/translation.h>
 101  #include <validation.h>
 102  #include <validationinterface.h>
 103  #include <walletinitinterface.h>
 104  
 105  #include <algorithm>
 106  #include <condition_variable>
 107  #include <cstdint>
 108  #include <cstdio>
 109  #include <fstream>
 110  #include <functional>
 111  #include <set>
 112  #include <string>
 113  #include <thread>
 114  #include <vector>
 115  
 116  #ifndef WIN32
 117  #include <cerrno>
 118  #include <signal.h>
 119  #include <sys/stat.h>
 120  #endif
 121  
 122  #include <boost/signals2/signal.hpp>
 123  
 124  #ifdef ENABLE_ZMQ
 125  #include <zmq/zmqabstractnotifier.h>
 126  #include <zmq/zmqnotificationinterface.h>
 127  #include <zmq/zmqrpc.h>
 128  #endif
 129  
 130  using common::AmountErrMsg;
 131  using common::InvalidPortErrMsg;
 132  using common::ResolveErrMsg;
 133  
 134  using node::ApplyArgsManOptions;
 135  using node::BlockManager;
 136  using node::CalculateCacheSizes;
 137  using node::ChainstateLoadResult;
 138  using node::ChainstateLoadStatus;
 139  using node::DEFAULT_PERSIST_MEMPOOL;
 140  using node::DEFAULT_PRINT_MODIFIED_FEE;
 141  using node::DEFAULT_STOPATHEIGHT;
 142  using node::DumpMempool;
 143  using node::ImportBlocks;
 144  using node::KernelNotifications;
 145  using node::LoadChainstate;
 146  using node::LoadMempool;
 147  using node::MempoolPath;
 148  using node::NodeContext;
 149  using node::ShouldPersistMempool;
 150  using node::VerifyLoadedChainstate;
 151  using util::Join;
 152  using util::ReplaceAll;
 153  using util::ToString;
 154  
 155  static constexpr bool DEFAULT_COREPOLICY{false};
 156  static constexpr bool DEFAULT_PROXYRANDOMIZE{true};
 157  static constexpr bool DEFAULT_REST_ENABLE{false};
 158  static constexpr bool DEFAULT_I2P_ACCEPT_INCOMING{true};
 159  static constexpr bool DEFAULT_STOPAFTERBLOCKIMPORT{false};
 160  
 161  //! Check if initial sync is done with no change in block height or queued downloads every 30s
 162  static constexpr auto SYNC_CHECK_INTERVAL{30s};
 163  
 164  #ifdef WIN32
 165  // Win32 LevelDB doesn't use filedescriptors, and the ones used for
 166  // accessing block files don't count towards the fd_set size limit
 167  // anyway.
 168  #define MIN_LEVELDB_FDS 0
 169  #else
 170  #define MIN_LEVELDB_FDS 150
 171  #endif
 172  
 173  static constexpr int MIN_CORE_FDS = MIN_LEVELDB_FDS + NUM_FDS_MESSAGE_CAPTURE;
 174  static const char* DEFAULT_ASMAP_FILENAME="ip_asn.map";
 175  
 176  /**
 177   * The PID file facilities.
 178   */
 179  static const char* LIMENKA_PID_FILENAME = "limenkad.pid";
 180  /**
 181   * True if this process has created a PID file.
 182   * Used to determine whether we should remove the PID file on shutdown.
 183   */
 184  static bool g_generated_pid{false};
 185  
 186  static fs::path GetPidFile(const ArgsManager& args)
 187  {
 188      return AbsPathForConfigVal(args, args.GetPathArg("-pid", LIMENKA_PID_FILENAME));
 189  }
 190  
 191  [[nodiscard]] static bool CreatePidFile(const ArgsManager& args)
 192  {
 193      if (args.IsArgNegated("-pid")) return true;
 194  
 195      std::ofstream file{GetPidFile(args)};
 196      if (file) {
 197  #ifdef WIN32
 198          tfm::format(file, "%d\n", GetCurrentProcessId());
 199  #else
 200          tfm::format(file, "%d\n", getpid());
 201  #endif
 202          g_generated_pid = true;
 203          return true;
 204      } else {
 205          return InitError(strprintf(_("Unable to create the PID file '%s': %s"), fs::PathToString(GetPidFile(args)), SysErrorString(errno)));
 206      }
 207  }
 208  
 209  static void RemovePidFile(const ArgsManager& args)
 210  {
 211      if (!g_generated_pid) return;
 212      const auto pid_path{GetPidFile(args)};
 213      if (std::error_code error; !fs::remove(pid_path, error)) {
 214          std::string msg{error ? error.message() : "File does not exist"};
 215          LogWarning("Unable to remove PID file (%s): %s", fs::PathToString(pid_path), msg);
 216      }
 217  }
 218  
 219  static std::optional<util::SignalInterrupt> g_shutdown;
 220  
 221  void InitContext(NodeContext& node)
 222  {
 223      assert(!g_shutdown);
 224      g_shutdown.emplace();
 225  
 226      node.args = &gArgs;
 227      node.shutdown_signal = &*g_shutdown;
 228      node.shutdown_request = [&node] {
 229          assert(node.shutdown_signal);
 230          if (!(*node.shutdown_signal)()) return false;
 231          // Wake any threads that may be waiting for the tip to change.
 232          if (node.notifications) WITH_LOCK(node.notifications->m_tip_block_mutex, node.notifications->m_tip_block_cv.notify_all());
 233          return true;
 234      };
 235  }
 236  
 237  //////////////////////////////////////////////////////////////////////////////
 238  //
 239  // Shutdown
 240  //
 241  
 242  //
 243  // Thread management and startup/shutdown:
 244  //
 245  // The network-processing threads are all part of a thread group
 246  // created by AppInit() or the Qt main() function.
 247  //
 248  // A clean exit happens when the SignalInterrupt object is triggered, which
 249  // makes the main thread's SignalInterrupt::wait() call return, and join all
 250  // other ongoing threads in the thread group to the main thread.
 251  // Shutdown() is then called to clean up database connections, and stop other
 252  // threads that should only be stopped after the main network-processing
 253  // threads have exited.
 254  //
 255  // Shutdown for Qt is very similar, only it uses a QTimer to detect
 256  // ShutdownRequested() getting set, and then does the normal Qt
 257  // shutdown thing.
 258  //
 259  
 260  bool ShutdownRequested(node::NodeContext& node)
 261  {
 262      return bool{*Assert(node.shutdown_signal)};
 263  }
 264  
 265  #if HAVE_SYSTEM
 266  static void ShutdownNotify(const ArgsManager& args)
 267  {
 268      std::vector<std::thread> threads;
 269      for (const auto& cmd : args.GetArgs("-shutdownnotify")) {
 270          threads.emplace_back(runCommand, cmd);
 271      }
 272      for (auto& t : threads) {
 273          t.join();
 274      }
 275  }
 276  #endif
 277  
 278  void Interrupt(NodeContext& node)
 279  {
 280  #if HAVE_SYSTEM
 281      ShutdownNotify(*node.args);
 282  #endif
 283      // Wake any threads that may be waiting for the tip to change.
 284      if (node.notifications) WITH_LOCK(node.notifications->m_tip_block_mutex, node.notifications->m_tip_block_cv.notify_all());
 285      InterruptHTTPServer();
 286      InterruptHTTPRPC();
 287      InterruptRPC();
 288      InterruptREST();
 289      InterruptTorControl();
 290      InterruptMapPort();
 291      if (node.connman)
 292          node.connman->Interrupt();
 293      for (auto* index : node.indexes) {
 294          index->Interrupt();
 295      }
 296  }
 297  
 298  void Shutdown(NodeContext& node)
 299  {
 300      static Mutex g_shutdown_mutex;
 301      TRY_LOCK(g_shutdown_mutex, lock_shutdown);
 302      if (!lock_shutdown) return;
 303      LogPrintf("%s: In progress...\n", __func__);
 304      Assert(node.args);
 305  
 306      /// Note: Shutdown() must be able to handle cases in which initialization failed part of the way,
 307      /// for example if the data directory was found to be locked.
 308      /// Be sure that anything that writes files or flushes caches only does this if the respective
 309      /// module was initialized.
 310      util::ThreadRename("shutoff");
 311      if (node.mempool) node.mempool->AddTransactionsUpdated(1);
 312  
 313      StopHTTPRPC();
 314      StopREST();
 315      StopRPC();
 316      StopHTTPServer();
 317      for (const auto& client : node.chain_clients) {
 318          client->flush();
 319      }
 320      for (auto& client : node.chain_clients) {
 321          try {
 322              client->stop();
 323          } catch (const ipc::Exception& e) {
 324              LogDebug(BCLog::IPC, "Chain client did not disconnect cleanly: %s", e.what());
 325              client.reset();
 326          }
 327      }
 328      StopMapPort();
 329  
 330      // Stop the cross-chain gossip bridge before any mempool teardown.
 331      if (node.mempool_bridge) {
 332          node.mempool_bridge->Stop();
 333          node.mempool_bridge.reset();
 334      }
 335  
 336      // Because these depend on each-other, we make sure that neither can be
 337      // using the other before destroying them.
 338      if (node.peerman && node.validation_signals) node.validation_signals->UnregisterValidationInterface(node.peerman.get());
 339      if (node.connman) node.connman->Stop();
 340  
 341      StopTorControl();
 342  
 343      if (node.background_init_thread.joinable()) node.background_init_thread.join();
 344      // After everything has been shut down, but before things get flushed, stop the
 345      // the scheduler. After this point, SyncWithValidationInterfaceQueue() should not be called anymore
 346      // as this would prevent the shutdown from completing.
 347      if (node.scheduler) node.scheduler->stop();
 348  
 349      // After the threads that potentially access these pointers have been stopped,
 350      // destruct and reset all to nullptr.
 351      node.peerman.reset();
 352      node.connman.reset();
 353      node.banman.reset();
 354      node.addrman.reset();
 355      node.netgroupman.reset();
 356  
 357      // Drop transactions we were still watching, record fee estimations and unregister
 358      // fee estimator from validation interface.
 359      if (node.fee_estimator) {
 360          node.fee_estimator->Flush();
 361          if (node.validation_signals) {
 362              node.validation_signals->UnregisterValidationInterface(node.fee_estimator.get());
 363          }
 364      }
 365  
 366      // FlushStateToDisk generates a ChainStateFlushed callback, which we should avoid missing
 367      if (node.chainman) {
 368          LOCK(cs_main);
 369          for (Chainstate* chainstate : node.chainman->GetAll()) {
 370              if (chainstate->CanFlushToDisk()) {
 371                  chainstate->ForceFlushStateToDisk();
 372              }
 373          }
 374      }
 375  
 376      // After there are no more peers/RPC left to give us new data which may generate
 377      // CValidationInterface callbacks, flush them...
 378      if (node.validation_signals) node.validation_signals->FlushBackgroundCallbacks();
 379  
 380      // Stop and delete all indexes only after flushing background callbacks.
 381      for (auto* index : node.indexes) index->Stop();
 382      if (g_txindex) g_txindex.reset();
 383      if (g_coin_stats_index) g_coin_stats_index.reset();
 384      DestroyAllBlockFilterIndexes();
 385      node.indexes.clear(); // all instances are nullptr now
 386  
 387      // Any future callbacks will be dropped. This should absolutely be safe - if
 388      // missing a callback results in an unrecoverable situation, unclean shutdown
 389      // would too. The only reason to do the above flushes is to let the wallet catch
 390      // up with our current chain to avoid any strange pruning edge cases and make
 391      // next startup faster by avoiding rescan.
 392  
 393      if (node.chainman) {
 394          LOCK(cs_main);
 395          for (Chainstate* chainstate : node.chainman->GetAll()) {
 396              if (chainstate->CanFlushToDisk()) {
 397                  chainstate->ForceFlushStateToDisk();
 398                  chainstate->ResetCoinsViews();
 399              }
 400          }
 401      }
 402  
 403      if (node.mempool && node.mempool->GetLoadTried() && ShouldPersistMempool(*node.args)) {
 404          DumpMempool(*node.mempool, MempoolPath(*node.args));
 405      }
 406  
 407  #ifdef ENABLE_ZMQ
 408      if (g_zmq_notification_interface) {
 409          if (node.validation_signals) node.validation_signals->UnregisterValidationInterface(g_zmq_notification_interface.get());
 410          g_zmq_notification_interface.reset();
 411      }
 412  #endif
 413  
 414      node.chain_clients.clear();
 415      if (node.validation_signals) {
 416          node.validation_signals->UnregisterAllValidationInterfaces();
 417      }
 418      node.mempool.reset();
 419      node.fee_estimator.reset();
 420      node.chainman.reset();
 421      node.validation_signals.reset();
 422      node.scheduler.reset();
 423      node.ecc_context.reset();
 424      node.kernel.reset();
 425  
 426      RemovePidFile(*node.args);
 427  
 428      LogPrintf("%s: done\n", __func__);
 429  }
 430  
 431  /**
 432   * Signal handlers are very limited in what they are allowed to do.
 433   * The execution context the handler is invoked in is not guaranteed,
 434   * so we restrict handler operations to just touching variables:
 435   */
 436  #ifndef WIN32
 437  static void HandleSIGTERM(int)
 438  {
 439      if (g_shutdown.has_value()) {
 440          (void)(*g_shutdown)();
 441      }
 442  }
 443  
 444  static void HandleSIGHUP(int)
 445  {
 446      LogInstance().m_reopen_file = true;
 447  }
 448  #else
 449  static BOOL WINAPI consoleCtrlHandler(DWORD dwCtrlType)
 450  {
 451      if (!(*Assert(g_shutdown))()) {
 452          LogError("Failed to send shutdown signal on Ctrl-C\n");
 453          return false;
 454      }
 455      Sleep(INFINITE);
 456      return true;
 457  }
 458  #endif
 459  
 460  #ifndef WIN32
 461  static void registerSignalHandler(int signal, void(*handler)(int))
 462  {
 463      struct sigaction sa;
 464      sa.sa_handler = handler;
 465      sigemptyset(&sa.sa_mask);
 466      sa.sa_flags = 0;
 467      sigaction(signal, &sa, nullptr);
 468  }
 469  #endif
 470  
 471  static constexpr std::string_view BIP14_EXAMPLE_UA{"/Name:Version/Name:Version/.../"};
 472  
 473  void SetupServerArgs(ArgsManager& argsman, bool can_listen_ipc)
 474  {
 475      SetupHelpOptions(argsman);
 476      argsman.AddArg("-help-debug", "Print help message with debugging options and exit", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST); // server-only for now
 477  
 478      init::AddLoggingArgs(argsman);
 479  
 480      const auto defaultBaseParams = CreateBaseChainParams(ChainType::MAIN);
 481      const auto testnetBaseParams = CreateBaseChainParams(ChainType::TESTNET);
 482      const auto testnet4BaseParams = CreateBaseChainParams(ChainType::TESTNET4);
 483      const auto signetBaseParams = CreateBaseChainParams(ChainType::SIGNET);
 484      const auto regtestBaseParams = CreateBaseChainParams(ChainType::REGTEST);
 485      const auto defaultChainParams = CreateChainParams(argsman, ChainType::MAIN);
 486      const auto testnetChainParams = CreateChainParams(argsman, ChainType::TESTNET);
 487      const auto testnet4ChainParams = CreateChainParams(argsman, ChainType::TESTNET4);
 488      const auto signetChainParams = CreateChainParams(argsman, ChainType::SIGNET);
 489      const auto regtestChainParams = CreateChainParams(argsman, ChainType::REGTEST);
 490  
 491      // Hidden Options
 492      std::vector<std::string> hidden_args = {
 493          "-dbcrashratio", "-forcecompactdb",
 494          // GUI args. These will be overwritten by SetupUIArgs for the GUI
 495          "-choosedatadir", "-lang=<lang>", "-min", "-resetguisettings", "-splash", "-uiplatform"};
 496  
 497      argsman.AddArg("-version", "Print version and exit", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
 498  #if HAVE_SYSTEM
 499      argsman.AddArg("-alertnotify=<cmd>", "Execute command when an alert is raised (%s in cmd is replaced by message)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
 500  #endif
 501      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, testnet3: %s, testnet4: %s, signet: %s)", defaultChainParams->GetConsensus().defaultAssumeValid.GetHex(), testnetChainParams->GetConsensus().defaultAssumeValid.GetHex(), testnet4ChainParams->GetConsensus().defaultAssumeValid.GetHex(), signetChainParams->GetConsensus().defaultAssumeValid.GetHex()), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
 502      argsman.AddArg("-blocksdir=<dir>", "Specify directory to hold blocks subdirectory for *.dat files (default: <datadir>)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
 503      argsman.AddArg("-blocksxor",
 504                     strprintf("Whether an XOR-key applies to blocksdir *.dat files. "
 505                               "The created XOR-key will be zeros for an existing blocksdir or when `-blocksxor=0` is "
 506                               "set, and random for a freshly initialized blocksdir. "
 507                               "(default: %u)",
 508                               kernel::DEFAULT_XOR_BLOCKSDIR),
 509                     ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
 510      argsman.AddArg("-fastprune", "Use smaller block files and lower minimum prune height for testing purposes", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
 511  #if HAVE_SYSTEM
 512      argsman.AddArg("-blocknotify=<cmd>", "Execute command when the best block changes (%s in cmd is replaced by block hash)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
 513  #endif
 514      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);
 515      argsman.AddArg("-blockreconstructionextratxnsize=<n>",
 516                     strprintf("Upper limit of memory usage (in megabytes) for keeping extra transactions in memory for compact block reconstructions (default: %s)",
 517                               DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN_SIZE / 1000000),
 518                     ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
 519      argsman.AddArg("-blocksonly", strprintf("Whether to reject transactions from network peers. Disables automatic broadcast and rebroadcast of transactions, unless the source peer has the 'forcerelay' permission. RPC transactions are not affected. (default: %u)", DEFAULT_BLOCKSONLY), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
 520      argsman.AddArg("-coinstatsindex", strprintf("Maintain coinstats index used by the gettxoutsetinfo RPC (default: %u)", DEFAULT_COINSTATSINDEX), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
 521      argsman.AddArg("-conf=<file>", strprintf("Specify path to read-only configuration file. Relative paths will be prefixed by datadir location (only useable from command line, not configuration file) (default: %s)", LIMENKA_CONF_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
 522      argsman.AddArg("-confrw=<file>", strprintf("Specify read/write configuration file. Relative paths will be prefixed by the network-specific datadir location (default: %s)", LIMENKA_RW_CONF_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
 523      argsman.AddArg("-corepolicy", strprintf("Use Limenka policy defaults (default: %u)", DEFAULT_COREPOLICY), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
 524      argsman.AddArg("-datadir=<dir>", "Specify data directory", ArgsManager::ALLOW_ANY | ArgsManager::DISALLOW_NEGATION, OptionsCategory::OPTIONS);
 525      argsman.AddArg("-dbbatchsize", strprintf("Maximum database write batch size in bytes (default: %u)", nDefaultDbBatchSize), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::OPTIONS);
 526      argsman.AddArg("-dbcache=<n>", strprintf("Maximum database cache size <n> MiB (minimum %s, default is platform dependent, between %s and %s). Make sure you have enough RAM. In addition, unused memory allocated to the mempool is shared with this cache (see -maxmempool).", MIN_DBCACHE_BYTES / 1_MiB, MIN_DEFAULT_DBCACHE / 1_MiB, MAX_DEFAULT_DBCACHE / 1_MiB), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
 527      argsman.AddArg("-dbfilesize",
 528                     strprintf("Target size of files within databases, in MiB (%u to %u, default: %u).",
 529                               1, 1024,
 530                               DEFAULT_DB_FILE_SIZE),
 531                     ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::OPTIONS);
 532      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);
 533      argsman.AddArg("-allowignoredconf", strprintf("For backwards compatibility, treat an unused %s file in the datadir as a warning, not an error.", LIMENKA_CONF_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
 534      argsman.AddArg("-loadblock=<file>", "Imports blocks from external file on startup", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
 535      argsman.AddArg("-lowmem=<n>", strprintf("If system available memory falls below <n> MiB, flush caches (0 to disable, default: %s)", g_low_memory_threshold / 1024 / 1024), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
 536      argsman.AddArg("-maxmempool=<n>", strprintf("Keep the transaction memory pool below <n> megabytes (default: %u)", DEFAULT_MAX_MEMPOOL_SIZE_MB), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
 537      argsman.AddArg("-maxorphantx=<n>", strprintf("Keep at most <n> unconnectable transactions in memory (default: %u)", DEFAULT_MAX_ORPHAN_TRANSACTIONS), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
 538      argsman.AddArg("-mempoolexpiry=<n>", strprintf("Do not keep transactions in the mempool longer than <n> hours (default: %u)", DEFAULT_MEMPOOL_EXPIRY_HOURS), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
 539      argsman.AddArg("-minimumchainwork=<hex>", strprintf("Minimum work assumed to exist on a valid chain in hex (default: %s, testnet3: %s, testnet4: %s, signet: %s)", defaultChainParams->GetConsensus().nMinimumChainWork.GetHex(), testnetChainParams->GetConsensus().nMinimumChainWork.GetHex(), testnet4ChainParams->GetConsensus().nMinimumChainWork.GetHex(), signetChainParams->GetConsensus().nMinimumChainWork.GetHex()), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::OPTIONS);
 540      argsman.AddArg("-par=<n>", strprintf("Set the number of script verification threads (0 = auto, up to %d, <0 = leave that many cores free, default: %d)",
 541          MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
 542      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);
 543      argsman.AddArg("-persistmempoolv1",
 544                     strprintf("Whether a mempool.dat file created by -persistmempool or the savemempool RPC will be written in the legacy format "
 545                               "(version 1) or the current format (version 2). This temporary option will be removed in the future. (default: %u)",
 546                               DEFAULT_PERSIST_V1_DAT),
 547                     ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
 548      argsman.AddArg("-pid=<file>", strprintf("Specify pid file. Relative paths will be prefixed by a net-specific datadir location. (default: %s)", LIMENKA_PID_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
 549      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. "
 550              "Warning: Reverting this setting requires re-downloading the entire blockchain. Wallets and indexes should be loaded at startup and kept active while pruning is enabled so they stay synchronized before old block data is deleted; wallets or indexes that fall behind pruned data may require a reindex. "
 551              "(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);
 552      argsman.AddArg("-pruneduringinit=<n>", "Temporarily adjusts the -prune setting until initial sync completes."
 553          " Ignored if pruning is disabled."
 554          " (default: -1 = same value as -prune)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
 555      argsman.AddArg("-reindex", "If enabled, wipe chain state and block index, and rebuild them from blk*.dat files on disk. Also wipe and rebuild other optional indexes that are active. If an assumeutxo snapshot was loaded, its chainstate will be wiped as well. The snapshot can then be reloaded via RPC. Setting this to auto automatically reindexes the block database if it is corrupted.", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
 556      argsman.AddArg("-reindex-chainstate", "If enabled, wipe chain state, and rebuild it from blk*.dat files on disk. If an assumeutxo snapshot was loaded, its chainstate will be wiped as well. The snapshot can then be reloaded via RPC.", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
 557      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)", LIMENKA_CONF_FILENAME, LIMENKA_SETTINGS_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
 558  #if HAVE_SYSTEM
 559      argsman.AddArg("-startupnotify=<cmd>", "Execute command on startup.", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
 560      argsman.AddArg("-shutdownnotify=<cmd>", "Execute command immediately before beginning shutdown. The need for shutdown may be urgent, so be careful not to delay it long (if the command doesn't require interaction with the server, consider having it fork into the background).", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
 561  #endif
 562      argsman.AddArg("-txindex", strprintf("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)", DEFAULT_TXINDEX), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
 563      argsman.AddArg("-blockfilterindex=<type>",
 564                   strprintf("Maintain an index of compact filters by block (default: %s, values: %s).", DEFAULT_BLOCKFILTERINDEX, ListBlockFilterTypes()) +
 565                   " If <type> is not supplied or if <type> = 1, certain indexes are enabled (currently just basic).",
 566                   ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
 567  
 568      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);
 569      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);
 570      argsman.AddArg("-bantime=<n>", strprintf("Default duration (in seconds) of manually configured bans (default: %u)", DEFAULT_MISBEHAVING_BANTIME), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
 571      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, testnet3: 127.0.0.1:%u=onion, testnet4: 127.0.0.1:%u=onion, signet: 127.0.0.1:%u=onion, regtest: 127.0.0.1:%u=onion)", defaultChainParams->GetDefaultPort() + 1, testnetChainParams->GetDefaultPort() + 1, testnet4ChainParams->GetDefaultPort() + 1, signetChainParams->GetDefaultPort() + 1, regtestChainParams->GetDefaultPort() + 1), ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::CONNECTION);
 572      argsman.AddArg("-cjdnsreachable", "If set, then this host is configured for CJDNS (connecting to fc00::/8 addresses would lead us to the CJDNS network, see doc/cjdns.md) (default: 0)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
 573      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);
 574      argsman.AddArg("-discover", "Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
 575      argsman.AddArg("-dns", strprintf("Allow DNS lookups for -addnode, -seednode and -connect (default: %u)", DEFAULT_NAME_LOOKUP), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
 576      argsman.AddArg("-dnsseed", strprintf("Query for peer addresses via DNS lookup, if low on addresses (default: %u unless -connect used or -maxconnections=0)", DEFAULT_DNSSEED), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
 577      argsman.AddArg("-externalip=<ip>", "Specify your own public address", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
 578      argsman.AddArg("-feefilter", strprintf("Tell other nodes to filter invs to us by our mempool min fee (default: %u)", DEFAULT_FEEFILTER), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::CONNECTION);
 579      argsman.AddArg("-fixedseeds", strprintf("Allow fixed seeds if DNS seeds don't provide peers (default: %u)", DEFAULT_FIXEDSEEDS), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
 580      argsman.AddArg("-forcednsseed", strprintf("Always query for peer addresses via DNS lookup (default: %u)", DEFAULT_FORCEDNSSEED), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
 581      argsman.AddArg("-listen", strprintf("Accept connections from outside (default: %u if no -proxy, -connect or -maxconnections=0)", DEFAULT_LISTEN), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
 582      argsman.AddArg("-listenonion", strprintf("Automatically create Tor onion service (default: %d)", DEFAULT_LISTEN_ONION), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
 583      argsman.AddArg("-mempoolbridge", "Enable the cross-chain mempool gossip bridge: unify limenka's transaction flow with foreign bitcoin networks (spamchain mainnet, blakecoin, ...). Only transaction gossip crosses - blocks and headers are never exchanged.", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
 584      argsman.AddArg("-bridgepeer=<net>:<host>[:port]", "Peer on a foreign network for the mempool bridge: mainnet, testnet4, signet, regtest, fork. Can be specified multiple times.", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
 585      argsman.AddArg("-maxconnections=<n>", strprintf("Maintain at most <n> automatic 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);
 586      argsman.AddArg("-maxstaleoutbound=<n>", strprintf("Tolerate at most <n> automatic outbound connections to peers running stale consensus rules (default: %u). This limit does not apply to connections manually added via -addnode or the addnode RPC. Connections to full nodes will still be sought and preferred over stale ones.", DEFAULT_MAXSTALEOUTBOUND), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
 587      argsman.AddArg("-maxreceivebuffer=<n>", strprintf("Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)", DEFAULT_MAXRECEIVEBUFFER), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
 588      argsman.AddArg("-maxsendbuffer=<n>", strprintf("Maximum per-connection memory usage for the send buffer, <n>*1000 bytes (default: %u)", DEFAULT_MAXSENDBUFFER), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
 589      argsman.AddArg("-maxuploadtarget=<n>", strprintf("Tries to keep outbound traffic under the given target per 24h. Limit does not apply to peers with 'download' permission or blocks created within past week. 0 = no limit (default: %s). Optional suffix units [k|K|m|M|g|G|t|T] (default: M). Lowercase is 1000 base while uppercase is 1024 base", DEFAULT_MAX_UPLOAD_TARGET), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
 590  #ifdef HAVE_SOCKADDR_UN
 591      argsman.AddArg("-onion=<ip:port|path>", "Use separate SOCKS5 proxy to reach peers via Tor onion services, set -noonion to disable (default: -proxy). May be a local file path prefixed with 'unix:'.", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
 592  #else
 593      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);
 594  #endif
 595      argsman.AddArg("-i2psam=<ip:port>", "I2P SAM proxy to reach I2P peers and accept I2P connections (default: none)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
 596      argsman.AddArg("-i2pacceptincoming", strprintf("Whether to accept inbound I2P connections (default: %i). Ignored if -i2psam is not set. Listening for inbound I2P connections is done through the SAM proxy, not by binding to a local address and port.", DEFAULT_I2P_ACCEPT_INCOMING), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
 597      argsman.AddArg("-onlynet=<net>", "Make automatic outbound connections only to network <net> (" + Join(GetNetworkNames(), ", ") + "). Inbound and manual connections are not affected by this option. It can be specified multiple times to allow multiple networks.", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
 598      argsman.AddArg("-v2transport", strprintf("Support v2 transport (default: %u)", DEFAULT_V2_TRANSPORT), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
 599      argsman.AddArg("-v2onlyclearnet", strprintf("Disallow outbound v1 connections on IPV4/IPV6 (default: %u). Enable this option only if you really need it. Use -listen=0 to disable inbound connections since they can be unencrypted.", false), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::CONNECTION);
 600      argsman.AddArg("-peerbloomfilters", strprintf("Support filtering of blocks and transactions with bloom filters (default: %s)", DEFAULT_PEERBLOOMFILTERS ? "1" : "localhost only"), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
 601      argsman.AddArg("-peerblockfilters", strprintf("Serve compact block filters to peers per BIP 157 (default: %u)", DEFAULT_PEERBLOCKFILTERS), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
 602      argsman.AddArg("-txreconciliation", strprintf("Enable transaction reconciliations per BIP 330 (default: %d)", DEFAULT_TXRECONCILIATION_ENABLE), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::CONNECTION);
 603      argsman.AddArg("-port=<port>", strprintf("Listen for connections on <port> (default: %u, testnet3: %u, testnet4: %u, signet: %u, regtest: %u). Not relevant for I2P (see doc/i2p.md). If set to a value x, the default onion listening port will be set to x+1.", defaultChainParams->GetDefaultPort(), testnetChainParams->GetDefaultPort(), testnet4ChainParams->GetDefaultPort(), signetChainParams->GetDefaultPort(), regtestChainParams->GetDefaultPort()), ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::CONNECTION);
 604      const std::string proxy_doc_for_value =
 605  #ifdef HAVE_SOCKADDR_UN
 606          "<ip>[:<port>]|unix:<path>";
 607  #else
 608          "<ip>[:<port>]";
 609  #endif
 610      const std::string proxy_doc_for_unix_socket =
 611  #ifdef HAVE_SOCKADDR_UN
 612          "May be a local file path prefixed with 'unix:' if the proxy supports it. ";
 613  #else
 614          "";
 615  #endif
 616      argsman.AddArg("-proxy=" + proxy_doc_for_value + "[=<network>]",
 617                     "Connect through SOCKS5 proxy, set -noproxy to disable. " +
 618                     proxy_doc_for_unix_socket +
 619                     "Could end in =network to set the proxy only for that network. " +
 620                     "The network can be any of ipv4, ipv6, tor or cjdns. " +
 621                     "(default: disabled)",
 622                     ArgsManager::ALLOW_ANY | ArgsManager::DISALLOW_ELISION,
 623                     OptionsCategory::CONNECTION);
 624      argsman.AddArg("-proxyrandomize", strprintf("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)", DEFAULT_PROXYRANDOMIZE), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
 625      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. During startup, seednodes will be tried before dnsseeds.", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
 626      argsman.AddArg("-networkactive", "Enable all P2P network activity (default: 1). Can be changed by the setnetworkactive RPC command", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
 627      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);
 628      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);
 629      argsman.AddArg("-torcontrol=<ip>:<port>", strprintf("Tor control host and port to use if onion listening enabled (default: %s). If no port is specified, the default port of %i will be used.", DEFAULT_TOR_CONTROL, DEFAULT_TOR_CONTROL_PORT), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
 630  #ifdef ENABLE_TOR_SUBPROCESS
 631      argsman.AddArg("-torexecute=<command>", strprintf("Tor command to use if not already running (default: %s)", DEFAULT_TOR_EXECUTE), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
 632  #else
 633      hidden_args.emplace_back("-torexecute=<command>");
 634  #endif
 635      argsman.AddArg("-torpassword=<pass>", "Tor control port password (default: empty)", ArgsManager::ALLOW_ANY | ArgsManager::SENSITIVE, OptionsCategory::CONNECTION);
 636  #ifdef USE_UPNP
 637      argsman.AddArg("-upnp", strprintf("Use UPnP to map the listening port (default: %u)", DEFAULT_UPNP), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
 638  #else
 639      hidden_args.emplace_back("-upnp");
 640  #endif
 641      argsman.AddArg("-natpmp", strprintf("Use PCP or NAT-PMP to map the listening port (default: %u)", DEFAULT_NATPMP), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
 642      argsman.AddArg("-whitebind=<[permissions@]addr>", "Bind to the given address and add permission flags to the peers connecting to it. "
 643          "Use [host]:port notation for IPv6. Allowed permissions: " + Join(NET_PERMISSIONS_DOC, ", ") + ". "
 644          "Specify multiple permissions separated by commas (default: download,noban,mempool,relay). Can be specified multiple times.", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
 645  
 646      argsman.AddArg("-whitelist=<[permissions@]IP address or network>", "Add permission flags to the peers using the given IP address (e.g. 1.2.3.4) or "
 647          "CIDR-notated network (e.g. 1.2.3.0/24). Uses the same permissions as "
 648          "-whitebind. "
 649          "Additional flags \"in\" and \"out\" control whether permissions apply to incoming connections and/or outgoing (default: incoming only). "
 650          "Can be specified multiple times.", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
 651  
 652      g_wallet_init_interface.AddWalletOptions(argsman);
 653  
 654  #ifdef ENABLE_ZMQ
 655      argsman.AddArg("-zmqpubhashblock=<address>", "Enable publish hash block in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
 656      argsman.AddArg("-zmqpubhashtx=<address>", "Enable publish hash transaction in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
 657      argsman.AddArg("-zmqpubhashwallettx=<address>", "Enable publish hash wallet transaction in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
 658      argsman.AddArg("-zmqpubrawblock=<address>", "Enable publish raw block in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
 659      argsman.AddArg("-zmqpubrawtx=<address>", "Enable publish raw transaction in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
 660      argsman.AddArg("-zmqpubrawwallettx=<address>", "Enable publish raw wallet transaction in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
 661      argsman.AddArg("-zmqpubsequence=<address>", "Enable publish hash block and tx sequence in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
 662      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);
 663      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);
 664      argsman.AddArg("-zmqpubhashwallettxhwm=<n>", strprintf("Set publish hash wallet transaction outbound message high water mark (default: %d)", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM), ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
 665      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);
 666      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);
 667      argsman.AddArg("-zmqpubrawwallettxhwm=<n>", strprintf("Set publish raw wallet transaction outbound message high water mark (default: %d)", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM), ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
 668      argsman.AddArg("-zmqpubsequencehwm=<n>", strprintf("Set publish hash sequence message high water mark (default: %d)", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM), ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
 669  #else
 670      hidden_args.emplace_back("-zmqpubhashblock=<address>");
 671      hidden_args.emplace_back("-zmqpubhashtx=<address>");
 672      hidden_args.emplace_back("-zmqpubhashwallettx=<address>");
 673      hidden_args.emplace_back("-zmqpubrawblock=<address>");
 674      hidden_args.emplace_back("-zmqpubrawtx=<address>");
 675      hidden_args.emplace_back("-zmqpubrawwallettx=<address>");
 676      hidden_args.emplace_back("-zmqpubsequence=<n>");
 677      hidden_args.emplace_back("-zmqpubhashblockhwm=<n>");
 678      hidden_args.emplace_back("-zmqpubhashtxhwm=<n>");
 679      hidden_args.emplace_back("-zmqpubhashwallettxhwm=<n>");
 680      hidden_args.emplace_back("-zmqpubrawblockhwm=<n>");
 681      hidden_args.emplace_back("-zmqpubrawtxhwm=<n>");
 682      hidden_args.emplace_back("-zmqpubrawwallettxhwm=<n>");
 683      hidden_args.emplace_back("-zmqpubsequencehwm=<n>");
 684  #endif
 685  
 686      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);
 687      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);
 688      argsman.AddArg("-checkblockindex", strprintf("Do a consistency check for the block tree, chainstate, and other validation data structures every <n> operations. Use 0 to disable. (default: %u, regtest: %u)", defaultChainParams->DefaultConsistencyChecks(), regtestChainParams->DefaultConsistencyChecks()), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
 689      argsman.AddArg("-checkaddrman=<n>", strprintf("Run addrman consistency checks every <n> operations. Use 0 to disable. (default: %u)", DEFAULT_ADDRMAN_CONSISTENCY_CHECKS), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
 690      argsman.AddArg("-checkmempool=<n>", strprintf("Run mempool consistency checks every <n> transactions. Use 0 to disable. (default: %u, regtest: %u)", defaultChainParams->DefaultConsistencyChecks(), regtestChainParams->DefaultConsistencyChecks()), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
 691      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);
 692      argsman.AddArg("-deprecatedrpc=<method>", "Allows deprecated RPC method(s) to be used", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
 693      argsman.AddArg("-stopafterblockimport", strprintf("Stop running after importing blocks from disk (default: %u)", DEFAULT_STOPAFTERBLOCKIMPORT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
 694      argsman.AddArg("-stopatheight", strprintf("Stop running after reaching the given height in the main chain (default: %u). Blocks after target height may be processed during shutdown.", DEFAULT_STOPATHEIGHT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
 695      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);
 696      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_KVB), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
 697      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);
 698      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_KVB), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
 699      argsman.AddArg("-test=<option>", "Pass a test-only option. Options include : " + Join(TEST_OPTIONS_DOC, ", ") + ".", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
 700      argsman.AddArg("-capturemessages", "Capture all P2P messages to disk", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
 701      argsman.AddArg("-mocktime=<n>", "Replace actual time with " + UNIX_EPOCH_TIME + " (default: 0)", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
 702      argsman.AddArg("-maxsigcachesize=<n>", strprintf("Limit sum of signature cache and script execution cache sizes to <n> MiB (default: %u)", DEFAULT_VALIDATION_CACHE_BYTES >> 20), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
 703      argsman.AddArg("-maxtipage=<n>",
 704                     strprintf("Maximum tip age in seconds to consider node in initial block download (default: %u)",
 705                               Ticks<std::chrono::seconds>(DEFAULT_MAX_TIP_AGE)),
 706                     ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
 707      argsman.AddArg("-printpriority", strprintf("Log transaction priority and fee rate in %s/kvB when mining blocks (default: %u)", CURRENCY_UNIT, DEFAULT_PRINT_MODIFIED_FEE), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
 708      argsman.AddArg("-uaappend=<uafragment>", "Append literal string to the user agent string (should only be used for software embedding)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
 709      argsman.AddArg("-uacomment=<cmt>", "Append comment to the user agent string", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
 710      argsman.AddArg("-uaspoof=<ua>", strprintf("Replace entire user agent string with custom identifier (should be formatted '%s' as specified in BIP 14)", BIP14_EXAMPLE_UA), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::CONNECTION);
 711  
 712      SetupChainParamsBaseOptions(argsman);
 713      argsman.AddArg("-consensusrules=<rules>", strprintf("Enforce the specified consensus rules (default: none). Must be %s to use this software.", CONSENSUSRULES_REQUIRED), ArgsManager::ALLOW_ANY, OptionsCategory::CHAINPARAMS);
 714      argsman.AddArg("-rdts_consent_flag=<n>", strprintf("Test RDTS consent flag <n> (default: %u)", static_cast<int64_t>(g_rdts_consent)), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
 715  
 716      argsman.AddArg("-acceptnonstddatacarrier",
 717                     strprintf("Relay and mine non-OP_RETURN datacarrier injection (default: %u)",
 718                               DEFAULT_ACCEPT_NON_STD_DATACARRIER),
 719                     ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
 720      argsman.AddArg("-acceptnonstdtxn", strprintf("Relay and mine \"non-standard\" transactions (default: %u)", DEFAULT_ACCEPT_NON_STD_TXN), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
 721      argsman.AddArg("-acceptunknownwitness",
 722                     strprintf("Relay transactions sending to unknown/future witness script versions (default: %u)", DEFAULT_ACCEPTUNKNOWNWITNESS),
 723                     ArgsManager::ALLOW_ANY,
 724                     OptionsCategory::NODE_RELAY);
 725      argsman.AddArg("-incrementalrelayfee=<amt>", strprintf("Fee rate (in %s/kvB) used to define cost of relay, used for mempool limiting and replacement policy. (default: %s)", CURRENCY_UNIT, FormatMoney(DEFAULT_INCREMENTAL_RELAY_FEE)), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::NODE_RELAY);
 726      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, OptionsCategory::NODE_RELAY);
 727      argsman.AddArg("-dustdynamic=off|[<multiplier>*]target:<blocks>|[<multiplier>*]mempool:<kvB>",
 728                     strprintf("Automatically raise dustrelayfee based on either the expected fee to be mined within <blocks> blocks, or to be within the best <kvB> kvB of this node's mempool. If unspecified, multiplier is %s. (default: %s)",
 729                               DEFAULT_DUST_RELAY_MULTIPLIER / 1000.,
 730                               DEFAULT_DUST_DYNAMIC), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
 731      argsman.AddArg("-acceptstalefeeestimates", strprintf("Read fee estimates even if they are stale (%sdefault: %u) fee estimates are considered stale if they are %s hours old", "regtest only; ", DEFAULT_ACCEPT_STALE_FEE_ESTIMATES, Ticks<std::chrono::hours>(MAX_FILE_AGE)), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
 732      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);
 733      argsman.AddArg("-bytespersigopstrict", strprintf("Minimum bytes per sigop in transactions we relay and mine (default: %u)", DEFAULT_BYTES_PER_SIGOP_STRICT), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
 734      argsman.AddArg("-datacarrier", strprintf("Relay and mine data carrier transactions (default: %u)", DEFAULT_ACCEPT_DATACARRIER), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
 735      argsman.AddArg("-datacarriercost", strprintf("Treat extra data in transactions as at least N vbytes per actual byte (default: %s)", DEFAULT_WEIGHT_PER_DATA_BYTE / 4.0), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
 736      argsman.AddArg("-datacarrierfullcount", strprintf("Apply datacarriersize limit to all known datacarrier methods (default: %u)", DEFAULT_DATACARRIER_FULLCOUNT), ArgsManager::ALLOW_ANY | (DEFAULT_DATACARRIER_FULLCOUNT ? uint32_t{ArgsManager::DEBUG_ONLY} : 0), OptionsCategory::NODE_RELAY);
 737      argsman.AddArg("-datacarriersize",
 738                     strprintf("Maximum size of data in data carrier transactions we relay and mine, in bytes (maximum %s, default: %u)",
 739                               MAX_OUTPUT_DATA_SIZE,
 740                               MAX_OP_RETURN_RELAY),
 741                     ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
 742      argsman.AddArg("-maxscriptsize", strprintf("Maximum size of scripts (including the entire witness stack) we relay and mine, in bytes (default: %s)", DEFAULT_SCRIPT_SIZE_POLICY_LIMIT), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
 743      argsman.AddArg("-maxtxlegacysigops",
 744                     strprintf("Maximum number of legacy sigops allowed in transactions we relay and mine, as measured by BIP54 (default: %s)",
 745                               MAX_TX_LEGACY_SIGOPS),
 746                     ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
 747      argsman.AddArg("-mempoolfullrbf", strprintf("Accept transaction replace-by-fee without requiring replaceability signaling (default: %u)", (DEFAULT_MEMPOOL_RBF_POLICY == RBFPolicy::Always)), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
 748      argsman.AddArg("-mempoolreplacement", strprintf("Set to 0 to disable RBF entirely, \"fee,optin\" to honour RBF opt-out signal, or \"fee,-optin\" to always RBF aka full RBF (default: %s)", "fee,-optin"), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
 749      argsman.AddArg("-mempooltruc", strprintf("Behaviour for transactions requesting TRUC limits: \"reject\" the transactions entirely, \"accept\" them just like any other, or \"enforce\" to impose their requested restrictions (default: %s)", "accept"), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
 750      argsman.AddArg("-permitbareanchor",
 751                     strprintf("Relay transactions that only have ephemeral anchor outputs (default: %u)", DEFAULT_PERMITBAREANCHOR),
 752                     ArgsManager::ALLOW_ANY,
 753                     OptionsCategory::NODE_RELAY);
 754      argsman.AddArg("-permitbaredatacarrier",
 755                     strprintf("Relay transactions that only have data carrier outputs (default: %u)", DEFAULT_PERMITBAREDATACARRIER),
 756                     ArgsManager::ALLOW_ANY,
 757                     OptionsCategory::NODE_RELAY);
 758      argsman.AddArg("-permitbarepubkey", strprintf("Relay legacy pubkey outputs (default: %u)", DEFAULT_PERMIT_BAREPUBKEY), ArgsManager::ALLOW_ANY,
 759                     OptionsCategory::NODE_RELAY);
 760      argsman.AddArg("-permitbaremultisig", strprintf("Relay transactions creating non-P2SH multisig outputs (default: %u)", DEFAULT_PERMIT_BAREMULTISIG), ArgsManager::ALLOW_ANY,
 761                     OptionsCategory::NODE_RELAY);
 762      argsman.AddArg("-permitephemeral=<options>",
 763                     strprintf("Relay transaction packages that include ephemeral outputs defined by comma-separated options (prefix each by '-' to force off): \"anchor\" to allow minimal anyone-can-spend anchors, \"send\" to allow ordinary output types to be considered ephemeral, and \"dust\" to allow for dust-amount outputs rather than strictly zero-value (default: %s)", "anchor,-send,-dust"),
 764                     ArgsManager::ALLOW_ANY,
 765                     OptionsCategory::NODE_RELAY);
 766      argsman.AddArg("-minrelaycoinblocks=<n>",
 767                     strprintf("Minimum \"coin blocks\" (measured in %s per block) that a transaction must be spending to be relayed (default: %s)",
 768                               CURRENCY_ATOM,
 769                               DEFAULT_MINRELAYCOINBLOCKS),
 770                     ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
 771      argsman.AddArg("-minrelaymaturity=<n>",
 772                     strprintf("Minimum number of blocks that inputs must mature before being spent in transactions we relay (default: %s)",
 773                               DEFAULT_MINRELAYMATURITY),
 774                     ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
 775      argsman.AddArg("-minrelaytxfee=<amt>", strprintf("Fees (in %s/kvB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)",
 776          CURRENCY_UNIT, FormatMoney(DEFAULT_MIN_RELAY_TX_FEE)), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
 777      argsman.AddArg("-rejectparasites", strprintf("Refuse to relay or mine parasitic overlay protocols (default: %u)", DEFAULT_REJECT_PARASITES), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
 778      argsman.AddArg("-rejecttokens",
 779                     strprintf("Refuse to relay or mine transactions involving non-limenka tokens (default: %u)",
 780                               DEFAULT_REJECT_TOKENS),
 781                     ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
 782      argsman.AddArg("-subdustfeepenalty",
 783                     strprintf("Reduce effective fee by the dust threshold for each sub-dust output, making dust-creating transactions require higher fees (default: %u)",
 784                               DEFAULT_SUBDUSTFEEPENALTY),
 785                     ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
 786      argsman.AddArg("-spkreuse=<policy>", strprintf("Either \"allow\" to relay/mine transactions reusing addresses or other pubkey scripts, or \"conflict\" to treat them as exclusive prior to being mined (default: %s)", DEFAULT_SPKREUSE), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
 787      argsman.AddArg("-whitelistforcerelay", strprintf("Add 'forcerelay' permission to whitelisted 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);
 788      argsman.AddArg("-whitelistrelay", strprintf("Add 'relay' permission to whitelisted peers with default permissions. This will accept relayed transactions even when not relaying transactions (default: %d)", DEFAULT_WHITELISTRELAY), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
 789  
 790  
 791      argsman.AddArg("-blockmaxsize=<n>", strprintf("Set maximum block size in bytes (default: %d)", DEFAULT_BLOCK_MAX_SIZE), ArgsManager::ALLOW_ANY, OptionsCategory::BLOCK_CREATION);
 792      argsman.AddArg("-blockmaxweight=<n>", strprintf("Set maximum BIP141 block weight (default: %d)", DEFAULT_BLOCK_MAX_WEIGHT), ArgsManager::ALLOW_ANY, OptionsCategory::BLOCK_CREATION);
 793      argsman.AddArg("-blockreservedweight=<n>", strprintf("Reserve space for the fixed-size block header plus the largest coinbase transaction the mining software may add to the block. (default: %d).", DEFAULT_BLOCK_RESERVED_WEIGHT), ArgsManager::ALLOW_ANY, OptionsCategory::BLOCK_CREATION);
 794      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);
 795      argsman.AddArg("-blockprioritysize=<n>", strprintf("Set maximum size of high-priority/low-fee transactions in bytes (default: %d)", DEFAULT_BLOCK_PRIORITY_SIZE), ArgsManager::ALLOW_ANY, OptionsCategory::BLOCK_CREATION);
 796      argsman.AddArg("-blockversion=<n>", "Override block version to test forking scenarios", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::BLOCK_CREATION);
 797  
 798      argsman.AddArg("-rest", strprintf("Accept public REST requests (default: %u)", DEFAULT_REST_ENABLE), ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
 799      argsman.AddArg("-rpcallowip=<ip>", "Allow JSON-RPC connections from specified source. Valid values 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), a network/CIDR (e.g. 1.2.3.4/24), all ipv4 (0.0.0.0/0), or all ipv6 (::/0). RFC4193 is allowed only if -cjdnsreachable=0. This option can be specified multiple times", ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
 800      argsman.AddArg("-rpcauth=<userpw>[:wallet]",
 801                     "Username and HMAC-SHA-256 hashed password for JSON-RPC connections. "
 802                     "The field <userpw> comes in the format: <USERNAME>:<SALT>$<HASH>. "
 803                     "A canonical python script is included in share/rpcauth. "
 804                     "The client then connects normally using the rpcuser=<USERNAME>/rpcpassword=<PASSWORD> pair of arguments. "
 805                     "A single wallet name can also be specified to restrict access to only that wallet, or '-' to deny all wallet access. "
 806                     "This option can be specified multiple times",
 807                     ArgsManager::ALLOW_ANY | ArgsManager::SENSITIVE, OptionsCategory::RPC);
 808      argsman.AddArg("-rpcauthfile=<userpw>", "A file with a single lines with same format as rpcauth. This option can be specified multiple times", ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
 809      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, OptionsCategory::RPC);
 810      argsman.AddArg("-rpcdoccheck", strprintf("Throw a non-fatal error at runtime if the documentation for an RPC is incorrect (default: %u)", DEFAULT_RPC_DOC_CHECK), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::RPC);
 811      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);
 812      argsman.AddArg("-rpccookieperms=<readable-by>", strprintf("Set permissions on the RPC auth cookie file so that it is readable by [owner|group|all] (default: owner [via umask 0077])"), ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
 813      argsman.AddArg("-rpcpassword=<pw>", "Password for JSON-RPC connections", ArgsManager::ALLOW_ANY | ArgsManager::SENSITIVE, OptionsCategory::RPC);
 814      argsman.AddArg("-rpcport=<port>", strprintf("Listen for JSON-RPC connections on <port> (default: %u, testnet3: %u, testnet4: %u, signet: %u, regtest: %u)", defaultBaseParams->RPCPort(), testnetBaseParams->RPCPort(), testnet4BaseParams->RPCPort(), signetBaseParams->RPCPort(), regtestBaseParams->RPCPort()), ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::RPC);
 815      argsman.AddArg("-rpcservertimeout=<n>", strprintf("Timeout during HTTP requests (default: %d)", DEFAULT_HTTP_SERVER_TIMEOUT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::RPC);
 816      argsman.AddArg("-rpcthreads=<n>", strprintf("Set the number of threads to service RPC calls (default: %d)", DEFAULT_HTTP_THREADS), ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
 817      argsman.AddArg("-rpcuser=<user>", "Username for JSON-RPC connections", ArgsManager::ALLOW_ANY | ArgsManager::SENSITIVE, OptionsCategory::RPC);
 818      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);
 819      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_ANY, OptionsCategory::RPC);
 820      argsman.AddArg("-rpcworkqueue=<n>", strprintf("Set the maximum depth of the work queue to service RPC calls (default: %d)", DEFAULT_HTTP_WORKQUEUE), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::RPC);
 821      argsman.AddArg("-server", "Accept command line and JSON-RPC commands", ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
 822      if (can_listen_ipc) {
 823          argsman.AddArg("-ipcbind=<address>", "Bind to Unix socket address and listen for incoming connections. Valid address values are \"unix\" to listen on the default path, <datadir>/node.sock, or \"unix:/custom/path\" to specify a custom path. Can be specified multiple times to listen on multiple paths. Default behavior is not to listen on any path. If relative paths are specified, they are interpreted relative to the network data directory. If paths include any parent directory components and the parent directories do not exist, they will be created.", ArgsManager::ALLOW_ANY, OptionsCategory::IPC);
 824      }
 825  
 826  #if HAVE_DECL_FORK
 827      argsman.AddArg("-daemon", strprintf("Run in the background as a daemon and accept commands (default: %d)", DEFAULT_DAEMON), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
 828      argsman.AddArg("-daemonwait", strprintf("Wait for initialization to be finished before exiting. This implies -daemon (default: %d)", DEFAULT_DAEMONWAIT), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
 829  #else
 830      hidden_args.emplace_back("-daemon");
 831      hidden_args.emplace_back("-daemonwait");
 832  #endif
 833  
 834      CStats::AddStatsOptions();
 835  
 836      // Add the hidden options
 837      argsman.AddHiddenArgs(hidden_args);
 838  }
 839  
 840  #if HAVE_SYSTEM
 841  static void StartupNotify(const ArgsManager& args)
 842  {
 843      for (const std::string& command : args.GetArgs("-startupnotify")) {
 844          std::thread t(runCommand, command);
 845          t.detach(); // thread runs free
 846      }
 847  }
 848  #endif
 849  
 850  static bool AppInitServers(NodeContext& node)
 851  {
 852      const ArgsManager& args = *Assert(node.args);
 853      if (!InitHTTPServer(*Assert(node.shutdown_signal))) {
 854          return false;
 855      }
 856      StartRPC();
 857      node.rpc_interruption_point = RpcInterruptionPoint;
 858      if (!StartHTTPRPC(&node))
 859          return false;
 860      if (args.GetBoolArg("-rest", DEFAULT_REST_ENABLE)) StartREST(&node);
 861      StartHTTPServer();
 862      return true;
 863  }
 864  
 865  // Parameter interaction based on rules
 866  void InitParameterInteraction(ArgsManager& args)
 867  {
 868      // Before any SoftSetArg so we get the actual user-set value
 869      g_pcp_warn_for_unauthorized = args.GetBoolArg("-natpmp", false);
 870  
 871      if (args.GetBoolArg("-corepolicy", DEFAULT_COREPOLICY)) {
 872          args.SoftSetArg("-incrementalrelayfee", FormatMoney(CORE_INCREMENTAL_RELAY_FEE));
 873          if (!args.IsArgSet("-minrelaytxfee")) {
 874              args.ForceSetArg("-minrelaytxfee", FormatMoney(std::max(ParseMoney(args.GetArg("-incrementalrelayfee", "")).value_or(0), CORE_INCREMENTAL_RELAY_FEE)));
 875          }
 876          args.SoftSetArg("-blockmintxfee", "0.00000001");
 877          args.SoftSetArg("-acceptnonstddatacarrier", "1");
 878          args.SoftSetArg("-blockreconstructionextratxn", "100");
 879          args.SoftSetArg("-blockreconstructionextratxnsize", strprintf("%s", std::numeric_limits<size_t>::max() / 1000000 + 1));
 880          args.SoftSetArg("-bytespersigopstrict", "0");
 881          args.SoftSetArg("-permitbaredatacarrier", "1");
 882          args.SoftSetArg("-permitbarepubkey", "1");
 883          args.SoftSetArg("-permitbaremultisig", "1");
 884          args.SoftSetArg("-rejectparasites", "0");
 885          args.SoftSetArg("-subdustfeepenalty", "0");
 886          args.SoftSetArg("-datacarriercost", "0.25");
 887          args.SoftSetArg("-datacarrierfullcount", "0");
 888          args.SoftSetArg("-maxtxlegacysigops", strprintf("%s", std::numeric_limits<unsigned int>::max()));
 889          args.SoftSetArg("-maxscriptsize", strprintf("%s", std::numeric_limits<unsigned int>::max()));
 890          args.SoftSetArg("-mempooltruc", "enforce");
 891          args.SoftSetArg("-permitephemeral", "anchor,send,dust");
 892          args.SoftSetArg("-spkreuse", "allow");
 893          args.SoftSetArg("-blockprioritysize", "0");
 894          args.SoftSetArg("-blockmaxsize", "4000000");
 895          args.SoftSetArg("-blockmaxweight", "4000000");
 896          LogWarning("-corepolicy=1 weakens relay security. Non-standard transactions may be accepted into the mempool. Use only on test networks.\n");
 897      }
 898  
 899      // when specifying an explicit binding address, you want to listen on it
 900      // even when -connect or -proxy is specified
 901      if (!args.GetArgs("-bind").empty()) {
 902          if (args.SoftSetBoolArg("-listen", true))
 903              LogInfo("parameter interaction: -bind set -> setting -listen=1\n");
 904      }
 905      if (!args.GetArgs("-whitebind").empty()) {
 906          if (args.SoftSetBoolArg("-listen", true))
 907              LogInfo("parameter interaction: -whitebind set -> setting -listen=1\n");
 908      }
 909  
 910      if (!args.GetArgs("-connect").empty() || args.IsArgNegated("-connect") || args.GetIntArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS) <= 0) {
 911          // when only connecting to trusted nodes, do not seed via DNS, or listen by default
 912          // do the same when connections are disabled
 913          if (args.SoftSetBoolArg("-dnsseed", false))
 914              LogInfo("parameter interaction: -connect or -maxconnections=0 set -> setting -dnsseed=0\n");
 915          if (args.SoftSetBoolArg("-listen", false))
 916              LogInfo("parameter interaction: -connect or -maxconnections=0 set -> setting -listen=0\n");
 917      }
 918  
 919      std::string proxy_arg = args.GetArg("-proxy", "");
 920      if (proxy_arg != "" && proxy_arg != "0") {
 921          // to protect privacy, do not listen by default if a default proxy server is specified
 922          if (args.SoftSetBoolArg("-listen", false))
 923              LogInfo("parameter interaction: -proxy set -> setting -listen=0\n");
 924          // to protect privacy, do not map ports when a proxy is set. The user may still specify -listen=1
 925          // to listen locally, so don't rely on this happening through -listen below.
 926          if (args.SoftSetBoolArg("-upnp", false))
 927              LogInfo("parameter interaction: -proxy set -> setting -upnp=0\n");
 928          if (args.SoftSetBoolArg("-natpmp", false)) {
 929              LogInfo("parameter interaction: -proxy set -> setting -natpmp=0\n");
 930          }
 931          // to protect privacy, do not discover addresses by default
 932          if (args.SoftSetBoolArg("-discover", false))
 933              LogInfo("parameter interaction: -proxy set -> setting -discover=0\n");
 934      }
 935  
 936      if (!args.GetBoolArg("-listen", DEFAULT_LISTEN)) {
 937          // do not map ports or try to retrieve public IP when not listening (pointless)
 938          if (args.GetBoolArg("-upnp", DEFAULT_UPNP)) {
 939              args.ForceSetArg("-upnp", "0");
 940              LogInfo("parameter interaction: -listen=0 -> setting -upnp=0\n");
 941          }
 942          if (args.GetBoolArg("-natpmp", DEFAULT_NATPMP)) {
 943              args.ForceSetArg("-natpmp", "0");
 944              LogInfo("parameter interaction: -listen=0 -> setting -natpmp=0\n");
 945          }
 946          if (args.SoftSetBoolArg("-discover", false))
 947              LogInfo("parameter interaction: -listen=0 -> setting -discover=0\n");
 948          if (args.SoftSetBoolArg("-listenonion", false))
 949              LogInfo("parameter interaction: -listen=0 -> setting -listenonion=0\n");
 950          if (args.SoftSetBoolArg("-i2pacceptincoming", false)) {
 951              LogInfo("parameter interaction: -listen=0 -> setting -i2pacceptincoming=0\n");
 952          }
 953      }
 954  
 955      if (!args.GetArgs("-externalip").empty()) {
 956          // if an explicit public IP is specified, do not try to find others
 957          if (args.SoftSetBoolArg("-discover", false))
 958              LogInfo("parameter interaction: -externalip set -> setting -discover=0\n");
 959      }
 960  
 961      if (args.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)) {
 962          // disable whitelistrelay in blocksonly mode
 963          if (args.SoftSetBoolArg("-whitelistrelay", false))
 964              LogInfo("parameter interaction: -blocksonly=1 -> setting -whitelistrelay=0\n");
 965          // Reduce default mempool size in blocksonly mode to avoid unexpected resource usage
 966          if (args.SoftSetArg("-maxmempool", ToString(DEFAULT_BLOCKSONLY_MAX_MEMPOOL_SIZE_MB)))
 967              LogInfo("parameter interaction: -blocksonly=1 -> setting -maxmempool=%d\n", DEFAULT_BLOCKSONLY_MAX_MEMPOOL_SIZE_MB);
 968      }
 969  
 970      // Forcing relay from whitelisted hosts implies we will accept relays from them in the first place.
 971      if (args.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
 972          if (args.SoftSetBoolArg("-whitelistrelay", true))
 973              LogInfo("parameter interaction: -whitelistforcerelay=1 -> setting -whitelistrelay=1\n");
 974      }
 975      const auto onlynets = args.GetArgs("-onlynet");
 976      if (!onlynets.empty()) {
 977          bool clearnet_reachable = std::any_of(onlynets.begin(), onlynets.end(), [](const auto& net) {
 978              const auto n = ParseNetwork(net);
 979              return n == NET_IPV4 || n == NET_IPV6;
 980          });
 981          if (!clearnet_reachable && args.SoftSetBoolArg("-dnsseed", false)) {
 982              LogInfo("parameter interaction: -onlynet excludes IPv4 and IPv6 -> setting -dnsseed=0\n");
 983          }
 984      }
 985  }
 986  
 987  /**
 988   * Initialize global loggers.
 989   *
 990   * Note that this is called very early in the process lifetime, so you should be
 991   * careful about what global state you rely on here.
 992   */
 993  void InitLogging(const ArgsManager& args)
 994  {
 995      init::SetLoggingOptions(args);
 996      init::LogPackageVersion();
 997  }
 998  
 999  namespace { // Variables internal to initialization process only
1000  
1001  int nMaxConnections;
1002  int available_fds;
1003  ServiceFlags g_local_services = ServiceFlags(NODE_NETWORK_LIMITED | NODE_WITNESS | NODE_REDUCED_DATA | NODE_P2SPKH);
1004  int64_t peer_connect_timeout;
1005  std::set<BlockFilterType> g_enabled_filter_types;
1006  
1007  } // namespace
1008  
1009  [[noreturn]] static void new_handler_terminate()
1010  {
1011      // Rather than throwing std::bad-alloc if allocation fails, terminate
1012      // immediately to (try to) avoid chain corruption.
1013      // Since logging may itself allocate memory, set the handler directly
1014      // to terminate first.
1015      std::set_new_handler(std::terminate);
1016      LogError("Out of memory. Terminating.\n");
1017  
1018      // The log was successful, terminate now.
1019      std::terminate();
1020  };
1021  
1022  bool AppInitBasicSetup(const ArgsManager& args, std::atomic<int>& exit_status)
1023  {
1024      // ********************************************************* Step 1: setup
1025  #ifdef _MSC_VER
1026      // Turn off Microsoft heap dump noise
1027      _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
1028      _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, 0));
1029      // Disable confusing "helpful" text message on abort, Ctrl-C
1030      _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
1031  #endif
1032  #ifdef WIN32
1033      // Enable heap terminate-on-corruption
1034      HeapSetInformation(nullptr, HeapEnableTerminationOnCorruption, nullptr, 0);
1035  #endif
1036      if (!SetupNetworking()) {
1037          return InitError(Untranslated("Initializing networking failed."));
1038      }
1039  
1040  #ifndef WIN32
1041      // Clean shutdown on SIGTERM
1042      registerSignalHandler(SIGTERM, HandleSIGTERM);
1043      registerSignalHandler(SIGINT, HandleSIGTERM);
1044  
1045      // Reopen debug.log on SIGHUP
1046      registerSignalHandler(SIGHUP, HandleSIGHUP);
1047  
1048      // Ignore SIGPIPE, otherwise it will bring the daemon down if the client closes unexpectedly
1049      signal(SIGPIPE, SIG_IGN);
1050  #else
1051      SetConsoleCtrlHandler(consoleCtrlHandler, true);
1052  #endif
1053  
1054      std::set_new_handler(new_handler_terminate);
1055  
1056      return true;
1057  }
1058  
1059  bool AppInitParameterInteraction(const ArgsManager& args)
1060  {
1061      const CChainParams& chainparams = Params();
1062      // ********************************************************* Step 2: parameter interactions
1063  
1064      // also see: InitParameterInteraction()
1065  
1066      // Error if network-specific options (-addnode, -connect, etc) are
1067      // specified in default section of config file, but not overridden
1068      // on the command line or in this chain's section of the config file.
1069      ChainType chain = args.GetChainType();
1070      if (chain == ChainType::SIGNET) {
1071          LogPrintf("Signet derived magic (message start): %s\n", HexStr(chainparams.MessageStart()));
1072      }
1073      bilingual_str errors;
1074      for (const auto& arg : args.GetUnsuitableSectionOnlyArgs()) {
1075          errors += strprintf(_("Config setting for %s only applied on %s network when in [%s] section."), arg, ChainTypeToString(chain), ChainTypeToString(chain)) + Untranslated("\n");
1076      }
1077  
1078      if (!errors.empty()) {
1079          return InitError(errors);
1080      }
1081  
1082      // Testnet3 deprecation warning
1083      if (chain == ChainType::TESTNET) {
1084          LogInfo("Warning: Support for testnet3 is deprecated and will be removed in an upcoming release. Consider switching to testnet4.\n");
1085      }
1086  
1087      // Warn if unrecognized section name are present in the config file.
1088      bilingual_str warnings;
1089      for (const auto& section : args.GetUnrecognizedSections()) {
1090          warnings += Untranslated(strprintf("%s:%i ", section.m_file, section.m_line)) + strprintf(_("Section [%s] is not recognized."), section.m_name) + Untranslated("\n");
1091      }
1092  
1093      if (!warnings.empty()) {
1094          InitWarning(warnings);
1095      }
1096  
1097      if (!fs::is_directory(args.GetBlocksDirPath())) {
1098          return InitError(strprintf(_("Specified blocks directory \"%s\" does not exist."), args.GetArg("-blocksdir", "")));
1099      }
1100  
1101      // parse and validate enabled filter types
1102      std::string blockfilterindex_value = args.GetArg("-blockfilterindex", DEFAULT_BLOCKFILTERINDEX);
1103      if (blockfilterindex_value == "" || blockfilterindex_value == "1") {
1104          g_enabled_filter_types = {BlockFilterType::BASIC};
1105      } else if (blockfilterindex_value != "0") {
1106          const std::vector<std::string> names = args.GetArgs("-blockfilterindex");
1107          for (const auto& name : names) {
1108              BlockFilterType filter_type;
1109              if (!BlockFilterTypeByName(name, filter_type)) {
1110                  return InitError(strprintf(_("Unknown -blockfilterindex value %s."), name));
1111              }
1112              g_enabled_filter_types.insert(filter_type);
1113          }
1114      }
1115  
1116      // Signal NODE_P2P_V2 if BIP324 v2 transport is enabled.
1117      if (args.GetBoolArg("-v2transport", DEFAULT_V2_TRANSPORT)) {
1118          g_local_services = ServiceFlags(g_local_services | NODE_P2P_V2);
1119      } else if (args.GetBoolArg("-v2onlyclearnet", false)) {
1120          return InitError(_("Cannot set -v2onlyclearnet to true when v2transport is disabled."));
1121      }
1122  
1123      // Signal NODE_COMPACT_FILTERS if peerblockfilters and basic filters index are both enabled.
1124      if (args.GetBoolArg("-peerblockfilters", DEFAULT_PEERBLOCKFILTERS)) {
1125          if (g_enabled_filter_types.count(BlockFilterType::BASIC) != 1) {
1126              return InitError(_("Cannot set -peerblockfilters without -blockfilterindex."));
1127          }
1128  
1129          g_local_services = ServiceFlags(g_local_services | NODE_COMPACT_FILTERS);
1130      }
1131  
1132      if (args.GetIntArg("-prune", 0)) {
1133          if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX))
1134              return InitError(_("Prune mode is incompatible with -txindex."));
1135          if (args.GetBoolArg("-reindex-chainstate", false)) {
1136              return InitError(_("Prune mode is incompatible with -reindex-chainstate. Use full -reindex instead."));
1137          }
1138      }
1139  
1140      // If -forcednsseed is set to true, ensure -dnsseed has not been set to false
1141      if (args.GetBoolArg("-forcednsseed", DEFAULT_FORCEDNSSEED) && !args.GetBoolArg("-dnsseed", DEFAULT_DNSSEED)){
1142          return InitError(_("Cannot set -forcednsseed to true when setting -dnsseed to false."));
1143      }
1144  
1145      // -bind and -whitebind can't be set when not listening
1146      size_t nUserBind = args.GetArgs("-bind").size() + args.GetArgs("-whitebind").size();
1147      if (nUserBind != 0 && !args.GetBoolArg("-listen", DEFAULT_LISTEN)) {
1148          return InitError(Untranslated("Cannot set -bind or -whitebind together with -listen=0"));
1149      }
1150  
1151      // if listen=0, then disallow listenonion=1
1152      if (!args.GetBoolArg("-listen", DEFAULT_LISTEN) && args.GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION)) {
1153          return InitError(Untranslated("Cannot set -listen=0 together with -listenonion=1"));
1154      }
1155  
1156      // Make sure enough file descriptors are available. We need to reserve enough FDs to account for the bare minimum,
1157      // plus all manual connections and all bound interfaces. Any remainder will be available for connection sockets
1158  
1159      // Number of bound interfaces (we have at least one)
1160      int nBind = std::max(nUserBind, size_t(1));
1161      // Maximum number of connections with other nodes, this accounts for all types of outbounds and inbounds except for manual
1162      int user_max_connection = args.GetIntArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
1163      if (user_max_connection < 0) {
1164          return InitError(Untranslated("-maxconnections must be greater or equal than zero"));
1165      }
1166      // Reserve enough FDs to account for the bare minimum, plus any manual connections, plus the bound interfaces
1167      int min_required_fds = MIN_CORE_FDS + MAX_ADDNODE_CONNECTIONS + nBind;
1168  
1169      // Try raising the FD limit to what we need (available_fds may be smaller than the requested amount if this fails)
1170      available_fds = RaiseFileDescriptorLimit(user_max_connection + min_required_fds);
1171      // If we are using select instead of poll, our actual limit may be even smaller
1172  #ifndef USE_POLL
1173      available_fds = std::min(FD_SETSIZE, available_fds);
1174  #endif
1175      if (available_fds < min_required_fds)
1176          return InitError(strprintf(_("Not enough file descriptors available. %d available, %d required."), available_fds, min_required_fds));
1177  
1178      // Trim requested connection counts, to fit into system limitations
1179      nMaxConnections = std::min(available_fds - min_required_fds, user_max_connection);
1180  
1181      if (nMaxConnections < user_max_connection)
1182          InitWarning(strprintf(_("Reducing -maxconnections from %d to %d, because of system limitations."), user_max_connection, nMaxConnections));
1183  
1184      // ********************************************************* Step 3: parameter-to-internal-flags
1185      if (auto result{init::SetLoggingCategories(args)}; !result) return InitError(util::ErrorString(result));
1186      if (auto result{init::SetLoggingLevel(args)}; !result) return InitError(util::ErrorString(result));
1187  
1188      nConnectTimeout = args.GetIntArg("-timeout", DEFAULT_CONNECT_TIMEOUT);
1189      if (nConnectTimeout <= 0) {
1190          nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
1191      }
1192  
1193      peer_connect_timeout = args.GetIntArg("-peertimeout", DEFAULT_PEER_CONNECT_TIMEOUT);
1194      if (peer_connect_timeout <= 0) {
1195          return InitError(Untranslated("peertimeout must be a positive integer."));
1196      }
1197  
1198      // Sanity check argument for min fee for including tx in block
1199      // TODO: Harmonize which arguments need sanity checking and where that happens
1200      if (args.IsArgSet("-blockmintxfee")) {
1201          if (!ParseMoney(args.GetArg("-blockmintxfee", ""))) {
1202              return InitError(AmountErrMsg("blockmintxfee", args.GetArg("-blockmintxfee", "")));
1203          }
1204      }
1205  
1206      if (args.IsArgSet("-blockmaxweight")) {
1207          const auto max_block_weight = args.GetIntArg("-blockmaxweight", DEFAULT_BLOCK_MAX_WEIGHT);
1208          if (max_block_weight > MAX_BLOCK_WEIGHT) {
1209              return InitError(strprintf(_("Specified -blockmaxweight (%d) exceeds consensus maximum block weight (%d)"), max_block_weight, MAX_BLOCK_WEIGHT));
1210          }
1211      }
1212  
1213      if (args.IsArgSet("-blockreservedweight")) {
1214          const auto block_reserved_weight = args.GetIntArg("-blockreservedweight", DEFAULT_BLOCK_RESERVED_WEIGHT);
1215          if (block_reserved_weight > MAX_BLOCK_WEIGHT) {
1216              return InitError(strprintf(_("Specified -blockreservedweight (%d) exceeds consensus maximum block weight (%d)"), block_reserved_weight, MAX_BLOCK_WEIGHT));
1217          }
1218          if (block_reserved_weight < MINIMUM_BLOCK_RESERVED_WEIGHT) {
1219              return InitError(strprintf(_("Specified -blockreservedweight (%d) is lower than minimum safety value of (%d)"), block_reserved_weight, MINIMUM_BLOCK_RESERVED_WEIGHT));
1220          }
1221      }
1222  
1223      if (auto parsed = args.GetFixedPointArg("-datacarriercost", 2)) {
1224          g_weight_per_data_byte = ((*parsed * WITNESS_SCALE_FACTOR) + 99) / 100;
1225      }
1226  
1227      g_script_size_policy_limit = args.GetIntArg("-maxscriptsize", g_script_size_policy_limit);
1228  
1229      nBytesPerSigOp = args.GetIntArg("-bytespersigop", nBytesPerSigOp);
1230      nBytesPerSigOpStrict = args.GetIntArg("-bytespersigopstrict", nBytesPerSigOpStrict);
1231  
1232      if (!g_wallet_init_interface.ParameterInteraction()) return false;
1233  
1234      {
1235          std::string strSpkReuse = gArgs.GetArg("-spkreuse", DEFAULT_SPKREUSE);
1236          // Uses string values so future versions can implement other modes
1237          if (strSpkReuse == "allow" || gArgs.GetBoolArg("-spkreuse", false)) {
1238              SpkReuseMode = SRM_ALLOW;
1239          } else {
1240              SpkReuseMode = SRM_REJECT;
1241          }
1242      }
1243  
1244      // Option to startup with mocktime set (used for regression testing):
1245      SetMockTime(args.GetIntArg("-mocktime", 0)); // SetMockTime(0) is a no-op
1246  
1247  
1248      if (args.GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS))
1249          g_local_services = ServiceFlags(g_local_services | NODE_BLOOM);
1250  
1251      const std::vector<std::string> test_options = args.GetArgs("-test");
1252      if (!test_options.empty()) {
1253          if (chainparams.GetChainType() != ChainType::REGTEST) {
1254              return InitError(Untranslated("-test=<option> can only be used with regtest"));
1255          }
1256          for (const std::string& option : test_options) {
1257              auto it = std::find_if(TEST_OPTIONS_DOC.begin(), TEST_OPTIONS_DOC.end(), [&option](const std::string& doc_option) {
1258                  size_t pos = doc_option.find(" (");
1259                  return (pos != std::string::npos) && (doc_option.substr(0, pos) == option);
1260              });
1261              if (it == TEST_OPTIONS_DOC.end()) {
1262                  InitWarning(strprintf(_("Unrecognised option \"%s\" provided in -test=<option>."), option));
1263              }
1264          }
1265      }
1266  
1267      // Also report errors from parsing before daemonization
1268      {
1269          kernel::Notifications notifications{};
1270          ChainstateManager::Options chainman_opts_dummy{
1271              .chainparams = chainparams,
1272              .datadir = args.GetDataDirNet(),
1273              .notifications = notifications,
1274          };
1275          auto chainman_result{ApplyArgsManOptions(args, chainman_opts_dummy)};
1276          if (!chainman_result) {
1277              return InitError(util::ErrorString(chainman_result));
1278          }
1279          BlockManager::Options blockman_opts_dummy{
1280              .chainparams = chainman_opts_dummy.chainparams,
1281              .blocks_dir = args.GetBlocksDirPath(),
1282              .notifications = chainman_opts_dummy.notifications,
1283              .block_tree_db_params = DBParams{
1284                  .path = args.GetDataDirNet() / "blocks" / "index",
1285                  .cache_bytes = 0,
1286              },
1287          };
1288          auto blockman_result{ApplyArgsManOptions(args, blockman_opts_dummy)};
1289          if (!blockman_result) {
1290              return InitError(util::ErrorString(blockman_result));
1291          }
1292          CTxMemPool::Options mempool_opts{};
1293          auto mempool_result{ApplyArgsManOptions(args, chainparams, mempool_opts)};
1294          if (!mempool_result) {
1295              return InitError(util::ErrorString(mempool_result));
1296          }
1297      }
1298  
1299      if (!CStats::parameterInteraction()) return false;
1300  
1301      return true;
1302  }
1303  
1304  static bool LockDirectory(const fs::path& dir, bool probeOnly)
1305  {
1306      // Make sure only a single process is using the directory.
1307      switch (util::LockDirectory(dir, ".lock", probeOnly)) {
1308      case util::LockResult::ErrorWrite:
1309          return InitError(strprintf(_("Cannot write to directory '%s'; check permissions."), fs::PathToString(dir)));
1310      case util::LockResult::ErrorLock:
1311          return InitError(strprintf(_("Cannot obtain a lock on directory %s. %s is probably already running."), fs::PathToString(dir), CLIENT_NAME));
1312      case util::LockResult::Success: return true;
1313      } // no default case, so the compiler can warn about missing cases
1314      assert(false);
1315  }
1316  static bool LockDirectories(bool probeOnly)
1317  {
1318      return LockDirectory(gArgs.GetDataDirNet(), probeOnly) && \
1319             LockDirectory(gArgs.GetBlocksDirPath(), probeOnly);
1320  }
1321  
1322  bool AppInitSanityChecks(const kernel::Context& kernel)
1323  {
1324      // ********************************************************* Step 4: sanity checks
1325      auto result{kernel::SanityChecks(kernel)};
1326      if (!result) {
1327          InitError(util::ErrorString(result));
1328          return InitError(strprintf(_("Initialization sanity check failed. %s is shutting down."), CLIENT_NAME));
1329      }
1330  
1331      if (!ECC_InitSanityCheck()) {
1332          return InitError(strprintf(_("Elliptic curve cryptography sanity check failure. %s is shutting down."), CLIENT_NAME));
1333      }
1334  
1335      // Probe the directory locks to give an early error message, if possible
1336      // We cannot hold the directory locks here, as the forking for daemon() hasn't yet happened,
1337      // and a fork will cause weird behavior to them.
1338      return LockDirectories(true);
1339  }
1340  
1341  bool AppInitLockDirectories()
1342  {
1343      // After daemonization get the directory locks again and hold on to them until exit
1344      // This creates a slight window for a race condition to happen, however this condition is harmless: it
1345      // will at most make us exit without printing a message to console.
1346      if (!LockDirectories(false)) {
1347          // Detailed error printed inside LockDirectory
1348          return false;
1349      }
1350      return true;
1351  }
1352  
1353  /**
1354   * Once initial block sync is finished and no change in block height or queued downloads,
1355   * sync utxo state to protect against data loss
1356   */
1357  static void SyncCoinsTipAfterChainSync(const NodeContext& node)
1358  {
1359      LOCK(node.chainman->GetMutex());
1360      if (node.chainman->IsInitialBlockDownload()) {
1361          LogDebug(BCLog::COINDB, "Node is still in IBD, rescheduling post-IBD chainstate disk sync...\n");
1362          node.scheduler->scheduleFromNow([&node] {
1363              SyncCoinsTipAfterChainSync(node);
1364          }, SYNC_CHECK_INTERVAL);
1365          return;
1366      }
1367  
1368      static auto last_chain_height{-1};
1369      const auto current_height{node.chainman->ActiveHeight()};
1370      if (last_chain_height != current_height) {
1371          LogDebug(BCLog::COINDB, "Chain height updated since last check, rescheduling post-IBD chainstate disk sync...\n");
1372          last_chain_height = current_height;
1373          node.scheduler->scheduleFromNow([&node] {
1374              SyncCoinsTipAfterChainSync(node);
1375          }, SYNC_CHECK_INTERVAL);
1376          return;
1377      }
1378  
1379      if (node.peerman->GetNumberOfPeersWithValidatedDownloads() > 0) {
1380          LogDebug(BCLog::COINDB, "Still downloading blocks from peers, rescheduling post-IBD chainstate disk sync...\n");
1381          node.scheduler->scheduleFromNow([&node] {
1382              SyncCoinsTipAfterChainSync(node);
1383          }, SYNC_CHECK_INTERVAL);
1384          return;
1385      }
1386  
1387      LogDebug(BCLog::COINDB, "Finished syncing to tip, syncing chainstate to disk\n");
1388      node.chainman->ActiveChainstate().CoinsTip().Sync();
1389  }
1390  
1391  bool AppInitInterfaces(NodeContext& node)
1392  {
1393      node.chain = node.init->makeChain();
1394      node.mining = node.init->makeMining();
1395      return true;
1396  }
1397  
1398  bool CheckHostPortOptions(const ArgsManager& args) {
1399      for (const std::string port_option : {
1400          "-port",
1401          "-rpcport",
1402      }) {
1403          if (args.IsArgSet(port_option)) {
1404              const std::string port = args.GetArg(port_option, "");
1405              uint16_t n;
1406              if (!ParseUInt16(port, &n) || n == 0) {
1407                  return InitError(InvalidPortErrMsg(port_option, port));
1408              }
1409          }
1410      }
1411  
1412      for ([[maybe_unused]] const auto& [arg, unix, suffix_allowed] : std::vector<std::tuple<std::string, bool, bool>>{
1413          // arg name          UNIX socket support  =suffix allowed
1414          {"-i2psam",          false,               false},
1415          {"-onion",           true,                false},
1416          {"-proxy",           true,                true},
1417          {"-bind",            false,               true},
1418          {"-rpcbind",         false,               false},
1419          {"-torcontrol",      false,               false},
1420          {"-whitebind",       false,               false},
1421          {"-zmqpubhashblock", true,                false},
1422          {"-zmqpubhashtx",    true,                false},
1423          {"-zmqpubrawblock",  true,                false},
1424          {"-zmqpubrawtx",     true,                false},
1425          {"-zmqpubsequence",  true,                false},
1426          {"-zmqpubhashwallettx", true,             false},
1427          {"-zmqpubrawwallettx",  true,             false},
1428      }) {
1429          for (const std::string& socket_addr : args.GetArgs(arg)) {
1430              const std::string param_value_hostport{
1431                  suffix_allowed ? socket_addr.substr(0, socket_addr.rfind('=')) : socket_addr};
1432              std::string host_out;
1433              uint16_t port_out{0};
1434              if (!SplitHostPort(param_value_hostport, port_out, host_out)) {
1435  #ifdef HAVE_SOCKADDR_UN
1436                  // Allow unix domain sockets for some options e.g. unix:/some/file/path
1437                  if (!unix || (!socket_addr.starts_with(ADDR_PREFIX_UNIX) && socket_addr.rfind("ipc:", 0) != 0)) {
1438                      return InitError(InvalidPortErrMsg(arg, socket_addr));
1439                  }
1440  #else
1441                  return InitError(InvalidPortErrMsg(arg, socket_addr));
1442  #endif
1443              }
1444          }
1445      }
1446  
1447      return true;
1448  }
1449  
1450  // A GUI user may opt to retry once with do_reindex set if there is a failure during chainstate initialization.
1451  // The function therefore has to support re-entry.
1452  static ChainstateLoadResult InitAndLoadChainstate(
1453      NodeContext& node,
1454      bool do_reindex,
1455      const bool do_reindex_chainstate,
1456      const kernel::CacheSizes& cache_sizes,
1457      const ArgsManager& args)
1458  {
1459      // This function may be called twice, so any dirty state must be reset.
1460      node.notifications.reset(); // Drop state, such as a cached tip block
1461      node.mempool.reset();
1462      node.chainman.reset(); // Drop state, such as an initialized m_block_tree_db
1463  
1464      const CChainParams& chainparams = Params();
1465  
1466      Assert(!node.notifications); // Was reset above
1467      node.notifications = std::make_unique<KernelNotifications>(Assert(node.shutdown_request), node.exit_status, *Assert(node.warnings));
1468      ReadNotificationArgs(args, *node.notifications);
1469  
1470      CTxMemPool::Options mempool_opts{
1471          .estimator = node.fee_estimator.get(),
1472          .scheduler = &*node.scheduler,
1473          .check_ratio = chainparams.DefaultConsistencyChecks() ? 1 : 0,
1474          .signals = node.validation_signals.get(),
1475      };
1476      Assert(ApplyArgsManOptions(args, chainparams, mempool_opts)); // no error can happen, already checked in AppInitParameterInteraction
1477      bilingual_str mempool_error;
1478      Assert(!node.mempool); // Was reset above
1479      node.mempool = std::make_unique<CTxMemPool>(mempool_opts, mempool_error);
1480      if (!mempool_error.empty()) {
1481          return {ChainstateLoadStatus::FAILURE_FATAL, mempool_error};
1482      }
1483      LogPrintf("* Using %.1f MiB for in-memory UTXO set (plus up to %.1f MiB of unused mempool space)\n", cache_sizes.coins * (1.0 / 1024 / 1024), mempool_opts.max_size_bytes * (1.0 / 1024 / 1024));
1484  
1485      if (gArgs.IsArgSet("-lowmem")) {
1486          g_low_memory_threshold = std::max(int64_t{0}, gArgs.GetIntArg("-lowmem", 0 /* not used */)) * 1024 * 1024;
1487      }
1488      if (g_low_memory_threshold > 0) {
1489          LogPrintf("* Flushing caches if available system memory drops below %s MiB\n", g_low_memory_threshold / 1024 / 1024);
1490      }
1491  
1492      ChainstateManager::Options chainman_opts{
1493          .chainparams = chainparams,
1494          .datadir = args.GetDataDirNet(),
1495          .notifications = *node.notifications,
1496          .signals = node.validation_signals.get(),
1497      };
1498      Assert(ApplyArgsManOptions(args, chainman_opts)); // no error can happen, already checked in AppInitParameterInteraction
1499  
1500      BlockManager::Options blockman_opts{
1501          .chainparams = chainman_opts.chainparams,
1502          .blocks_dir = args.GetBlocksDirPath(),
1503          .notifications = chainman_opts.notifications,
1504          .block_tree_db_params = DBParams{
1505              .path = args.GetDataDirNet() / "blocks" / "index",
1506              .cache_bytes = cache_sizes.block_tree_db,
1507              .wipe_data = do_reindex,
1508          },
1509      };
1510      Assert(ApplyArgsManOptions(args, blockman_opts)); // no error can happen, already checked in AppInitParameterInteraction
1511  
1512      // Creating the chainstate manager internally creates a BlockManager, opens
1513      // the blocks tree db, and wipes existing block files in case of a reindex.
1514      // The coinsdb is opened at a later point on LoadChainstate.
1515      Assert(!node.chainman); // Was reset above
1516      try {
1517          node.chainman = std::make_unique<ChainstateManager>(*Assert(node.shutdown_signal), chainman_opts, blockman_opts);
1518      } catch (dbwrapper_error& e) {
1519          LogError("%s", e.what());
1520          return {ChainstateLoadStatus::FAILURE, _("Error opening block database")};
1521      } catch (std::exception& e) {
1522          return {ChainstateLoadStatus::FAILURE_FATAL, Untranslated(strprintf("Failed to initialize ChainstateManager: %s", e.what()))};
1523      }
1524      ChainstateManager& chainman = *node.chainman;
1525      if (chainman.m_interrupt) return {ChainstateLoadStatus::INTERRUPTED, {}};
1526  
1527      // This is defined and set here instead of inline in validation.h to avoid a hard
1528      // dependency between validation and index/base, since the latter is not in
1529      // liblimenkakernel.
1530      chainman.snapshot_download_completed = [&node]() {
1531          if (!node.chainman->m_blockman.IsPruneMode()) {
1532              LogPrintf("[snapshot] re-enabling NODE_NETWORK services\n");
1533              node.connman->AddLocalServices(NODE_NETWORK);
1534          }
1535          LogPrintf("[snapshot] restarting indexes\n");
1536          // Drain the validation interface queue to ensure that the old indexes
1537          // don't have any pending work.
1538          Assert(node.validation_signals)->SyncWithValidationInterfaceQueue();
1539          for (auto* index : node.indexes) {
1540              index->Interrupt();
1541              index->Stop();
1542              if (!(index->Init() && index->StartBackgroundSync())) {
1543                  LogWarning("[snapshot] Failed to restart index %s on snapshot chain", index->GetName());
1544              }
1545          }
1546      };
1547      node::ChainstateLoadOptions options;
1548      options.mempool = Assert(node.mempool.get());
1549      options.wipe_chainstate_db = do_reindex || do_reindex_chainstate;
1550      options.prune = chainman.m_blockman.IsPruneMode();
1551      options.check_blocks = args.GetIntArg("-checkblocks", DEFAULT_CHECKBLOCKS);
1552      options.check_level = args.GetIntArg("-checklevel", DEFAULT_CHECKLEVEL);
1553      options.require_full_verification = args.IsArgSet("-checkblocks") || args.IsArgSet("-checklevel");
1554      options.coins_error_cb = [] {
1555          uiInterface.ThreadSafeMessageBox(
1556              _("Error reading from database, shutting down."),
1557              "", CClientUIInterface::MSG_ERROR);
1558      };
1559      uiInterface.InitMessage(_("Loading block index…"));
1560      auto catch_exceptions = [](auto&& f) -> ChainstateLoadResult {
1561          try {
1562              return f();
1563          } catch (const std::exception& e) {
1564              LogError("%s\n", e.what());
1565              return std::make_tuple(node::ChainstateLoadStatus::FAILURE, _("Error loading databases"));
1566          }
1567      };
1568      auto [status, error] = catch_exceptions([&] { return LoadChainstate(chainman, cache_sizes, options); });
1569      if (status == node::ChainstateLoadStatus::SUCCESS) {
1570          uiInterface.InitMessage(_("Verifying blocks…"));
1571          if (chainman.m_blockman.m_have_pruned && options.check_blocks > MIN_BLOCKS_TO_KEEP) {
1572              LogWarning("pruned datadir may not have more than %d blocks; only checking available blocks\n",
1573                         MIN_BLOCKS_TO_KEEP);
1574          }
1575          std::tie(status, error) = catch_exceptions([&] { return VerifyLoadedChainstate(chainman, options); });
1576          if (status == node::ChainstateLoadStatus::SUCCESS) {
1577              LogInfo("Block index and chainstate loaded");
1578          }
1579      }
1580      return {status, error};
1581  };
1582  
1583  bool UserProtocolRulesCheck()
1584  {
1585      const auto rules_requested{gArgs.GetArgs(CONSENSUSRULES_CONFIG_NAME)};
1586      for (const auto& rulesok : rules_requested) {
1587          if (rulesok == CONSENSUSRULES_REQUIRED) continue;
1588          return InitError(strprintf(_("Unknown rule specified in -%s: %s"), CONSENSUSRULES_CONFIG_NAME, rulesok));
1589      }
1590      return true;
1591  }
1592  
1593  bool UserProtocolRulesConsent()
1594  {
1595      if (g_rdts_consent == RDTSConsentFlag::IMPLICIT) {
1596          LogPrintf("User already consented to '%s' consensus rules (at installation)\n", CONSENSUSRULES_REQUIRED);
1597          return true;
1598      }
1599      for (const auto& rulesok : gArgs.GetArgs(CONSENSUSRULES_CONFIG_NAME)) {
1600          if (rulesok == CONSENSUSRULES_REQUIRED) {
1601              LogPrintf("User already consented to '%s' consensus rules (in config)\n", CONSENSUSRULES_REQUIRED);
1602              return true;
1603          }
1604      }
1605  
1606      bilingual_str msg = strprintf(_(
1607          "BIP110/RDTS Network Upgrade\n"
1608          "\n"
1609          "This version of %s applies the BIP110 (RDTS) network upgrade, "
1610          "which fixes critical vulnerabilities in long-standing network design. "
1611          "However, you are in control of your own software, and this application asks for explicit confirmation.\n"
1612          "\n"
1613          "Important: "
1614          "Because this upgrade already has broad community support, "
1615          "reverting to an older software version does not reject it. "
1616          "Running outdated software after any network upgrade only leaves your node vulnerable to displaying fake or fraudulent transactions. "
1617          "To effectively reject this upgrade, you need to run alternative software designed to split away from the upgraded network.\n"
1618          "\n"
1619          "For more information, see: %s"
1620      ),
1621          CLIENT_NAME,
1622          "https://limenkaknots.org/learn/2026-rdts");
1623      const bilingual_str msg_manual_suffix = strprintf(_(
1624          "To confirm this upgrade, add to your %s file: %s"
1625      ),
1626          gArgs.GetPathArg("-conf", LIMENKA_CONF_FILENAME).utf8string(),
1627          CONSENSUSRULES_CONFIG_NAME + "=" + CONSENSUSRULES_REQUIRED);
1628      const bilingual_str msg_manual = msg + Untranslated("\n\n") + msg_manual_suffix;
1629  
1630      if (!gArgs.GetSettingsPath()) {
1631          msg = msg_manual;
1632      }
1633  
1634      const bool consent = uiInterface.ThreadSafeQuestion(
1635          _("Attention:") + Untranslated(" ") + msg,
1636          msg_manual.original
1637          , "Attention", CClientUIInterface::MSG_WARNING | CClientUIInterface::BTN_ABORT);
1638  
1639      if (consent) {
1640          if (gArgs.GetSettingsPath()) {
1641              // Write to settings.json so we don't ask anymore
1642              LogPrintf("User interactively consented to '%s' consensus rules (%s)\n", CONSENSUSRULES_REQUIRED, "remembering for next time");
1643              gArgs.LockSettings([&](common::Settings& settings) {
1644                  auto& setting = settings.rw_settings[CONSENSUSRULES_CONFIG_NAME];
1645                  if (setting.isArray()) {
1646                      // Normally, it doesn't make sense to support multiple rulesets, but if the user has done so already, don't lose the current set
1647                      setting.push_back(CONSENSUSRULES_REQUIRED);
1648                  } else {
1649                      setting = CONSENSUSRULES_REQUIRED;
1650                  }
1651              });
1652              gArgs.WriteSettingsFile();
1653          } else {
1654              LogPrintf("User interactively consented to '%s' consensus rules (%s)\n", CONSENSUSRULES_REQUIRED, "settings disabled, so can't save");
1655          }
1656      }
1657  
1658      return consent;
1659  }
1660  
1661  bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
1662  {
1663      const ArgsManager& args = *Assert(node.args);
1664      const CChainParams& chainparams = Params();
1665  
1666      auto opt_max_upload = ParseByteUnits(args.GetArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET), ByteUnit::M);
1667      if (!opt_max_upload) {
1668          return InitError(strprintf(_("Unable to parse -maxuploadtarget: '%s'"), args.GetArg("-maxuploadtarget", "")));
1669      }
1670  
1671      // ********************************************************* Step 4a: application initialization
1672      if (!CreatePidFile(args)) {
1673          // Detailed error printed inside CreatePidFile().
1674          return false;
1675      }
1676      if (!init::StartLogging(args)) {
1677          // Detailed error printed inside StartLogging().
1678          return false;
1679      }
1680  
1681      LogPrintf("Using at most %i automatic connections (%i file descriptors available)\n", nMaxConnections, available_fds);
1682  
1683      // Warn about relative -datadir path.
1684      if (args.IsArgSet("-datadir") && !args.GetPathArg("-datadir").is_absolute()) {
1685          LogWarning("Relative datadir option '%s' specified, which will be interpreted relative to the "
1686                     "current working directory '%s'. This is fragile, because if limenka is started in the future "
1687                     "from a different location, it will be unable to locate the current data files. There could "
1688                     "also be data loss if limenka is started while in a temporary directory.",
1689                     args.GetArg("-datadir", ""), fs::PathToString(fs::current_path()));
1690      }
1691  
1692      assert(!node.scheduler);
1693      node.scheduler = std::make_unique<CScheduler>();
1694      auto& scheduler = *node.scheduler;
1695  
1696      // Start the lightweight task scheduler thread
1697      scheduler.m_service_thread = std::thread(util::TraceThread, "scheduler", [&] { scheduler.serviceQueue(); });
1698  
1699      // Gather some entropy once per minute.
1700      scheduler.scheduleEvery([]{
1701          RandAddPeriodic();
1702      }, std::chrono::minutes{1});
1703  
1704      // Check disk space every 5 minutes to avoid db corruption.
1705      scheduler.scheduleEvery([&args, &node]{
1706          constexpr uint64_t min_disk_space = 50 << 20; // 50 MB
1707          if (!CheckDiskSpace(args.GetBlocksDirPath(), min_disk_space)) {
1708              LogError("Shutting down due to lack of disk space!\n");
1709              if (!(Assert(node.shutdown_request))()) {
1710                  LogError("Failed to send shutdown signal after disk space check\n");
1711              }
1712          }
1713      }, std::chrono::minutes{5});
1714  
1715      if (args.GetBoolArg("-logratelimit", BCLog::DEFAULT_LOGRATELIMIT)) {
1716          LogInstance().SetRateLimiting(BCLog::LogRateLimiter::Create(
1717              [&scheduler](auto func, auto window) { scheduler.scheduleEvery(std::move(func), window); },
1718              BCLog::RATELIMIT_MAX_BYTES,
1719              BCLog::RATELIMIT_WINDOW));
1720      } else {
1721          LogInfo("Log rate limiting disabled");
1722      }
1723  
1724      assert(!node.validation_signals);
1725      node.validation_signals = std::make_unique<ValidationSignals>(std::make_unique<SerialTaskRunner>(scheduler));
1726      auto& validation_signals = *node.validation_signals;
1727  
1728      // Create client interfaces for wallets that are supposed to be loaded
1729      // according to -wallet and -disablewallet options. This only constructs
1730      // the interfaces, it doesn't load wallet data. Wallets actually get loaded
1731      // when load() and start() interface methods are called below.
1732      g_wallet_init_interface.Construct(node);
1733      uiInterface.InitWallet();
1734  
1735      if (!UserProtocolRulesCheck()) {
1736          return false;
1737      }
1738  
1739      if (!(chainparams.IsTestChain() || UserProtocolRulesConsent())) {
1740          if (g_rdts_consent == RDTSConsentFlag::RUNTIME_CHECK) {
1741              return InitError(_("User has not consented to supported protocol rules. Exiting"));
1742          } else if (g_rdts_consent == RDTSConsentFlag::UNSUPPORTED_UNSAFE_NO_ENFORCEMENT) {
1743              LogError("User has not consented to supported protocol rules. This node will NOT enforce them. Warning every hour.");
1744              g_local_services = ServiceFlags(g_local_services & ~NODE_REDUCED_DATA);
1745              scheduler.scheduleEvery([]{
1746                  LogError("RDTS is not enabled. This node is therefore vulnerable to displaying fake or fraudulent transactions.\n");
1747                  LogError("For more information, see: %s\n", "https://limenkaknots.org/learn/2026-rdts");
1748                  LogError("To enable RDTS enforcement and disable this warning, add to %s: %s\n",
1749                      gArgs.GetPathArg("-conf", LIMENKA_CONF_FILENAME).utf8string(),
1750                      CONSENSUSRULES_CONFIG_NAME + "=" + CONSENSUSRULES_REQUIRED);
1751              }, std::chrono::hours{1});
1752          } else {
1753              LogError("User has not consented to supported protocol rules. This node will STILL enforce them. Warning every hour.");
1754              g_rdts_warning = true;
1755              scheduler.scheduleEvery([]{
1756                  LogError("This software applies the BIP110/RDTS network upgrade, which fixes critical vulnerabilities, but explicit user confirmation has not been configured.\n");
1757                  LogError("For more information, see: %s\n", "https://limenkaknots.org/learn/2026-rdts");
1758                  LogError("To confirm this upgrade and dismiss this warning, add to your %s file: %s\n",
1759                      gArgs.GetPathArg("-conf", LIMENKA_CONF_FILENAME).utf8string(),
1760                      CONSENSUSRULES_CONFIG_NAME + "=" + CONSENSUSRULES_REQUIRED);
1761              }, std::chrono::hours{1});
1762          }
1763      }
1764  
1765      if (interfaces::Ipc* ipc = node.init->ipc()) {
1766          for (std::string address : gArgs.GetArgs("-ipcbind")) {
1767              try {
1768                  ipc->listenAddress(address);
1769              } catch (const std::exception& e) {
1770                  return InitError(Untranslated(strprintf("Unable to bind to IPC address '%s'. %s", address, e.what())));
1771              }
1772              LogPrintf("Listening for IPC requests on address %s\n", address);
1773          }
1774      }
1775  
1776      /* Register RPC commands regardless of -server setting so they will be
1777       * available in the GUI RPC console even if external calls are disabled.
1778       */
1779      RegisterAllCoreRPCCommands(tableRPC);
1780      for (const auto& client : node.chain_clients) {
1781          client->registerRpcs();
1782      }
1783  #ifdef ENABLE_ZMQ
1784      RegisterZMQRPCCommands(tableRPC);
1785  #endif
1786  
1787      // Check port numbers
1788      if (!CheckHostPortOptions(args)) return false;
1789  
1790      // Configure reachable networks before we start the RPC server.
1791      // This is necessary for -rpcallowip to distinguish CJDNS from other RFC4193
1792      const auto onlynets = args.GetArgs("-onlynet");
1793      if (!onlynets.empty()) {
1794          g_reachable_nets.RemoveAll();
1795          for (const std::string& snet : onlynets) {
1796              enum Network net = ParseNetwork(snet);
1797              if (net == NET_UNROUTABLE)
1798                  return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet));
1799              g_reachable_nets.Add(net);
1800          }
1801      }
1802  
1803      if (!args.IsArgSet("-cjdnsreachable")) {
1804          if (!onlynets.empty() && g_reachable_nets.Contains(NET_CJDNS)) {
1805              return InitError(
1806                  _("Outbound connections restricted to CJDNS (-onlynet=cjdns) but "
1807                    "-cjdnsreachable is not provided"));
1808          }
1809          g_reachable_nets.Remove(NET_CJDNS);
1810      }
1811      // Now g_reachable_nets.Contains(NET_CJDNS) is true if:
1812      // 1. -cjdnsreachable is given and
1813      // 2.1. -onlynet is not given or
1814      // 2.2. -onlynet=cjdns is given
1815  
1816      /* Start the RPC server already.  It will be started in "warmup" mode
1817       * and not really process calls already (but it will signify connections
1818       * that the server is there and will be ready later).  Warmup mode will
1819       * be disabled when initialisation is finished.
1820       */
1821      if (args.GetBoolArg("-server", false)) {
1822          uiInterface.InitMessage_connect(SetRPCWarmupStatus);
1823          if (!AppInitServers(node))
1824              return InitError(_("Unable to start HTTP server. See debug log for details."));
1825      }
1826  
1827      // ********************************************************* Step 5: verify wallet database integrity
1828      for (const auto& client : node.chain_clients) {
1829          if (!client->verify()) {
1830              return false;
1831          }
1832      }
1833  
1834      // ********************************************************* Step 6: network initialization
1835      // Note that we absolutely cannot open any actual connections
1836      // until the very end ("start node") as the UTXO/block state
1837      // is not yet setup and may end up being set up twice if we
1838      // need to reindex later.
1839  
1840      fListen = args.GetBoolArg("-listen", DEFAULT_LISTEN);
1841      fDiscover = args.GetBoolArg("-discover", true);
1842  
1843      PeerManager::Options peerman_opts{};
1844      ApplyArgsManOptions(args, peerman_opts);
1845  
1846      {
1847  
1848          // Read asmap file if configured
1849          std::vector<bool> asmap;
1850          if (args.IsArgSet("-asmap") && !args.IsArgNegated("-asmap")) {
1851              fs::path asmap_path = args.GetPathArg("-asmap", DEFAULT_ASMAP_FILENAME);
1852              if (!asmap_path.is_absolute()) {
1853                  asmap_path = args.GetDataDirNet() / asmap_path;
1854              }
1855              if (!fs::exists(asmap_path)) {
1856                  InitError(strprintf(_("Could not find asmap file %s"), fs::quoted(fs::PathToString(asmap_path))));
1857                  return false;
1858              }
1859              asmap = DecodeAsmap(asmap_path);
1860              if (asmap.size() == 0) {
1861                  InitError(strprintf(_("Could not parse asmap file %s"), fs::quoted(fs::PathToString(asmap_path))));
1862                  return false;
1863              }
1864              const uint256 asmap_version = (HashWriter{} << asmap).GetHash();
1865              LogPrintf("Using asmap version %s for IP bucketing\n", asmap_version.ToString());
1866          } else {
1867              LogPrintf("Using /16 prefix for IP bucketing\n");
1868          }
1869  
1870          // Initialize netgroup manager
1871          assert(!node.netgroupman);
1872          node.netgroupman = std::make_unique<NetGroupManager>(std::move(asmap));
1873  
1874          // Initialize addrman
1875          assert(!node.addrman);
1876          uiInterface.InitMessage(_("Loading P2P addresses…"));
1877          auto addrman{LoadAddrman(*node.netgroupman, args)};
1878          if (!addrman) return InitError(util::ErrorString(addrman));
1879          node.addrman = std::move(*addrman);
1880      }
1881  
1882      FastRandomContext rng;
1883      assert(!node.banman);
1884      node.banman = std::make_unique<BanMan>(args.GetDataDirNet() / "banlist", &uiInterface, args.GetIntArg("-bantime", DEFAULT_MISBEHAVING_BANTIME));
1885      assert(!node.connman);
1886      node.connman = std::make_unique<CConnman>(rng.rand64(),
1887                                                rng.rand64(),
1888                                                *node.addrman, *node.netgroupman, chainparams, args.GetBoolArg("-networkactive", true));
1889  
1890      assert(!node.fee_estimator);
1891      // Don't initialize fee estimation with old data if we don't relay transactions,
1892      // as they would never get updated.
1893      if (!peerman_opts.ignore_incoming_txs) {
1894          bool read_stale_estimates = args.GetBoolArg("-acceptstalefeeestimates", DEFAULT_ACCEPT_STALE_FEE_ESTIMATES);
1895          node.fee_estimator = std::make_unique<CBlockPolicyEstimator>(FeeestPath(args), read_stale_estimates);
1896  
1897          // Flush estimates to disk periodically
1898          CBlockPolicyEstimator* fee_estimator = node.fee_estimator.get();
1899          scheduler.scheduleEvery([fee_estimator] { fee_estimator->FlushFeeEstimates(); }, FEE_FLUSH_INTERVAL);
1900          validation_signals.RegisterValidationInterface(fee_estimator);
1901      }
1902  
1903      for (const std::string& socket_addr : args.GetArgs("-bind")) {
1904          std::string host_out;
1905          uint16_t port_out{0};
1906          std::string bind_socket_addr = socket_addr.substr(0, socket_addr.rfind('='));
1907          if (!SplitHostPort(bind_socket_addr, port_out, host_out)) {
1908              return InitError(InvalidPortErrMsg("-bind", socket_addr));
1909          }
1910      }
1911  
1912      // sanitize comments per BIP-0014, format user agent and check total size
1913      std::vector<std::string> uacomments;
1914      for (const std::string& cmt : args.GetArgs("-uacomment")) {
1915          if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT))
1916              return InitError(strprintf(_("User Agent comment (%s) contains unsafe characters."), cmt));
1917          uacomments.push_back(cmt);
1918      }
1919      strSubVersion = FormatSubVersion(UA_NAME, CLIENT_VERSION, uacomments);
1920      if (gArgs.IsArgSet("-uaspoof")) {
1921          std::string uaspoof_val = gArgs.GetArg("-uaspoof", "");
1922          if (uaspoof_val == "0" || uaspoof_val.empty()) {
1923              // explicitly disabled, do nothing
1924          } else if (uaspoof_val == "1") {
1925              // enabled, but not specified: just use base name for now
1926              strSubVersion = FormatSubVersion(UA_NAME, CLIENT_VERSION, uacomments, /*base_name_only=*/ true);
1927          } else {
1928              if (uaspoof_val.at(0) != '/') {
1929                  InitWarning(strprintf(_("Specified %s option is not in BIP 14 format. User-agent strings should look like '%s'."), "uaspoof", BIP14_EXAMPLE_UA));
1930              }
1931              if (!uacomments.empty()) {
1932                  InitWarning(_("Both uaspoof and uacomment(s) are specified, but uacomment(s) are ignored when uaspoof is in use."));
1933              }
1934              strSubVersion = uaspoof_val;
1935          }
1936      }
1937      for (auto append : gArgs.GetArgs("-uaappend")) {
1938          if (append.back() != '/') append += '/';
1939          strSubVersion += append;
1940      }
1941      if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
1942          return InitError(strprintf(_("Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments."),
1943              strSubVersion.size(), MAX_SUBVERSION_LENGTH));
1944      }
1945  
1946      // Requesting DNS seeds entails connecting to IPv4/IPv6, which -onlynet options may prohibit:
1947      // If -dnsseed=1 is explicitly specified, abort. If it's left unspecified by the user, we skip
1948      // the DNS seeds by adjusting -dnsseed in InitParameterInteraction.
1949      if (args.GetBoolArg("-dnsseed") == true && !g_reachable_nets.Contains(NET_IPV4) && !g_reachable_nets.Contains(NET_IPV6)) {
1950          return InitError(strprintf(_("Incompatible options: -dnsseed=1 was explicitly specified, but -onlynet forbids connections to IPv4/IPv6")));
1951      };
1952  
1953      // Check for host lookup allowed before parsing any network related parameters
1954      fNameLookup = args.GetBoolArg("-dns", DEFAULT_NAME_LOOKUP);
1955  
1956      Proxy onion_proxy;
1957  
1958      bool proxyRandomize = args.GetBoolArg("-proxyrandomize", DEFAULT_PROXYRANDOMIZE);
1959      // -proxy sets a proxy for outgoing network traffic, possibly per network.
1960      // -noproxy, -proxy=0 or -proxy="" can be used to remove the proxy setting, this is the default
1961      Proxy ipv4_proxy;
1962      Proxy ipv6_proxy;
1963      Proxy name_proxy;
1964      Proxy cjdns_proxy;
1965      for (const std::string& param_value : args.GetArgs("-proxy")) {
1966          const auto eq_pos{param_value.rfind('=')};
1967          const std::string proxyArg{param_value.substr(0, eq_pos)}; // e.g. 127.0.0.1:9050=ipv4 -> 127.0.0.1:9050
1968          std::string net_str;
1969          if (eq_pos != std::string::npos) {
1970              if (eq_pos + 1 == param_value.length()) {
1971                  return InitError(strprintf(_("Invalid -proxy address or hostname, ends with '=': '%s'"), param_value));
1972              }
1973              net_str = ToLower(param_value.substr(eq_pos + 1)); // e.g. 127.0.0.1:9050=ipv4 -> ipv4
1974          }
1975  
1976          Proxy addrProxy;
1977        if (!proxyArg.empty() && proxyArg != "0") {
1978          if (IsUnixSocketPath(proxyArg)) {
1979              addrProxy = Proxy(proxyArg, proxyRandomize);
1980          } else {
1981              const std::optional<CService> proxyAddr{Lookup(proxyArg, 9050, fNameLookup)};
1982              if (!proxyAddr.has_value()) {
1983                  return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg));
1984              }
1985  
1986              addrProxy = Proxy(proxyAddr.value(), proxyRandomize);
1987          }
1988  
1989          if (!addrProxy.IsValid())
1990              return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg));
1991        }
1992  
1993          if (net_str.empty()) { // For all networks.
1994              ipv4_proxy = ipv6_proxy = name_proxy = cjdns_proxy = onion_proxy = addrProxy;
1995          } else if (net_str == "ipv4") {
1996              ipv4_proxy = name_proxy = addrProxy;
1997          } else if (net_str == "ipv6") {
1998              ipv6_proxy = name_proxy = addrProxy;
1999          } else if (net_str == "tor" || net_str == "onion") {
2000              onion_proxy = addrProxy;
2001          } else if (net_str == "cjdns") {
2002              cjdns_proxy = addrProxy;
2003          } else {
2004              return InitError(strprintf(_("Unrecognized network in -proxy='%s': '%s'"), param_value, net_str));
2005          }
2006      }
2007      if (ipv4_proxy.IsValid()) {
2008          SetProxy(NET_IPV4, ipv4_proxy);
2009      }
2010      if (ipv6_proxy.IsValid()) {
2011          SetProxy(NET_IPV6, ipv6_proxy);
2012      }
2013      if (name_proxy.IsValid()) {
2014          SetNameProxy(name_proxy);
2015      }
2016      if (cjdns_proxy.IsValid()) {
2017          SetProxy(NET_CJDNS, cjdns_proxy);
2018      }
2019  
2020      const bool onlynet_used_with_onion{!onlynets.empty() && g_reachable_nets.Contains(NET_ONION)};
2021  
2022      // -onion can be used to set only a proxy for .onion, or override normal proxy for .onion addresses
2023      // -noonion (or -onion=0) disables connecting to .onion entirely
2024      // An empty string is used to not override the onion proxy (in which case it defaults to -proxy set above, or none)
2025      std::string onionArg = args.GetArg("-onion", "");
2026      if (onionArg != "") {
2027          if (onionArg == "0") { // Handle -noonion/-onion=0
2028              onion_proxy = Proxy{};
2029              if (onlynet_used_with_onion) {
2030                  return InitError(
2031                      _("Outbound connections restricted to Tor (-onlynet=onion) but the proxy for "
2032                        "reaching the Tor network is explicitly forbidden: -onion=0"));
2033              }
2034          } else {
2035              if (IsUnixSocketPath(onionArg)) {
2036                  onion_proxy = Proxy(onionArg, proxyRandomize);
2037              } else {
2038                  const std::optional<CService> addr{Lookup(onionArg, 9050, fNameLookup)};
2039                  if (!addr.has_value() || !addr->IsValid()) {
2040                      return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg));
2041                  }
2042  
2043                  onion_proxy = Proxy(addr.value(), proxyRandomize);
2044              }
2045          }
2046      }
2047  
2048      if (onion_proxy.IsValid()) {
2049          SetProxy(NET_ONION, onion_proxy);
2050      } else {
2051          // If -listenonion is set, then we will (try to) connect to the Tor control port
2052          // later from the torcontrol thread and may retrieve the onion proxy from there.
2053          const bool listenonion_disabled{!args.GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION)};
2054          if (onlynet_used_with_onion && listenonion_disabled) {
2055              return InitError(
2056                  _("Outbound connections restricted to Tor (-onlynet=onion) but the proxy for "
2057                    "reaching the Tor network is not provided: none of -proxy, -onion or "
2058                    "-listenonion is given"));
2059          }
2060          g_reachable_nets.Remove(NET_ONION);
2061      }
2062  
2063      for (const std::string& strAddr : args.GetArgs("-externalip")) {
2064          const std::optional<CService> addrLocal{Lookup(strAddr, GetListenPort(), fNameLookup)};
2065          if (addrLocal.has_value() && addrLocal->IsValid())
2066              AddLocal(addrLocal.value(), LOCAL_MANUAL);
2067          else
2068              return InitError(ResolveErrMsg("externalip", strAddr));
2069      }
2070  
2071  #ifdef ENABLE_ZMQ
2072      g_zmq_notification_interface = CZMQNotificationInterface::Create(
2073          [&chainman = node.chainman](std::vector<uint8_t>& block, const CBlockIndex& index) {
2074              assert(chainman);
2075              return chainman->m_blockman.ReadRawBlock(block, WITH_LOCK(cs_main, return index.GetBlockPos()));
2076          });
2077  
2078      if (g_zmq_notification_interface) {
2079          validation_signals.RegisterValidationInterface(g_zmq_notification_interface.get());
2080      }
2081  #endif
2082  
2083      // ********************************************************* Step 7: load block chain
2084  
2085      // cache size calculations
2086      if (args.GetIntArg("-dbcache")) {
2087          node::LogOversizedDbCache(args);
2088      } else {
2089          node::LogAutoDbCacheSettings();
2090      }
2091      const auto [index_cache_sizes, kernel_cache_sizes] = CalculateCacheSizes(args, g_enabled_filter_types.size());
2092  
2093      LogInfo("Cache configuration:");
2094      LogInfo("* Using %.1f MiB for block index database", kernel_cache_sizes.block_tree_db * (1.0 / 1024 / 1024));
2095      if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
2096          LogInfo("* Using %.1f MiB for transaction index database", index_cache_sizes.tx_index * (1.0 / 1024 / 1024));
2097      }
2098      for (BlockFilterType filter_type : g_enabled_filter_types) {
2099          LogInfo("* Using %.1f MiB for %s block filter index database",
2100                    index_cache_sizes.filter_index * (1.0 / 1024 / 1024), BlockFilterTypeName(filter_type));
2101      }
2102      LogInfo("* Using %.1f MiB for chain state database", kernel_cache_sizes.coins_db * (1.0 / 1024 / 1024));
2103  
2104      assert(!node.mempool);
2105      assert(!node.chainman);
2106  
2107      bool do_reindex{args.GetBoolArg("-reindex", false)};
2108      const bool do_reindex_chainstate{args.GetBoolArg("-reindex-chainstate", false)};
2109  
2110      // Chainstate initialization and loading may be retried once with reindexing by GUI users
2111      auto [status, error] = InitAndLoadChainstate(
2112          node,
2113          do_reindex,
2114          do_reindex_chainstate,
2115          kernel_cache_sizes,
2116          args);
2117      if (status == ChainstateLoadStatus::FAILURE && !do_reindex && !ShutdownRequested(node)) {
2118          // If reindex=auto, directly start the reindex
2119          bool fAutoReindex = (args.GetArg("-reindex", "0") == "auto");
2120          bool do_retry;
2121          if (!fAutoReindex) {
2122          // suggest a reindex
2123              do_retry = HasTestOption(args, "reindex_after_failure_noninteractive_yes") ||
2124              uiInterface.ThreadSafeQuestion(
2125              error + Untranslated(".\n\n") + _("Do you want to rebuild the databases now?"),
2126              error.original + ".\nPlease restart with -reindex or -reindex-chainstate to recover.",
2127              "", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
2128          } else {
2129              LogPrintf("Automatically running a reindex.\n");
2130              do_retry = true;
2131          }
2132          if (!do_retry) {
2133              return false;
2134          }
2135          do_reindex = true;
2136          if (!Assert(node.shutdown_signal)->reset()) {
2137              LogError("Internal error: failed to reset shutdown signal.\n");
2138          }
2139          std::tie(status, error) = InitAndLoadChainstate(
2140              node,
2141              do_reindex,
2142              do_reindex_chainstate,
2143              kernel_cache_sizes,
2144              args);
2145      }
2146      if (status != ChainstateLoadStatus::SUCCESS && status != ChainstateLoadStatus::INTERRUPTED) {
2147          return InitError(error);
2148      }
2149  
2150      // As LoadBlockIndex can take several minutes, it's possible the user
2151      // requested to kill the GUI during the last operation. If so, exit.
2152      if (ShutdownRequested(node)) {
2153          LogPrintf("Shutdown requested. Exiting.\n");
2154          return true;
2155      }
2156  
2157      ChainstateManager& chainman = *Assert(node.chainman);
2158  
2159      // Apply flag day transitions to mempool options (taproot rejection, etc.)
2160      if (node.mempool) {
2161          const int64_t tip_mtp = chainman.ActiveChain().Tip()
2162              ? chainman.ActiveChain().Tip()->GetMedianTimePast()
2163              : 0;
2164          ApplyMempoolFlagDay(tip_mtp, node.mempool->m_opts, args);
2165      }
2166  
2167      auto& kernel_notifications{*Assert(node.notifications)};
2168  
2169      assert(!node.peerman);
2170      node.peerman = PeerManager::make(*node.connman, *node.addrman,
2171                                       node.banman.get(), chainman,
2172                                       *node.mempool, *node.warnings,
2173                                       peerman_opts);
2174      validation_signals.RegisterValidationInterface(node.peerman.get());
2175  
2176      // ********************************************************* Step 8: start indexers
2177  
2178      if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
2179          g_txindex = std::make_unique<TxIndex>(interfaces::MakeChain(node), index_cache_sizes.tx_index, false, do_reindex);
2180          node.indexes.emplace_back(g_txindex.get());
2181      }
2182  
2183      for (const auto& filter_type : g_enabled_filter_types) {
2184          InitBlockFilterIndex([&]{ return interfaces::MakeChain(node); }, filter_type, index_cache_sizes.filter_index, false, do_reindex);
2185          node.indexes.emplace_back(GetBlockFilterIndex(filter_type));
2186      }
2187  
2188      if (args.GetBoolArg("-coinstatsindex", DEFAULT_COINSTATSINDEX)) {
2189          g_coin_stats_index = std::make_unique<CoinStatsIndex>(interfaces::MakeChain(node), /*cache_size=*/0, false, do_reindex);
2190          node.indexes.emplace_back(g_coin_stats_index.get());
2191      }
2192  
2193      // Init indexes
2194      for (auto index : node.indexes) if (!index->Init()) return false;
2195  
2196      // ********************************************************* Step 9: load wallet
2197      for (const auto& client : node.chain_clients) {
2198          if (!client->load()) {
2199              return false;
2200          }
2201      }
2202  
2203      // ********************************************************* Step 10: data directory maintenance
2204  
2205      // if pruning, perform the initial blockstore prune
2206      // after any wallet rescanning has taken place.
2207      if (chainman.m_blockman.IsPruneMode()) {
2208          if (chainman.m_blockman.m_blockfiles_indexed) {
2209              LOCK(cs_main);
2210              for (Chainstate* chainstate : chainman.GetAll()) {
2211                  uiInterface.InitMessage(_("Pruning blockstore…"));
2212                  chainstate->PruneAndFlush();
2213              }
2214          }
2215      } else {
2216          // Prior to setting NODE_NETWORK, check if we can provide historical blocks.
2217          if (!WITH_LOCK(chainman.GetMutex(), return chainman.BackgroundSyncInProgress())) {
2218              LogInfo("Setting NODE_NETWORK in non-prune mode");
2219              g_local_services = ServiceFlags(g_local_services | NODE_NETWORK);
2220          } else {
2221              LogPrintf("Running node in NODE_NETWORK_LIMITED mode until snapshot background sync completes\n");
2222          }
2223      }
2224  
2225      // ********************************************************* Step 11: import blocks
2226  
2227      if (!CheckDiskSpace(args.GetDataDirNet())) {
2228          InitError(strprintf(_("Error: Disk space is low for %s"), fs::quoted(fs::PathToString(args.GetDataDirNet()))));
2229          return false;
2230      }
2231      if (!CheckDiskSpace(args.GetBlocksDirPath())) {
2232          InitError(strprintf(_("Error: Disk space is low for %s"), fs::quoted(fs::PathToString(args.GetBlocksDirPath()))));
2233          return false;
2234      }
2235  
2236      int chain_active_height = WITH_LOCK(cs_main, return chainman.ActiveChain().Height());
2237  
2238      // On first startup, warn on low block storage space
2239      if (!do_reindex && !do_reindex_chainstate && chain_active_height <= 1) {
2240          uint64_t assumed_chain_bytes{chainparams.AssumedBlockchainSize() * 1'000'000'000};
2241          uint64_t additional_bytes_needed{
2242              chainman.m_blockman.IsPruneMode() ?
2243                  std::min(chainman.m_blockman.GetPruneTarget(), assumed_chain_bytes) :
2244                  assumed_chain_bytes};
2245  
2246          if (!CheckDiskSpace(args.GetBlocksDirPath(), additional_bytes_needed)) {
2247              InitWarning(strprintf(_(
2248                      "Disk space for %s may not accommodate the block files. " \
2249                      "Approximately %u GB of data will be stored in this directory."
2250                  ),
2251                  fs::quoted(fs::PathToString(args.GetBlocksDirPath())),
2252                  CeilDiv(additional_bytes_needed, 1'000'000'000)
2253              ));
2254          }
2255      }
2256  
2257  #if HAVE_SYSTEM
2258      if (args.IsArgSet("-blocknotify")) {
2259          auto blocknotify_commands = args.GetArgs("-blocknotify");
2260          uiInterface.NotifyBlockTip_connect([blocknotify_commands](SynchronizationState sync_state, const CBlockIndex* pBlockIndex) {
2261              if (sync_state != SynchronizationState::POST_INIT || !pBlockIndex) return;
2262              const std::string blockhash_hex = pBlockIndex->GetBlockHash().GetHex();
2263              for (std::string command : blocknotify_commands) {
2264                  ReplaceAll(command, "%s", blockhash_hex);
2265  
2266                  std::thread t(runCommand, command);
2267                  t.detach(); // thread runs free
2268              }
2269          });
2270      }
2271  #endif
2272  
2273      std::vector<fs::path> vImportFiles;
2274      for (const std::string& strFile : args.GetArgs("-loadblock")) {
2275          vImportFiles.push_back(fs::PathFromString(strFile));
2276      }
2277  
2278      node.background_init_thread = std::thread(&util::TraceThread, "initload", [=, &chainman, &args, &node] {
2279          ScheduleBatchPriority();
2280          // Import blocks and ActivateBestChain()
2281          ImportBlocks(chainman, vImportFiles);
2282          WITH_LOCK(::cs_main, chainman.UpdateIBDStatus());
2283          if (args.GetBoolArg("-stopafterblockimport", DEFAULT_STOPAFTERBLOCKIMPORT)) {
2284              LogPrintf("Stopping after block import\n");
2285              if (!(Assert(node.shutdown_request))()) {
2286                  LogError("Failed to send shutdown signal after finishing block import\n");
2287              }
2288              return;
2289          }
2290  
2291          // Start indexes initial sync
2292          if (!StartIndexBackgroundSync(node)) {
2293              bilingual_str err_str = _("Failed to start indexes, shutting down..");
2294              chainman.GetNotifications().fatalError(err_str);
2295              return;
2296          }
2297          // Load mempool from disk
2298          if (auto* pool{chainman.ActiveChainstate().GetMempool()}) {
2299              LoadMempool(*pool, ShouldPersistMempool(args) ? MempoolPath(args) : fs::path{}, chainman.ActiveChainstate(), {
2300                  .load_knots_data = true,
2301              });
2302              pool->SetLoadTried(!chainman.m_interrupt);
2303          }
2304      });
2305  
2306      /*
2307       * Wait for genesis block to be processed. Typically kernel_notifications.m_tip_block
2308       * has already been set by a call to LoadChainTip() in CompleteChainstateInitialization().
2309       * But this is skipped if the chainstate doesn't exist yet or is being wiped:
2310       *
2311       * 1. first startup with an empty datadir
2312       * 2. reindex
2313       * 3. reindex-chainstate
2314       *
2315       * In these case it's connected by a call to ActivateBestChain() in the initload thread.
2316       */
2317      {
2318          WAIT_LOCK(kernel_notifications.m_tip_block_mutex, lock);
2319          kernel_notifications.m_tip_block_cv.wait(lock, [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
2320              return kernel_notifications.TipBlock() || ShutdownRequested(node);
2321          });
2322      }
2323  
2324      if (ShutdownRequested(node)) {
2325          return true;
2326      }
2327  
2328      // ********************************************************* Step 12: start node
2329  
2330      int64_t best_block_time{};
2331      {
2332          LOCK(chainman.GetMutex());
2333          const auto& tip{*Assert(chainman.ActiveTip())};
2334          LogPrintf("block tree size = %u\n", chainman.BlockIndex().size());
2335          chain_active_height = tip.nHeight;
2336          best_block_time = tip.GetBlockTime();
2337          if (tip_info) {
2338              tip_info->block_height = chain_active_height;
2339              tip_info->block_time = best_block_time;
2340              tip_info->verification_progress = chainman.GuessVerificationProgress(&tip);
2341          }
2342          if (tip_info && chainman.m_best_header) {
2343              tip_info->header_height = chainman.m_best_header->nHeight;
2344              tip_info->header_time = chainman.m_best_header->GetBlockTime();
2345          }
2346      }
2347      LogPrintf("nBestHeight = %d\n", chain_active_height);
2348      if (node.peerman) node.peerman->SetBestBlock(chain_active_height, std::chrono::seconds{best_block_time});
2349  
2350      // Map ports with UPnP or NAT-PMP
2351      StartMapPort(args.GetBoolArg("-upnp", DEFAULT_UPNP), args.GetBoolArg("-natpmp", DEFAULT_NATPMP));
2352  
2353      CConnman::Options connOptions;
2354      connOptions.m_local_services = g_local_services;
2355      connOptions.m_max_automatic_connections = nMaxConnections;
2356      connOptions.uiInterface = &uiInterface;
2357      connOptions.m_banman = node.banman.get();
2358      connOptions.m_msgproc = node.peerman.get();
2359      connOptions.nSendBufferMaxSize = 1000 * args.GetIntArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER);
2360      connOptions.nReceiveFloodSize = 1000 * args.GetIntArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER);
2361      connOptions.m_added_nodes = args.GetArgs("-addnode");
2362      connOptions.nMaxOutboundLimit = *opt_max_upload;
2363      connOptions.m_peer_connect_timeout = peer_connect_timeout;
2364      connOptions.whitelist_forcerelay = args.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY);
2365      connOptions.whitelist_relay = args.GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY);
2366      connOptions.m_capture_messages = args.GetBoolArg("-capturemessages", false);
2367      connOptions.disable_v1conn_clearnet = args.GetBoolArg("-v2onlyclearnet", false);
2368  
2369      // Port to bind to if `-bind=addr` is provided without a `:port` suffix.
2370      const uint16_t default_bind_port =
2371          static_cast<uint16_t>(args.GetIntArg("-port", Params().GetDefaultPort()));
2372  
2373      const uint16_t default_bind_port_onion = default_bind_port + 1;
2374  
2375      const auto BadPortWarning = [](const char* prefix, uint16_t port) {
2376          return strprintf(_("%s request to listen on port %u. This port is considered \"bad\" and "
2377                             "thus it is unlikely that any peer will connect to it. See "
2378                             "doc/p2p-bad-ports.md for details and a full list."),
2379                           prefix,
2380                           port);
2381      };
2382  
2383      for (const std::string& bind_arg : args.GetArgs("-bind")) {
2384          std::optional<CService> bind_addr;
2385          const size_t index = bind_arg.rfind('=');
2386          if (index == std::string::npos) {
2387              bind_addr = Lookup(bind_arg, default_bind_port, /*fAllowLookup=*/false);
2388              if (bind_addr.has_value()) {
2389                  connOptions.vBinds.push_back(bind_addr.value());
2390                  if (IsBadPort(bind_addr.value().GetPort())) {
2391                      InitWarning(BadPortWarning("-bind", bind_addr.value().GetPort()));
2392                  }
2393                  continue;
2394              }
2395          } else {
2396              const std::string network_type = bind_arg.substr(index + 1);
2397              if (network_type == "onion") {
2398                  const std::string truncated_bind_arg = bind_arg.substr(0, index);
2399                  bind_addr = Lookup(truncated_bind_arg, default_bind_port_onion, false);
2400                  if (bind_addr.has_value()) {
2401                      connOptions.onion_binds.push_back(bind_addr.value());
2402                      continue;
2403                  }
2404              }
2405          }
2406          return InitError(ResolveErrMsg("bind", bind_arg));
2407      }
2408  
2409      NetPermissionFlags all_permission_flags{NetPermissionFlags::None};
2410  
2411      for (const std::string& strBind : args.GetArgs("-whitebind")) {
2412          NetWhitebindPermissions whitebind;
2413          bilingual_str error;
2414          if (!NetWhitebindPermissions::TryParse(strBind, whitebind, error)) return InitError(error);
2415          NetPermissions::AddFlag(all_permission_flags, whitebind.m_flags);
2416          connOptions.vWhiteBinds.push_back(whitebind);
2417      }
2418  
2419      // If the user did not specify -bind= or -whitebind= then we bind
2420      // on any address - 0.0.0.0 (IPv4) and :: (IPv6).
2421      connOptions.bind_on_any = args.GetArgs("-bind").empty() && args.GetArgs("-whitebind").empty();
2422  
2423      // Emit a warning if a bad port is given to -port= but only if -bind and -whitebind are not
2424      // given, because if they are, then -port= is ignored.
2425      if (connOptions.bind_on_any && args.IsArgSet("-port")) {
2426          const uint16_t port_arg = args.GetIntArg("-port", 0);
2427          if (IsBadPort(port_arg)) {
2428              InitWarning(BadPortWarning("-port", port_arg));
2429          }
2430      }
2431  
2432      connOptions.listenonion = args.GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION);
2433  
2434      CService onion_service_target;
2435      if (!connOptions.onion_binds.empty()) {
2436          onion_service_target = connOptions.onion_binds.front();
2437      } else if (!connOptions.vBinds.empty()) {
2438          onion_service_target = connOptions.vBinds.front();
2439          if (connOptions.listenonion) {
2440              std::string alternate_connections{"clearnet"}, only_from_localhost;
2441              if (onion_service_target.IsBindAny()) {
2442                  only_from_localhost = " from localhost";
2443              } else if (onion_service_target.IsLocal()) {
2444                  alternate_connections = "local";
2445              }
2446              InitWarning(strprintf(_("You are using a common listening port (%s) for both Tor and %s connections. All connections to this port%s will be assumed to be Tor connections, and will be denied any whitelist permissions. If this is not your intent, setup a separate -bind=<addr>[:<port>]=onion configuration, or set -listenonion=0."),
2447                                    onion_service_target.ToStringAddrPort(),
2448                                    alternate_connections,
2449                                    only_from_localhost));
2450          }
2451      } else {
2452          onion_service_target = DefaultOnionServiceTarget(default_bind_port_onion);
2453          connOptions.onion_binds.push_back(onion_service_target);
2454      }
2455  
2456      if (connOptions.listenonion) {
2457          if (connOptions.onion_binds.size() > 1) {
2458              InitWarning(strprintf(_("More than one onion bind address is provided. Using %s "
2459                                      "for the automatically created Tor onion service."),
2460                                    onion_service_target.ToStringAddrPort()));
2461          }
2462          if (onion_service_target.IsBindAny()) {
2463              CNetAddr loopback_addr = onion_service_target;
2464              // NOTE: GetNetwork is not_publicly_routable here
2465              if (onion_service_target.ToStringAddr() == "0.0.0.0") {
2466                  loopback_addr = LookupHost("127.0.0.1", /*fAllowLookup=*/false).value();
2467              } else {
2468                  loopback_addr = LookupHost("[::1]", /*fAllowLookup=*/false).value();
2469              }
2470              onion_service_target.SetIP(loopback_addr);
2471          }
2472          StartTorControl(onion_service_target);
2473      }
2474  
2475      if (connOptions.bind_on_any) {
2476          // Only add all IP addresses of the machine if we would be listening on
2477          // any address - 0.0.0.0 (IPv4) and :: (IPv6).
2478          Discover();
2479      }
2480  
2481      std::vector<std::string> whitelist_opts = args.GetArgs("-whitelist");
2482      if ((g_local_services & NODE_BLOOM) != NODE_BLOOM && args.GetBoolArg("-peerbloomfilters", true)) {
2483          // If peerbloomfilters isn't specified, enable it only for localhost by default
2484          whitelist_opts.emplace_back("in,out,bloomfilter@127.0.0.0/8");
2485          whitelist_opts.emplace_back("in,out,bloomfilter@[::1]/128");
2486      }
2487  
2488      for (const auto& net : whitelist_opts) {
2489          NetWhitelistPermissions subnet;
2490          ConnectionDirection connection_direction;
2491          bilingual_str error;
2492          if (!NetWhitelistPermissions::TryParse(net, subnet, connection_direction, error)) return InitError(error);
2493          NetPermissions::AddFlag(all_permission_flags, subnet.m_flags);
2494          if (connection_direction & ConnectionDirection::In) {
2495              connOptions.vWhitelistedRangeIncoming.push_back(subnet);
2496          }
2497          if (connection_direction & ConnectionDirection::Out) {
2498              connOptions.vWhitelistedRangeOutgoing.push_back(subnet);
2499          }
2500      }
2501  
2502      if (NetPermissions::HasFlag(all_permission_flags, NetPermissionFlags::BlockFilters_Explicit)) {
2503          if (g_enabled_filter_types.count(BlockFilterType::BASIC) != 1) {
2504              return InitError(_("Cannot grant blockfilters permission without -blockfilterindex."));
2505          }
2506      }
2507  
2508      connOptions.vSeedNodes = args.GetArgs("-seednode");
2509  
2510      const auto connect = args.GetArgs("-connect");
2511      if (!connect.empty() || args.IsArgNegated("-connect")) {
2512          // Do not initiate other outgoing connections when connecting to trusted
2513          // nodes, or when -noconnect is specified.
2514          connOptions.m_use_addrman_outgoing = false;
2515  
2516          if (connect.size() != 1 || connect[0] != "0") {
2517              connOptions.m_specified_outgoing = connect;
2518          }
2519          if (!connOptions.m_specified_outgoing.empty() && !connOptions.vSeedNodes.empty()) {
2520              LogPrintf("-seednode is ignored when -connect is used\n");
2521          }
2522  
2523          if (args.IsArgSet("-dnsseed") && args.GetBoolArg("-dnsseed", DEFAULT_DNSSEED) && args.IsArgSet("-proxy")) {
2524              LogPrintf("-dnsseed is ignored when -connect is used and -proxy is specified\n");
2525          }
2526      }
2527  
2528      const std::string& i2psam_arg = args.GetArg("-i2psam", "");
2529      if (!i2psam_arg.empty()) {
2530          const std::optional<CService> addr{Lookup(i2psam_arg, 7656, fNameLookup)};
2531          if (!addr.has_value() || !addr->IsValid()) {
2532              return InitError(strprintf(_("Invalid -i2psam address or hostname: '%s'"), i2psam_arg));
2533          }
2534          SetProxy(NET_I2P, Proxy{addr.value()});
2535      } else {
2536          if (!onlynets.empty() && g_reachable_nets.Contains(NET_I2P)) {
2537              return InitError(
2538                  _("Outbound connections restricted to i2p (-onlynet=i2p) but "
2539                    "-i2psam is not provided"));
2540          }
2541          g_reachable_nets.Remove(NET_I2P);
2542      }
2543  
2544      connOptions.m_i2p_accept_incoming = args.GetBoolArg("-i2pacceptincoming", DEFAULT_I2P_ACCEPT_INCOMING);
2545  
2546      if (!node.connman->Start(scheduler, connOptions)) {
2547          return false;
2548      }
2549  
2550      // Cross-chain mempool gossip bridge: joins limenka's transaction flow
2551      // with the foreign networks.  Transactions leak in both directions;
2552      // blocks and headers never cross.
2553      if (args.GetBoolArg("-mempoolbridge", false)) {
2554          const auto bridge_peers = args.GetArgs("-bridgepeer");
2555          if (!bridge_peers.empty()) {
2556              node.mempool_bridge = std::make_shared<node::MempoolBridge>(node);
2557              if (!node.mempool_bridge->Start(bridge_peers)) {
2558                  node.mempool_bridge.reset();
2559              }
2560          } else {
2561              LogPrintf("mempoolbridge: -mempoolbridge set but no -bridgepeer entries given\n");
2562          }
2563      }
2564  
2565      // ********************************************************* Step 13: finished
2566  
2567      // At this point, the RPC is "started", but still in warmup, which means it
2568      // cannot yet be called. Before we make it callable, we need to make sure
2569      // that the RPC's view of the best block is valid and consistent with
2570      // ChainstateManager's active tip.
2571      SetRPCWarmupFinished();
2572  
2573      uiInterface.InitMessage(_("Done loading"));
2574  
2575  
2576      for (const auto& client : node.chain_clients) {
2577          client->start(scheduler);
2578      }
2579  
2580      BanMan* banman = node.banman.get();
2581      scheduler.scheduleEvery([banman]{
2582          banman->DumpBanlist();
2583      }, DUMP_BANS_INTERVAL);
2584  
2585      banman->SetScheduler(scheduler);
2586  
2587      if (node.peerman) node.peerman->StartScheduledTasks(scheduler);
2588  
2589  #if HAVE_SYSTEM
2590      StartupNotify(args);
2591  #endif
2592  
2593      if (node.chainman->IsInitialBlockDownload()) {
2594          node.scheduler->scheduleFromNow([&node] {
2595              SyncCoinsTipAfterChainSync(node);
2596          }, SYNC_CHECK_INTERVAL);
2597      }
2598  
2599      return true;
2600  }
2601  
2602  bool StartIndexBackgroundSync(NodeContext& node)
2603  {
2604      // Find the oldest block among all indexes.
2605      // This block is used to verify that we have the required blocks' data stored on disk,
2606      // starting from that point up to the current tip.
2607      // indexes_start_block='nullptr' means "start from height 0".
2608      std::optional<const CBlockIndex*> indexes_start_block;
2609      BaseIndex* older_index{nullptr};
2610      ChainstateManager& chainman = *Assert(node.chainman);
2611      const Chainstate& chainstate = WITH_LOCK(::cs_main, return chainman.GetChainstateForIndexing());
2612      const CChain& index_chain = chainstate.m_chain;
2613  
2614      for (auto index : node.indexes) {
2615          const IndexSummary& summary = index->GetSummary();
2616          if (summary.synced) continue;
2617  
2618          // Get the last common block between the index best block and the active chain
2619          LOCK(::cs_main);
2620          const CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(summary.best_block_hash);
2621          if (!index_chain.Contains(pindex)) {
2622              pindex = index_chain.FindFork(pindex);
2623          }
2624  
2625          if (!indexes_start_block || !pindex || pindex->nHeight < indexes_start_block.value()->nHeight) {
2626              indexes_start_block = pindex;
2627              older_index = index;
2628              if (!pindex) break; // Starting from genesis so no need to look for earlier block.
2629          }
2630      };
2631  
2632      // Verify all blocks needed to sync to current tip are present.
2633      if (indexes_start_block) {
2634          LOCK(::cs_main);
2635          const CBlockIndex* start_block = *indexes_start_block;
2636          if (!start_block) start_block = chainman.ActiveChain().Genesis();
2637          if (!chainman.m_blockman.CheckBlockDataAvailability(*index_chain.Tip(), *Assert(start_block))) {
2638              return InitError(strprintf(
2639                  _("Index \"%s\" needs block data that has been pruned.\nRestart with -reindex to rebuild (re-downloading the entire blockchain), or %s to disable."),
2640                  older_index->GetName(), older_index->GetDisableAction()));
2641          }
2642      }
2643  
2644      // Start threads
2645      for (auto index : node.indexes) if (!index->StartBackgroundSync()) return false;
2646      return true;
2647  }
2648