Bitcoin ABC  0.26.3
P2P Digital Currency
init.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2018 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 
6 #if defined(HAVE_CONFIG_H)
7 #include <config/bitcoin-config.h>
8 #endif
9 
10 #include <init.h>
11 
12 #include <kernel/mempool_persist.h>
14 
15 #include <addrman.h>
16 #include <avalanche/avalanche.h>
17 #include <avalanche/processor.h>
18 #include <avalanche/proof.h> // For AVALANCHE_LEGACY_PROOF_DEFAULT
19 #include <avalanche/validation.h>
20 #include <avalanche/voterecord.h> // For AVALANCHE_VOTE_STALE_*
21 #include <banman.h>
22 #include <blockfilter.h>
23 #include <chain.h>
24 #include <chainparams.h>
25 #include <common/args.h>
26 #include <compat/sanity.h>
27 #include <config.h>
28 #include <consensus/amount.h>
29 #include <currencyunit.h>
30 #include <flatfile.h>
31 #include <hash.h>
32 #include <httprpc.h>
33 #include <httpserver.h>
34 #include <index/blockfilterindex.h>
35 #include <index/coinstatsindex.h>
36 #include <index/txindex.h>
37 #include <init/common.h>
38 #include <interfaces/chain.h>
39 #include <interfaces/node.h>
40 #include <mapport.h>
41 #include <mempool_args.h>
42 #include <net.h>
43 #include <net_permissions.h>
44 #include <net_processing.h>
45 #include <netbase.h>
46 #include <node/blockmanager_args.h>
47 #include <node/blockstorage.h>
48 #include <node/caches.h>
49 #include <node/chainstate.h>
51 #include <node/context.h>
54 #include <node/miner.h>
55 #include <node/peerman_args.h>
56 #include <node/ui_interface.h>
58 #include <policy/policy.h>
59 #include <policy/settings.h>
60 #include <rpc/blockchain.h>
61 #include <rpc/register.h>
62 #include <rpc/server.h>
63 #include <rpc/util.h>
64 #include <scheduler.h>
65 #include <script/scriptcache.h>
66 #include <script/sigcache.h>
67 #include <script/standard.h>
68 #include <shutdown.h>
69 #include <sync.h>
70 #include <timedata.h>
71 #include <torcontrol.h>
72 #include <txdb.h>
73 #include <txmempool.h>
74 #include <util/asmap.h>
75 #include <util/check.h>
76 #include <util/fs.h>
77 #include <util/fs_helpers.h>
78 #include <util/moneystr.h>
79 #include <util/string.h>
80 #include <util/syserror.h>
81 #include <util/thread.h>
82 #include <util/threadnames.h>
83 #include <util/translation.h>
84 #include <validation.h>
85 #include <validationinterface.h>
86 #include <walletinitinterface.h>
87 
88 #include <boost/signals2/signal.hpp>
89 
90 #if ENABLE_CHRONIK
91 #include <chronik-cpp/chronik.h>
92 #endif
93 
94 #if ENABLE_ZMQ
97 #include <zmq/zmqrpc.h>
98 #endif
99 
100 #ifndef WIN32
101 #include <cerrno>
102 #include <csignal>
103 #include <sys/stat.h>
104 #endif
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 
117 using kernel::DumpMempool;
119 
121 using node::BlockManager;
122 using node::CacheSizes;
125 using node::fReindex;
128 using node::MempoolPath;
129 using node::NodeContext;
131 using node::ThreadImport;
133 
134 static const bool DEFAULT_PROXYRANDOMIZE = true;
135 static const bool DEFAULT_REST_ENABLE = false;
136 static constexpr bool DEFAULT_CHRONIK = false;
137 
138 #ifdef WIN32
139 // Win32 LevelDB doesn't use filedescriptors, and the ones used for accessing
140 // block files don't count towards the fd_set size limit anyway.
141 #define MIN_CORE_FILEDESCRIPTORS 0
142 #else
143 #define MIN_CORE_FILEDESCRIPTORS 150
144 #endif
145 
146 static const char *DEFAULT_ASMAP_FILENAME = "ip_asn.map";
147 
151 static const char *BITCOIN_PID_FILENAME = "bitcoind.pid";
152 
153 static fs::path GetPidFile(const ArgsManager &args) {
154  return AbsPathForConfigVal(args,
155  args.GetPathArg("-pid", BITCOIN_PID_FILENAME));
156 }
157 
158 [[nodiscard]] static bool CreatePidFile(const ArgsManager &args) {
159  std::ofstream file{GetPidFile(args)};
160  if (file) {
161 #ifdef WIN32
162  tfm::format(file, "%d\n", GetCurrentProcessId());
163 #else
164  tfm::format(file, "%d\n", getpid());
165 #endif
166  return true;
167  } else {
168  return InitError(strprintf(_("Unable to create the PID file '%s': %s"),
170  SysErrorString(errno)));
171  }
172 }
173 
175 //
176 // Shutdown
177 //
178 
179 //
180 // Thread management and startup/shutdown:
181 //
182 // The network-processing threads are all part of a thread group created by
183 // AppInit() or the Qt main() function.
184 //
185 // A clean exit happens when StartShutdown() or the SIGTERM signal handler sets
186 // fRequestShutdown, which makes main thread's WaitForShutdown() interrupts the
187 // thread group.
188 // And then, WaitForShutdown() makes all other on-going threads in the thread
189 // group join the main thread.
190 // Shutdown() is then called to clean up database connections, and stop other
191 // threads that should only be stopped after the main network-processing threads
192 // have exited.
193 //
194 // Shutdown for Qt is very similar, only it uses a QTimer to detect
195 // ShutdownRequested() getting set, and then does the normal Qt shutdown thing.
196 //
197 
201  InterruptRPC();
202  InterruptREST();
205  if (node.avalanche) {
206  // Avalanche needs to be stopped before we interrupt the thread group as
207  // the scheduler will stop working then.
208  node.avalanche->stopEventLoop();
209  }
210  if (node.connman) {
211  node.connman->Interrupt();
212  }
213  if (g_txindex) {
214  g_txindex->Interrupt();
215  }
216  ForEachBlockFilterIndex([](BlockFilterIndex &index) { index.Interrupt(); });
217  if (g_coin_stats_index) {
218  g_coin_stats_index->Interrupt();
219  }
220 }
221 
223  static Mutex g_shutdown_mutex;
224  TRY_LOCK(g_shutdown_mutex, lock_shutdown);
225  if (!lock_shutdown) {
226  return;
227  }
228  LogPrintf("%s: In progress...\n", __func__);
229  Assert(node.args);
230 
235  util::ThreadRename("shutoff");
236  if (node.mempool) {
237  node.mempool->AddTransactionsUpdated(1);
238  }
239 
240  StopHTTPRPC();
241  StopREST();
242  StopRPC();
243  StopHTTPServer();
244  for (const auto &client : node.chain_clients) {
245  client->flush();
246  }
247  StopMapPort();
248 
249  // Because avalanche and the network depend on each other, it is important
250  // to shut them down in this order:
251  // 1. Stop avalanche event loop.
252  // 2. Shutdown network processing.
253  // 3. Destroy avalanche::Processor.
254  // 4. Destroy CConnman
255  if (node.avalanche) {
256  node.avalanche->stopEventLoop();
257  }
258 
259  // Because these depend on each-other, we make sure that neither can be
260  // using the other before destroying them.
261  if (node.peerman) {
262  UnregisterValidationInterface(node.peerman.get());
263  }
264  if (node.connman) {
265  node.connman->Stop();
266  }
267 
268  StopTorControl();
269 
270  // After everything has been shut down, but before things get flushed, stop
271  // the CScheduler/checkqueue, scheduler and load block thread.
272  if (node.scheduler) {
273  node.scheduler->stop();
274  }
275  if (node.chainman && node.chainman->m_load_block.joinable()) {
276  node.chainman->m_load_block.join();
277  }
279 
280  // After the threads that potentially access these pointers have been
281  // stopped, destruct and reset all to nullptr.
282  node.peerman.reset();
283 
284  // Destroy various global instances
285  node.avalanche.reset();
286  node.connman.reset();
287  node.banman.reset();
288  node.addrman.reset();
289 
290  if (node.mempool && node.mempool->GetLoadTried() &&
291  ShouldPersistMempool(*node.args)) {
292  DumpMempool(*node.mempool, MempoolPath(*node.args));
293  }
294 
295  // FlushStateToDisk generates a ChainStateFlushed callback, which we should
296  // avoid missing
297  if (node.chainman) {
298  LOCK(cs_main);
299  for (Chainstate *chainstate : node.chainman->GetAll()) {
300  if (chainstate->CanFlushToDisk()) {
301  chainstate->ForceFlushStateToDisk();
302  }
303  }
304  }
305 
306  // After there are no more peers/RPC left to give us new data which may
307  // generate CValidationInterface callbacks, flush them...
309 
310 #if ENABLE_CHRONIK
311  if (node.args->GetBoolArg("-chronik", DEFAULT_CHRONIK)) {
312  chronik::Stop();
313  }
314 #endif
315 
316  // Stop and delete all indexes only after flushing background callbacks.
317  if (g_txindex) {
318  g_txindex->Stop();
319  g_txindex.reset();
320  }
321  if (g_coin_stats_index) {
322  g_coin_stats_index->Stop();
323  g_coin_stats_index.reset();
324  }
325  ForEachBlockFilterIndex([](BlockFilterIndex &index) { index.Stop(); });
327 
328  // Any future callbacks will be dropped. This should absolutely be safe - if
329  // missing a callback results in an unrecoverable situation, unclean
330  // shutdown would too. The only reason to do the above flushes is to let the
331  // wallet catch up with our current chain to avoid any strange pruning edge
332  // cases and make next startup faster by avoiding rescan.
333 
334  if (node.chainman) {
335  LOCK(cs_main);
336  for (Chainstate *chainstate : node.chainman->GetAll()) {
337  if (chainstate->CanFlushToDisk()) {
338  chainstate->ForceFlushStateToDisk();
339  chainstate->ResetCoinsViews();
340  }
341  }
342  }
343  for (const auto &client : node.chain_clients) {
344  client->stop();
345  }
346 
347 #if ENABLE_ZMQ
351  }
352 #endif
353 
354  node.chain_clients.clear();
358  node.mempool.reset();
359  node.chainman.reset();
360  node.scheduler.reset();
361 
362  try {
363  if (!fs::remove(GetPidFile(*node.args))) {
364  LogPrintf("%s: Unable to remove PID file: File does not exist\n",
365  __func__);
366  }
367  } catch (const fs::filesystem_error &e) {
368  LogPrintf("%s: Unable to remove PID file: %s\n", __func__,
370  }
371 
372  LogPrintf("%s: done\n", __func__);
373 }
374 
380 #ifndef WIN32
381 static void HandleSIGTERM(int) {
382  StartShutdown();
383 }
384 
385 static void HandleSIGHUP(int) {
386  LogInstance().m_reopen_file = true;
387 }
388 #else
389 static BOOL WINAPI consoleCtrlHandler(DWORD dwCtrlType) {
390  StartShutdown();
391  Sleep(INFINITE);
392  return true;
393 }
394 #endif
395 
396 #ifndef WIN32
397 static void registerSignalHandler(int signal, void (*handler)(int)) {
398  struct sigaction sa;
399  sa.sa_handler = handler;
400  sigemptyset(&sa.sa_mask);
401  sa.sa_flags = 0;
402  sigaction(signal, &sa, NULL);
403 }
404 #endif
405 
406 static boost::signals2::connection rpc_notify_block_change_connection;
407 static void OnRPCStarted() {
408  rpc_notify_block_change_connection = uiInterface.NotifyBlockTip_connect(
409  std::bind(RPCNotifyBlockChange, std::placeholders::_2));
410 }
411 
412 static void OnRPCStopped() {
414  RPCNotifyBlockChange(nullptr);
415  g_best_block_cv.notify_all();
416  LogPrint(BCLog::RPC, "RPC stopped.\n");
417 }
418 
420  assert(!node.args);
421  node.args = &gArgs;
422  ArgsManager &argsman = *node.args;
423 
424  SetupHelpOptions(argsman);
425  SetupCurrencyUnitOptions(argsman);
426  // server-only for now
427  argsman.AddArg("-help-debug",
428  "Print help message with debugging options and exit", false,
430 
431  init::AddLoggingArgs(argsman);
432 
433  const auto defaultBaseParams =
435  const auto testnetBaseParams =
437  const auto regtestBaseParams =
439  const auto defaultChainParams =
441  const auto testnetChainParams =
443  const auto regtestChainParams =
445 
446  // Hidden Options
447  std::vector<std::string> hidden_args = {
448  "-dbcrashratio",
449  "-forcecompactdb",
450  "-maxaddrtosend",
451  "-parkdeepreorg",
452  "-automaticunparking",
453  "-replayprotectionactivationtime",
454  "-enableminerfund",
455  "-chronikallowpause",
456  "-chronikcors",
457  // GUI args. These will be overwritten by SetupUIArgs for the GUI
458  "-allowselfsignedrootcertificates",
459  "-choosedatadir",
460  "-lang=<lang>",
461  "-min",
462  "-resetguisettings",
463  "-rootcertificates=<file>",
464  "-splash",
465  "-uiplatform",
466  // TODO remove after the Nov. 2024 upgrade
467  "-augustoactivationtime",
468  };
469 
470  // Set all of the args and their help
471  // When adding new options to the categories, please keep and ensure
472  // alphabetical ordering. Do not translate _(...) -help-debug options, Many
473  // technical terms, and only a very small audience, so is unnecessary stress
474  // to translators.
475  argsman.AddArg("-version", "Print version and exit", ArgsManager::ALLOW_ANY,
477 #if defined(HAVE_SYSTEM)
478  argsman.AddArg(
479  "-alertnotify=<cmd>",
480  "Execute command when a relevant alert is received or we see "
481  "a really long fork (%s in cmd is replaced by message)",
483 #endif
484  argsman.AddArg(
485  "-assumevalid=<hex>",
486  strprintf(
487  "If this block is in the chain assume that it and its ancestors "
488  "are valid and potentially skip their script verification (0 to "
489  "verify all, default: %s, testnet: %s)",
490  defaultChainParams->GetConsensus().defaultAssumeValid.GetHex(),
491  testnetChainParams->GetConsensus().defaultAssumeValid.GetHex()),
493  argsman.AddArg("-blocksdir=<dir>",
494  "Specify directory to hold blocks subdirectory for *.dat "
495  "files (default: <datadir>)",
497  argsman.AddArg("-fastprune",
498  "Use smaller block files and lower minimum prune height for "
499  "testing purposes",
502 #if defined(HAVE_SYSTEM)
503  argsman.AddArg("-blocknotify=<cmd>",
504  "Execute command when the best block changes (%s in cmd is "
505  "replaced by block hash)",
507 #endif
508  argsman.AddArg("-blockreconstructionextratxn=<n>",
509  strprintf("Extra transactions to keep in memory for compact "
510  "block reconstructions (default: %u)",
513  argsman.AddArg(
514  "-blocksonly",
515  strprintf("Whether to reject transactions from network peers. "
516  "Automatic broadcast and rebroadcast of any transactions "
517  "from inbound peers is disabled, unless the peer has the "
518  "'forcerelay' permission. RPC transactions are"
519  " not affected. (default: %u)",
522  argsman.AddArg("-coinstatsindex",
523  strprintf("Maintain coinstats index used by the "
524  "gettxoutsetinfo RPC (default: %u)",
527  argsman.AddArg(
528  "-conf=<file>",
529  strprintf("Specify path to read-only configuration file. Relative "
530  "paths will be prefixed by datadir location. (default: %s)",
533  argsman.AddArg("-datadir=<dir>", "Specify data directory",
535  argsman.AddArg(
536  "-dbbatchsize",
537  strprintf("Maximum database write batch size in bytes (default: %u)",
541  argsman.AddArg(
542  "-dbcache=<n>",
543  strprintf("Set database cache size in MiB (%d to %d, default: %d)",
546  argsman.AddArg(
547  "-includeconf=<file>",
548  "Specify additional configuration file, relative to the -datadir path "
549  "(only useable from configuration file, not command line)",
551  argsman.AddArg("-loadblock=<file>",
552  "Imports blocks from external file on startup",
554  argsman.AddArg("-maxmempool=<n>",
555  strprintf("Keep the transaction memory pool below <n> "
556  "megabytes (default: %u)",
559  argsman.AddArg("-maxorphantx=<n>",
560  strprintf("Keep at most <n> unconnectable transactions in "
561  "memory (default: %u)",
564  argsman.AddArg("-mempoolexpiry=<n>",
565  strprintf("Do not keep transactions in the mempool longer "
566  "than <n> hours (default: %u)",
569  argsman.AddArg(
570  "-minimumchainwork=<hex>",
571  strprintf(
572  "Minimum work assumed to exist on a valid chain in hex "
573  "(default: %s, testnet: %s)",
574  defaultChainParams->GetConsensus().nMinimumChainWork.GetHex(),
575  testnetChainParams->GetConsensus().nMinimumChainWork.GetHex()),
578  argsman.AddArg(
579  "-par=<n>",
580  strprintf("Set the number of script verification threads (%u to %d, 0 "
581  "= auto, <0 = leave that many cores free, default: %d)",
585  argsman.AddArg("-persistmempool",
586  strprintf("Whether to save the mempool on shutdown and load "
587  "on restart (default: %u)",
590  argsman.AddArg(
591  "-pid=<file>",
592  strprintf("Specify pid file. Relative paths will be prefixed "
593  "by a net-specific datadir location. (default: %s)",
596  argsman.AddArg(
597  "-prune=<n>",
598  strprintf("Reduce storage requirements by enabling pruning (deleting) "
599  "of old blocks. This allows the pruneblockchain RPC to be "
600  "called to delete specific blocks, and enables automatic "
601  "pruning of old blocks if a target size in MiB is provided. "
602  "This mode is incompatible with -txindex, -coinstatsindex "
603  "and -rescan. Warning: Reverting this setting requires "
604  "re-downloading the entire blockchain. (default: 0 = disable "
605  "pruning blocks, 1 = allow manual pruning via RPC, >=%u = "
606  "automatically prune block files to stay under the specified "
607  "target size in MiB)",
608  MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024),
610  argsman.AddArg(
611  "-reindex-chainstate",
612  "Rebuild chain state from the currently indexed blocks. When "
613  "in pruning mode or if blocks on disk might be corrupted, use "
614  "full -reindex instead.",
616  argsman.AddArg(
617  "-reindex",
618  "Rebuild chain state and block index from the blk*.dat files on disk",
620  argsman.AddArg(
621  "-settings=<file>",
622  strprintf(
623  "Specify path to dynamic settings data file. Can be disabled with "
624  "-nosettings. File is written at runtime and not meant to be "
625  "edited by users (use %s instead for custom settings). Relative "
626  "paths will be prefixed by datadir location. (default: %s)",
629 #if HAVE_SYSTEM
630  argsman.AddArg("-startupnotify=<cmd>", "Execute command on startup.",
632 #endif
633 #ifndef WIN32
634  argsman.AddArg(
635  "-sysperms",
636  "Create new files with system default permissions, instead of umask "
637  "077 (only effective with disabled wallet functionality)",
639 #else
640  hidden_args.emplace_back("-sysperms");
641 #endif
642  argsman.AddArg("-txindex",
643  strprintf("Maintain a full transaction index, used by the "
644  "getrawtransaction rpc call (default: %d)",
647 #if ENABLE_CHRONIK
648  argsman.AddArg(
649  "-chronik",
650  strprintf("Enable the Chronik indexer, which can be read via a "
651  "dedicated HTTP/Protobuf interface (default: %d)",
654  argsman.AddArg(
655  "-chronikbind=<addr>[:port]",
656  strprintf(
657  "Bind the Chronik indexer to the given address to listen for "
658  "HTTP/Protobuf connections to access the index. Unlike the "
659  "JSON-RPC, it's ok to have this publicly exposed on the internet. "
660  "This option can be specified multiple times (default: %s; default "
661  "port: %u, testnet: %u, regtest: %u)",
662  Join(chronik::DEFAULT_BINDS, ", "),
663  defaultBaseParams->ChronikPort(), testnetBaseParams->ChronikPort(),
664  regtestBaseParams->ChronikPort()),
667  argsman.AddArg("-chroniktokenindex",
668  "Enable token indexing in Chronik (default: 1)",
670  argsman.AddArg("-chroniklokadidindex",
671  "Enable LOKAD ID indexing in Chronik (default: 1)",
673  argsman.AddArg("-chronikreindex",
674  "Reindex the Chronik indexer from genesis, but leave the "
675  "other indexes untouched",
677  argsman.AddArg(
678  "-chroniktxnumcachebuckets",
679  strprintf(
680  "Tuning param of the TxNumCache, specifies how many buckets "
681  "to use on the belt. Caution against setting this too high, "
682  "it may slow down indexing. Set to 0 to disable. (default: %d)",
683  chronik::DEFAULT_TX_NUM_CACHE_BUCKETS),
685  argsman.AddArg(
686  "-chroniktxnumcachebucketsize",
687  strprintf(
688  "Tuning param of the TxNumCache, specifies the size of each bucket "
689  "on the belt. Unlike the number of buckets, this may be increased "
690  "without much danger of slowing the indexer down. The total cache "
691  "size will be `num_buckets * bucket_size * 40B`, so by default the "
692  "cache will require %dkB of memory. (default: %d)",
693  chronik::DEFAULT_TX_NUM_CACHE_BUCKETS *
694  chronik::DEFAULT_TX_NUM_CACHE_BUCKET_SIZE * 40 / 1000,
695  chronik::DEFAULT_TX_NUM_CACHE_BUCKET_SIZE),
697  argsman.AddArg("-chronikperfstats",
698  "Output some performance statistics (e.g. num cache hits, "
699  "seconds spent) into a <datadir>/perf folder. (default: 0)",
701 #endif
702  argsman.AddArg(
703  "-blockfilterindex=<type>",
704  strprintf("Maintain an index of compact filters by block "
705  "(default: %s, values: %s).",
707  " If <type> is not supplied or if <type> = 1, indexes for "
708  "all known types are enabled.",
710  argsman.AddArg(
711  "-usecashaddr",
712  "Use Cash Address for destination encoding instead of base58 "
713  "(activate by default on Jan, 14)",
715 
716  argsman.AddArg(
717  "-addnode=<ip>",
718  "Add a node to connect to and attempt to keep the connection "
719  "open (see the `addnode` RPC command help for more info)",
722  argsman.AddArg("-asmap=<file>",
723  strprintf("Specify asn mapping used for bucketing of the "
724  "peers (default: %s). Relative paths will be "
725  "prefixed by the net-specific datadir location.",
728  argsman.AddArg("-bantime=<n>",
729  strprintf("Default duration (in seconds) of manually "
730  "configured bans (default: %u)",
733  argsman.AddArg(
734  "-bind=<addr>[:<port>][=onion]",
735  strprintf("Bind to given address and always listen on it (default: "
736  "0.0.0.0). Use [host]:port notation for IPv6. Append =onion "
737  "to tag any incoming connections to that address and port as "
738  "incoming Tor connections (default: 127.0.0.1:%u=onion, "
739  "testnet: 127.0.0.1:%u=onion, regtest: 127.0.0.1:%u=onion)",
740  defaultBaseParams->OnionServiceTargetPort(),
741  testnetBaseParams->OnionServiceTargetPort(),
742  regtestBaseParams->OnionServiceTargetPort()),
745  argsman.AddArg(
746  "-connect=<ip>",
747  "Connect only to the specified node(s); -connect=0 disables automatic "
748  "connections (the rules for this peer are the same as for -addnode)",
751  argsman.AddArg(
752  "-discover",
753  "Discover own IP addresses (default: 1 when listening and no "
754  "-externalip or -proxy)",
756  argsman.AddArg("-dns",
757  strprintf("Allow DNS lookups for -addnode, -seednode and "
758  "-connect (default: %d)",
761  argsman.AddArg(
762  "-dnsseed",
763  strprintf(
764  "Query for peer addresses via DNS lookup, if low on addresses "
765  "(default: %u unless -connect used)",
768  argsman.AddArg("-externalip=<ip>", "Specify your own public address",
770  argsman.AddArg(
771  "-fixedseeds",
772  strprintf(
773  "Allow fixed seeds if DNS seeds don't provide peers (default: %u)",
776  argsman.AddArg(
777  "-forcednsseed",
778  strprintf(
779  "Always query for peer addresses via DNS lookup (default: %d)",
782  argsman.AddArg("-overridednsseed",
783  "If set, only use the specified DNS seed when "
784  "querying for peer addresses via DNS lookup.",
786  argsman.AddArg(
787  "-listen",
788  "Accept connections from outside (default: 1 if no -proxy or -connect)",
790  argsman.AddArg(
791  "-listenonion",
792  strprintf("Automatically create Tor onion service (default: %d)",
795  argsman.AddArg(
796  "-maxconnections=<n>",
797  strprintf("Maintain at most <n> connections to peers. The effective "
798  "limit depends on system limitations and might be lower than "
799  "the specified value (default: %u)",
802  argsman.AddArg("-maxreceivebuffer=<n>",
803  strprintf("Maximum per-connection receive buffer, <n>*1000 "
804  "bytes (default: %u)",
807  argsman.AddArg(
808  "-maxsendbuffer=<n>",
809  strprintf(
810  "Maximum per-connection send buffer, <n>*1000 bytes (default: %u)",
813  argsman.AddArg(
814  "-maxtimeadjustment",
815  strprintf("Maximum allowed median peer time offset adjustment. Local "
816  "perspective of time may be influenced by peers forward or "
817  "backward by this amount. (default: %u seconds)",
820  argsman.AddArg("-onion=<ip:port>",
821  strprintf("Use separate SOCKS5 proxy to reach peers via Tor "
822  "onion services (default: %s)",
823  "-proxy"),
825  argsman.AddArg("-i2psam=<ip:port>",
826  "I2P SAM proxy to reach I2P peers and accept I2P "
827  "connections (default: none)",
829  argsman.AddArg(
830  "-i2pacceptincoming",
831  "If set and -i2psam is also set then incoming I2P connections are "
832  "accepted via the SAM proxy. If this is not set but -i2psam is set "
833  "then only outgoing connections will be made to the I2P network. "
834  "Ignored if -i2psam is not set. Listening for incoming I2P connections "
835  "is done through the SAM proxy, not by binding to a local address and "
836  "port (default: 1)",
838 
839  argsman.AddArg(
840  "-onlynet=<net>",
841  "Make outgoing connections only through network <net> (" +
842  Join(GetNetworkNames(), ", ") +
843  "). Incoming connections are not affected by this option. This "
844  "option can be specified multiple times to allow multiple "
845  "networks. Warning: if it is used with non-onion networks "
846  "and the -onion or -proxy option is set, then outbound onion "
847  "connections will still be made; use -noonion or -onion=0 to "
848  "disable outbound onion connections in this case",
850  argsman.AddArg("-peerbloomfilters",
851  strprintf("Support filtering of blocks and transaction with "
852  "bloom filters (default: %d)",
855  argsman.AddArg(
856  "-peerblockfilters",
857  strprintf(
858  "Serve compact block filters to peers per BIP 157 (default: %u)",
861  argsman.AddArg("-permitbaremultisig",
862  strprintf("Relay non-P2SH multisig (default: %d)",
865  // TODO: remove the sentence "Nodes not using ... incoming connections."
866  // once the changes from https://github.com/bitcoin/bitcoin/pull/23542 have
867  // become widespread.
868  argsman.AddArg("-port=<port>",
869  strprintf("Listen for connections on <port>. Nodes not "
870  "using the default ports (default: %u, "
871  "testnet: %u, regtest: %u) are unlikely to get "
872  "incoming connections. Not relevant for I2P (see "
873  "doc/i2p.md).",
874  defaultChainParams->GetDefaultPort(),
875  testnetChainParams->GetDefaultPort(),
876  regtestChainParams->GetDefaultPort()),
879  argsman.AddArg("-proxy=<ip:port>", "Connect through SOCKS5 proxy",
881  argsman.AddArg(
882  "-proxyrandomize",
883  strprintf("Randomize credentials for every proxy connection. "
884  "This enables Tor stream isolation (default: %d)",
887  argsman.AddArg(
888  "-seednode=<ip>",
889  "Connect to a node to retrieve peer addresses, and disconnect",
891  argsman.AddArg(
892  "-networkactive",
893  "Enable all P2P network activity (default: 1). Can be changed "
894  "by the setnetworkactive RPC command",
896  argsman.AddArg("-timeout=<n>",
897  strprintf("Specify connection timeout in milliseconds "
898  "(minimum: 1, default: %d)",
901  argsman.AddArg(
902  "-peertimeout=<n>",
903  strprintf("Specify p2p connection timeout in seconds. This option "
904  "determines the amount of time a peer may be inactive before "
905  "the connection to it is dropped. (minimum: 1, default: %d)",
908  argsman.AddArg(
909  "-torcontrol=<ip>:<port>",
910  strprintf(
911  "Tor control port to use if onion listening enabled (default: %s)",
914  argsman.AddArg("-torpassword=<pass>",
915  "Tor control port password (default: empty)",
918 #ifdef USE_UPNP
919 #if USE_UPNP
920  argsman.AddArg("-upnp",
921  "Use UPnP to map the listening port (default: 1 when "
922  "listening and no -proxy)",
924 #else
925  argsman.AddArg(
926  "-upnp",
927  strprintf("Use UPnP to map the listening port (default: %u)", 0),
929 #endif
930 #else
931  hidden_args.emplace_back("-upnp");
932 #endif
933 #ifdef USE_NATPMP
934  argsman.AddArg(
935  "-natpmp",
936  strprintf("Use NAT-PMP to map the listening port (default: %s)",
937  DEFAULT_NATPMP ? "1 when listening and no -proxy" : "0"),
939 #else
940  hidden_args.emplace_back("-natpmp");
941 #endif // USE_NATPMP
942  argsman.AddArg(
943  "-whitebind=<[permissions@]addr>",
944  "Bind to the given address and add permission flags to the peers "
945  "connecting to it."
946  "Use [host]:port notation for IPv6. Allowed permissions: " +
947  Join(NET_PERMISSIONS_DOC, ", ") +
948  ". "
949  "Specify multiple permissions separated by commas (default: "
950  "download,noban,mempool,relay). Can be specified multiple times.",
952 
953  argsman.AddArg("-whitelist=<[permissions@]IP address or network>",
954  "Add permission flags to the peers connecting from the "
955  "given IP address (e.g. 1.2.3.4) or CIDR-notated network "
956  "(e.g. 1.2.3.0/24). "
957  "Uses the same permissions as -whitebind. Can be specified "
958  "multiple times.",
960  argsman.AddArg(
961  "-maxuploadtarget=<n>",
962  strprintf("Tries to keep outbound traffic under the given target (in "
963  "MiB per 24h). Limit does not apply to peers with 'download' "
964  "permission. 0 = no limit (default: %d)",
967 
969 
970 #if ENABLE_ZMQ
971  argsman.AddArg("-zmqpubhashblock=<address>",
972  "Enable publish hash block in <address>",
974  argsman.AddArg("-zmqpubhashtx=<address>",
975  "Enable publish hash transaction in <address>",
977  argsman.AddArg("-zmqpubrawblock=<address>",
978  "Enable publish raw block in <address>",
980  argsman.AddArg("-zmqpubrawtx=<address>",
981  "Enable publish raw transaction in <address>",
983  argsman.AddArg("-zmqpubsequence=<address>",
984  "Enable publish hash block and tx sequence in <address>",
986  argsman.AddArg(
987  "-zmqpubhashblockhwm=<n>",
988  strprintf("Set publish hash block outbound message high water "
989  "mark (default: %d)",
992  argsman.AddArg(
993  "-zmqpubhashtxhwm=<n>",
994  strprintf("Set publish hash transaction outbound message high "
995  "water mark (default: %d)",
997  false, OptionsCategory::ZMQ);
998  argsman.AddArg(
999  "-zmqpubrawblockhwm=<n>",
1000  strprintf("Set publish raw block outbound message high water "
1001  "mark (default: %d)",
1004  argsman.AddArg(
1005  "-zmqpubrawtxhwm=<n>",
1006  strprintf("Set publish raw transaction outbound message high "
1007  "water mark (default: %d)",
1010  argsman.AddArg("-zmqpubsequencehwm=<n>",
1011  strprintf("Set publish hash sequence message high water mark"
1012  " (default: %d)",
1015 #else
1016  hidden_args.emplace_back("-zmqpubhashblock=<address>");
1017  hidden_args.emplace_back("-zmqpubhashtx=<address>");
1018  hidden_args.emplace_back("-zmqpubrawblock=<address>");
1019  hidden_args.emplace_back("-zmqpubrawtx=<address>");
1020  hidden_args.emplace_back("-zmqpubsequence=<n>");
1021  hidden_args.emplace_back("-zmqpubhashblockhwm=<n>");
1022  hidden_args.emplace_back("-zmqpubhashtxhwm=<n>");
1023  hidden_args.emplace_back("-zmqpubrawblockhwm=<n>");
1024  hidden_args.emplace_back("-zmqpubrawtxhwm=<n>");
1025  hidden_args.emplace_back("-zmqpubsequencehwm=<n>");
1026 #endif
1027 
1028  argsman.AddArg(
1029  "-checkblocks=<n>",
1030  strprintf("How many blocks to check at startup (default: %u, 0 = all)",
1034  argsman.AddArg("-checklevel=<n>",
1035  strprintf("How thorough the block verification of "
1036  "-checkblocks is: %s (0-4, default: %u)",
1040  argsman.AddArg("-checkblockindex",
1041  strprintf("Do a consistency check for the block tree, "
1042  "chainstate, and other validation data structures "
1043  "occasionally. (default: %u, regtest: %u)",
1044  defaultChainParams->DefaultConsistencyChecks(),
1045  regtestChainParams->DefaultConsistencyChecks()),
1048  argsman.AddArg("-checkaddrman=<n>",
1049  strprintf("Run addrman consistency checks every <n> "
1050  "operations. Use 0 to disable. (default: %u)",
1054  argsman.AddArg(
1055  "-checkmempool=<n>",
1056  strprintf("Run mempool consistency checks every <n> transactions. Use "
1057  "0 to disable. (default: %u, regtest: %u)",
1058  defaultChainParams->DefaultConsistencyChecks(),
1059  regtestChainParams->DefaultConsistencyChecks()),
1062  argsman.AddArg("-checkpoints",
1063  strprintf("Only accept block chain matching built-in "
1064  "checkpoints (default: %d)",
1068  argsman.AddArg("-deprecatedrpc=<method>",
1069  "Allows deprecated RPC method(s) to be used",
1072  argsman.AddArg(
1073  "-stopafterblockimport",
1074  strprintf("Stop running after importing blocks from disk (default: %d)",
1078  argsman.AddArg("-stopatheight",
1079  strprintf("Stop running after reaching the given height in "
1080  "the main chain (default: %u)",
1084  argsman.AddArg("-addrmantest", "Allows to test address relay on localhost",
1087  argsman.AddArg("-capturemessages", "Capture all P2P messages to disk",
1090  argsman.AddArg("-mocktime=<n>",
1091  "Replace actual time with " + UNIX_EPOCH_TIME +
1092  " (default: 0)",
1095  argsman.AddArg(
1096  "-maxsigcachesize=<n>",
1097  strprintf("Limit size of signature cache to <n> MiB (default: %u)",
1101  argsman.AddArg(
1102  "-maxscriptcachesize=<n>",
1103  strprintf("Limit size of script cache to <n> MiB (default: %u)",
1107  argsman.AddArg("-maxtipage=<n>",
1108  strprintf("Maximum tip age in seconds to consider node in "
1109  "initial block download (default: %u)",
1110  Ticks<std::chrono::seconds>(DEFAULT_MAX_TIP_AGE)),
1113 
1114  argsman.AddArg("-uacomment=<cmt>",
1115  "Append comment to the user agent string",
1117  argsman.AddArg("-uaclientname=<clientname>", "Set user agent client name",
1119  argsman.AddArg("-uaclientversion=<clientversion>",
1120  "Set user agent client version", ArgsManager::ALLOW_ANY,
1122 
1123  SetupChainParamsBaseOptions(argsman);
1124 
1125  argsman.AddArg(
1126  "-acceptnonstdtxn",
1127  strprintf(
1128  "Relay and mine \"non-standard\" transactions (%sdefault: %u)",
1129  "testnet/regtest only; ", defaultChainParams->RequireStandard()),
1132  argsman.AddArg("-excessiveblocksize=<n>",
1133  strprintf("Do not accept blocks larger than this limit, in "
1134  "bytes (default: %d)",
1138  const auto &ticker = Currency::get().ticker;
1139  argsman.AddArg(
1140  "-dustrelayfee=<amt>",
1141  strprintf("Fee rate (in %s/kB) used to define dust, the value of an "
1142  "output such that it will cost about 1/3 of its value in "
1143  "fees at this fee rate to spend it. (default: %s)",
1144  ticker, FormatMoney(DUST_RELAY_TX_FEE)),
1147 
1148  argsman.AddArg(
1149  "-bytespersigcheck",
1150  strprintf("Equivalent bytes per sigCheck in transactions for relay and "
1151  "mining (default: %u).",
1154  argsman.AddArg(
1155  "-bytespersigop",
1156  strprintf("DEPRECATED: Equivalent bytes per sigCheck in transactions "
1157  "for relay and mining (default: %u). This has been "
1158  "deprecated since v0.26.8 and will be removed in the future, "
1159  "please use -bytespersigcheck instead.",
1162  argsman.AddArg(
1163  "-datacarrier",
1164  strprintf("Relay and mine data carrier transactions (default: %d)",
1167  argsman.AddArg(
1168  "-datacarriersize",
1169  strprintf("Maximum size of data in data carrier transactions "
1170  "we relay and mine (default: %u)",
1173  argsman.AddArg(
1174  "-minrelaytxfee=<amt>",
1175  strprintf("Fees (in %s/kB) smaller than this are rejected for "
1176  "relaying, mining and transaction creation (default: %s)",
1179  argsman.AddArg(
1180  "-whitelistrelay",
1181  strprintf("Add 'relay' permission to whitelisted inbound peers "
1182  "with default permissions. This will accept relayed "
1183  "transactions even when not relaying transactions "
1184  "(default: %d)",
1187  argsman.AddArg(
1188  "-whitelistforcerelay",
1189  strprintf("Add 'forcerelay' permission to whitelisted inbound peers"
1190  " with default permissions. This will relay transactions "
1191  "even if the transactions were already in the mempool "
1192  "(default: %d)",
1195 
1196  argsman.AddArg("-blockmaxsize=<n>",
1197  strprintf("Set maximum block size in bytes (default: %d)",
1200  argsman.AddArg(
1201  "-blockmintxfee=<amt>",
1202  strprintf("Set lowest fee rate (in %s/kB) for transactions to "
1203  "be included in block creation. (default: %s)",
1206 
1207  argsman.AddArg("-blockversion=<n>",
1208  "Override block version to test forking scenarios",
1211 
1212  argsman.AddArg("-server", "Accept command line and JSON-RPC commands",
1214  argsman.AddArg("-rest",
1215  strprintf("Accept public REST requests (default: %d)",
1218  argsman.AddArg(
1219  "-rpcbind=<addr>[:port]",
1220  "Bind to given address to listen for JSON-RPC connections. Do not "
1221  "expose the RPC server to untrusted networks such as the public "
1222  "internet! This option is ignored unless -rpcallowip is also passed. "
1223  "Port is optional and overrides -rpcport. Use [host]:port notation "
1224  "for IPv6. This option can be specified multiple times (default: "
1225  "127.0.0.1 and ::1 i.e., localhost)",
1229  argsman.AddArg(
1230  "-rpcdoccheck",
1231  strprintf("Throw a non-fatal error at runtime if the documentation for "
1232  "an RPC is incorrect (default: %u)",
1235  argsman.AddArg(
1236  "-rpccookiefile=<loc>",
1237  "Location of the auth cookie. Relative paths will be prefixed "
1238  "by a net-specific datadir location. (default: data dir)",
1240  argsman.AddArg("-rpcuser=<user>", "Username for JSON-RPC connections",
1243  argsman.AddArg("-rpcpassword=<pw>", "Password for JSON-RPC connections",
1246  argsman.AddArg(
1247  "-rpcwhitelist=<whitelist>",
1248  "Set a whitelist to filter incoming RPC calls for a specific user. The "
1249  "field <whitelist> comes in the format: <USERNAME>:<rpc 1>,<rpc "
1250  "2>,...,<rpc n>. If multiple whitelists are set for a given user, they "
1251  "are set-intersected. See -rpcwhitelistdefault documentation for "
1252  "information on default whitelist behavior.",
1254  argsman.AddArg(
1255  "-rpcwhitelistdefault",
1256  "Sets default behavior for rpc whitelisting. Unless "
1257  "rpcwhitelistdefault is set to 0, if any -rpcwhitelist is set, the rpc "
1258  "server acts as if all rpc users are subject to "
1259  "empty-unless-otherwise-specified whitelists. If rpcwhitelistdefault "
1260  "is set to 1 and no -rpcwhitelist is set, rpc server acts as if all "
1261  "rpc users are subject to empty whitelists.",
1263  argsman.AddArg(
1264  "-rpcauth=<userpw>",
1265  "Username and HMAC-SHA-256 hashed password for JSON-RPC connections. "
1266  "The field <userpw> comes in the format: <USERNAME>:<SALT>$<HASH>. A "
1267  "canonical python script is included in share/rpcauth. The client then "
1268  "connects normally using the rpcuser=<USERNAME>/rpcpassword=<PASSWORD> "
1269  "pair of arguments. This option can be specified multiple times",
1271  argsman.AddArg("-rpcport=<port>",
1272  strprintf("Listen for JSON-RPC connections on <port> "
1273  "(default: %u, testnet: %u, regtest: %u)",
1274  defaultBaseParams->RPCPort(),
1275  testnetBaseParams->RPCPort(),
1276  regtestBaseParams->RPCPort()),
1279  argsman.AddArg(
1280  "-rpcallowip=<ip>",
1281  "Allow JSON-RPC connections from specified source. Valid for "
1282  "<ip> are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. "
1283  "1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24). "
1284  "This option can be specified multiple times",
1286  argsman.AddArg(
1287  "-rpcthreads=<n>",
1288  strprintf(
1289  "Set the number of threads to service RPC calls (default: %d)",
1292  argsman.AddArg(
1293  "-rpccorsdomain=value",
1294  "Domain from which to accept cross origin requests (browser enforced)",
1296 
1297  argsman.AddArg("-rpcworkqueue=<n>",
1298  strprintf("Set the depth of the work queue to service RPC "
1299  "calls (default: %d)",
1303  argsman.AddArg("-rpcservertimeout=<n>",
1304  strprintf("Timeout during HTTP requests (default: %d)",
1308 
1309 #if HAVE_DECL_FORK
1310  argsman.AddArg("-daemon",
1311  strprintf("Run in the background as a daemon and accept "
1312  "commands (default: %d)",
1313  DEFAULT_DAEMON),
1315  argsman.AddArg("-daemonwait",
1316  strprintf("Wait for initialization to be finished before "
1317  "exiting. This implies -daemon (default: %d)",
1320 #else
1321  hidden_args.emplace_back("-daemon");
1322  hidden_args.emplace_back("-daemonwait");
1323 #endif
1324 
1325  // Avalanche options.
1326  argsman.AddArg("-avalanche",
1327  strprintf("Enable the avalanche feature (default: %u)",
1330  argsman.AddArg(
1331  "-avalanchestakingrewards",
1332  strprintf("Enable the avalanche staking rewards feature (default: %u, "
1333  "testnet: %u, regtest: %u)",
1334  defaultChainParams->GetConsensus().enableStakingRewards,
1335  testnetChainParams->GetConsensus().enableStakingRewards,
1336  regtestChainParams->GetConsensus().enableStakingRewards),
1338  argsman.AddArg("-avalancheconflictingproofcooldown",
1339  strprintf("Mandatory cooldown before a proof conflicting "
1340  "with an already registered one can be considered "
1341  "in seconds (default: %u)",
1344  argsman.AddArg("-avalanchepeerreplacementcooldown",
1345  strprintf("Mandatory cooldown before a peer can be replaced "
1346  "in seconds (default: %u)",
1349  argsman.AddArg(
1350  "-avaminquorumstake",
1351  strprintf(
1352  "Minimum amount of known stake for a usable quorum (default: %s)",
1355  argsman.AddArg(
1356  "-avaminquorumconnectedstakeratio",
1357  strprintf("Minimum proportion of known stake we"
1358  " need nodes for to have a usable quorum (default: %s)",
1361  argsman.AddArg(
1362  "-avaminavaproofsnodecount",
1363  strprintf("Minimum number of node that needs to send us an avaproofs"
1364  " message before we consider we have a usable quorum"
1365  " (default: %s)",
1368  argsman.AddArg(
1369  "-avastalevotethreshold",
1370  strprintf("Number of avalanche votes before a voted item goes stale "
1371  "when voting confidence is low (default: %u)",
1374  argsman.AddArg(
1375  "-avastalevotefactor",
1376  strprintf(
1377  "Factor affecting the number of avalanche votes before a voted "
1378  "item goes stale when voting confidence is high (default: %u)",
1381  argsman.AddArg("-avacooldown",
1382  strprintf("Mandatory cooldown between two avapoll in "
1383  "milliseconds (default: %u)",
1386  argsman.AddArg(
1387  "-avatimeout",
1388  strprintf("Avalanche query timeout in milliseconds (default: %u)",
1391  argsman.AddArg(
1392  "-avadelegation",
1393  "Avalanche proof delegation to the master key used by this node "
1394  "(default: none). Should be used in conjunction with -avaproof and "
1395  "-avamasterkey",
1397  argsman.AddArg("-avaproof",
1398  "Avalanche proof to be used by this node (default: none)",
1400  argsman.AddArg(
1401  "-avaproofstakeutxoconfirmations",
1402  strprintf(
1403  "Minimum number of confirmations before a stake utxo is mature"
1404  " enough to be included into a proof. Utxos in the mempool are not "
1405  "accepted (i.e this value must be greater than 0) (default: %s)",
1408  argsman.AddArg("-avaproofstakeutxodustthreshold",
1409  strprintf("Minimum value each stake utxo must have to be "
1410  "considered valid (default: %s)",
1413  argsman.AddArg("-avamasterkey",
1414  "Master key associated with the proof. If a proof is "
1415  "required, this is mandatory.",
1418  argsman.AddArg("-avasessionkey", "Avalanche session key (default: random)",
1421  argsman.AddArg(
1422  "-maxavalancheoutbound",
1423  strprintf(
1424  "Set the maximum number of avalanche outbound peers to connect to. "
1425  "Note that this option takes precedence over the -maxconnections "
1426  "option (default: %u).",
1429  argsman.AddArg(
1430  "-persistavapeers",
1431  strprintf("Whether to save the avalanche peers upon shutdown and load "
1432  "them upon startup (default: %u).",
1435 
1436  hidden_args.emplace_back("-avalanchepreconsensus");
1437 
1438  // Add the hidden options
1439  argsman.AddHiddenArgs(hidden_args);
1440 }
1441 
1442 static bool fHaveGenesis = false;
1444 static std::condition_variable g_genesis_wait_cv;
1445 
1446 static void BlockNotifyGenesisWait(const CBlockIndex *pBlockIndex) {
1447  if (pBlockIndex != nullptr) {
1448  {
1450  fHaveGenesis = true;
1451  }
1452  g_genesis_wait_cv.notify_all();
1453  }
1454 }
1455 
1456 #if HAVE_SYSTEM
1457 static void StartupNotify(const ArgsManager &args) {
1458  std::string cmd = args.GetArg("-startupnotify", "");
1459  if (!cmd.empty()) {
1460  std::thread t(runCommand, cmd);
1461  // thread runs free
1462  t.detach();
1463  }
1464 }
1465 #endif
1466 
1467 static bool AppInitServers(Config &config,
1468  HTTPRPCRequestProcessor &httpRPCRequestProcessor,
1469  NodeContext &node) {
1470  const ArgsManager &args = *Assert(node.args);
1473  if (!InitHTTPServer(config)) {
1474  return false;
1475  }
1476 
1477  StartRPC();
1478  node.rpc_interruption_point = RpcInterruptionPoint;
1479 
1480  if (!StartHTTPRPC(httpRPCRequestProcessor)) {
1481  return false;
1482  }
1483  if (args.GetBoolArg("-rest", DEFAULT_REST_ENABLE)) {
1484  StartREST(&node);
1485  }
1486 
1487  StartHTTPServer();
1488  return true;
1489 }
1490 
1491 // Parameter interaction based on rules
1493  // when specifying an explicit binding address, you want to listen on it
1494  // even when -connect or -proxy is specified.
1495  if (args.IsArgSet("-bind")) {
1496  if (args.SoftSetBoolArg("-listen", true)) {
1497  LogPrintf(
1498  "%s: parameter interaction: -bind set -> setting -listen=1\n",
1499  __func__);
1500  }
1501  }
1502  if (args.IsArgSet("-whitebind")) {
1503  if (args.SoftSetBoolArg("-listen", true)) {
1504  LogPrintf("%s: parameter interaction: -whitebind set -> setting "
1505  "-listen=1\n",
1506  __func__);
1507  }
1508  }
1509 
1510  if (args.IsArgSet("-connect")) {
1511  // when only connecting to trusted nodes, do not seed via DNS, or listen
1512  // by default.
1513  if (args.SoftSetBoolArg("-dnsseed", false)) {
1514  LogPrintf("%s: parameter interaction: -connect set -> setting "
1515  "-dnsseed=0\n",
1516  __func__);
1517  }
1518  if (args.SoftSetBoolArg("-listen", false)) {
1519  LogPrintf("%s: parameter interaction: -connect set -> setting "
1520  "-listen=0\n",
1521  __func__);
1522  }
1523  }
1524 
1525  if (args.IsArgSet("-proxy")) {
1526  // to protect privacy, do not listen by default if a default proxy
1527  // server is specified.
1528  if (args.SoftSetBoolArg("-listen", false)) {
1529  LogPrintf(
1530  "%s: parameter interaction: -proxy set -> setting -listen=0\n",
1531  __func__);
1532  }
1533  // to protect privacy, do not map ports when a proxy is set. The user
1534  // may still specify -listen=1 to listen locally, so don't rely on this
1535  // happening through -listen below.
1536  if (args.SoftSetBoolArg("-upnp", false)) {
1537  LogPrintf(
1538  "%s: parameter interaction: -proxy set -> setting -upnp=0\n",
1539  __func__);
1540  }
1541  if (args.SoftSetBoolArg("-natpmp", false)) {
1542  LogPrintf(
1543  "%s: parameter interaction: -proxy set -> setting -natpmp=0\n",
1544  __func__);
1545  }
1546  // to protect privacy, do not discover addresses by default
1547  if (args.SoftSetBoolArg("-discover", false)) {
1548  LogPrintf("%s: parameter interaction: -proxy set -> setting "
1549  "-discover=0\n",
1550  __func__);
1551  }
1552  }
1553 
1554  if (!args.GetBoolArg("-listen", DEFAULT_LISTEN)) {
1555  // do not map ports or try to retrieve public IP when not listening
1556  // (pointless)
1557  if (args.SoftSetBoolArg("-upnp", false)) {
1558  LogPrintf(
1559  "%s: parameter interaction: -listen=0 -> setting -upnp=0\n",
1560  __func__);
1561  }
1562  if (args.SoftSetBoolArg("-natpmp", false)) {
1563  LogPrintf(
1564  "%s: parameter interaction: -listen=0 -> setting -natpmp=0\n",
1565  __func__);
1566  }
1567  if (args.SoftSetBoolArg("-discover", false)) {
1568  LogPrintf(
1569  "%s: parameter interaction: -listen=0 -> setting -discover=0\n",
1570  __func__);
1571  }
1572  if (args.SoftSetBoolArg("-listenonion", false)) {
1573  LogPrintf("%s: parameter interaction: -listen=0 -> setting "
1574  "-listenonion=0\n",
1575  __func__);
1576  }
1577  if (args.SoftSetBoolArg("-i2pacceptincoming", false)) {
1578  LogPrintf("%s: parameter interaction: -listen=0 -> setting "
1579  "-i2pacceptincoming=0\n",
1580  __func__);
1581  }
1582  }
1583 
1584  if (args.IsArgSet("-externalip")) {
1585  // if an explicit public IP is specified, do not try to find others
1586  if (args.SoftSetBoolArg("-discover", false)) {
1587  LogPrintf("%s: parameter interaction: -externalip set -> setting "
1588  "-discover=0\n",
1589  __func__);
1590  }
1591  }
1592 
1593  // disable whitelistrelay in blocksonly mode
1594  if (args.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)) {
1595  if (args.SoftSetBoolArg("-whitelistrelay", false)) {
1596  LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting "
1597  "-whitelistrelay=0\n",
1598  __func__);
1599  }
1600  }
1601 
1602  // Forcing relay from whitelisted hosts implies we will accept relays from
1603  // them in the first place.
1604  if (args.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
1605  if (args.SoftSetBoolArg("-whitelistrelay", true)) {
1606  LogPrintf("%s: parameter interaction: -whitelistforcerelay=1 -> "
1607  "setting -whitelistrelay=1\n",
1608  __func__);
1609  }
1610  }
1611 
1612  // If avalanche is set, soft set all the feature flags accordingly.
1613  if (args.IsArgSet("-avalanche")) {
1614  const bool fAvalanche =
1615  args.GetBoolArg("-avalanche", AVALANCHE_DEFAULT_ENABLED);
1616  args.SoftSetBoolArg("-automaticunparking", !fAvalanche);
1617  }
1618 }
1619 
1626 void InitLogging(const ArgsManager &args) {
1629 }
1630 
1631 namespace { // Variables internal to initialization process only
1632 
1633 int nMaxConnections;
1634 int nUserMaxConnections;
1635 int nFD;
1637 int64_t peer_connect_timeout;
1638 std::set<BlockFilterType> g_enabled_filter_types;
1639 
1640 } // namespace
1641 
1642 [[noreturn]] static void new_handler_terminate() {
1643  // Rather than throwing std::bad-alloc if allocation fails, terminate
1644  // immediately to (try to) avoid chain corruption. Since LogPrintf may
1645  // itself allocate memory, set the handler directly to terminate first.
1646  std::set_new_handler(std::terminate);
1647  LogPrintf("Error: Out of memory. Terminating.\n");
1648 
1649  // The log was successful, terminate now.
1650  std::terminate();
1651 };
1652 
1653 bool AppInitBasicSetup(const ArgsManager &args) {
1654 // Step 1: setup
1655 #ifdef _MSC_VER
1656  // Turn off Microsoft heap dump noise
1657  _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
1658  _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, nullptr,
1659  OPEN_EXISTING, 0, 0));
1660  // Disable confusing "helpful" text message on abort, Ctrl-C
1661  _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
1662 #endif
1663 #ifdef WIN32
1664  // Enable Data Execution Prevention (DEP)
1665  SetProcessDEPPolicy(PROCESS_DEP_ENABLE);
1666 #endif
1667  if (!InitShutdownState()) {
1668  return InitError(
1669  Untranslated("Initializing wait-for-shutdown state failed."));
1670  }
1671 
1672  if (!SetupNetworking()) {
1673  return InitError(Untranslated("Initializing networking failed"));
1674  }
1675 
1676 #ifndef WIN32
1677  if (!args.GetBoolArg("-sysperms", false)) {
1678  umask(077);
1679  }
1680 
1681  // Clean shutdown on SIGTERM
1684 
1685  // Reopen debug.log on SIGHUP
1687 
1688  // Ignore SIGPIPE, otherwise it will bring the daemon down if the client
1689  // closes unexpectedly
1690  signal(SIGPIPE, SIG_IGN);
1691 #else
1692  SetConsoleCtrlHandler(consoleCtrlHandler, true);
1693 #endif
1694 
1695  std::set_new_handler(new_handler_terminate);
1696 
1697  return true;
1698 }
1699 
1700 bool AppInitParameterInteraction(Config &config, const ArgsManager &args) {
1701  const CChainParams &chainparams = config.GetChainParams();
1702  // Step 2: parameter interactions
1703 
1704  // also see: InitParameterInteraction()
1705 
1706  // Error if network-specific options (-addnode, -connect, etc) are
1707  // specified in default section of config file, but not overridden
1708  // on the command line or in this network's section of the config file.
1709  std::string network = args.GetChainName();
1710  bilingual_str errors;
1711  for (const auto &arg : args.GetUnsuitableSectionOnlyArgs()) {
1712  errors += strprintf(_("Config setting for %s only applied on %s "
1713  "network when in [%s] section.") +
1714  Untranslated("\n"),
1715  arg, network, network);
1716  }
1717 
1718  if (!errors.empty()) {
1719  return InitError(errors);
1720  }
1721 
1722  // Warn if unrecognized section name are present in the config file.
1723  bilingual_str warnings;
1724  for (const auto &section : args.GetUnrecognizedSections()) {
1725  warnings += strprintf(Untranslated("%s:%i ") +
1726  _("Section [%s] is not recognized.") +
1727  Untranslated("\n"),
1728  section.m_file, section.m_line, section.m_name);
1729  }
1730 
1731  if (!warnings.empty()) {
1732  InitWarning(warnings);
1733  }
1734 
1735  if (!fs::is_directory(args.GetBlocksDirPath())) {
1736  return InitError(
1737  strprintf(_("Specified blocks directory \"%s\" does not exist."),
1738  args.GetArg("-blocksdir", "")));
1739  }
1740 
1741  // parse and validate enabled filter types
1742  std::string blockfilterindex_value =
1743  args.GetArg("-blockfilterindex", DEFAULT_BLOCKFILTERINDEX);
1744  if (blockfilterindex_value == "" || blockfilterindex_value == "1") {
1745  g_enabled_filter_types = AllBlockFilterTypes();
1746  } else if (blockfilterindex_value != "0") {
1747  const std::vector<std::string> names =
1748  args.GetArgs("-blockfilterindex");
1749  for (const auto &name : names) {
1750  BlockFilterType filter_type;
1751  if (!BlockFilterTypeByName(name, filter_type)) {
1752  return InitError(
1753  strprintf(_("Unknown -blockfilterindex value %s."), name));
1754  }
1755  g_enabled_filter_types.insert(filter_type);
1756  }
1757  }
1758 
1759  // Signal NODE_COMPACT_FILTERS if peerblockfilters and basic filters index
1760  // are both enabled.
1761  if (args.GetBoolArg("-peerblockfilters", DEFAULT_PEERBLOCKFILTERS)) {
1762  if (g_enabled_filter_types.count(BlockFilterType::BASIC) != 1) {
1763  return InitError(
1764  _("Cannot set -peerblockfilters without -blockfilterindex."));
1765  }
1766 
1767  nLocalServices = ServiceFlags(nLocalServices | NODE_COMPACT_FILTERS);
1768  }
1769 
1770  // if using block pruning, then disallow txindex, coinstatsindex and chronik
1771  if (args.GetIntArg("-prune", 0)) {
1772  if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
1773  return InitError(_("Prune mode is incompatible with -txindex."));
1774  }
1775  if (args.GetBoolArg("-coinstatsindex", DEFAULT_COINSTATSINDEX)) {
1776  return InitError(
1777  _("Prune mode is incompatible with -coinstatsindex."));
1778  }
1779  if (args.GetBoolArg("-chronik", DEFAULT_CHRONIK)) {
1780  return InitError(_("Prune mode is incompatible with -chronik."));
1781  }
1782  }
1783 
1784  // -bind and -whitebind can't be set when not listening
1785  size_t nUserBind =
1786  args.GetArgs("-bind").size() + args.GetArgs("-whitebind").size();
1787  if (nUserBind != 0 && !args.GetBoolArg("-listen", DEFAULT_LISTEN)) {
1788  return InitError(Untranslated(
1789  "Cannot set -bind or -whitebind together with -listen=0"));
1790  }
1791 
1792  // Make sure enough file descriptors are available
1793  int nBind = std::max(nUserBind, size_t(1));
1794  nUserMaxConnections =
1795  args.GetIntArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
1796  nMaxConnections = std::max(nUserMaxConnections, 0);
1797 
1798  // -maxavalancheoutbound takes precedence over -maxconnections
1799  const int maxAvalancheOutbound = args.GetIntArg(
1800  "-maxavalancheoutbound", DEFAULT_MAX_AVALANCHE_OUTBOUND_CONNECTIONS);
1801  const bool fAvalanche =
1802  args.GetBoolArg("-avalanche", AVALANCHE_DEFAULT_ENABLED);
1803  if (fAvalanche && maxAvalancheOutbound > nMaxConnections) {
1804  nMaxConnections = std::max(maxAvalancheOutbound, nMaxConnections);
1805  // Indicate the value set by the user
1806  LogPrintf("Increasing -maxconnections from %d to %d to comply with "
1807  "-maxavalancheoutbound\n",
1808  nUserMaxConnections, nMaxConnections);
1809  }
1810 
1811  // Trim requested connection counts, to fit into system limitations
1812  // <int> in std::min<int>(...) to work around FreeBSD compilation issue
1813  // described in #2695
1815  nMaxConnections + nBind + MIN_CORE_FILEDESCRIPTORS +
1817 #ifdef USE_POLL
1818  int fd_max = nFD;
1819 #else
1820  int fd_max = FD_SETSIZE;
1821 #endif
1822  nMaxConnections = std::max(
1823  std::min<int>(nMaxConnections,
1824  fd_max - nBind - MIN_CORE_FILEDESCRIPTORS -
1826  0);
1827  if (nFD < MIN_CORE_FILEDESCRIPTORS) {
1828  return InitError(_("Not enough file descriptors available."));
1829  }
1830  nMaxConnections =
1832  nMaxConnections);
1833 
1834  if (nMaxConnections < nUserMaxConnections) {
1835  // Not categorizing as "Warning" because this is the normal behavior for
1836  // platforms using the select() interface for which FD_SETSIZE is
1837  // usually 1024.
1838  LogPrintf("Reducing -maxconnections from %d to %d, because of system "
1839  "limitations.\n",
1840  nUserMaxConnections, nMaxConnections);
1841  }
1842 
1843  // Step 3: parameter-to-internal-flags
1845 
1846  // Configure excessive block size.
1847  const int64_t nProposedExcessiveBlockSize =
1848  args.GetIntArg("-excessiveblocksize", DEFAULT_MAX_BLOCK_SIZE);
1849  if (nProposedExcessiveBlockSize <= 0 ||
1850  !config.SetMaxBlockSize(nProposedExcessiveBlockSize)) {
1851  return InitError(
1852  _("Excessive block size must be > 1,000,000 bytes (1MB)"));
1853  }
1854 
1855  // Check blockmaxsize does not exceed maximum accepted block size.
1856  const int64_t nProposedMaxGeneratedBlockSize =
1857  args.GetIntArg("-blockmaxsize", DEFAULT_MAX_GENERATED_BLOCK_SIZE);
1858  if (nProposedMaxGeneratedBlockSize <= 0) {
1859  return InitError(_("Max generated block size must be greater than 0"));
1860  }
1861  if (uint64_t(nProposedMaxGeneratedBlockSize) > config.GetMaxBlockSize()) {
1862  return InitError(_("Max generated block size (blockmaxsize) cannot "
1863  "exceed the excessive block size "
1864  "(excessiveblocksize)"));
1865  }
1866 
1868  if (nConnectTimeout <= 0) {
1870  }
1871 
1872  peer_connect_timeout =
1873  args.GetIntArg("-peertimeout", DEFAULT_PEER_CONNECT_TIMEOUT);
1874  if (peer_connect_timeout <= 0) {
1875  return InitError(Untranslated(
1876  "peertimeout cannot be configured with a negative value."));
1877  }
1878 
1879  // Sanity check argument for min fee for including tx in block
1880  // TODO: Harmonize which arguments need sanity checking and where that
1881  // happens.
1882  if (args.IsArgSet("-blockmintxfee")) {
1883  Amount n = Amount::zero();
1884  if (!ParseMoney(args.GetArg("-blockmintxfee", ""), n)) {
1885  return InitError(AmountErrMsg("blockmintxfee",
1886  args.GetArg("-blockmintxfee", "")));
1887  }
1888  }
1889 
1891  args.IsArgSet("-bytespersigcheck")
1892  ? args.GetIntArg("-bytespersigcheck", nBytesPerSigCheck)
1893  : args.GetIntArg("-bytespersigop", nBytesPerSigCheck);
1894 
1896  return false;
1897  }
1898 
1899  // Option to startup with mocktime set (used for regression testing):
1900  SetMockTime(args.GetIntArg("-mocktime", 0)); // SetMockTime(0) is a no-op
1901 
1902  if (args.GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS)) {
1903  nLocalServices = ServiceFlags(nLocalServices | NODE_BLOOM);
1904  }
1905 
1906  if (args.IsArgSet("-proxy") && args.GetArg("-proxy", "").empty()) {
1907  return InitError(_(
1908  "No proxy server specified. Use -proxy=<ip> or -proxy=<ip:port>."));
1909  }
1910 
1911  // Avalanche parameters
1912  const int64_t stakeUtxoMinConfirmations =
1913  args.GetIntArg("-avaproofstakeutxoconfirmations",
1915 
1916  if (!chainparams.IsTestChain() &&
1917  stakeUtxoMinConfirmations !=
1919  return InitError(_("Avalanche stake UTXO minimum confirmations can "
1920  "only be set on test chains."));
1921  }
1922 
1923  if (stakeUtxoMinConfirmations <= 0) {
1924  return InitError(_("Avalanche stake UTXO minimum confirmations must be "
1925  "a positive integer."));
1926  }
1927 
1928  if (args.IsArgSet("-avaproofstakeutxodustthreshold")) {
1929  Amount amount = Amount::zero();
1930  auto parsed = ParseMoney(
1931  args.GetArg("-avaproofstakeutxodustthreshold", ""), amount);
1932  if (!parsed || Amount::zero() == amount) {
1933  return InitError(AmountErrMsg(
1934  "avaproofstakeutxodustthreshold",
1935  args.GetArg("-avaproofstakeutxodustthreshold", "")));
1936  }
1937 
1938  if (!chainparams.IsTestChain() &&
1939  amount != avalanche::PROOF_DUST_THRESHOLD) {
1940  return InitError(_("Avalanche stake UTXO dust threshold can "
1941  "only be set on test chains."));
1942  }
1943  }
1944 
1945  // This is a staking node
1946  if (fAvalanche && args.IsArgSet("-avaproof")) {
1947  if (!args.GetBoolArg("-listen", true)) {
1948  return InitError(_("Running a staking node requires accepting "
1949  "inbound connections. Please enable -listen."));
1950  }
1951  if (args.IsArgSet("-proxy")) {
1952  return InitError(_("Running a staking node behind a proxy is not "
1953  "supported. Please disable -proxy."));
1954  }
1955  if (args.IsArgSet("-i2psam")) {
1956  return InitError(_("Running a staking node behind I2P is not "
1957  "supported. Please disable -i2psam."));
1958  }
1959  if (args.IsArgSet("-onlynet")) {
1960  return InitError(
1961  _("Restricting the outbound network is not supported when "
1962  "running a staking node. Please disable -onlynet."));
1963  }
1964  }
1965 
1966  // Also report errors from parsing before daemonization
1967  {
1968  KernelNotifications notifications{};
1969  ChainstateManager::Options chainman_opts_dummy{
1970  .config = config,
1971  .datadir = args.GetDataDirNet(),
1972  .notifications = notifications,
1973  };
1974  if (const auto error{ApplyArgsManOptions(args, chainman_opts_dummy)}) {
1975  return InitError(*error);
1976  }
1977  BlockManager::Options blockman_opts_dummy{
1978  .chainparams = chainman_opts_dummy.config.GetChainParams(),
1979  .blocks_dir = args.GetBlocksDirPath(),
1980  };
1981  if (const auto error{ApplyArgsManOptions(args, blockman_opts_dummy)}) {
1982  return InitError(*error);
1983  }
1984  }
1985 
1986  return true;
1987 }
1988 
1989 static bool LockDataDirectory(bool probeOnly) {
1990  // Make sure only a single Bitcoin process is using the data directory.
1991  fs::path datadir = gArgs.GetDataDirNet();
1992  if (!DirIsWritable(datadir)) {
1993  return InitError(strprintf(
1994  _("Cannot write to data directory '%s'; check permissions."),
1995  fs::PathToString(datadir)));
1996  }
1997  if (!LockDirectory(datadir, ".lock", probeOnly)) {
1998  return InitError(strprintf(_("Cannot obtain a lock on data directory "
1999  "%s. %s is probably already running."),
2000  fs::PathToString(datadir), PACKAGE_NAME));
2001  }
2002  return true;
2003 }
2004 
2006  // Step 4: sanity checks
2007 
2008  init::SetGlobals();
2009 
2010  // Sanity check
2011  if (!init::SanityChecks()) {
2012  return InitError(strprintf(
2013  _("Initialization sanity check failed. %s is shutting down."),
2014  PACKAGE_NAME));
2015  }
2016 
2017  // Probe the data directory lock to give an early error message, if possible
2018  // We cannot hold the data directory lock here, as the forking for daemon()
2019  // hasn't yet happened, and a fork will cause weird behavior to it.
2020  return LockDataDirectory(true);
2021 }
2022 
2024  // After daemonization get the data directory lock again and hold on to it
2025  // until exit. This creates a slight window for a race condition to happen,
2026  // however this condition is harmless: it will at most make us exit without
2027  // printing a message to console.
2028  if (!LockDataDirectory(false)) {
2029  // Detailed error printed inside LockDataDirectory
2030  return false;
2031  }
2032  return true;
2033 }
2034 
2036  node.chain = interfaces::MakeChain(node, Params());
2037  // Create client interfaces for wallets that are supposed to be loaded
2038  // according to -wallet and -disablewallet options. This only constructs
2039  // the interfaces, it doesn't load wallet data. Wallets actually get loaded
2040  // when load() and start() interface methods are called below.
2042  return true;
2043 }
2044 
2045 bool AppInitMain(Config &config, RPCServer &rpcServer,
2046  HTTPRPCRequestProcessor &httpRPCRequestProcessor,
2047  NodeContext &node,
2049  // Step 4a: application initialization
2050  const ArgsManager &args = *Assert(node.args);
2051  const CChainParams &chainparams = config.GetChainParams();
2052 
2053  if (!CreatePidFile(args)) {
2054  // Detailed error printed inside CreatePidFile().
2055  return false;
2056  }
2057  if (!init::StartLogging(args)) {
2058  // Detailed error printed inside StartLogging().
2059  return false;
2060  }
2061 
2062  LogPrintf("Using at most %i automatic connections (%i file descriptors "
2063  "available)\n",
2064  nMaxConnections, nFD);
2065 
2066  // Warn about relative -datadir path.
2067  if (args.IsArgSet("-datadir") &&
2068  !args.GetPathArg("-datadir").is_absolute()) {
2069  LogPrintf("Warning: relative datadir option '%s' specified, which will "
2070  "be interpreted relative to the current working directory "
2071  "'%s'. This is fragile, because if bitcoin is started in the "
2072  "future from a different location, it will be unable to "
2073  "locate the current data files. There could also be data "
2074  "loss if bitcoin is started while in a temporary "
2075  "directory.\n",
2076  args.GetArg("-datadir", ""),
2077  fs::PathToString(fs::current_path()));
2078  }
2079 
2080  ValidationCacheSizes validation_cache_sizes{};
2081  ApplyArgsManOptions(args, validation_cache_sizes);
2082 
2083  if (!InitSignatureCache(validation_cache_sizes.signature_cache_bytes)) {
2084  return InitError(strprintf(
2085  _("Unable to allocate memory for -maxsigcachesize: '%s' MiB"),
2086  args.GetIntArg("-maxsigcachesize",
2087  DEFAULT_MAX_SIG_CACHE_BYTES >> 20)));
2088  }
2090  validation_cache_sizes.script_execution_cache_bytes)) {
2091  return InitError(strprintf(
2092  _("Unable to allocate memory for -maxscriptcachesize: '%s' MiB"),
2093  args.GetIntArg("-maxscriptcachesize",
2095  }
2096 
2097  int script_threads = args.GetIntArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
2098  if (script_threads <= 0) {
2099  // -par=0 means autodetect (number of cores - 1 script threads)
2100  // -par=-n means "leave n cores free" (number of cores - n - 1 script
2101  // threads)
2102  script_threads += GetNumCores();
2103  }
2104 
2105  // Subtract 1 because the main thread counts towards the par threads
2106  script_threads = std::max(script_threads - 1, 0);
2107 
2108  // Number of script-checking threads <= MAX_SCRIPTCHECK_THREADS
2109  script_threads = std::min(script_threads, MAX_SCRIPTCHECK_THREADS);
2110 
2111  LogPrintf("Script verification uses %d additional threads\n",
2112  script_threads);
2113  if (script_threads >= 1) {
2114  StartScriptCheckWorkerThreads(script_threads);
2115  }
2116 
2117  assert(!node.scheduler);
2118  node.scheduler = std::make_unique<CScheduler>();
2119 
2120  // Start the lightweight task scheduler thread
2121  node.scheduler->m_service_thread =
2122  std::thread(&util::TraceThread, "scheduler",
2123  [&] { node.scheduler->serviceQueue(); });
2124 
2125  // Gather some entropy once per minute.
2126  node.scheduler->scheduleEvery(
2127  [] {
2128  RandAddPeriodic();
2129  return true;
2130  },
2131  std::chrono::minutes{1});
2132 
2134 
2139  RegisterAllRPCCommands(config, rpcServer, tableRPC);
2140  for (const auto &client : node.chain_clients) {
2141  client->registerRpcs();
2142  }
2143 #if ENABLE_ZMQ
2145 #endif
2146 
2153  if (args.GetBoolArg("-server", false)) {
2154  uiInterface.InitMessage_connect(SetRPCWarmupStatus);
2155  if (!AppInitServers(config, httpRPCRequestProcessor, node)) {
2156  return InitError(
2157  _("Unable to start HTTP server. See debug log for details."));
2158  }
2159  }
2160 
2161  // Step 5: verify wallet database integrity
2162  for (const auto &client : node.chain_clients) {
2163  if (!client->verify()) {
2164  return false;
2165  }
2166  }
2167 
2168  // Step 6: network initialization
2169 
2170  // Note that we absolutely cannot open any actual connections
2171  // until the very end ("start node") as the UTXO/block state
2172  // is not yet setup and may end up being set up twice if we
2173  // need to reindex later.
2174 
2175  fListen = args.GetBoolArg("-listen", DEFAULT_LISTEN);
2176  fDiscover = args.GetBoolArg("-discover", true);
2177 
2178  {
2179  // Initialize addrman
2180  assert(!node.addrman);
2181 
2182  // Read asmap file if configured
2183  std::vector<bool> asmap;
2184  if (args.IsArgSet("-asmap")) {
2185  fs::path asmap_path =
2186  args.GetPathArg("-asmap", DEFAULT_ASMAP_FILENAME);
2187  if (!asmap_path.is_absolute()) {
2188  asmap_path = args.GetDataDirNet() / asmap_path;
2189  }
2190  if (!fs::exists(asmap_path)) {
2191  InitError(strprintf(_("Could not find asmap file %s"),
2192  fs::quoted(fs::PathToString(asmap_path))));
2193  return false;
2194  }
2195  asmap = DecodeAsmap(asmap_path);
2196  if (asmap.size() == 0) {
2197  InitError(strprintf(_("Could not parse asmap file %s"),
2198  fs::quoted(fs::PathToString(asmap_path))));
2199  return false;
2200  }
2201  const uint256 asmap_version = (HashWriter{} << asmap).GetHash();
2202  LogPrintf("Using asmap version %s for IP bucketing\n",
2203  asmap_version.ToString());
2204  } else {
2205  LogPrintf("Using /16 prefix for IP bucketing\n");
2206  }
2207 
2208  uiInterface.InitMessage(_("Loading P2P addresses...").translated);
2209  auto addrman{LoadAddrman(chainparams, asmap, args)};
2210  if (!addrman) {
2211  return InitError(util::ErrorString(addrman));
2212  }
2213  node.addrman = std::move(*addrman);
2214  }
2215 
2216  assert(!node.banman);
2217  node.banman = std::make_unique<BanMan>(
2218  args.GetDataDirNet() / "banlist.dat", config.GetChainParams(),
2219  &uiInterface, args.GetIntArg("-bantime", DEFAULT_MISBEHAVING_BANTIME));
2220  assert(!node.connman);
2221  node.connman = std::make_unique<CConnman>(
2222  config, GetRand<uint64_t>(), GetRand<uint64_t>(), *node.addrman,
2223  args.GetBoolArg("-networkactive", true));
2224 
2225  // sanitize comments per BIP-0014, format user agent and check total size
2226  std::vector<std::string> uacomments;
2227  for (const std::string &cmt : args.GetArgs("-uacomment")) {
2228  if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT)) {
2229  return InitError(strprintf(
2230  _("User Agent comment (%s) contains unsafe characters."), cmt));
2231  }
2232  uacomments.push_back(cmt);
2233  }
2234  const std::string client_name = args.GetArg("-uaclientname", CLIENT_NAME);
2235  const std::string client_version =
2236  args.GetArg("-uaclientversion", FormatVersion(CLIENT_VERSION));
2237  if (client_name != SanitizeString(client_name, SAFE_CHARS_UA_COMMENT)) {
2238  return InitError(strprintf(
2239  _("-uaclientname (%s) contains invalid characters."), client_name));
2240  }
2241  if (client_version !=
2242  SanitizeString(client_version, SAFE_CHARS_UA_COMMENT)) {
2243  return InitError(
2244  strprintf(_("-uaclientversion (%s) contains invalid characters."),
2245  client_version));
2246  }
2247  const std::string strSubVersion =
2248  FormatUserAgent(client_name, client_version, uacomments);
2249  if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
2250  return InitError(strprintf(
2251  _("Total length of network version string (%i) exceeds maximum "
2252  "length (%i). Reduce the number or size of uacomments."),
2253  strSubVersion.size(), MAX_SUBVERSION_LENGTH));
2254  }
2255 
2256  if (args.IsArgSet("-onlynet")) {
2257  std::set<enum Network> nets;
2258  for (const std::string &snet : args.GetArgs("-onlynet")) {
2259  enum Network net = ParseNetwork(snet);
2260  if (net == NET_UNROUTABLE) {
2261  return InitError(strprintf(
2262  _("Unknown network specified in -onlynet: '%s'"), snet));
2263  }
2264  nets.insert(net);
2265  }
2266  for (int n = 0; n < NET_MAX; n++) {
2267  enum Network net = (enum Network)n;
2268  if (!nets.count(net)) {
2269  SetReachable(net, false);
2270  }
2271  }
2272  }
2273 
2274  // Check for host lookup allowed before parsing any network related
2275  // parameters
2276  fNameLookup = args.GetBoolArg("-dns", DEFAULT_NAME_LOOKUP);
2277 
2278  bool proxyRandomize =
2279  args.GetBoolArg("-proxyrandomize", DEFAULT_PROXYRANDOMIZE);
2280  // -proxy sets a proxy for all outgoing network traffic
2281  // -noproxy (or -proxy=0) as well as the empty string can be used to not set
2282  // a proxy, this is the default
2283  std::string proxyArg = args.GetArg("-proxy", "");
2284  SetReachable(NET_ONION, false);
2285  if (proxyArg != "" && proxyArg != "0") {
2286  CService proxyAddr;
2287  if (!Lookup(proxyArg, proxyAddr, 9050, fNameLookup)) {
2288  return InitError(strprintf(
2289  _("Invalid -proxy address or hostname: '%s'"), proxyArg));
2290  }
2291 
2292  proxyType addrProxy = proxyType(proxyAddr, proxyRandomize);
2293  if (!addrProxy.IsValid()) {
2294  return InitError(strprintf(
2295  _("Invalid -proxy address or hostname: '%s'"), proxyArg));
2296  }
2297 
2298  SetProxy(NET_IPV4, addrProxy);
2299  SetProxy(NET_IPV6, addrProxy);
2300  SetProxy(NET_ONION, addrProxy);
2301  SetNameProxy(addrProxy);
2302  // by default, -proxy sets onion as reachable, unless -noonion later
2303  SetReachable(NET_ONION, true);
2304  }
2305 
2306  // -onion can be used to set only a proxy for .onion, or override normal
2307  // proxy for .onion addresses.
2308  // -noonion (or -onion=0) disables connecting to .onion entirely. An empty
2309  // string is used to not override the onion proxy (in which case it defaults
2310  // to -proxy set above, or none)
2311  std::string onionArg = args.GetArg("-onion", "");
2312  if (onionArg != "") {
2313  if (onionArg == "0") {
2314  // Handle -noonion/-onion=0
2315  SetReachable(NET_ONION, false);
2316  } else {
2317  CService onionProxy;
2318  if (!Lookup(onionArg, onionProxy, 9050, fNameLookup)) {
2319  return InitError(strprintf(
2320  _("Invalid -onion address or hostname: '%s'"), onionArg));
2321  }
2322  proxyType addrOnion = proxyType(onionProxy, proxyRandomize);
2323  if (!addrOnion.IsValid()) {
2324  return InitError(strprintf(
2325  _("Invalid -onion address or hostname: '%s'"), onionArg));
2326  }
2327  SetProxy(NET_ONION, addrOnion);
2328  SetReachable(NET_ONION, true);
2329  }
2330  }
2331 
2332  for (const std::string &strAddr : args.GetArgs("-externalip")) {
2333  CService addrLocal;
2334  if (Lookup(strAddr, addrLocal, GetListenPort(), fNameLookup) &&
2335  addrLocal.IsValid()) {
2336  AddLocal(addrLocal, LOCAL_MANUAL);
2337  } else {
2338  return InitError(ResolveErrMsg("externalip", strAddr));
2339  }
2340  }
2341 
2342 #if ENABLE_ZMQ
2344  [&chainman = node.chainman](CBlock &block, const CBlockIndex &index) {
2345  assert(chainman);
2346  return chainman->m_blockman.ReadBlockFromDisk(block, index);
2347  });
2348 
2351  }
2352 #endif
2353 
2354  // Step 7: load block chain
2355 
2356  node.notifications = std::make_unique<KernelNotifications>();
2357  fReindex = args.GetBoolArg("-reindex", false);
2358  bool fReindexChainState = args.GetBoolArg("-reindex-chainstate", false);
2359 
2360  ChainstateManager::Options chainman_opts{
2361  .config = config,
2362  .datadir = args.GetDataDirNet(),
2363  .adjusted_time_callback = GetAdjustedTime,
2364  .notifications = *node.notifications,
2365  };
2366  // no error can happen, already checked in AppInitParameterInteraction
2367  Assert(!ApplyArgsManOptions(args, chainman_opts));
2368 
2369  if (chainman_opts.checkpoints_enabled) {
2370  LogPrintf("Checkpoints will be verified.\n");
2371  } else {
2372  LogPrintf("Skipping checkpoint verification.\n");
2373  }
2374 
2375  BlockManager::Options blockman_opts{
2376  .chainparams = chainman_opts.config.GetChainParams(),
2377  .blocks_dir = args.GetBlocksDirPath(),
2378  };
2379  // no error can happen, already checked in AppInitParameterInteraction
2380  Assert(!ApplyArgsManOptions(args, blockman_opts));
2381 
2382  // cache size calculations
2383  CacheSizes cache_sizes =
2384  CalculateCacheSizes(args, g_enabled_filter_types.size());
2385 
2386  LogPrintf("Cache configuration:\n");
2387  LogPrintf("* Using %.1f MiB for block index database\n",
2388  cache_sizes.block_tree_db * (1.0 / 1024 / 1024));
2389  if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
2390  LogPrintf("* Using %.1f MiB for transaction index database\n",
2391  cache_sizes.tx_index * (1.0 / 1024 / 1024));
2392  }
2393  for (BlockFilterType filter_type : g_enabled_filter_types) {
2394  LogPrintf("* Using %.1f MiB for %s block filter index database\n",
2395  cache_sizes.filter_index * (1.0 / 1024 / 1024),
2396  BlockFilterTypeName(filter_type));
2397  }
2398  LogPrintf("* Using %.1f MiB for chain state database\n",
2399  cache_sizes.coins_db * (1.0 / 1024 / 1024));
2400 
2401  assert(!node.mempool);
2402  assert(!node.chainman);
2403 
2404  CTxMemPool::Options mempool_opts{
2405  .check_ratio = chainparams.DefaultConsistencyChecks() ? 1 : 0,
2406  };
2407  if (const auto err{ApplyArgsManOptions(args, chainparams, mempool_opts)}) {
2408  return InitError(*err);
2409  }
2410  mempool_opts.check_ratio =
2411  std::clamp<int>(mempool_opts.check_ratio, 0, 1'000'000);
2412 
2413  // FIXME: this legacy limit comes from the DEFAULT_DESCENDANT_SIZE_LIMIT
2414  // (101) that was enforced before the wellington activation. While it's
2415  // still a good idea to have some minimum mempool size, using this value as
2416  // a threshold is no longer relevant.
2417  int64_t nMempoolSizeMin = 101 * 1000 * 40;
2418  if (mempool_opts.max_size_bytes < 0 ||
2419  (!chainparams.IsTestChain() &&
2420  mempool_opts.max_size_bytes < nMempoolSizeMin)) {
2421  return InitError(strprintf(_("-maxmempool must be at least %d MB"),
2422  std::ceil(nMempoolSizeMin / 1000000.0)));
2423  }
2424  LogPrintf("* Using %.1f MiB for in-memory UTXO set (plus up to %.1f MiB of "
2425  "unused mempool space)\n",
2426  cache_sizes.coins * (1.0 / 1024 / 1024),
2427  mempool_opts.max_size_bytes * (1.0 / 1024 / 1024));
2428 
2429  for (bool fLoaded = false; !fLoaded && !ShutdownRequested();) {
2430  node.mempool = std::make_unique<CTxMemPool>(mempool_opts);
2431 
2432  node.chainman =
2433  std::make_unique<ChainstateManager>(chainman_opts, blockman_opts);
2434  ChainstateManager &chainman = *node.chainman;
2435 
2437  options.mempool = Assert(node.mempool.get());
2438  options.reindex = node::fReindex;
2439  options.reindex_chainstate = fReindexChainState;
2440  options.prune = chainman.m_blockman.IsPruneMode();
2441  options.check_blocks =
2442  args.GetIntArg("-checkblocks", DEFAULT_CHECKBLOCKS);
2443  options.check_level = args.GetIntArg("-checklevel", DEFAULT_CHECKLEVEL);
2444  options.require_full_verification =
2445  args.IsArgSet("-checkblocks") || args.IsArgSet("-checklevel");
2447  options.coins_error_cb = [] {
2448  uiInterface.ThreadSafeMessageBox(
2449  _("Error reading from database, shutting down."), "",
2451  };
2452 
2453  uiInterface.InitMessage(_("Loading block index...").translated);
2454 
2455  const int64_t load_block_index_start_time = GetTimeMillis();
2456  auto catch_exceptions = [](auto &&f) {
2457  try {
2458  return f();
2459  } catch (const std::exception &e) {
2460  LogPrintf("%s\n", e.what());
2461  return std::make_tuple(node::ChainstateLoadStatus::FAILURE,
2462  _("Error opening block database"));
2463  }
2464  };
2465  auto [status, error] = catch_exceptions(
2466  [&] { return LoadChainstate(chainman, cache_sizes, options); });
2467  if (status == node::ChainstateLoadStatus::SUCCESS) {
2468  uiInterface.InitMessage(_("Verifying blocks...").translated);
2469  if (chainman.m_blockman.m_have_pruned &&
2470  options.check_blocks > MIN_BLOCKS_TO_KEEP) {
2471  LogPrintf("Prune: pruned datadir may not have more than %d "
2472  "blocks; only checking available blocks\n",
2474  }
2475  std::tie(status, error) = catch_exceptions(
2476  [&] { return VerifyLoadedChainstate(chainman, options); });
2477  if (status == node::ChainstateLoadStatus::SUCCESS) {
2478  fLoaded = true;
2479  LogPrintf(" block index %15dms\n",
2480  GetTimeMillis() - load_block_index_start_time);
2481  }
2482  }
2483 
2486  status ==
2488  return InitError(error);
2489  }
2490 
2491  if (!fLoaded && !ShutdownRequested()) {
2492  // first suggest a reindex
2493  if (!options.reindex) {
2494  bool fRet = uiInterface.ThreadSafeQuestion(
2495  error + Untranslated(".\n\n") +
2496  _("Do you want to rebuild the block database now?"),
2497  error.original + ".\nPlease restart with -reindex or "
2498  "-reindex-chainstate to recover.",
2499  "",
2502  if (fRet) {
2503  fReindex = true;
2504  AbortShutdown();
2505  } else {
2506  LogPrintf("Aborted block database rebuild. Exiting.\n");
2507  return false;
2508  }
2509  } else {
2510  return InitError(error);
2511  }
2512  }
2513  }
2514 
2515  // As LoadBlockIndex can take several minutes, it's possible the user
2516  // requested to kill the GUI during the last operation. If so, exit.
2517  // As the program has not fully started yet, Shutdown() is possibly
2518  // overkill.
2519  if (ShutdownRequested()) {
2520  LogPrintf("Shutdown requested. Exiting.\n");
2521  return false;
2522  }
2523 
2524  ChainstateManager &chainman = *Assert(node.chainman);
2525 
2526  if (args.GetBoolArg("-avalanche", AVALANCHE_DEFAULT_ENABLED)) {
2527  // Initialize Avalanche.
2528  bilingual_str avalancheError;
2530  args, *node.chain, node.connman.get(), chainman, node.mempool.get(),
2531  *node.scheduler, avalancheError);
2532  if (!node.avalanche) {
2533  InitError(avalancheError);
2534  return false;
2535  }
2536 
2537  if (node.avalanche->isAvalancheServiceAvailable()) {
2538  nLocalServices = ServiceFlags(nLocalServices | NODE_AVALANCHE);
2539  }
2540  }
2541 
2542  PeerManager::Options peerman_opts{};
2543  ApplyArgsManOptions(args, peerman_opts);
2544 
2545  assert(!node.peerman);
2546  node.peerman = PeerManager::make(*node.connman, *node.addrman,
2547  node.banman.get(), chainman, *node.mempool,
2548  node.avalanche.get(), peerman_opts);
2549  RegisterValidationInterface(node.peerman.get());
2550 
2551  // Encoded addresses using cashaddr instead of base58.
2552  // We do this by default to avoid confusion with BTC addresses.
2553  config.SetCashAddrEncoding(args.GetBoolArg("-usecashaddr", true));
2554 
2555  // Step 8: load indexers
2556  if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
2557  auto result{
2559  chainman.m_blockman.m_block_tree_db)))};
2560  if (!result) {
2561  return InitError(util::ErrorString(result));
2562  }
2563 
2564  g_txindex =
2565  std::make_unique<TxIndex>(cache_sizes.tx_index, false, fReindex);
2566  if (!g_txindex->Start(chainman.ActiveChainstate())) {
2567  return false;
2568  }
2569  }
2570 
2571  for (const auto &filter_type : g_enabled_filter_types) {
2572  InitBlockFilterIndex(filter_type, cache_sizes.filter_index, false,
2573  fReindex);
2574  if (!GetBlockFilterIndex(filter_type)
2575  ->Start(chainman.ActiveChainstate())) {
2576  return false;
2577  }
2578  }
2579 
2580  if (args.GetBoolArg("-coinstatsindex", DEFAULT_COINSTATSINDEX)) {
2581  g_coin_stats_index = std::make_unique<CoinStatsIndex>(
2582  /* cache size */ 0, false, fReindex);
2583  if (!g_coin_stats_index->Start(chainman.ActiveChainstate())) {
2584  return false;
2585  }
2586  }
2587 
2588 #if ENABLE_CHRONIK
2589  if (args.GetBoolArg("-chronik", DEFAULT_CHRONIK)) {
2590  const bool fReindexChronik =
2591  fReindex || args.GetBoolArg("-chronikreindex", false);
2592  if (!chronik::Start(args, config, node, fReindexChronik)) {
2593  return false;
2594  }
2595  }
2596 #endif
2597 
2598  // Step 9: load wallet
2599  for (const auto &client : node.chain_clients) {
2600  if (!client->load()) {
2601  return false;
2602  }
2603  }
2604 
2605  // Step 10: data directory maintenance
2606 
2607  // if pruning, unset the service bit and perform the initial blockstore
2608  // prune after any wallet rescanning has taken place.
2609  if (chainman.m_blockman.IsPruneMode()) {
2610  LogPrintf("Unsetting NODE_NETWORK on prune mode\n");
2611  nLocalServices = ServiceFlags(nLocalServices & ~NODE_NETWORK);
2612  if (!fReindex) {
2613  LOCK(cs_main);
2614  for (Chainstate *chainstate : chainman.GetAll()) {
2615  uiInterface.InitMessage(_("Pruning blockstore...").translated);
2616  chainstate->PruneAndFlush();
2617  }
2618  }
2619  }
2620 
2621  // Step 11: import blocks
2622  if (!CheckDiskSpace(args.GetDataDirNet())) {
2623  InitError(
2624  strprintf(_("Error: Disk space is low for %s"),
2626  return false;
2627  }
2628  if (!CheckDiskSpace(args.GetBlocksDirPath())) {
2629  InitError(
2630  strprintf(_("Error: Disk space is low for %s"),
2632  return false;
2633  }
2634 
2635  // Either install a handler to notify us when genesis activates, or set
2636  // fHaveGenesis directly.
2637  // No locking, as this happens before any background thread is started.
2638  boost::signals2::connection block_notify_genesis_wait_connection;
2639  if (WITH_LOCK(chainman.GetMutex(),
2640  return chainman.ActiveChain().Tip() == nullptr)) {
2641  block_notify_genesis_wait_connection =
2642  uiInterface.NotifyBlockTip_connect(
2643  std::bind(BlockNotifyGenesisWait, std::placeholders::_2));
2644  } else {
2645  fHaveGenesis = true;
2646  }
2647 
2648 #if defined(HAVE_SYSTEM)
2649  const std::string block_notify = args.GetArg("-blocknotify", "");
2650  if (!block_notify.empty()) {
2651  uiInterface.NotifyBlockTip_connect([block_notify](
2652  SynchronizationState sync_state,
2653  const CBlockIndex *pBlockIndex) {
2654  if (sync_state != SynchronizationState::POST_INIT || !pBlockIndex) {
2655  return;
2656  }
2657  std::string command = block_notify;
2658  ReplaceAll(command, "%s", pBlockIndex->GetBlockHash().GetHex());
2659  std::thread t(runCommand, command);
2660  // thread runs free
2661  t.detach();
2662  });
2663  }
2664 #endif
2665 
2666  std::vector<fs::path> vImportFiles;
2667  for (const std::string &strFile : args.GetArgs("-loadblock")) {
2668  vImportFiles.push_back(fs::PathFromString(strFile));
2669  }
2670 
2671  avalanche::Processor *const avalanche = node.avalanche.get();
2672  chainman.m_load_block =
2673  std::thread(&util::TraceThread, "loadblk", [=, &chainman, &args] {
2674  ThreadImport(chainman, avalanche, vImportFiles,
2675  ShouldPersistMempool(args) ? MempoolPath(args)
2676  : fs::path{});
2677  });
2678 
2679  // Wait for genesis block to be processed
2680  {
2682  // We previously could hang here if StartShutdown() is called prior to
2683  // ThreadImport getting started, so instead we just wait on a timer to
2684  // check ShutdownRequested() regularly.
2685  while (!fHaveGenesis && !ShutdownRequested()) {
2686  g_genesis_wait_cv.wait_for(lock, std::chrono::milliseconds(500));
2687  }
2688  block_notify_genesis_wait_connection.disconnect();
2689  }
2690 
2691  if (ShutdownRequested()) {
2692  return false;
2693  }
2694 
2695  // Step 12: start node
2696 
2697  int chain_active_height;
2698 
2700  {
2701  LOCK(cs_main);
2702  LogPrintf("block tree size = %u\n", chainman.BlockIndex().size());
2703  chain_active_height = chainman.ActiveChain().Height();
2704  if (tip_info) {
2705  tip_info->block_height = chain_active_height;
2706  tip_info->block_time =
2707  chainman.ActiveChain().Tip()
2708  ? chainman.ActiveChain().Tip()->GetBlockTime()
2709  : chainman.GetParams().GenesisBlock().GetBlockTime();
2711  chainman.GetParams().TxData(), chainman.ActiveChain().Tip());
2712  }
2713  if (tip_info && chainman.m_best_header) {
2714  tip_info->header_height = chainman.m_best_header->nHeight;
2715  tip_info->header_time = chainman.m_best_header->GetBlockTime();
2716  }
2717  }
2718  LogPrintf("nBestHeight = %d\n", chain_active_height);
2719  if (node.peerman) {
2720  node.peerman->SetBestHeight(chain_active_height);
2721  }
2722 
2723  // Map ports with UPnP or NAT-PMP.
2724  StartMapPort(args.GetBoolArg("-upnp", DEFAULT_UPNP),
2725  args.GetBoolArg("-natpmp", DEFAULT_NATPMP));
2726 
2727  CConnman::Options connOptions;
2728  connOptions.nLocalServices = nLocalServices;
2729  connOptions.nMaxConnections = nMaxConnections;
2730  connOptions.m_max_avalanche_outbound =
2731  node.avalanche
2732  ? args.GetIntArg("-maxavalancheoutbound",
2734  : 0;
2735  connOptions.m_max_outbound_full_relay = std::min(
2737  connOptions.nMaxConnections - connOptions.m_max_avalanche_outbound);
2738  connOptions.m_max_outbound_block_relay = std::min(
2740  connOptions.nMaxConnections - connOptions.m_max_avalanche_outbound -
2741  connOptions.m_max_outbound_full_relay);
2742  connOptions.nMaxAddnode = MAX_ADDNODE_CONNECTIONS;
2743  connOptions.nMaxFeeler = MAX_FEELER_CONNECTIONS;
2744  connOptions.uiInterface = &uiInterface;
2745  connOptions.m_banman = node.banman.get();
2746  connOptions.m_msgproc.push_back(node.peerman.get());
2747  if (node.avalanche) {
2748  connOptions.m_msgproc.push_back(node.avalanche.get());
2749  }
2750  connOptions.nSendBufferMaxSize =
2751  1000 * args.GetIntArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER);
2752  connOptions.nReceiveFloodSize =
2753  1000 * args.GetIntArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER);
2754  connOptions.m_added_nodes = args.GetArgs("-addnode");
2755 
2756  connOptions.nMaxOutboundLimit =
2757  1024 * 1024 *
2758  args.GetIntArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET);
2759  connOptions.m_peer_connect_timeout = peer_connect_timeout;
2760 
2761  // Port to bind to if `-bind=addr` is provided without a `:port` suffix.
2762  const uint16_t default_bind_port = static_cast<uint16_t>(
2763  args.GetIntArg("-port", config.GetChainParams().GetDefaultPort()));
2764 
2765  const auto BadPortWarning = [](const char *prefix, uint16_t port) {
2766  return strprintf(_("%s request to listen on port %u. This port is "
2767  "considered \"bad\" and "
2768  "thus it is unlikely that any Bitcoin ABC peers "
2769  "connect to it. See "
2770  "doc/p2p-bad-ports.md for details and a full list."),
2771  prefix, port);
2772  };
2773 
2774  for (const std::string &bind_arg : args.GetArgs("-bind")) {
2775  CService bind_addr;
2776  const size_t index = bind_arg.rfind('=');
2777  if (index == std::string::npos) {
2778  if (Lookup(bind_arg, bind_addr, default_bind_port,
2779  /*fAllowLookup=*/false)) {
2780  connOptions.vBinds.push_back(bind_addr);
2781  if (IsBadPort(bind_addr.GetPort())) {
2782  InitWarning(BadPortWarning("-bind", bind_addr.GetPort()));
2783  }
2784  continue;
2785  }
2786  } else {
2787  const std::string network_type = bind_arg.substr(index + 1);
2788  if (network_type == "onion") {
2789  const std::string truncated_bind_arg =
2790  bind_arg.substr(0, index);
2791  if (Lookup(truncated_bind_arg, bind_addr,
2792  BaseParams().OnionServiceTargetPort(), false)) {
2793  connOptions.onion_binds.push_back(bind_addr);
2794  continue;
2795  }
2796  }
2797  }
2798  return InitError(ResolveErrMsg("bind", bind_arg));
2799  }
2800 
2801  for (const std::string &strBind : args.GetArgs("-whitebind")) {
2802  NetWhitebindPermissions whitebind;
2804  if (!NetWhitebindPermissions::TryParse(strBind, whitebind, error)) {
2805  return InitError(error);
2806  }
2807  connOptions.vWhiteBinds.push_back(whitebind);
2808  }
2809 
2810  // If the user did not specify -bind= or -whitebind= then we bind
2811  // on any address - 0.0.0.0 (IPv4) and :: (IPv6).
2812  connOptions.bind_on_any =
2813  args.GetArgs("-bind").empty() && args.GetArgs("-whitebind").empty();
2814 
2815  // Emit a warning if a bad port is given to -port= but only if -bind and
2816  // -whitebind are not given, because if they are, then -port= is ignored.
2817  if (connOptions.bind_on_any && args.IsArgSet("-port")) {
2818  const uint16_t port_arg = args.GetIntArg("-port", 0);
2819  if (IsBadPort(port_arg)) {
2820  InitWarning(BadPortWarning("-port", port_arg));
2821  }
2822  }
2823 
2824  CService onion_service_target;
2825  if (!connOptions.onion_binds.empty()) {
2826  onion_service_target = connOptions.onion_binds.front();
2827  } else {
2828  onion_service_target = DefaultOnionServiceTarget();
2829  connOptions.onion_binds.push_back(onion_service_target);
2830  }
2831 
2832  if (args.GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION)) {
2833  if (connOptions.onion_binds.size() > 1) {
2835  _("More than one onion bind address is provided. Using %s "
2836  "for the automatically created Tor onion service."),
2837  onion_service_target.ToStringIPPort()));
2838  }
2839  StartTorControl(onion_service_target);
2840  }
2841 
2842  if (connOptions.bind_on_any) {
2843  // Only add all IP addresses of the machine if we would be listening on
2844  // any address - 0.0.0.0 (IPv4) and :: (IPv6).
2845  Discover();
2846  }
2847 
2848  for (const auto &net : args.GetArgs("-whitelist")) {
2849  NetWhitelistPermissions subnet;
2851  if (!NetWhitelistPermissions::TryParse(net, subnet, error)) {
2852  return InitError(error);
2853  }
2854  connOptions.vWhitelistedRange.push_back(subnet);
2855  }
2856 
2857  connOptions.vSeedNodes = args.GetArgs("-seednode");
2858 
2859  // Initiate outbound connections unless connect=0
2860  connOptions.m_use_addrman_outgoing = !args.IsArgSet("-connect");
2861  if (!connOptions.m_use_addrman_outgoing) {
2862  const auto connect = args.GetArgs("-connect");
2863  if (connect.size() != 1 || connect[0] != "0") {
2864  connOptions.m_specified_outgoing = connect;
2865  }
2866  }
2867 
2868  const std::string &i2psam_arg = args.GetArg("-i2psam", "");
2869  if (!i2psam_arg.empty()) {
2870  CService addr;
2871  if (!Lookup(i2psam_arg, addr, 7656, fNameLookup) || !addr.IsValid()) {
2872  return InitError(strprintf(
2873  _("Invalid -i2psam address or hostname: '%s'"), i2psam_arg));
2874  }
2875  SetReachable(NET_I2P, true);
2876  SetProxy(NET_I2P, proxyType{addr});
2877  } else {
2878  SetReachable(NET_I2P, false);
2879  }
2880 
2881  connOptions.m_i2p_accept_incoming =
2882  args.GetBoolArg("-i2pacceptincoming", true);
2883 
2884  if (!node.connman->Start(*node.scheduler, connOptions)) {
2885  return false;
2886  }
2887 
2888  // Step 13: finished
2889 
2890  // At this point, the RPC is "started", but still in warmup, which means it
2891  // cannot yet be called. Before we make it callable, we need to make sure
2892  // that the RPC's view of the best block is valid and consistent with
2893  // ChainstateManager's active tip.
2894  //
2895  // If we do not do this, RPC's view of the best block will be height=0 and
2896  // hash=0x0. This will lead to erroroneous responses for things like
2897  // waitforblockheight.
2899  WITH_LOCK(chainman.GetMutex(), return chainman.ActiveTip()));
2901 
2902  uiInterface.InitMessage(_("Done loading").translated);
2903 
2904  for (const auto &client : node.chain_clients) {
2905  client->start(*node.scheduler);
2906  }
2907 
2908  BanMan *banman = node.banman.get();
2909  node.scheduler->scheduleEvery(
2910  [banman] {
2911  banman->DumpBanlist();
2912  return true;
2913  },
2915 
2916  // Start Avalanche's event loop.
2917  if (node.avalanche) {
2918  node.avalanche->startEventLoop(*node.scheduler);
2919  }
2920 
2921  if (node.peerman) {
2922  node.peerman->StartScheduledTasks(*node.scheduler);
2923  }
2924 
2925 #if HAVE_SYSTEM
2926  StartupNotify(args);
2927 #endif
2928 
2929  return true;
2930 }
util::Result< std::unique_ptr< AddrMan > > LoadAddrman(const CChainParams &chainparams, const std::vector< bool > &asmap, const ArgsManager &args)
Returns an error string on failure.
Definition: addrdb.cpp:165
static constexpr int32_t DEFAULT_ADDRMAN_CONSISTENCY_CHECKS
Default for -checkaddrman.
Definition: addrman.h:29
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
Definition: args.cpp:737
const char *const BITCOIN_SETTINGS_FILENAME
Definition: args.cpp:36
ArgsManager gArgs
Definition: args.cpp:38
const char *const BITCOIN_CONF_FILENAME
Definition: args.cpp:35
fs::path AbsPathForConfigVal(const ArgsManager &args, const fs::path &path, bool net_specific=true)
Most paths passed as configuration arguments are treated as relative to the datadir if they are not a...
Definition: configfile.cpp:234
std::vector< bool > DecodeAsmap(fs::path path)
Read asmap from provided binary file.
Definition: asmap.cpp:294
static constexpr bool DEFAULT_PERSIST_AVAPEERS
Default for -persistavapeers.
Definition: avalanche.h:63
static constexpr double AVALANCHE_DEFAULT_MIN_QUORUM_CONNECTED_STAKE_RATIO
Default minimum percentage of stake-weighted peers we must have a node for to constitute a usable quo...
Definition: avalanche.h:53
static constexpr size_t AVALANCHE_DEFAULT_PEER_REPLACEMENT_COOLDOWN
Peer replacement cooldown time default value in seconds.
Definition: avalanche.h:34
static constexpr double AVALANCHE_DEFAULT_MIN_AVAPROOFS_NODE_COUNT
Default minimum number of nodes that sent us an avaproofs message before we can consider our quorum s...
Definition: avalanche.h:60
static constexpr Amount AVALANCHE_DEFAULT_MIN_QUORUM_STAKE
Default minimum cumulative stake of all known peers that constitutes a usable quorum.
Definition: avalanche.h:46
static constexpr size_t AVALANCHE_DEFAULT_CONFLICTING_PROOF_COOLDOWN
Conflicting proofs cooldown time default value in seconds.
Definition: avalanche.h:28
static constexpr bool AVALANCHE_DEFAULT_ENABLED
Is avalanche enabled by default.
Definition: avalanche.h:22
static constexpr size_t AVALANCHE_DEFAULT_COOLDOWN
Avalanche default cooldown in milliseconds.
Definition: avalanche.h:40
static constexpr unsigned int DEFAULT_MISBEHAVING_BANTIME
Definition: banman.h:20
static constexpr std::chrono::minutes DUMP_BANS_INTERVAL
Definition: banman.h:22
void RPCNotifyBlockChange(const CBlockIndex *pindex)
Callback for when block tip changed.
Definition: blockchain.cpp:234
const std::string & BlockFilterTypeName(BlockFilterType filter_type)
Get the human-readable name for a filter type.
const std::string & ListBlockFilterTypes()
Get a comma-separated list of known filter type names.
bool BlockFilterTypeByName(const std::string &name, BlockFilterType &filter_type)
Find a filter type by its human-readable name.
const std::set< BlockFilterType > & AllBlockFilterTypes()
Get a list of known filter types.
BlockFilterType
Definition: blockfilter.h:88
void DestroyAllBlockFilterIndexes()
Destroy all open block filter indexes.
BlockFilterIndex * GetBlockFilterIndex(BlockFilterType filter_type)
Get a block filter index by type.
void ForEachBlockFilterIndex(std::function< void(BlockFilterIndex &)> fn)
Iterate over all running block filter indexes, invoking fn on each.
bool InitBlockFilterIndex(BlockFilterType filter_type, size_t n_cache_size, bool f_memory, bool f_wipe)
Initialize a block filter index for the given type if one does not already exist.
static const char *const DEFAULT_BLOCKFILTERINDEX
std::unique_ptr< const CChainParams > CreateChainParams(const ArgsManager &args, const std::string &chain)
Creates and returns a std::unique_ptr<CChainParams> of the chosen chain.
Definition: chainparams.cpp:32
const CChainParams & Params()
Return the currently selected parameters.
Definition: chainparams.cpp:19
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
void SetupChainParamsBaseOptions(ArgsManager &argsman)
Set the arguments for chainparams.
std::unique_ptr< CBaseChainParams > CreateBaseChainParams(const std::string &chain)
Port numbers for incoming Tor connections (8334, 18334, 38334, 18445) have been chosen arbitrarily to...
static constexpr bool DEFAULT_CHECKPOINTS_ENABLED
static constexpr auto DEFAULT_MAX_TIP_AGE
#define Assert(val)
Identity function.
Definition: check.h:84
const std::set< std::string > GetUnsuitableSectionOnlyArgs() const
Log warnings for options in m_section_only_args when they are specified in the default section but no...
Definition: args.cpp:133
const fs::path & GetBlocksDirPath() const
Get blocks directory path.
Definition: args.cpp:289
@ NETWORK_ONLY
Definition: args.h:110
@ ALLOW_ANY
Definition: args.h:103
@ DEBUG_ONLY
Definition: args.h:104
@ ALLOW_INT
Definition: args.h:101
@ ALLOW_BOOL
Definition: args.h:100
@ ALLOW_STRING
Definition: args.h:102
@ SENSITIVE
Definition: args.h:112
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
Definition: args.cpp:371
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: args.cpp:381
const fs::path & GetDataDirNet() const
Get data directory path with appended network identifier.
Definition: args.h:215
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Definition: args.cpp:526
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: args.cpp:494
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn't already have a value.
Definition: args.cpp:589
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: args.cpp:556
void AddHiddenArgs(const std::vector< std::string > &args)
Add many hidden arguments.
Definition: args.cpp:642
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
Definition: args.cpp:620
fs::path GetPathArg(std::string arg, const fs::path &default_value={}) const
Return path argument or default value.
Definition: args.cpp:275
const std::list< SectionInfo > GetUnrecognizedSections() const
Log warnings for unrecognized section names in the config file.
Definition: args.cpp:157
std::string GetChainName() const
Looks for -regtest, -testnet and returns the appropriate BIP70 chain name.
Definition: args.cpp:793
std::atomic< bool > m_reopen_file
Definition: logging.h:112
Definition: banman.h:58
void DumpBanlist()
Definition: banman.cpp:49
void Stop()
Stops the instance from staying in sync with blockchain updates.
Definition: base.cpp:392
BlockFilterIndex is used to store and retrieve block filters, hashes, and headers for a range of bloc...
static const std::string REGTEST
static const std::string TESTNET
static const std::string MAIN
BIP70 chain name strings (main, test or regtest)
int64_t GetBlockTime() const
Definition: block.h:57
Definition: block.h:60
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: blockindex.h:25
int64_t GetBlockTime() const
Definition: blockindex.h:180
BlockHash GetBlockHash() const
Definition: blockindex.h:146
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:150
int Height() const
Return the maximal height in the chain.
Definition: chain.h:186
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:80
bool DefaultConsistencyChecks() const
Default value for -checkmempool and -checkblockindex argument.
Definition: chainparams.h:107
const ChainTxData & TxData() const
Definition: chainparams.h:140
bool IsTestChain() const
If this chain is exclusively used for testing.
Definition: chainparams.h:111
uint16_t GetDefaultPort() const
Definition: chainparams.h:95
const CBlock & GenesisBlock() const
Definition: chainparams.h:105
void UnregisterBackgroundSignalScheduler()
Unregister a CScheduler to give callbacks which should run in the background - these callbacks will n...
void RegisterBackgroundSignalScheduler(CScheduler &scheduler)
Register a CScheduler to give callbacks which should run in the background (may only be called once)
void FlushBackgroundCallbacks()
Call any remaining callbacks on the calling thread.
bool IsValid() const
Definition: netaddress.cpp:479
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:545
std::string ToStringIPPort() const
uint16_t GetPort() const
static const int DEFAULT_ZMQ_SNDHWM
static std::unique_ptr< CZMQNotificationInterface > Create(std::function< bool(CBlock &, const CBlockIndex &)> get_block_by_index)
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:695
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:1218
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1428
const CChainParams & GetParams() const
Definition: validation.h:1312
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:1438
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
Definition: validation.h:1342
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1434
std::thread m_load_block
Definition: validation.h:1347
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(std::vector< Chainstate * GetAll)()
Instantiate a new chainstate.
Definition: validation.h:1395
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:1350
Definition: config.h:19
virtual uint64_t GetMaxBlockSize() const =0
virtual const CChainParams & GetChainParams() const =0
virtual bool SetMaxBlockSize(uint64_t maxBlockSize)=0
virtual void SetCashAddrEncoding(bool)=0
Different type to mark Mutex at global scope.
Definition: sync.h:144
A writer stream (for serialization) that computes a 256-bit hash.
Definition: hash.h:99
static bool TryParse(const std::string &str, NetWhitebindPermissions &output, bilingual_str &error)
static bool TryParse(const std::string &str, NetWhitelistPermissions &output, bilingual_str &error)
static std::unique_ptr< PeerManager > make(CConnman &connman, AddrMan &addrman, BanMan *banman, ChainstateManager &chainman, CTxMemPool &pool, avalanche::Processor *const avalanche, Options opts)
Class for registering and managing all RPC calls.
Definition: server.h:40
virtual void AddWalletOptions(ArgsManager &argsman) const =0
Get wallet help string.
virtual void Construct(node::NodeContext &node) const =0
Add wallets that should be opened to list of chain clients.
virtual bool ParameterInteraction() const =0
Check wallet parameter interaction.
static std::unique_ptr< Processor > MakeProcessor(const ArgsManager &argsman, interfaces::Chain &chain, CConnman *connman, ChainstateManager &chainman, CTxMemPool *mempoolIn, CScheduler &scheduler, bilingual_str &error)
Definition: processor.cpp:217
std::string ToString() const
Definition: uint256.h:80
std::string GetHex() const
Definition: uint256.cpp:16
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:30
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
Definition: blockstorage.h:74
const CBlockIndex *GetFirstStoredBlock(const CBlockIndex &start_block) EXCLUSIVE_LOCKS_REQUIRED(bool m_have_pruned
Find the first block that is not pruned.
Definition: blockstorage.h:264
bool IsPruneMode() const
Whether running in -prune mode.
Definition: blockstorage.h:235
bool IsValid() const
Definition: netbase.h:38
256-bit opaque blob.
Definition: uint256.h:129
std::string FormatVersion(int nVersion)
std::string FormatUserAgent(const std::string &name, const std::string &version, const std::vector< std::string > &comments)
Format the subversion field according to BIP 14 spec.
static constexpr int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
Definition: clientversion.h:38
const std::string CLIENT_NAME
std::unique_ptr< CoinStatsIndex > g_coin_stats_index
The global UTXO set hash object.
static constexpr bool DEFAULT_COINSTATSINDEX
static const uint64_t DEFAULT_MAX_BLOCK_SIZE
Default setting for maximum allowed size for a block, in bytes.
Definition: consensus.h:20
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:7
void SetupCurrencyUnitOptions(ArgsManager &argsman)
Definition: currencyunit.cpp:9
bilingual_str AmountErrMsg(const std::string &optname, const std::string &strValue)
Definition: error.cpp:53
bilingual_str ResolveErrMsg(const std::string &optname, const std::string &strBind)
Definition: error.cpp:44
bool LockDirectory(const fs::path &directory, const std::string lockfile_name, bool probe_only)
Definition: fs_helpers.cpp:58
bool DirIsWritable(const fs::path &directory)
Definition: fs_helpers.cpp:97
int RaiseFileDescriptorLimit(int nMinFD)
This function tries to raise the file descriptor limit to the requested number.
Definition: fs_helpers.cpp:182
bool CheckDiskSpace(const fs::path &dir, uint64_t additional_bytes)
Definition: fs_helpers.cpp:111
void InterruptHTTPRPC()
Interrupt HTTP RPC subsystem.
Definition: httprpc.cpp:471
void StopHTTPRPC()
Stop HTTP RPC subsystem.
Definition: httprpc.cpp:475
bool StartHTTPRPC(HTTPRPCRequestProcessor &httpRPCRequestProcessor)
Start HTTP RPC subsystem.
Definition: httprpc.cpp:450
void StartREST(const std::any &context)
Start HTTP REST subsystem.
Definition: rest.cpp:832
void StopREST()
Stop HTTP REST subsystem.
Definition: rest.cpp:844
void InterruptREST()
Interrupt RPC REST subsystem.
Definition: rest.cpp:842
void InterruptHTTPServer()
Interrupt HTTP server threads.
Definition: httpserver.cpp:472
void StartHTTPServer()
Start HTTP server.
Definition: httpserver.cpp:460
void StopHTTPServer()
Stop HTTP server.
Definition: httpserver.cpp:483
bool InitHTTPServer(Config &config)
Initialize HTTP server.
Definition: httpserver.cpp:382
static const int DEFAULT_HTTP_SERVER_TIMEOUT
Definition: httpserver.h:14
static const int DEFAULT_HTTP_WORKQUEUE
Definition: httpserver.h:13
static const int DEFAULT_HTTP_THREADS
Definition: httpserver.h:12
Common init functions shared by bitcoin-node, bitcoin-wallet, etc.
static const char * BITCOIN_PID_FILENAME
The PID file facilities.
Definition: init.cpp:151
static bool CreatePidFile(const ArgsManager &args)
Definition: init.cpp:158
static const bool DEFAULT_PROXYRANDOMIZE
Definition: init.cpp:134
void Interrupt(NodeContext &node)
Interrupt threads.
Definition: init.cpp:198
void InitLogging(const ArgsManager &args)
Initialize global loggers.
Definition: init.cpp:1626
bool AppInitLockDataDirectory()
Lock bitcoin data directory.
Definition: init.cpp:2023
void SetupServerArgs(NodeContext &node)
Register all arguments with the ArgsManager.
Definition: init.cpp:419
static bool AppInitServers(Config &config, HTTPRPCRequestProcessor &httpRPCRequestProcessor, NodeContext &node)
Definition: init.cpp:1467
#define MIN_CORE_FILEDESCRIPTORS
Definition: init.cpp:143
static bool fHaveGenesis
Definition: init.cpp:1442
void Shutdown(NodeContext &node)
Definition: init.cpp:222
static void HandleSIGTERM(int)
Signal handlers are very limited in what they are allowed to do.
Definition: init.cpp:381
static GlobalMutex g_genesis_wait_mutex
Definition: init.cpp:1443
static void OnRPCStarted()
Definition: init.cpp:407
static void HandleSIGHUP(int)
Definition: init.cpp:385
static fs::path GetPidFile(const ArgsManager &args)
Definition: init.cpp:153
static std::condition_variable g_genesis_wait_cv
Definition: init.cpp:1444
bool AppInitMain(Config &config, RPCServer &rpcServer, HTTPRPCRequestProcessor &httpRPCRequestProcessor, NodeContext &node, interfaces::BlockAndHeaderTipInfo *tip_info)
Bitcoin main initialization.
Definition: init.cpp:2045
static constexpr bool DEFAULT_CHRONIK
Definition: init.cpp:136
bool AppInitBasicSetup(const ArgsManager &args)
Initialize bitcoin: Basic context setup.
Definition: init.cpp:1653
bool AppInitSanityChecks()
Initialization sanity checks: ecc init, sanity checks, dir lock.
Definition: init.cpp:2005
bool AppInitInterfaces(NodeContext &node)
Initialize node and wallet interface pointers.
Definition: init.cpp:2035
static const char * DEFAULT_ASMAP_FILENAME
Definition: init.cpp:146
void InitParameterInteraction(ArgsManager &args)
Parameter interaction: change current parameters depending on various rules.
Definition: init.cpp:1492
static void BlockNotifyGenesisWait(const CBlockIndex *pBlockIndex)
Definition: init.cpp:1446
static void OnRPCStopped()
Definition: init.cpp:412
static bool LockDataDirectory(bool probeOnly)
Definition: init.cpp:1989
static void registerSignalHandler(int signal, void(*handler)(int))
Definition: init.cpp:397
bool AppInitParameterInteraction(Config &config, const ArgsManager &args)
Initialization: parameter interaction.
Definition: init.cpp:1700
static const bool DEFAULT_REST_ENABLE
Definition: init.cpp:135
static boost::signals2::connection rpc_notify_block_change_connection
Definition: init.cpp:406
static void new_handler_terminate()
Definition: init.cpp:1642
static constexpr bool DEFAULT_DAEMON
Default value for -daemon option.
Definition: init.h:16
static constexpr bool DEFAULT_DAEMONWAIT
Default value for -daemonwait option.
Definition: init.h:18
BCLog::Logger & LogInstance()
Definition: logging.cpp:20
bool error(const char *fmt, const Args &...args)
Definition: logging.h:226
#define LogPrint(category,...)
Definition: logging.h:211
#define LogPrintf(...)
Definition: logging.h:207
void StartMapPort(bool use_upnp, bool use_natpmp)
Definition: mapport.cpp:362
void StopMapPort()
Definition: mapport.cpp:368
void InterruptMapPort()
Definition: mapport.cpp:365
static constexpr bool DEFAULT_NATPMP
Definition: mapport.h:17
static constexpr bool DEFAULT_UPNP
Definition: mapport.h:11
std::optional< bilingual_str > ApplyArgsManOptions(const ArgsManager &argsman, const CChainParams &chainparams, MemPoolOptions &mempool_opts)
Overlay the options set in argsman on top of corresponding members in mempool_opts.
static constexpr unsigned int DEFAULT_MAX_MEMPOOL_SIZE_MB
Default for -maxmempool, maximum megabytes of mempool memory usage.
static constexpr unsigned int DEFAULT_MEMPOOL_EXPIRY_HOURS
Default for -mempoolexpiry, expiration time for mempool transactions in hours.
std::string FormatMoney(const Amount amt)
Do not use these functions to represent or parse monetary amounts to or from JSON but use AmountFromV...
Definition: moneystr.cpp:13
bool ParseMoney(const std::string &money_string, Amount &nRet)
Parse an amount denoted in full coins.
Definition: moneystr.cpp:37
@ RPC
Definition: logging.h:47
void OnStarted(std::function< void()> slot)
Definition: server.cpp:113
void OnStopped(std::function< void()> slot)
Definition: server.cpp:117
static constexpr Amount PROOF_DUST_THRESHOLD
Minimum amount per utxo.
Definition: proof.h:40
static auto quoted(const std::string &s)
Definition: fs.h:107
static bool exists(const path &p)
Definition: fs.h:102
static std::string PathToString(const path &path)
Convert path object to byte string.
Definition: fs.h:142
static path PathFromString(const std::string &string)
Convert byte string to path object.
Definition: fs.h:165
std::string get_filesystem_error_message(const fs::filesystem_error &e)
Definition: fs.cpp:142
void AddLoggingArgs(ArgsManager &argsman)
Definition: common.cpp:65
void SetLoggingCategories(const ArgsManager &args)
Definition: common.cpp:161
bool SanityChecks()
Ensure a usable environment with all necessary library support.
Definition: common.cpp:43
void SetGlobals()
Definition: common.cpp:30
bool StartLogging(const ArgsManager &args)
Definition: common.cpp:189
void SetLoggingOptions(const ArgsManager &args)
Definition: common.cpp:140
void UnsetGlobals()
Definition: common.cpp:38
void LogPackageVersion()
Definition: common.cpp:236
std::unique_ptr< Chain > MakeChain(node::NodeContext &node, const CChainParams &params)
Return implementation of Chain interface.
Definition: interfaces.cpp:795
static constexpr bool DEFAULT_STOPAFTERBLOCKIMPORT
bool DumpMempool(const CTxMemPool &pool, const fs::path &dump_path, FopenFn mockable_fopen_function, bool skip_file_commit)
Definition: init.h:28
@ FAILURE_FATAL
Fatal error which should not prompt to reindex.
@ FAILURE
Generic failure which reindexing may fix.
CacheSizes CalculateCacheSizes(const ArgsManager &args, size_t n_indexes)
Definition: caches.cpp:12
fs::path MempoolPath(const ArgsManager &argsman)
bool ShouldPersistMempool(const ArgsManager &argsman)
void ThreadImport(ChainstateManager &chainman, avalanche::Processor *const avalanche, std::vector< fs::path > vImportFiles, const fs::path &mempool_path)
std::optional< bilingual_str > ApplyArgsManOptions(const ArgsManager &args, BlockManager::Options &opts)
ChainstateLoadResult LoadChainstate(ChainstateManager &chainman, const CacheSizes &cache_sizes, const ChainstateLoadOptions &options)
This sequence can have 4 types of outcomes:
Definition: chainstate.cpp:167
ChainstateLoadResult VerifyLoadedChainstate(ChainstateManager &chainman, const ChainstateLoadOptions &options)
Definition: chainstate.cpp:262
static constexpr bool DEFAULT_PERSIST_MEMPOOL
Default for -persistmempool, indicating whether the node should attempt to automatically load the mem...
std::atomic_bool fReindex
void format(std::ostream &out, const char *fmt, const Args &...args)
Format list of arguments to the stream according to given format string.
Definition: tinyformat.h:1112
bilingual_str ErrorString(const Result< T > &result)
Definition: result.h:78
void TraceThread(const char *thread_name, std::function< void()> thread_func)
A wrapper for do-something-once thread functions.
Definition: thread.cpp:13
void ThreadRename(std::string &&)
Rename a thread both in terms of an internal (in-memory) name as well as its system thread name.
Definition: threadnames.cpp:48
uint16_t GetListenPort()
Definition: net.cpp:137
bool fDiscover
Definition: net.cpp:125
bool fListen
Definition: net.cpp:126
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
Definition: net.cpp:317
bool AddLocal(const CService &addr, int nScore)
Definition: net.cpp:278
void Discover()
Look up IP addresses from all interfaces on the machine and add them to the list of local addresses t...
Definition: net.cpp:2789
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
Definition: net.h:93
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
Definition: net.h:69
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
Definition: net.h:76
static const size_t DEFAULT_MAXSENDBUFFER
Definition: net.h:107
static const int NUM_FDS_MESSAGE_CAPTURE
Number of file descriptors required for message capture.
Definition: net.h:101
static const bool DEFAULT_BLOCKSONLY
Default for blocks only.
Definition: net.h:97
static const bool DEFAULT_WHITELISTFORCERELAY
Default for -whitelistforcerelay.
Definition: net.h:57
static const bool DEFAULT_FORCEDNSSEED
Definition: net.h:103
static const bool DEFAULT_WHITELISTRELAY
Default for -whitelistrelay.
Definition: net.h:55
static constexpr uint64_t DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
Definition: net.h:95
static const size_t DEFAULT_MAXRECEIVEBUFFER
Definition: net.h:106
static const int DEFAULT_MAX_AVALANCHE_OUTBOUND_CONNECTIONS
Maximum number of avalanche enabled outgoing connections by default.
Definition: net.h:83
static const bool DEFAULT_FIXEDSEEDS
Definition: net.h:105
static const int MAX_FEELER_CONNECTIONS
Maximum number of feeler connections.
Definition: net.h:85
static const bool DEFAULT_LISTEN
-listen default
Definition: net.h:87
static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT
-peertimeout default
Definition: net.h:99
static const bool DEFAULT_DNSSEED
Definition: net.h:104
static const int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS
Maximum number of automatic outgoing nodes over which we'll relay everything (blocks,...
Definition: net.h:74
@ LOCAL_MANUAL
Definition: net.h:242
static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
Definition: net.h:78
const std::vector< std::string > NET_PERMISSIONS_DOC
static const uint32_t DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN
Default number of non-mempool transactions to keep around for block reconstruction.
static const uint32_t DEFAULT_MAX_ORPHAN_TRANSACTIONS
Default for -maxorphantx, maximum number of orphan transactions kept in memory.
static const bool DEFAULT_PEERBLOCKFILTERS
Network
A network type.
Definition: netaddress.h:44
@ NET_I2P
I2P.
Definition: netaddress.h:59
@ NET_MAX
Dummy value to indicate the number of NET_* constants.
Definition: netaddress.h:69
@ NET_ONION
TOR (v2 or v3)
Definition: netaddress.h:56
@ NET_IPV6
IPv6.
Definition: netaddress.h:53
@ NET_IPV4
IPv4.
Definition: netaddress.h:50
@ NET_UNROUTABLE
Addresses from these networks are not publicly routable on the global Internet.
Definition: netaddress.h:47
enum Network ParseNetwork(const std::string &net_in)
Definition: netbase.cpp:91
bool Lookup(const std::string &name, std::vector< CService > &vAddr, uint16_t portDefault, bool fAllowLookup, unsigned int nMaxSolutions, DNSLookupFn dns_lookup_function)
Resolve a service string to its corresponding service.
Definition: netbase.cpp:222
bool fNameLookup
Definition: netbase.cpp:38
int nConnectTimeout
Definition: netbase.cpp:37
std::vector< std::string > GetNetworkNames(bool append_unroutable)
Return a vector of publicly routable Network names; optionally append NET_UNROUTABLE.
Definition: netbase.cpp:136
bool SetNameProxy(const proxyType &addrProxy)
Set the name proxy to use for all connections to nodes specified by a hostname.
Definition: netbase.cpp:730
bool IsBadPort(uint16_t port)
Determine if a port is "bad" from the perspective of attempting to connect to a node on that port.
Definition: netbase.cpp:859
bool SetProxy(enum Network net, const proxyType &addrProxy)
Definition: netbase.cpp:710
static const int DEFAULT_NAME_LOOKUP
-dns default
Definition: netbase.h:29
static const int DEFAULT_CONNECT_TIMEOUT
-timeout default
Definition: netbase.h:27
uint32_t nBytesPerSigCheck
Definition: settings.cpp:10
static constexpr uint64_t DEFAULT_MAX_GENERATED_BLOCK_SIZE
Default for -blockmaxsize, which controls the maximum size of block the mining code will create.
Definition: policy.h:25
static constexpr Amount DUST_RELAY_TX_FEE(1000 *SATOSHI)
Min feerate for defining dust.
static constexpr bool DEFAULT_PERMIT_BAREMULTISIG
Default for -permitbaremultisig.
Definition: policy.h:56
static constexpr Amount DEFAULT_MIN_RELAY_TX_FEE_PER_KB(1000 *SATOSHI)
Default for -minrelaytxfee, minimum relay fee for transactions.
static constexpr unsigned int DEFAULT_BYTES_PER_SIGCHECK
Default for -bytespersigcheck .
Definition: policy.h:54
static constexpr Amount DEFAULT_BLOCK_MIN_TX_FEE_PER_KB(1000 *SATOSHI)
Default for -blockmintxfee, which sets the minimum feerate for a transaction in blocks created by min...
static constexpr std::chrono::milliseconds AVALANCHE_DEFAULT_QUERY_TIMEOUT
How long before we consider that a query timed out.
Definition: processor.h:57
static constexpr int AVALANCHE_DEFAULT_STAKE_UTXO_CONFIRMATIONS
Minimum number of confirmations before a stake utxo is mature enough to be included into a proof.
Definition: proof.h:35
ServiceFlags
nServices flags.
Definition: protocol.h:335
@ NODE_NETWORK_LIMITED
Definition: protocol.h:365
@ NODE_BLOOM
Definition: protocol.h:352
@ NODE_NETWORK
Definition: protocol.h:342
@ NODE_COMPACT_FILTERS
Definition: protocol.h:360
@ NODE_AVALANCHE
Definition: protocol.h:380
void RandAddPeriodic() noexcept
Gather entropy from various expensive sources, and feed them to the PRNG state.
Definition: random.cpp:645
static void RegisterAllRPCCommands(const Config &config, RPCServer &rpcServer, CRPCTable &rpcTable)
Register all context-sensitive RPC commands.
Definition: register.h:42
const char * prefix
Definition: rest.cpp:817
bool(* handler)(Config &config, const std::any &context, HTTPRequest *req, const std::string &strReq)
Definition: rest.cpp:818
const char * name
Definition: rest.cpp:47
const std::string UNIX_EPOCH_TIME
String used to describe UNIX epoch time in documentation, factored out to a constant for consistency.
Definition: util.cpp:22
static constexpr bool DEFAULT_RPC_DOC_CHECK
Definition: util.h:29
bool InitScriptExecutionCache(size_t max_size_bytes)
Initializes the script-execution cache.
Definition: scriptcache.cpp:76
static constexpr size_t DEFAULT_MAX_SCRIPT_CACHE_BYTES
Definition: scriptcache.h:45
void SetRPCWarmupFinished()
Mark warmup as done.
Definition: server.cpp:393
void StartRPC()
Definition: server.cpp:348
void StopRPC()
Definition: server.cpp:365
void InterruptRPC()
Definition: server.cpp:354
void SetRPCWarmupStatus(const std::string &newStatus)
Set the RPC warmup status.
Definition: server.cpp:388
CRPCTable tableRPC
Definition: server.cpp:683
void RpcInterruptionPoint()
Throw JSONRPCError if RPC is not running.
Definition: server.cpp:382
bool ShutdownRequested()
Returns true if a shutdown is requested, false otherwise.
Definition: shutdown.cpp:85
bool InitShutdownState()
Initialize shutdown state.
Definition: shutdown.cpp:43
void StartShutdown()
Request shutdown of the application.
Definition: shutdown.cpp:55
void AbortShutdown()
Clear shutdown flag.
Definition: shutdown.cpp:76
bool InitSignatureCache(size_t max_size_bytes)
Definition: sigcache.cpp:85
static constexpr size_t DEFAULT_MAX_SIG_CACHE_BYTES
Definition: sigcache.h:18
static const unsigned int MAX_OP_RETURN_RELAY
Default setting for nMaxDatacarrierBytes.
Definition: standard.h:36
static const bool DEFAULT_ACCEPT_DATACARRIER
Definition: standard.h:17
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
@ SAFE_CHARS_UA_COMMENT
BIP-0014 subset.
Definition: strencodings.h:24
void ReplaceAll(std::string &in_out, const std::string &search, const std::string &substitute)
Definition: string.cpp:10
auto Join(const std::vector< T > &list, const BaseType &separator, UnaryOp unary_op) -> decltype(unary_op(list.at(0)))
Join a list of items.
Definition: string.h:53
Definition: amount.h:19
static constexpr Amount zero() noexcept
Definition: amount.h:32
int m_max_outbound_block_relay
Definition: net.h:858
unsigned int nReceiveFloodSize
Definition: net.h:866
int m_max_outbound_full_relay
Definition: net.h:857
std::vector< NetWhitebindPermissions > vWhiteBinds
Definition: net.h:871
uint64_t nMaxOutboundLimit
Definition: net.h:867
std::vector< NetWhitelistPermissions > vWhitelistedRange
Definition: net.h:870
CClientUIInterface * uiInterface
Definition: net.h:862
int m_max_avalanche_outbound
Definition: net.h:859
std::vector< CService > onion_binds
Definition: net.h:873
int nMaxFeeler
Definition: net.h:861
std::vector< std::string > m_specified_outgoing
Definition: net.h:878
int nMaxConnections
Definition: net.h:856
ServiceFlags nLocalServices
Definition: net.h:855
std::vector< std::string > m_added_nodes
Definition: net.h:879
int64_t m_peer_connect_timeout
Definition: net.h:868
std::vector< CService > vBinds
Definition: net.h:872
unsigned int nSendBufferMaxSize
Definition: net.h:865
bool m_i2p_accept_incoming
Definition: net.h:880
std::vector< std::string > vSeedNodes
Definition: net.h:869
BanMan * m_banman
Definition: net.h:864
bool m_use_addrman_outgoing
Definition: net.h:877
std::vector< NetEventsInterface * > m_msgproc
Definition: net.h:863
bool bind_on_any
True if the user did not specify -bind= or -whitebind= and thus we should bind on 0....
Definition: net.h:876
int nMaxAddnode
Definition: net.h:860
static const Currency & get()
Definition: amount.cpp:18
std::string ticker
Definition: amount.h:150
Bilingual messages:
Definition: translation.h:17
bool empty() const
Definition: translation.h:27
std::string translated
Definition: translation.h:19
Block and header tip information.
Definition: node.h:49
An options struct for ChainstateManager, more ergonomically referred to as ChainstateManager::Options...
Options struct containing options for constructing a CTxMemPool.
int check_ratio
The ratio used to determine how often sanity checks will run.
int64_t tx_index
Definition: caches.h:18
int64_t coins
Definition: caches.h:17
int64_t block_tree_db
Definition: caches.h:15
int64_t filter_index
Definition: caches.h:19
int64_t coins_db
Definition: caches.h:16
std::function< void()> coins_error_cb
Definition: chainstate.h:37
std::function< bool()> check_interrupt
Definition: chainstate.h:36
NodeContext struct containing references to chain state and connection state.
Definition: context.h:43
#define WAIT_LOCK(cs, name)
Definition: sync.h:317
#define LOCK(cs)
Definition: sync.h:306
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:357
#define TRY_LOCK(cs, name)
Definition: sync.h:314
std::string SysErrorString(int err)
Return system error string from errno value.
Definition: syserror.cpp:14
bool SetupNetworking()
Definition: system.cpp:98
int GetNumCores()
Return the number of cores available on the current system.
Definition: system.cpp:111
int64_t GetTimeMillis()
Returns the system time (not mockable)
Definition: time.cpp:101
void SetMockTime(int64_t nMockTimeIn)
DEPRECATED Use SetMockTime with chrono type.
Definition: time.cpp:89
NodeClock::time_point GetAdjustedTime()
Definition: timedata.cpp:35
static const int64_t DEFAULT_MAX_TIME_ADJUSTMENT
Definition: timedata.h:16
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1202
CService DefaultOnionServiceTarget()
Definition: torcontrol.cpp:871
const std::string DEFAULT_TOR_CONTROL
Default control port.
Definition: torcontrol.cpp:38
void InterruptTorControl()
Definition: torcontrol.cpp:853
void StartTorControl(CService onion_service_target)
Definition: torcontrol.cpp:834
void StopTorControl()
Definition: torcontrol.cpp:863
static const bool DEFAULT_LISTEN_ONION
Definition: torcontrol.h:16
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:68
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:36
util::Result< void > CheckLegacyTxindex(CBlockTreeDB &block_tree_db)
Definition: txdb.cpp:37
static constexpr int64_t MAX_DB_CACHE_MB
max. -dbcache (MiB)
Definition: txdb.h:38
static constexpr int64_t MIN_DB_CACHE_MB
min. -dbcache (MiB)
Definition: txdb.h:36
static constexpr int64_t DEFAULT_DB_BATCH_SIZE
-dbbatchsize default (bytes)
Definition: txdb.h:42
static constexpr int64_t DEFAULT_DB_CACHE_MB
-dbcache default (MiB)
Definition: txdb.h:40
std::unique_ptr< TxIndex > g_txindex
The global transaction index, used in GetTransaction. May be null.
Definition: txindex.cpp:16
static constexpr bool DEFAULT_TXINDEX
Definition: txindex.h:15
CClientUIInterface uiInterface
void InitWarning(const bilingual_str &str)
Show warning message.
bool InitError(const bilingual_str &str)
Show error message.
void StartScriptCheckWorkerThreads(int threads_num)
Run instances of script checking worker threads.
std::condition_variable g_best_block_cv
Definition: validation.cpp:114
double GuessVerificationProgress(const ChainTxData &data, const CBlockIndex *pindex)
Guess how far we are in the verification process at the given block index require cs_main if pindex h...
void StopScriptCheckWorkerThreads()
Stop all of the script checking worker threads.
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument 'checklevel'.
Definition: validation.cpp:97
assert(!tx.IsCoinBase())
static constexpr int DEFAULT_CHECKLEVEL
Definition: validation.h:96
static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES
Require that user allocate at least 550 MiB for block & undo files (blk???.dat and rev?...
Definition: validation.h:110
static const unsigned int MIN_BLOCKS_TO_KEEP
Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ActiveChain().Tip() will not be pr...
Definition: validation.h:94
static const int MAX_SCRIPTCHECK_THREADS
Maximum number of dedicated script-checking threads allowed.
Definition: validation.h:82
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition: validation.h:113
static const int DEFAULT_SCRIPTCHECK_THREADS
-par default (number of script-checking threads, 0 = auto)
Definition: validation.h:84
static const signed int DEFAULT_CHECKBLOCKS
Definition: validation.h:95
static const bool DEFAULT_PEERBLOOMFILTERS
Definition: validation.h:86
static const int DEFAULT_STOPATHEIGHT
Default for -stopatheight.
Definition: validation.h:89
CMainSignals & GetMainSignals()
void UnregisterAllValidationInterfaces()
Unregister all subscribers.
void UnregisterValidationInterface(CValidationInterface *callbacks)
Unregister subscriber.
void RegisterValidationInterface(CValidationInterface *callbacks)
Register subscriber.
static constexpr uint32_t AVALANCHE_VOTE_STALE_FACTOR
Scaling factor applied to confidence to determine staleness threshold.
Definition: voterecord.h:35
static constexpr uint32_t AVALANCHE_VOTE_STALE_THRESHOLD
Number of votes before a record may be considered as stale.
Definition: voterecord.h:22
const WalletInitInterface & g_wallet_init_interface
Definition: init.cpp:41
std::unique_ptr< CZMQNotificationInterface > g_zmq_notification_interface
void RegisterZMQRPCCommands(CRPCTable &t)
Definition: zmqrpc.cpp:68