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 <addrman.h>
13 #include <avalanche/avalanche.h>
14 #include <avalanche/processor.h>
15 #include <avalanche/proof.h> // For AVALANCHE_LEGACY_PROOF_DEFAULT
16 #include <avalanche/validation.h>
17 #include <avalanche/voterecord.h> // For AVALANCHE_VOTE_STALE_*
18 #include <banman.h>
19 #include <blockfilter.h>
20 #include <chain.h>
21 #include <chainparams.h>
22 #include <compat/sanity.h>
23 #include <config.h>
24 #include <consensus/amount.h>
25 #include <currencyunit.h>
26 #include <flatfile.h>
27 #include <fs.h>
28 #include <hash.h>
29 #include <httprpc.h>
30 #include <httpserver.h>
31 #include <index/blockfilterindex.h>
32 #include <index/coinstatsindex.h>
33 #include <index/txindex.h>
34 #include <init/common.h>
35 #include <interfaces/chain.h>
36 #include <interfaces/node.h>
37 #include <mapport.h>
38 #include <net.h>
39 #include <net_permissions.h>
40 #include <net_processing.h>
41 #include <netbase.h>
42 #include <node/blockstorage.h>
43 #include <node/caches.h>
44 #include <node/chainstate.h>
45 #include <node/context.h>
46 #include <node/miner.h>
47 #include <node/ui_interface.h>
48 #include <policy/mempool.h>
49 #include <policy/policy.h>
50 #include <policy/settings.h>
51 #include <rpc/blockchain.h>
52 #include <rpc/register.h>
53 #include <rpc/server.h>
54 #include <rpc/util.h>
55 #include <scheduler.h>
56 #include <script/scriptcache.h>
57 #include <script/sigcache.h>
58 #include <script/standard.h>
59 #include <shutdown.h>
60 #include <sync.h>
61 #include <timedata.h>
62 #include <torcontrol.h>
63 #include <txdb.h>
64 #include <txmempool.h>
65 #include <txorphanage.h>
66 #include <util/asmap.h>
67 #include <util/check.h>
68 #include <util/moneystr.h>
69 #include <util/string.h>
70 #include <util/thread.h>
71 #include <util/threadnames.h>
72 #include <util/translation.h>
73 #include <validation.h>
74 #include <validationinterface.h>
75 #include <walletinitinterface.h>
76 
77 #include <boost/signals2/signal.hpp>
78 
79 #if ENABLE_CHRONIK
80 #include <chronik-cpp/chronik.h>
81 #endif
82 
83 #if ENABLE_ZMQ
86 #include <zmq/zmqrpc.h>
87 #endif
88 
89 #ifndef WIN32
90 #include <cerrno>
91 #include <csignal>
92 #include <sys/stat.h>
93 #endif
94 #include <algorithm>
95 #include <cstdint>
96 #include <cstdio>
97 #include <functional>
98 #include <set>
99 #include <thread>
100 #include <vector>
101 
102 using node::CacheSizes;
108 using node::fPruneMode;
109 using node::fReindex;
111 using node::NodeContext;
112 using node::nPruneTarget;
113 using node::ThreadImport;
115 
116 static const bool DEFAULT_PROXYRANDOMIZE = true;
117 static const bool DEFAULT_REST_ENABLE = false;
118 static constexpr bool DEFAULT_CHRONIK = false;
119 
120 #ifdef WIN32
121 // Win32 LevelDB doesn't use filedescriptors, and the ones used for accessing
122 // block files don't count towards the fd_set size limit anyway.
123 #define MIN_CORE_FILEDESCRIPTORS 0
124 #else
125 #define MIN_CORE_FILEDESCRIPTORS 150
126 #endif
127 
128 static const char *DEFAULT_ASMAP_FILENAME = "ip_asn.map";
129 
133 static const char *BITCOIN_PID_FILENAME = "bitcoind.pid";
134 
135 static fs::path GetPidFile(const ArgsManager &args) {
136  return AbsPathForConfigVal(
138 }
139 
140 [[nodiscard]] static bool CreatePidFile(const ArgsManager &args) {
141  fsbridge::ofstream file{GetPidFile(args)};
142  if (file) {
143 #ifdef WIN32
144  tfm::format(file, "%d\n", GetCurrentProcessId());
145 #else
146  tfm::format(file, "%d\n", getpid());
147 #endif
148  return true;
149  } else {
150  return InitError(strprintf(_("Unable to create the PID file '%s': %s"),
152  std::strerror(errno)));
153  }
154 }
155 
157 //
158 // Shutdown
159 //
160 
161 //
162 // Thread management and startup/shutdown:
163 //
164 // The network-processing threads are all part of a thread group created by
165 // AppInit() or the Qt main() function.
166 //
167 // A clean exit happens when StartShutdown() or the SIGTERM signal handler sets
168 // fRequestShutdown, which makes main thread's WaitForShutdown() interrupts the
169 // thread group.
170 // And then, WaitForShutdown() makes all other on-going threads in the thread
171 // group join the main thread.
172 // Shutdown() is then called to clean up database connections, and stop other
173 // threads that should only be stopped after the main network-processing threads
174 // have exited.
175 //
176 // Shutdown for Qt is very similar, only it uses a QTimer to detect
177 // ShutdownRequested() getting set, and then does the normal Qt shutdown thing.
178 //
179 
183  InterruptRPC();
184  InterruptREST();
187  if (g_avalanche) {
188  // Avalanche needs to be stopped before we interrupt the thread group as
189  // the scheduler will stop working then.
190  g_avalanche->stopEventLoop();
191  }
192  if (node.connman) {
193  node.connman->Interrupt();
194  }
195  if (g_txindex) {
196  g_txindex->Interrupt();
197  }
198  ForEachBlockFilterIndex([](BlockFilterIndex &index) { index.Interrupt(); });
199  if (g_coin_stats_index) {
200  g_coin_stats_index->Interrupt();
201  }
202 }
203 
205  static Mutex g_shutdown_mutex;
206  TRY_LOCK(g_shutdown_mutex, lock_shutdown);
207  if (!lock_shutdown) {
208  return;
209  }
210  LogPrintf("%s: In progress...\n", __func__);
211  Assert(node.args);
212 
217  util::ThreadRename("shutoff");
218  if (node.mempool) {
219  node.mempool->AddTransactionsUpdated(1);
220  }
221 
222  StopHTTPRPC();
223  StopREST();
224  StopRPC();
225  StopHTTPServer();
226  for (const auto &client : node.chain_clients) {
227  client->flush();
228  }
229  StopMapPort();
230 
231  // Because avalanche and the network depend on each other, it is important
232  // to shut them down in this order:
233  // 1. Stop avalanche event loop.
234  // 2. Shutdown network processing.
235  // 3. Destroy avalanche::Processor.
236  // 4. Destroy CConnman
237  if (g_avalanche) {
238  g_avalanche->stopEventLoop();
239  }
240 
241  // Because these depend on each-other, we make sure that neither can be
242  // using the other before destroying them.
243  if (node.peerman) {
244  UnregisterValidationInterface(node.peerman.get());
245  }
246  if (node.connman) {
247  node.connman->Stop();
248  }
249 
250 #if ENABLE_CHRONIK
251  chronik::Stop();
252 #endif
253 
254  StopTorControl();
255 
256  // After everything has been shut down, but before things get flushed, stop
257  // the CScheduler/checkqueue, scheduler and load block thread.
258  if (node.scheduler) {
259  node.scheduler->stop();
260  }
261  if (node.chainman && node.chainman->m_load_block.joinable()) {
262  node.chainman->m_load_block.join();
263  }
265 
266  // After the threads that potentially access these pointers have been
267  // stopped, destruct and reset all to nullptr.
268  node.peerman.reset();
269 
270  // Destroy various global instances
271  g_avalanche.reset();
272  node.connman.reset();
273  node.banman.reset();
274  node.addrman.reset();
275 
276  if (node.mempool && node.mempool->IsLoaded() &&
277  node.args->GetBoolArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
278  DumpMempool(*node.mempool);
279  }
280 
281  // FlushStateToDisk generates a ChainStateFlushed callback, which we should
282  // avoid missing
283  if (node.chainman) {
284  LOCK(cs_main);
285  for (Chainstate *chainstate : node.chainman->GetAll()) {
286  if (chainstate->CanFlushToDisk()) {
287  chainstate->ForceFlushStateToDisk();
288  }
289  }
290  }
291 
292  // After there are no more peers/RPC left to give us new data which may
293  // generate CValidationInterface callbacks, flush them...
295 
296  // Stop and delete all indexes only after flushing background callbacks.
297  if (g_txindex) {
298  g_txindex->Stop();
299  g_txindex.reset();
300  }
301  if (g_coin_stats_index) {
302  g_coin_stats_index->Stop();
303  g_coin_stats_index.reset();
304  }
305  ForEachBlockFilterIndex([](BlockFilterIndex &index) { index.Stop(); });
307 
308  // Any future callbacks will be dropped. This should absolutely be safe - if
309  // missing a callback results in an unrecoverable situation, unclean
310  // shutdown would too. The only reason to do the above flushes is to let the
311  // wallet catch up with our current chain to avoid any strange pruning edge
312  // cases and make next startup faster by avoiding rescan.
313 
314  if (node.chainman) {
315  LOCK(cs_main);
316  for (Chainstate *chainstate : node.chainman->GetAll()) {
317  if (chainstate->CanFlushToDisk()) {
318  chainstate->ForceFlushStateToDisk();
319  chainstate->ResetCoinsViews();
320  }
321  }
322  }
323  for (const auto &client : node.chain_clients) {
324  client->stop();
325  }
326 
327 #if ENABLE_ZMQ
332  }
333 #endif
334 
335  node.chain_clients.clear();
339  node.mempool.reset();
340  node.chainman.reset();
341  node.scheduler.reset();
342 
343  try {
344  if (!fs::remove(GetPidFile(*node.args))) {
345  LogPrintf("%s: Unable to remove PID file: File does not exist\n",
346  __func__);
347  }
348  } catch (const fs::filesystem_error &e) {
349  LogPrintf("%s: Unable to remove PID file: %s\n", __func__,
351  }
352 
353  node.args = nullptr;
354  LogPrintf("%s: done\n", __func__);
355 }
356 
362 #ifndef WIN32
363 static void HandleSIGTERM(int) {
364  StartShutdown();
365 }
366 
367 static void HandleSIGHUP(int) {
368  LogInstance().m_reopen_file = true;
369 }
370 #else
371 static BOOL WINAPI consoleCtrlHandler(DWORD dwCtrlType) {
372  StartShutdown();
373  Sleep(INFINITE);
374  return true;
375 }
376 #endif
377 
378 #ifndef WIN32
379 static void registerSignalHandler(int signal, void (*handler)(int)) {
380  struct sigaction sa;
381  sa.sa_handler = handler;
382  sigemptyset(&sa.sa_mask);
383  sa.sa_flags = 0;
384  sigaction(signal, &sa, NULL);
385 }
386 #endif
387 
388 static boost::signals2::connection rpc_notify_block_change_connection;
389 static void OnRPCStarted() {
390  rpc_notify_block_change_connection = uiInterface.NotifyBlockTip_connect(
391  std::bind(RPCNotifyBlockChange, std::placeholders::_2));
392 }
393 
394 static void OnRPCStopped() {
396  RPCNotifyBlockChange(nullptr);
397  g_best_block_cv.notify_all();
398  LogPrint(BCLog::RPC, "RPC stopped.\n");
399 }
400 
402  assert(!node.args);
403  node.args = &gArgs;
404  ArgsManager &argsman = *node.args;
405 
406  SetupHelpOptions(argsman);
407  SetupCurrencyUnitOptions(argsman);
408  // server-only for now
409  argsman.AddArg("-help-debug",
410  "Print help message with debugging options and exit", false,
412 
413  init::AddLoggingArgs(argsman);
414 
415  const auto defaultBaseParams =
417  const auto testnetBaseParams =
419  const auto regtestBaseParams =
421  const auto defaultChainParams = CreateChainParams(CBaseChainParams::MAIN);
422  const auto testnetChainParams =
424  const auto regtestChainParams =
426 
427  // Hidden Options
428  std::vector<std::string> hidden_args = {
429  "-dbcrashratio",
430  "-forcecompactdb",
431  "-maxaddrtosend",
432  "-parkdeepreorg",
433  "-automaticunparking",
434  "-replayprotectionactivationtime",
435  "-enableminerfund",
436  // GUI args. These will be overwritten by SetupUIArgs for the GUI
437  "-allowselfsignedrootcertificates",
438  "-choosedatadir",
439  "-lang=<lang>",
440  "-min",
441  "-resetguisettings",
442  "-rootcertificates=<file>",
443  "-splash",
444  "-uiplatform",
445  // TODO remove after the May 2023 upgrade
446  "-wellingtonactivationtime",
447  };
448 
449  // Set all of the args and their help
450  // When adding new options to the categories, please keep and ensure
451  // alphabetical ordering. Do not translate _(...) -help-debug options, Many
452  // technical terms, and only a very small audience, so is unnecessary stress
453  // to translators.
454  argsman.AddArg("-version", "Print version and exit", ArgsManager::ALLOW_ANY,
456 #if defined(HAVE_SYSTEM)
457  argsman.AddArg(
458  "-alertnotify=<cmd>",
459  "Execute command when a relevant alert is received or we see "
460  "a really long fork (%s in cmd is replaced by message)",
462 #endif
463  argsman.AddArg(
464  "-assumevalid=<hex>",
465  strprintf(
466  "If this block is in the chain assume that it and its ancestors "
467  "are valid and potentially skip their script verification (0 to "
468  "verify all, default: %s, testnet: %s)",
469  defaultChainParams->GetConsensus().defaultAssumeValid.GetHex(),
470  testnetChainParams->GetConsensus().defaultAssumeValid.GetHex()),
472  argsman.AddArg("-blocksdir=<dir>",
473  "Specify directory to hold blocks subdirectory for *.dat "
474  "files (default: <datadir>)",
476  argsman.AddArg("-fastprune",
477  "Use smaller block files and lower minimum prune height for "
478  "testing purposes",
481 #if defined(HAVE_SYSTEM)
482  argsman.AddArg("-blocknotify=<cmd>",
483  "Execute command when the best block changes (%s in cmd is "
484  "replaced by block hash)",
486 #endif
487  argsman.AddArg("-blockreconstructionextratxn=<n>",
488  strprintf("Extra transactions to keep in memory for compact "
489  "block reconstructions (default: %u)",
492  argsman.AddArg(
493  "-blocksonly",
494  strprintf("Whether to reject transactions from network peers. "
495  "Automatic broadcast and rebroadcast of any transactions "
496  "from inbound peers is disabled, unless the peer has the "
497  "'forcerelay' permission. RPC transactions are"
498  " not affected. (default: %u)",
501  argsman.AddArg("-coinstatsindex",
502  strprintf("Maintain coinstats index used by the "
503  "gettxoutsetinfo RPC (default: %u)",
506  argsman.AddArg(
507  "-conf=<file>",
508  strprintf("Specify path to read-only configuration file. Relative "
509  "paths will be prefixed by datadir location. (default: %s)",
512  argsman.AddArg("-datadir=<dir>", "Specify data directory",
514  argsman.AddArg(
515  "-dbbatchsize",
516  strprintf("Maximum database write batch size in bytes (default: %u)",
520  argsman.AddArg(
521  "-dbcache=<n>",
522  strprintf("Set database cache size in MiB (%d to %d, default: %d)",
525  argsman.AddArg(
526  "-includeconf=<file>",
527  "Specify additional configuration file, relative to the -datadir path "
528  "(only useable from configuration file, not command line)",
530  argsman.AddArg("-loadblock=<file>",
531  "Imports blocks from external file on startup",
533  argsman.AddArg("-maxmempool=<n>",
534  strprintf("Keep the transaction memory pool below <n> "
535  "megabytes (default: %u)",
538  argsman.AddArg("-maxorphantx=<n>",
539  strprintf("Keep at most <n> unconnectable transactions in "
540  "memory (default: %u)",
543  argsman.AddArg("-mempoolexpiry=<n>",
544  strprintf("Do not keep transactions in the mempool longer "
545  "than <n> hours (default: %u)",
548  argsman.AddArg(
549  "-minimumchainwork=<hex>",
550  strprintf(
551  "Minimum work assumed to exist on a valid chain in hex "
552  "(default: %s, testnet: %s)",
553  defaultChainParams->GetConsensus().nMinimumChainWork.GetHex(),
554  testnetChainParams->GetConsensus().nMinimumChainWork.GetHex()),
557  argsman.AddArg(
558  "-par=<n>",
559  strprintf("Set the number of script verification threads (%u to %d, 0 "
560  "= auto, <0 = leave that many cores free, default: %d)",
564  argsman.AddArg("-persistmempool",
565  strprintf("Whether to save the mempool on shutdown and load "
566  "on restart (default: %u)",
569  argsman.AddArg(
570  "-pid=<file>",
571  strprintf("Specify pid file. Relative paths will be prefixed "
572  "by a net-specific datadir location. (default: %s)",
575  argsman.AddArg(
576  "-prune=<n>",
577  strprintf("Reduce storage requirements by enabling pruning (deleting) "
578  "of old blocks. This allows the pruneblockchain RPC to be "
579  "called to delete specific blocks, and enables automatic "
580  "pruning of old blocks if a target size in MiB is provided. "
581  "This mode is incompatible with -txindex, -coinstatsindex "
582  "and -rescan. Warning: Reverting this setting requires "
583  "re-downloading the entire blockchain. (default: 0 = disable "
584  "pruning blocks, 1 = allow manual pruning via RPC, >=%u = "
585  "automatically prune block files to stay under the specified "
586  "target size in MiB)",
587  MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024),
589  argsman.AddArg(
590  "-reindex-chainstate",
591  "Rebuild chain state from the currently indexed blocks. When "
592  "in pruning mode or if blocks on disk might be corrupted, use "
593  "full -reindex instead.",
595  argsman.AddArg(
596  "-reindex",
597  "Rebuild chain state and block index from the blk*.dat files on disk",
599  argsman.AddArg(
600  "-settings=<file>",
601  strprintf(
602  "Specify path to dynamic settings data file. Can be disabled with "
603  "-nosettings. File is written at runtime and not meant to be "
604  "edited by users (use %s instead for custom settings). Relative "
605  "paths will be prefixed by datadir location. (default: %s)",
608 #if HAVE_SYSTEM
609  argsman.AddArg("-startupnotify=<cmd>", "Execute command on startup.",
611 #endif
612 #ifndef WIN32
613  argsman.AddArg(
614  "-sysperms",
615  "Create new files with system default permissions, instead of umask "
616  "077 (only effective with disabled wallet functionality)",
618 #else
619  hidden_args.emplace_back("-sysperms");
620 #endif
621  argsman.AddArg("-txindex",
622  strprintf("Maintain a full transaction index, used by the "
623  "getrawtransaction rpc call (default: %d)",
626 #if ENABLE_CHRONIK
627  argsman.AddArg(
628  "-chronik",
629  strprintf("Enable the Chronik indexer, which can be read via a "
630  "dedicated HTTP/Protobuf interface (default: %d)",
633  argsman.AddArg(
634  "-chronikbind=<addr>[:port]",
635  strprintf(
636  "Bind the Chronik indexer to the given address to listen for "
637  "HTTP/Protobuf connections to access the index. Unlike the "
638  "JSON-RPC, it's ok to have this publicly exposed on the internet. "
639  "This option can be specified multiple times (default: %s; default "
640  "port: %u, testnet: %u, regtest: %u)",
641  Join(chronik::DEFAULT_BINDS, ", "),
642  defaultBaseParams->ChronikPort(), testnetBaseParams->ChronikPort(),
643  regtestBaseParams->ChronikPort()),
646  argsman.AddArg("-chronikreindex",
647  "Reindex the Chronik indexer from genesis, but leave the "
648  "other indexes untouched",
650 #endif
651  argsman.AddArg(
652  "-blockfilterindex=<type>",
653  strprintf("Maintain an index of compact filters by block "
654  "(default: %s, values: %s).",
656  " If <type> is not supplied or if <type> = 1, indexes for "
657  "all known types are enabled.",
659  argsman.AddArg(
660  "-usecashaddr",
661  "Use Cash Address for destination encoding instead of base58 "
662  "(activate by default on Jan, 14)",
664 
665  argsman.AddArg(
666  "-addnode=<ip>",
667  "Add a node to connect to and attempt to keep the connection "
668  "open (see the `addnode` RPC command help for more info)",
671  argsman.AddArg("-asmap=<file>",
672  strprintf("Specify asn mapping used for bucketing of the "
673  "peers (default: %s). Relative paths will be "
674  "prefixed by the net-specific datadir location.",
677  argsman.AddArg("-bantime=<n>",
678  strprintf("Default duration (in seconds) of manually "
679  "configured bans (default: %u)",
682  argsman.AddArg(
683  "-bind=<addr>[:<port>][=onion]",
684  strprintf("Bind to given address and always listen on it (default: "
685  "0.0.0.0). Use [host]:port notation for IPv6. Append =onion "
686  "to tag any incoming connections to that address and port as "
687  "incoming Tor connections (default: 127.0.0.1:%u=onion, "
688  "testnet: 127.0.0.1:%u=onion, regtest: 127.0.0.1:%u=onion)",
689  defaultBaseParams->OnionServiceTargetPort(),
690  testnetBaseParams->OnionServiceTargetPort(),
691  regtestBaseParams->OnionServiceTargetPort()),
694  argsman.AddArg(
695  "-connect=<ip>",
696  "Connect only to the specified node(s); -connect=0 disables automatic "
697  "connections (the rules for this peer are the same as for -addnode)",
700  argsman.AddArg(
701  "-discover",
702  "Discover own IP addresses (default: 1 when listening and no "
703  "-externalip or -proxy)",
705  argsman.AddArg("-dns",
706  strprintf("Allow DNS lookups for -addnode, -seednode and "
707  "-connect (default: %d)",
710  argsman.AddArg(
711  "-dnsseed",
712  strprintf(
713  "Query for peer addresses via DNS lookup, if low on addresses "
714  "(default: %u unless -connect used)",
717  argsman.AddArg("-externalip=<ip>", "Specify your own public address",
719  argsman.AddArg(
720  "-fixedseeds",
721  strprintf(
722  "Allow fixed seeds if DNS seeds don't provide peers (default: %u)",
725  argsman.AddArg(
726  "-forcednsseed",
727  strprintf(
728  "Always query for peer addresses via DNS lookup (default: %d)",
731  argsman.AddArg("-overridednsseed",
732  "If set, only use the specified DNS seed when "
733  "querying for peer addresses via DNS lookup.",
735  argsman.AddArg(
736  "-listen",
737  "Accept connections from outside (default: 1 if no -proxy or -connect)",
739  argsman.AddArg(
740  "-listenonion",
741  strprintf("Automatically create Tor onion service (default: %d)",
744  argsman.AddArg(
745  "-maxconnections=<n>",
746  strprintf("Maintain at most <n> connections to peers. The effective "
747  "limit depends on system limitations and might be lower than "
748  "the specified value (default: %u)",
751  argsman.AddArg("-maxreceivebuffer=<n>",
752  strprintf("Maximum per-connection receive buffer, <n>*1000 "
753  "bytes (default: %u)",
756  argsman.AddArg(
757  "-maxsendbuffer=<n>",
758  strprintf(
759  "Maximum per-connection send buffer, <n>*1000 bytes (default: %u)",
762  argsman.AddArg(
763  "-maxtimeadjustment",
764  strprintf("Maximum allowed median peer time offset adjustment. Local "
765  "perspective of time may be influenced by peers forward or "
766  "backward by this amount. (default: %u seconds)",
769  argsman.AddArg("-onion=<ip:port>",
770  strprintf("Use separate SOCKS5 proxy to reach peers via Tor "
771  "onion services (default: %s)",
772  "-proxy"),
774  argsman.AddArg("-i2psam=<ip:port>",
775  "I2P SAM proxy to reach I2P peers and accept I2P "
776  "connections (default: none)",
778  argsman.AddArg(
779  "-i2pacceptincoming",
780  "If set and -i2psam is also set then incoming I2P connections are "
781  "accepted via the SAM proxy. If this is not set but -i2psam is set "
782  "then only outgoing connections will be made to the I2P network. "
783  "Ignored if -i2psam is not set. Listening for incoming I2P connections "
784  "is done through the SAM proxy, not by binding to a local address and "
785  "port (default: 1)",
787 
788  argsman.AddArg(
789  "-onlynet=<net>",
790  "Make outgoing connections only through network <net> (" +
791  Join(GetNetworkNames(), ", ") +
792  "). Incoming connections are not affected by this option. This "
793  "option can be specified multiple times to allow multiple "
794  "networks. Warning: if it is used with non-onion networks "
795  "and the -onion or -proxy option is set, then outbound onion "
796  "connections will still be made; use -noonion or -onion=0 to "
797  "disable outbound onion connections in this case",
799  argsman.AddArg("-peerbloomfilters",
800  strprintf("Support filtering of blocks and transaction with "
801  "bloom filters (default: %d)",
804  argsman.AddArg(
805  "-peerblockfilters",
806  strprintf(
807  "Serve compact block filters to peers per BIP 157 (default: %u)",
810  argsman.AddArg("-permitbaremultisig",
811  strprintf("Relay non-P2SH multisig (default: %d)",
814  // TODO: remove the sentence "Nodes not using ... incoming connections."
815  // once the changes from https://github.com/bitcoin/bitcoin/pull/23542 have
816  // become widespread.
817  argsman.AddArg("-port=<port>",
818  strprintf("Listen for connections on <port>. Nodes not "
819  "using the default ports (default: %u, "
820  "testnet: %u, regtest: %u) are unlikely to get "
821  "incoming connections. Not relevant for I2P (see "
822  "doc/i2p.md).",
823  defaultChainParams->GetDefaultPort(),
824  testnetChainParams->GetDefaultPort(),
825  regtestChainParams->GetDefaultPort()),
828  argsman.AddArg("-proxy=<ip:port>", "Connect through SOCKS5 proxy",
830  argsman.AddArg(
831  "-proxyrandomize",
832  strprintf("Randomize credentials for every proxy connection. "
833  "This enables Tor stream isolation (default: %d)",
836  argsman.AddArg(
837  "-seednode=<ip>",
838  "Connect to a node to retrieve peer addresses, and disconnect",
840  argsman.AddArg(
841  "-networkactive",
842  "Enable all P2P network activity (default: 1). Can be changed "
843  "by the setnetworkactive RPC command",
845  argsman.AddArg("-timeout=<n>",
846  strprintf("Specify connection timeout in milliseconds "
847  "(minimum: 1, default: %d)",
850  argsman.AddArg(
851  "-peertimeout=<n>",
852  strprintf("Specify p2p connection timeout in seconds. This option "
853  "determines the amount of time a peer may be inactive before "
854  "the connection to it is dropped. (minimum: 1, default: %d)",
857  argsman.AddArg(
858  "-torcontrol=<ip>:<port>",
859  strprintf(
860  "Tor control port to use if onion listening enabled (default: %s)",
863  argsman.AddArg("-torpassword=<pass>",
864  "Tor control port password (default: empty)",
867 #ifdef USE_UPNP
868 #if USE_UPNP
869  argsman.AddArg("-upnp",
870  "Use UPnP to map the listening port (default: 1 when "
871  "listening and no -proxy)",
873 #else
874  argsman.AddArg(
875  "-upnp",
876  strprintf("Use UPnP to map the listening port (default: %u)", 0),
878 #endif
879 #else
880  hidden_args.emplace_back("-upnp");
881 #endif
882 #ifdef USE_NATPMP
883  argsman.AddArg(
884  "-natpmp",
885  strprintf("Use NAT-PMP to map the listening port (default: %s)",
886  DEFAULT_NATPMP ? "1 when listening and no -proxy" : "0"),
888 #else
889  hidden_args.emplace_back("-natpmp");
890 #endif // USE_NATPMP
891  argsman.AddArg(
892  "-whitebind=<[permissions@]addr>",
893  "Bind to the given address and add permission flags to the peers "
894  "connecting to it."
895  "Use [host]:port notation for IPv6. Allowed permissions: " +
896  Join(NET_PERMISSIONS_DOC, ", ") +
897  ". "
898  "Specify multiple permissions separated by commas (default: "
899  "download,noban,mempool,relay). Can be specified multiple times.",
901 
902  argsman.AddArg("-whitelist=<[permissions@]IP address or network>",
903  "Add permission flags to the peers connecting from the "
904  "given IP address (e.g. 1.2.3.4) or CIDR-notated network "
905  "(e.g. 1.2.3.0/24). "
906  "Uses the same permissions as -whitebind. Can be specified "
907  "multiple times.",
909  argsman.AddArg(
910  "-maxuploadtarget=<n>",
911  strprintf("Tries to keep outbound traffic under the given target (in "
912  "MiB per 24h). Limit does not apply to peers with 'download' "
913  "permission. 0 = no limit (default: %d)",
916 
918 
919 #if ENABLE_ZMQ
920  argsman.AddArg("-zmqpubhashblock=<address>",
921  "Enable publish hash block in <address>",
923  argsman.AddArg("-zmqpubhashtx=<address>",
924  "Enable publish hash transaction in <address>",
926  argsman.AddArg("-zmqpubrawblock=<address>",
927  "Enable publish raw block in <address>",
929  argsman.AddArg("-zmqpubrawtx=<address>",
930  "Enable publish raw transaction in <address>",
932  argsman.AddArg("-zmqpubsequence=<address>",
933  "Enable publish hash block and tx sequence in <address>",
935  argsman.AddArg(
936  "-zmqpubhashblockhwm=<n>",
937  strprintf("Set publish hash block outbound message high water "
938  "mark (default: %d)",
941  argsman.AddArg(
942  "-zmqpubhashtxhwm=<n>",
943  strprintf("Set publish hash transaction outbound message high "
944  "water mark (default: %d)",
946  false, OptionsCategory::ZMQ);
947  argsman.AddArg(
948  "-zmqpubrawblockhwm=<n>",
949  strprintf("Set publish raw block outbound message high water "
950  "mark (default: %d)",
953  argsman.AddArg(
954  "-zmqpubrawtxhwm=<n>",
955  strprintf("Set publish raw transaction outbound message high "
956  "water mark (default: %d)",
959  argsman.AddArg("-zmqpubsequencehwm=<n>",
960  strprintf("Set publish hash sequence message high water mark"
961  " (default: %d)",
964 #else
965  hidden_args.emplace_back("-zmqpubhashblock=<address>");
966  hidden_args.emplace_back("-zmqpubhashtx=<address>");
967  hidden_args.emplace_back("-zmqpubrawblock=<address>");
968  hidden_args.emplace_back("-zmqpubrawtx=<address>");
969  hidden_args.emplace_back("-zmqpubsequence=<n>");
970  hidden_args.emplace_back("-zmqpubhashblockhwm=<n>");
971  hidden_args.emplace_back("-zmqpubhashtxhwm=<n>");
972  hidden_args.emplace_back("-zmqpubrawblockhwm=<n>");
973  hidden_args.emplace_back("-zmqpubrawtxhwm=<n>");
974  hidden_args.emplace_back("-zmqpubsequencehwm=<n>");
975 #endif
976 
977  argsman.AddArg(
978  "-checkblocks=<n>",
979  strprintf("How many blocks to check at startup (default: %u, 0 = all)",
983  argsman.AddArg("-checklevel=<n>",
984  strprintf("How thorough the block verification of "
985  "-checkblocks is: %s (0-4, default: %u)",
989  argsman.AddArg("-checkblockindex",
990  strprintf("Do a consistency check for the block tree, "
991  "chainstate, and other validation data structures "
992  "occasionally. (default: %u, regtest: %u)",
993  defaultChainParams->DefaultConsistencyChecks(),
994  regtestChainParams->DefaultConsistencyChecks()),
997  argsman.AddArg("-checkaddrman=<n>",
998  strprintf("Run addrman consistency checks every <n> "
999  "operations. Use 0 to disable. (default: %u)",
1003  argsman.AddArg(
1004  "-checkmempool=<n>",
1005  strprintf("Run mempool consistency checks every <n> transactions. Use "
1006  "0 to disable. (default: %u, regtest: %u)",
1007  defaultChainParams->DefaultConsistencyChecks(),
1008  regtestChainParams->DefaultConsistencyChecks()),
1011  argsman.AddArg("-checkpoints",
1012  strprintf("Only accept block chain matching built-in "
1013  "checkpoints (default: %d)",
1017  argsman.AddArg("-deprecatedrpc=<method>",
1018  "Allows deprecated RPC method(s) to be used",
1021  argsman.AddArg(
1022  "-stopafterblockimport",
1023  strprintf("Stop running after importing blocks from disk (default: %d)",
1027  argsman.AddArg("-stopatheight",
1028  strprintf("Stop running after reaching the given height in "
1029  "the main chain (default: %u)",
1033  // TODO Remove after wellington activation
1034  argsman.AddArg(
1035  "-limitancestorcount=<n>",
1036  strprintf("DEPRECATED: Do not accept transactions if number of "
1037  "in-mempool ancestors is <n> or more (default: %u). This is "
1038  "no longer evaluated after the May 15th 2023 eCash network "
1039  "upgrade.",
1043  argsman.AddArg(
1044  "-limitancestorsize=<n>",
1045  strprintf("DEPRECATED: Do not accept transactions whose size with all "
1046  "in-mempool ancestors exceeds <n> kilobytes (default: %u). "
1047  "This is no longer evaluated after the May 15th 2023 eCash "
1048  "network upgrade.",
1052  argsman.AddArg(
1053  "-limitdescendantcount=<n>",
1054  strprintf("DEPRECATED: Do not accept transactions if any ancestor "
1055  "would have <n> or more in-mempool descendants (default: %u)"
1056  ". This is no longer evaluated after the May 15th 2023 eCash "
1057  "network upgrade.",
1061  argsman.AddArg(
1062  "-limitdescendantsize=<n>",
1063  strprintf("DEPRECATED: Do not accept transactions if any ancestor "
1064  "would have more than <n> kilobytes of in-mempool "
1065  "descendants (default: %u). This is no longer evaluated "
1066  "after the May 15th 2023 eCash network upgrade.",
1070  argsman.AddArg("-addrmantest", "Allows to test address relay on localhost",
1073  argsman.AddArg("-capturemessages", "Capture all P2P messages to disk",
1076  argsman.AddArg("-mocktime=<n>",
1077  "Replace actual time with " + UNIX_EPOCH_TIME +
1078  " (default: 0)",
1081  argsman.AddArg(
1082  "-maxsigcachesize=<n>",
1083  strprintf("Limit size of signature cache to <n> MiB (default: %u)",
1087  argsman.AddArg(
1088  "-maxscriptcachesize=<n>",
1089  strprintf("Limit size of script cache to <n> MiB (default: %u)",
1093  argsman.AddArg("-maxtipage=<n>",
1094  strprintf("Maximum tip age in seconds to consider node in "
1095  "initial block download (default: %u)",
1099 
1100  argsman.AddArg("-uacomment=<cmt>",
1101  "Append comment to the user agent string",
1103  argsman.AddArg("-uaclientname=<clientname>", "Set user agent client name",
1105  argsman.AddArg("-uaclientversion=<clientversion>",
1106  "Set user agent client version", ArgsManager::ALLOW_ANY,
1108 
1109  SetupChainParamsBaseOptions(argsman);
1110 
1111  argsman.AddArg(
1112  "-acceptnonstdtxn",
1113  strprintf(
1114  "Relay and mine \"non-standard\" transactions (%sdefault: %u)",
1115  "testnet/regtest only; ", defaultChainParams->RequireStandard()),
1118  argsman.AddArg("-excessiveblocksize=<n>",
1119  strprintf("Do not accept blocks larger than this limit, in "
1120  "bytes (default: %d)",
1124  const auto &ticker = Currency::get().ticker;
1125  argsman.AddArg(
1126  "-dustrelayfee=<amt>",
1127  strprintf("Fee rate (in %s/kB) used to define dust, the value of an "
1128  "output such that it will cost about 1/3 of its value in "
1129  "fees at this fee rate to spend it. (default: %s)",
1130  ticker, FormatMoney(DUST_RELAY_TX_FEE)),
1133 
1134  argsman.AddArg(
1135  "-bytespersigcheck",
1136  strprintf("Equivalent bytes per sigCheck in transactions for relay and "
1137  "mining (default: %u).",
1140  argsman.AddArg(
1141  "-bytespersigop",
1142  strprintf("DEPRECATED: Equivalent bytes per sigCheck in transactions "
1143  "for relay and mining (default: %u). This has been "
1144  "deprecated since v0.26.8 and will be removed in the future, "
1145  "please use -bytespersigcheck instead.",
1148  argsman.AddArg(
1149  "-datacarrier",
1150  strprintf("Relay and mine data carrier transactions (default: %d)",
1153  argsman.AddArg(
1154  "-datacarriersize",
1155  strprintf("Maximum size of data in data carrier transactions "
1156  "we relay and mine (default: %u)",
1159  argsman.AddArg(
1160  "-minrelaytxfee=<amt>",
1161  strprintf("Fees (in %s/kB) smaller than this are rejected for "
1162  "relaying, mining and transaction creation (default: %s)",
1165  argsman.AddArg(
1166  "-whitelistrelay",
1167  strprintf("Add 'relay' permission to whitelisted inbound peers "
1168  "with default permissions. This will accept relayed "
1169  "transactions even when not relaying transactions "
1170  "(default: %d)",
1173  argsman.AddArg(
1174  "-whitelistforcerelay",
1175  strprintf("Add 'forcerelay' permission to whitelisted inbound peers"
1176  " with default permissions. This will relay transactions "
1177  "even if the transactions were already in the mempool "
1178  "(default: %d)",
1181 
1182  // Not sure this really belongs here, but it will do for now.
1183  // FIXME: This doesn't work anyways.
1184  argsman.AddArg("-excessutxocharge=<amt>",
1185  strprintf("Fees (in %s/kB) to charge per utxo created for "
1186  "relaying, and mining (default: %s)",
1187  ticker, FormatMoney(DEFAULT_UTXO_FEE)),
1190 
1191  argsman.AddArg("-blockmaxsize=<n>",
1192  strprintf("Set maximum block size in bytes (default: %d)",
1195  argsman.AddArg(
1196  "-blockmintxfee=<amt>",
1197  strprintf("Set lowest fee rate (in %s/kB) for transactions to "
1198  "be included in block creation. (default: %s)",
1201 
1202  argsman.AddArg("-blockversion=<n>",
1203  "Override block version to test forking scenarios",
1206 
1207  argsman.AddArg("-server", "Accept command line and JSON-RPC commands",
1209  argsman.AddArg("-rest",
1210  strprintf("Accept public REST requests (default: %d)",
1213  argsman.AddArg(
1214  "-rpcbind=<addr>[:port]",
1215  "Bind to given address to listen for JSON-RPC connections. Do not "
1216  "expose the RPC server to untrusted networks such as the public "
1217  "internet! This option is ignored unless -rpcallowip is also passed. "
1218  "Port is optional and overrides -rpcport. Use [host]:port notation "
1219  "for IPv6. This option can be specified multiple times (default: "
1220  "127.0.0.1 and ::1 i.e., localhost)",
1224  argsman.AddArg(
1225  "-rpccookiefile=<loc>",
1226  "Location of the auth cookie. Relative paths will be prefixed "
1227  "by a net-specific datadir location. (default: data dir)",
1229  argsman.AddArg("-rpcuser=<user>", "Username for JSON-RPC connections",
1232  argsman.AddArg("-rpcpassword=<pw>", "Password for JSON-RPC connections",
1235  argsman.AddArg(
1236  "-rpcwhitelist=<whitelist>",
1237  "Set a whitelist to filter incoming RPC calls for a specific user. The "
1238  "field <whitelist> comes in the format: <USERNAME>:<rpc 1>,<rpc "
1239  "2>,...,<rpc n>. If multiple whitelists are set for a given user, they "
1240  "are set-intersected. See -rpcwhitelistdefault documentation for "
1241  "information on default whitelist behavior.",
1243  argsman.AddArg(
1244  "-rpcwhitelistdefault",
1245  "Sets default behavior for rpc whitelisting. Unless "
1246  "rpcwhitelistdefault is set to 0, if any -rpcwhitelist is set, the rpc "
1247  "server acts as if all rpc users are subject to "
1248  "empty-unless-otherwise-specified whitelists. If rpcwhitelistdefault "
1249  "is set to 1 and no -rpcwhitelist is set, rpc server acts as if all "
1250  "rpc users are subject to empty whitelists.",
1252  argsman.AddArg(
1253  "-rpcauth=<userpw>",
1254  "Username and HMAC-SHA-256 hashed password for JSON-RPC connections. "
1255  "The field <userpw> comes in the format: <USERNAME>:<SALT>$<HASH>. A "
1256  "canonical python script is included in share/rpcauth. The client then "
1257  "connects normally using the rpcuser=<USERNAME>/rpcpassword=<PASSWORD> "
1258  "pair of arguments. This option can be specified multiple times",
1260  argsman.AddArg("-rpcport=<port>",
1261  strprintf("Listen for JSON-RPC connections on <port> "
1262  "(default: %u, testnet: %u, regtest: %u)",
1263  defaultBaseParams->RPCPort(),
1264  testnetBaseParams->RPCPort(),
1265  regtestBaseParams->RPCPort()),
1268  argsman.AddArg(
1269  "-rpcallowip=<ip>",
1270  "Allow JSON-RPC connections from specified source. Valid for "
1271  "<ip> are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. "
1272  "1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24). "
1273  "This option can be specified multiple times",
1275  argsman.AddArg(
1276  "-rpcthreads=<n>",
1277  strprintf(
1278  "Set the number of threads to service RPC calls (default: %d)",
1281  argsman.AddArg(
1282  "-rpccorsdomain=value",
1283  "Domain from which to accept cross origin requests (browser enforced)",
1285 
1286  argsman.AddArg("-rpcworkqueue=<n>",
1287  strprintf("Set the depth of the work queue to service RPC "
1288  "calls (default: %d)",
1292  argsman.AddArg("-rpcservertimeout=<n>",
1293  strprintf("Timeout during HTTP requests (default: %d)",
1297 
1298 #if HAVE_DECL_FORK
1299  argsman.AddArg("-daemon",
1300  strprintf("Run in the background as a daemon and accept "
1301  "commands (default: %d)",
1302  DEFAULT_DAEMON),
1304  argsman.AddArg("-daemonwait",
1305  strprintf("Wait for initialization to be finished before "
1306  "exiting. This implies -daemon (default: %d)",
1309 #else
1310  hidden_args.emplace_back("-daemon");
1311  hidden_args.emplace_back("-daemonwait");
1312 #endif
1313 
1314  // Avalanche options.
1315  argsman.AddArg("-avalanche",
1316  strprintf("Enable the avalanche feature (default: %u)",
1319  argsman.AddArg("-avalancheconflictingproofcooldown",
1320  strprintf("Mandatory cooldown before a proof conflicting "
1321  "with an already registered one can be considered "
1322  "in seconds (default: %u)",
1325  argsman.AddArg("-avalanchepeerreplacementcooldown",
1326  strprintf("Mandatory cooldown before a peer can be replaced "
1327  "in seconds (default: %u)",
1330  argsman.AddArg(
1331  "-avaminquorumstake",
1332  strprintf(
1333  "Minimum amount of known stake for a usable quorum (default: %s)",
1336  argsman.AddArg(
1337  "-avaminquorumconnectedstakeratio",
1338  strprintf("Minimum proportion of known stake we"
1339  " need nodes for to have a usable quorum (default: %s)",
1342  argsman.AddArg(
1343  "-avaminavaproofsnodecount",
1344  strprintf("Minimum number of node that needs to send us an avaproofs"
1345  " message before we consider we have a usable quorum"
1346  " (default: %s)",
1349  argsman.AddArg(
1350  "-avastalevotethreshold",
1351  strprintf("Number of avalanche votes before a voted item goes stale "
1352  "when voting confidence is low (default: %u)",
1355  argsman.AddArg(
1356  "-avastalevotefactor",
1357  strprintf(
1358  "Factor affecting the number of avalanche votes before a voted "
1359  "item goes stale when voting confidence is high (default: %u)",
1362  argsman.AddArg("-avacooldown",
1363  strprintf("Mandatory cooldown between two avapoll in "
1364  "milliseconds (default: %u)",
1367  argsman.AddArg(
1368  "-avatimeout",
1369  strprintf("Avalanche query timeout in milliseconds (default: %u)",
1372  argsman.AddArg(
1373  "-avadelegation",
1374  "Avalanche proof delegation to the master key used by this node "
1375  "(default: none). Should be used in conjunction with -avaproof and "
1376  "-avamasterkey",
1378  argsman.AddArg("-avaproof",
1379  "Avalanche proof to be used by this node (default: none)",
1381  argsman.AddArg(
1382  "-avaproofstakeutxoconfirmations",
1383  strprintf(
1384  "Minimum number of confirmations before a stake utxo is mature"
1385  " enough to be included into a proof. Utxos in the mempool are not "
1386  "accepted (i.e this value must be greater than 0) (default: %s)",
1389  argsman.AddArg("-avaproofstakeutxodustthreshold",
1390  strprintf("Minimum value each stake utxo must have to be "
1391  "considered valid (default: %s)",
1394  argsman.AddArg("-avamasterkey",
1395  "Master key associated with the proof. If a proof is "
1396  "required, this is mandatory.",
1399  argsman.AddArg("-avasessionkey", "Avalanche session key (default: random)",
1402  argsman.AddArg(
1403  "-maxavalancheoutbound",
1404  strprintf(
1405  "Set the maximum number of avalanche outbound peers to connect to. "
1406  "Note that the -maxconnections option takes precedence (default: "
1407  "%u).",
1410 
1411  hidden_args.emplace_back("-avalanchepreconsensus");
1412 
1413  // Add the hidden options
1414  argsman.AddHiddenArgs(hidden_args);
1415 }
1416 
1417 std::string LicenseInfo() {
1418  const std::string URL_SOURCE_CODE =
1419  "<https://github.com/Bitcoin-ABC/bitcoin-abc>";
1420  const std::string URL_WEBSITE = "<https://www.bitcoinabc.org>";
1421 
1422  return CopyrightHolders(strprintf(_("Copyright (C) %i-%i").translated, 2009,
1423  COPYRIGHT_YEAR) +
1424  " ") +
1425  "\n" + "\n" +
1426  strprintf(_("Please contribute if you find %s useful. "
1427  "Visit %s for further information about the software.")
1428  .translated,
1429  PACKAGE_NAME, URL_WEBSITE) +
1430  "\n" +
1431  strprintf(_("The source code is available from %s.").translated,
1432  URL_SOURCE_CODE) +
1433  "\n" + "\n" + _("This is experimental software.").translated + "\n" +
1434  strprintf(_("Distributed under the MIT software license, see the "
1435  "accompanying file %s or %s")
1436  .translated,
1437  "COPYING", "<https://opensource.org/licenses/MIT>") +
1438  "\n" + "\n" +
1439  strprintf(_("This product includes software developed by the "
1440  "OpenSSL Project for use in the OpenSSL Toolkit %s and "
1441  "cryptographic software written by Eric Young and UPnP "
1442  "software written by Thomas Bernard.")
1443  .translated,
1444  "<https://www.openssl.org>") +
1445  "\n";
1446 }
1447 
1448 static bool fHaveGenesis = false;
1450 static std::condition_variable g_genesis_wait_cv;
1451 
1452 static void BlockNotifyGenesisWait(const CBlockIndex *pBlockIndex) {
1453  if (pBlockIndex != nullptr) {
1454  {
1456  fHaveGenesis = true;
1457  }
1458  g_genesis_wait_cv.notify_all();
1459  }
1460 }
1461 
1462 #if HAVE_SYSTEM
1463 static void StartupNotify(const ArgsManager &args) {
1464  std::string cmd = args.GetArg("-startupnotify", "");
1465  if (!cmd.empty()) {
1466  std::thread t(runCommand, cmd);
1467  // thread runs free
1468  t.detach();
1469  }
1470 }
1471 #endif
1472 
1473 static bool AppInitServers(Config &config,
1474  HTTPRPCRequestProcessor &httpRPCRequestProcessor,
1475  NodeContext &node) {
1476  const ArgsManager &args = *Assert(node.args);
1479  if (!InitHTTPServer(config)) {
1480  return false;
1481  }
1482 
1483  StartRPC();
1484  node.rpc_interruption_point = RpcInterruptionPoint;
1485 
1486  if (!StartHTTPRPC(httpRPCRequestProcessor)) {
1487  return false;
1488  }
1489  if (args.GetBoolArg("-rest", DEFAULT_REST_ENABLE)) {
1490  StartREST(&node);
1491  }
1492 
1493  StartHTTPServer();
1494  return true;
1495 }
1496 
1497 // Parameter interaction based on rules
1499  // when specifying an explicit binding address, you want to listen on it
1500  // even when -connect or -proxy is specified.
1501  if (args.IsArgSet("-bind")) {
1502  if (args.SoftSetBoolArg("-listen", true)) {
1503  LogPrintf(
1504  "%s: parameter interaction: -bind set -> setting -listen=1\n",
1505  __func__);
1506  }
1507  }
1508  if (args.IsArgSet("-whitebind")) {
1509  if (args.SoftSetBoolArg("-listen", true)) {
1510  LogPrintf("%s: parameter interaction: -whitebind set -> setting "
1511  "-listen=1\n",
1512  __func__);
1513  }
1514  }
1515 
1516  if (args.IsArgSet("-connect")) {
1517  // when only connecting to trusted nodes, do not seed via DNS, or listen
1518  // by default.
1519  if (args.SoftSetBoolArg("-dnsseed", false)) {
1520  LogPrintf("%s: parameter interaction: -connect set -> setting "
1521  "-dnsseed=0\n",
1522  __func__);
1523  }
1524  if (args.SoftSetBoolArg("-listen", false)) {
1525  LogPrintf("%s: parameter interaction: -connect set -> setting "
1526  "-listen=0\n",
1527  __func__);
1528  }
1529  }
1530 
1531  if (args.IsArgSet("-proxy")) {
1532  // to protect privacy, do not listen by default if a default proxy
1533  // server is specified.
1534  if (args.SoftSetBoolArg("-listen", false)) {
1535  LogPrintf(
1536  "%s: parameter interaction: -proxy set -> setting -listen=0\n",
1537  __func__);
1538  }
1539  // to protect privacy, do not map ports when a proxy is set. The user
1540  // may still specify -listen=1 to listen locally, so don't rely on this
1541  // happening through -listen below.
1542  if (args.SoftSetBoolArg("-upnp", false)) {
1543  LogPrintf(
1544  "%s: parameter interaction: -proxy set -> setting -upnp=0\n",
1545  __func__);
1546  }
1547  if (args.SoftSetBoolArg("-natpmp", false)) {
1548  LogPrintf(
1549  "%s: parameter interaction: -proxy set -> setting -natpmp=0\n",
1550  __func__);
1551  }
1552  // to protect privacy, do not discover addresses by default
1553  if (args.SoftSetBoolArg("-discover", false)) {
1554  LogPrintf("%s: parameter interaction: -proxy set -> setting "
1555  "-discover=0\n",
1556  __func__);
1557  }
1558  }
1559 
1560  if (!args.GetBoolArg("-listen", DEFAULT_LISTEN)) {
1561  // do not map ports or try to retrieve public IP when not listening
1562  // (pointless)
1563  if (args.SoftSetBoolArg("-upnp", false)) {
1564  LogPrintf(
1565  "%s: parameter interaction: -listen=0 -> setting -upnp=0\n",
1566  __func__);
1567  }
1568  if (args.SoftSetBoolArg("-natpmp", false)) {
1569  LogPrintf(
1570  "%s: parameter interaction: -listen=0 -> setting -natpmp=0\n",
1571  __func__);
1572  }
1573  if (args.SoftSetBoolArg("-discover", false)) {
1574  LogPrintf(
1575  "%s: parameter interaction: -listen=0 -> setting -discover=0\n",
1576  __func__);
1577  }
1578  if (args.SoftSetBoolArg("-listenonion", false)) {
1579  LogPrintf("%s: parameter interaction: -listen=0 -> setting "
1580  "-listenonion=0\n",
1581  __func__);
1582  }
1583  if (args.SoftSetBoolArg("-i2pacceptincoming", false)) {
1584  LogPrintf("%s: parameter interaction: -listen=0 -> setting "
1585  "-i2pacceptincoming=0\n",
1586  __func__);
1587  }
1588  }
1589 
1590  if (args.IsArgSet("-externalip")) {
1591  // if an explicit public IP is specified, do not try to find others
1592  if (args.SoftSetBoolArg("-discover", false)) {
1593  LogPrintf("%s: parameter interaction: -externalip set -> setting "
1594  "-discover=0\n",
1595  __func__);
1596  }
1597  }
1598 
1599  // disable whitelistrelay in blocksonly mode
1600  if (args.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)) {
1601  if (args.SoftSetBoolArg("-whitelistrelay", false)) {
1602  LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting "
1603  "-whitelistrelay=0\n",
1604  __func__);
1605  }
1606  }
1607 
1608  // Forcing relay from whitelisted hosts implies we will accept relays from
1609  // them in the first place.
1610  if (args.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
1611  if (args.SoftSetBoolArg("-whitelistrelay", true)) {
1612  LogPrintf("%s: parameter interaction: -whitelistforcerelay=1 -> "
1613  "setting -whitelistrelay=1\n",
1614  __func__);
1615  }
1616  }
1617 
1618  // If avalanche is set, soft set all the feature flags accordingly.
1619  if (args.IsArgSet("-avalanche")) {
1620  const bool fAvalanche =
1621  args.GetBoolArg("-avalanche", AVALANCHE_DEFAULT_ENABLED);
1622  args.SoftSetBoolArg("-automaticunparking", !fAvalanche);
1623  }
1624 }
1625 
1632 void InitLogging(const ArgsManager &args) {
1635 }
1636 
1637 namespace { // Variables internal to initialization process only
1638 
1639 int nMaxConnections;
1640 int nUserMaxConnections;
1641 int nFD;
1643 int64_t peer_connect_timeout;
1644 std::set<BlockFilterType> g_enabled_filter_types;
1645 
1646 } // namespace
1647 
1648 [[noreturn]] static void new_handler_terminate() {
1649  // Rather than throwing std::bad-alloc if allocation fails, terminate
1650  // immediately to (try to) avoid chain corruption. Since LogPrintf may
1651  // itself allocate memory, set the handler directly to terminate first.
1652  std::set_new_handler(std::terminate);
1653  LogPrintf("Error: Out of memory. Terminating.\n");
1654 
1655  // The log was successful, terminate now.
1656  std::terminate();
1657 };
1658 
1659 bool AppInitBasicSetup(const ArgsManager &args) {
1660 // Step 1: setup
1661 #ifdef _MSC_VER
1662  // Turn off Microsoft heap dump noise
1663  _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
1664  _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, nullptr,
1665  OPEN_EXISTING, 0, 0));
1666  // Disable confusing "helpful" text message on abort, Ctrl-C
1667  _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
1668 #endif
1669 #ifdef WIN32
1670  // Enable Data Execution Prevention (DEP)
1671  SetProcessDEPPolicy(PROCESS_DEP_ENABLE);
1672 #endif
1673  if (!InitShutdownState()) {
1674  return InitError(
1675  Untranslated("Initializing wait-for-shutdown state failed."));
1676  }
1677 
1678  if (!SetupNetworking()) {
1679  return InitError(Untranslated("Initializing networking failed"));
1680  }
1681 
1682 #ifndef WIN32
1683  if (!args.GetBoolArg("-sysperms", false)) {
1684  umask(077);
1685  }
1686 
1687  // Clean shutdown on SIGTERM
1690 
1691  // Reopen debug.log on SIGHUP
1693 
1694  // Ignore SIGPIPE, otherwise it will bring the daemon down if the client
1695  // closes unexpectedly
1696  signal(SIGPIPE, SIG_IGN);
1697 #else
1698  SetConsoleCtrlHandler(consoleCtrlHandler, true);
1699 #endif
1700 
1701  std::set_new_handler(new_handler_terminate);
1702 
1703  return true;
1704 }
1705 
1706 bool AppInitParameterInteraction(Config &config, const ArgsManager &args) {
1707  const CChainParams &chainparams = config.GetChainParams();
1708  // Step 2: parameter interactions
1709 
1710  // also see: InitParameterInteraction()
1711 
1712  // Error if network-specific options (-addnode, -connect, etc) are
1713  // specified in default section of config file, but not overridden
1714  // on the command line or in this network's section of the config file.
1715  std::string network = args.GetChainName();
1716  bilingual_str errors;
1717  for (const auto &arg : args.GetUnsuitableSectionOnlyArgs()) {
1718  errors += strprintf(_("Config setting for %s only applied on %s "
1719  "network when in [%s] section.") +
1720  Untranslated("\n"),
1721  arg, network, network);
1722  }
1723 
1724  if (!errors.empty()) {
1725  return InitError(errors);
1726  }
1727 
1728  // Warn if unrecognized section name are present in the config file.
1729  bilingual_str warnings;
1730  for (const auto &section : args.GetUnrecognizedSections()) {
1731  warnings += strprintf(Untranslated("%s:%i ") +
1732  _("Section [%s] is not recognized.") +
1733  Untranslated("\n"),
1734  section.m_file, section.m_line, section.m_name);
1735  }
1736 
1737  if (!warnings.empty()) {
1738  InitWarning(warnings);
1739  }
1740 
1741  if (!fs::is_directory(args.GetBlocksDirPath())) {
1742  return InitError(
1743  strprintf(_("Specified blocks directory \"%s\" does not exist."),
1744  args.GetArg("-blocksdir", "")));
1745  }
1746 
1747  // parse and validate enabled filter types
1748  std::string blockfilterindex_value =
1749  args.GetArg("-blockfilterindex", DEFAULT_BLOCKFILTERINDEX);
1750  if (blockfilterindex_value == "" || blockfilterindex_value == "1") {
1751  g_enabled_filter_types = AllBlockFilterTypes();
1752  } else if (blockfilterindex_value != "0") {
1753  const std::vector<std::string> names =
1754  args.GetArgs("-blockfilterindex");
1755  for (const auto &name : names) {
1756  BlockFilterType filter_type;
1757  if (!BlockFilterTypeByName(name, filter_type)) {
1758  return InitError(
1759  strprintf(_("Unknown -blockfilterindex value %s."), name));
1760  }
1761  g_enabled_filter_types.insert(filter_type);
1762  }
1763  }
1764 
1765  // Signal NODE_COMPACT_FILTERS if peerblockfilters and basic filters index
1766  // are both enabled.
1767  if (args.GetBoolArg("-peerblockfilters", DEFAULT_PEERBLOCKFILTERS)) {
1768  if (g_enabled_filter_types.count(BlockFilterType::BASIC) != 1) {
1769  return InitError(
1770  _("Cannot set -peerblockfilters without -blockfilterindex."));
1771  }
1772 
1773  nLocalServices = ServiceFlags(nLocalServices | NODE_COMPACT_FILTERS);
1774  }
1775 
1776  // if using block pruning, then disallow txindex, coinstatsindex and chronik
1777  if (args.GetIntArg("-prune", 0)) {
1778  if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
1779  return InitError(_("Prune mode is incompatible with -txindex."));
1780  }
1781  if (args.GetBoolArg("-coinstatsindex", DEFAULT_COINSTATSINDEX)) {
1782  return InitError(
1783  _("Prune mode is incompatible with -coinstatsindex."));
1784  }
1785  if (args.GetBoolArg("-chronik", DEFAULT_CHRONIK)) {
1786  return InitError(_("Prune mode is incompatible with -chronik."));
1787  }
1788  }
1789 
1790  // -bind and -whitebind can't be set when not listening
1791  size_t nUserBind =
1792  args.GetArgs("-bind").size() + args.GetArgs("-whitebind").size();
1793  if (nUserBind != 0 && !args.GetBoolArg("-listen", DEFAULT_LISTEN)) {
1794  return InitError(Untranslated(
1795  "Cannot set -bind or -whitebind together with -listen=0"));
1796  }
1797 
1798  // Make sure enough file descriptors are available
1799  int nBind = std::max(nUserBind, size_t(1));
1800  nUserMaxConnections =
1801  args.GetIntArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
1802  nMaxConnections = std::max(nUserMaxConnections, 0);
1803 
1804  // Trim requested connection counts, to fit into system limitations
1805  // <int> in std::min<int>(...) to work around FreeBSD compilation issue
1806  // described in #2695
1808  nMaxConnections + nBind + MIN_CORE_FILEDESCRIPTORS +
1810 #ifdef USE_POLL
1811  int fd_max = nFD;
1812 #else
1813  int fd_max = FD_SETSIZE;
1814 #endif
1815  nMaxConnections = std::max(
1816  std::min<int>(nMaxConnections,
1817  fd_max - nBind - MIN_CORE_FILEDESCRIPTORS -
1819  0);
1820  if (nFD < MIN_CORE_FILEDESCRIPTORS) {
1821  return InitError(_("Not enough file descriptors available."));
1822  }
1823  nMaxConnections =
1825  nMaxConnections);
1826 
1827  if (nMaxConnections < nUserMaxConnections) {
1828  // Not categorizing as "Warning" because this is the normal behavior for
1829  // platforms using the select() interface for which FD_SETSIZE is
1830  // usually 1024.
1831  LogPrintf("Reducing -maxconnections from %d to %d, because of system "
1832  "limitations.\n",
1833  nUserMaxConnections, nMaxConnections);
1834  }
1835 
1836  // Step 3: parameter-to-internal-flags
1838 
1839  fCheckBlockIndex = args.GetBoolArg("-checkblockindex",
1840  chainparams.DefaultConsistencyChecks());
1842  args.GetBoolArg("-checkpoints", DEFAULT_CHECKPOINTS_ENABLED);
1843  if (fCheckpointsEnabled) {
1844  LogPrintf("Checkpoints will be verified.\n");
1845  } else {
1846  LogPrintf("Skipping checkpoint verification.\n");
1847  }
1848 
1850  args.GetArg("-assumevalid",
1851  chainparams.GetConsensus().defaultAssumeValid.GetHex()));
1852  if (!hashAssumeValid.IsNull()) {
1853  LogPrintf("Assuming ancestors of block %s have valid signatures.\n",
1855  } else {
1856  LogPrintf("Validating signatures for all blocks.\n");
1857  }
1858 
1859  if (args.IsArgSet("-minimumchainwork")) {
1860  const std::string minChainWorkStr =
1861  args.GetArg("-minimumchainwork", "");
1862  if (!IsHexNumber(minChainWorkStr)) {
1863  return InitError(strprintf(
1864  Untranslated(
1865  "Invalid non-hex (%s) minimum chain work value specified"),
1866  minChainWorkStr));
1867  }
1868  nMinimumChainWork = UintToArith256(uint256S(minChainWorkStr));
1869  } else {
1872  }
1873  LogPrintf("Setting nMinimumChainWork=%s\n", nMinimumChainWork.GetHex());
1874  if (nMinimumChainWork <
1876  LogPrintf("Warning: nMinimumChainWork set below default value of %s\n",
1877  chainparams.GetConsensus().nMinimumChainWork.GetHex());
1878  }
1879 
1880  // mempool limits
1881  int64_t nMempoolSizeMax =
1882  args.GetIntArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
1883  int64_t nMempoolSizeMin =
1884  args.GetIntArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) *
1885  1000 * 40;
1886  if (nMempoolSizeMax < 0 || nMempoolSizeMax < nMempoolSizeMin) {
1887  return InitError(strprintf(_("-maxmempool must be at least %d MB"),
1888  std::ceil(nMempoolSizeMin / 1000000.0)));
1889  }
1890 
1891  // Configure excessive block size.
1892  const int64_t nProposedExcessiveBlockSize =
1893  args.GetIntArg("-excessiveblocksize", DEFAULT_MAX_BLOCK_SIZE);
1894  if (nProposedExcessiveBlockSize <= 0 ||
1895  !config.SetMaxBlockSize(nProposedExcessiveBlockSize)) {
1896  return InitError(
1897  _("Excessive block size must be > 1,000,000 bytes (1MB)"));
1898  }
1899 
1900  // Check blockmaxsize does not exceed maximum accepted block size.
1901  const int64_t nProposedMaxGeneratedBlockSize =
1902  args.GetIntArg("-blockmaxsize", DEFAULT_MAX_GENERATED_BLOCK_SIZE);
1903  if (nProposedMaxGeneratedBlockSize <= 0) {
1904  return InitError(_("Max generated block size must be greater than 0"));
1905  }
1906  if (uint64_t(nProposedMaxGeneratedBlockSize) > config.GetMaxBlockSize()) {
1907  return InitError(_("Max generated block size (blockmaxsize) cannot "
1908  "exceed the excessive block size "
1909  "(excessiveblocksize)"));
1910  }
1911 
1912  // block pruning; get the amount of disk space (in MiB) to allot for block &
1913  // undo files
1914  int64_t nPruneArg = args.GetIntArg("-prune", 0);
1915  if (nPruneArg < 0) {
1916  return InitError(
1917  _("Prune cannot be configured with a negative value."));
1918  }
1919  nPruneTarget = (uint64_t)nPruneArg * 1024 * 1024;
1920  if (nPruneArg == 1) {
1921  // manual pruning: -prune=1
1922  LogPrintf("Block pruning enabled. Use RPC call "
1923  "pruneblockchain(height) to manually prune block and undo "
1924  "files.\n");
1925  nPruneTarget = std::numeric_limits<uint64_t>::max();
1926  fPruneMode = true;
1927  } else if (nPruneTarget) {
1929  return InitError(
1930  strprintf(_("Prune configured below the minimum of %d MiB. "
1931  "Please use a higher number."),
1932  MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
1933  }
1934  LogPrintf("Prune configured to target %u MiB on disk for block and "
1935  "undo files.\n",
1936  nPruneTarget / 1024 / 1024);
1937  fPruneMode = true;
1938  }
1939 
1941  if (nConnectTimeout <= 0) {
1943  }
1944 
1945  peer_connect_timeout =
1946  args.GetIntArg("-peertimeout", DEFAULT_PEER_CONNECT_TIMEOUT);
1947  if (peer_connect_timeout <= 0) {
1948  return InitError(Untranslated(
1949  "peertimeout cannot be configured with a negative value."));
1950  }
1951 
1952  // Obtain the amount to charge excess UTXO
1953  if (args.IsArgSet("-excessutxocharge")) {
1954  Amount n = Amount::zero();
1955  auto parsed = ParseMoney(args.GetArg("-excessutxocharge", ""), n);
1956  if (!parsed || Amount::zero() > n) {
1957  return InitError(AmountErrMsg(
1958  "excessutxocharge", args.GetArg("-excessutxocharge", "")));
1959  }
1960  config.SetExcessUTXOCharge(n);
1961  } else {
1963  }
1964 
1965  if (args.IsArgSet("-minrelaytxfee")) {
1966  Amount n = Amount::zero();
1967  auto parsed = ParseMoney(args.GetArg("-minrelaytxfee", ""), n);
1968  if (!parsed || n == Amount::zero()) {
1969  return InitError(AmountErrMsg("minrelaytxfee",
1970  args.GetArg("-minrelaytxfee", "")));
1971  }
1972  // High fee check is done afterward in CWallet::Create()
1974  }
1975 
1976  // Sanity check argument for min fee for including tx in block
1977  // TODO: Harmonize which arguments need sanity checking and where that
1978  // happens.
1979  if (args.IsArgSet("-blockmintxfee")) {
1980  Amount n = Amount::zero();
1981  if (!ParseMoney(args.GetArg("-blockmintxfee", ""), n)) {
1982  return InitError(AmountErrMsg("blockmintxfee",
1983  args.GetArg("-blockmintxfee", "")));
1984  }
1985  }
1986 
1987  // Feerate used to define dust. Shouldn't be changed lightly as old
1988  // implementations may inadvertently create non-standard transactions.
1989  if (args.IsArgSet("-dustrelayfee")) {
1990  Amount n = Amount::zero();
1991  auto parsed = ParseMoney(args.GetArg("-dustrelayfee", ""), n);
1992  if (!parsed || Amount::zero() == n) {
1993  return InitError(
1994  AmountErrMsg("dustrelayfee", args.GetArg("-dustrelayfee", "")));
1995  }
1996  dustRelayFee = CFeeRate(n);
1997  }
1998 
2000  !args.GetBoolArg("-acceptnonstdtxn", !chainparams.RequireStandard());
2001  if (!chainparams.IsTestChain() && !fRequireStandard) {
2002  return InitError(strprintf(
2003  Untranslated(
2004  "acceptnonstdtxn is not currently supported for %s chain"),
2005  chainparams.NetworkIDString()));
2006  }
2008  args.IsArgSet("-bytespersigcheck")
2009  ? args.GetIntArg("-bytespersigcheck", nBytesPerSigCheck)
2010  : args.GetIntArg("-bytespersigop", nBytesPerSigCheck);
2011 
2013  return false;
2014  }
2015 
2017  args.GetBoolArg("-permitbaremultisig", DEFAULT_PERMIT_BAREMULTISIG);
2019  args.GetBoolArg("-datacarrier", DEFAULT_ACCEPT_DATACARRIER);
2020 
2021  // Option to startup with mocktime set (used for regression testing):
2022  SetMockTime(args.GetIntArg("-mocktime", 0)); // SetMockTime(0) is a no-op
2023 
2024  if (args.GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS)) {
2025  nLocalServices = ServiceFlags(nLocalServices | NODE_BLOOM);
2026  }
2027 
2028  nMaxTipAge = args.GetIntArg("-maxtipage", DEFAULT_MAX_TIP_AGE);
2029 
2030  if (args.IsArgSet("-proxy") && args.GetArg("-proxy", "").empty()) {
2031  return InitError(_(
2032  "No proxy server specified. Use -proxy=<ip> or -proxy=<ip:port>."));
2033  }
2034 
2035  // Avalanche parameters
2036  const int64_t stakeUtxoMinConfirmations =
2037  args.GetIntArg("-avaproofstakeutxoconfirmations",
2039 
2040  if (!chainparams.IsTestChain() &&
2041  stakeUtxoMinConfirmations !=
2043  return InitError(_("Avalanche stake UTXO minimum confirmations can "
2044  "only be set on test chains."));
2045  }
2046 
2047  if (stakeUtxoMinConfirmations <= 0) {
2048  return InitError(_("Avalanche stake UTXO minimum confirmations must be "
2049  "a positive integer."));
2050  }
2051 
2052  if (args.IsArgSet("-avaproofstakeutxodustthreshold")) {
2053  Amount amount = Amount::zero();
2054  auto parsed = ParseMoney(
2055  args.GetArg("-avaproofstakeutxodustthreshold", ""), amount);
2056  if (!parsed || Amount::zero() == amount) {
2057  return InitError(AmountErrMsg(
2058  "avaproofstakeutxodustthreshold",
2059  args.GetArg("-avaproofstakeutxodustthreshold", "")));
2060  }
2061 
2062  if (!chainparams.IsTestChain() &&
2063  amount != avalanche::PROOF_DUST_THRESHOLD) {
2064  return InitError(_("Avalanche stake UTXO dust threshold can "
2065  "only be set on test chains."));
2066  }
2067  }
2068 
2069  return true;
2070 }
2071 
2072 static bool LockDataDirectory(bool probeOnly) {
2073  // Make sure only a single Bitcoin process is using the data directory.
2074  fs::path datadir = gArgs.GetDataDirNet();
2075  if (!DirIsWritable(datadir)) {
2076  return InitError(strprintf(
2077  _("Cannot write to data directory '%s'; check permissions."),
2078  fs::PathToString(datadir)));
2079  }
2080  if (!LockDirectory(datadir, ".lock", probeOnly)) {
2081  return InitError(strprintf(_("Cannot obtain a lock on data directory "
2082  "%s. %s is probably already running."),
2083  fs::PathToString(datadir), PACKAGE_NAME));
2084  }
2085  return true;
2086 }
2087 
2089  // Step 4: sanity checks
2090 
2091  init::SetGlobals();
2092 
2093  // Sanity check
2094  if (!init::SanityChecks()) {
2095  return InitError(strprintf(
2096  _("Initialization sanity check failed. %s is shutting down."),
2097  PACKAGE_NAME));
2098  }
2099 
2100  // Probe the data directory lock to give an early error message, if possible
2101  // We cannot hold the data directory lock here, as the forking for daemon()
2102  // hasn't yet happened, and a fork will cause weird behavior to it.
2103  return LockDataDirectory(true);
2104 }
2105 
2107  // After daemonization get the data directory lock again and hold on to it
2108  // until exit. This creates a slight window for a race condition to happen,
2109  // however this condition is harmless: it will at most make us exit without
2110  // printing a message to console.
2111  if (!LockDataDirectory(false)) {
2112  // Detailed error printed inside LockDataDirectory
2113  return false;
2114  }
2115  return true;
2116 }
2117 
2119  node.chain = interfaces::MakeChain(node, Params());
2120  // Create client interfaces for wallets that are supposed to be loaded
2121  // according to -wallet and -disablewallet options. This only constructs
2122  // the interfaces, it doesn't load wallet data. Wallets actually get loaded
2123  // when load() and start() interface methods are called below.
2125  return true;
2126 }
2127 
2128 bool AppInitMain(Config &config, RPCServer &rpcServer,
2129  HTTPRPCRequestProcessor &httpRPCRequestProcessor,
2130  NodeContext &node,
2132  // Step 4a: application initialization
2133  const ArgsManager &args = *Assert(node.args);
2134  const CChainParams &chainparams = config.GetChainParams();
2135 
2136  if (!CreatePidFile(args)) {
2137  // Detailed error printed inside CreatePidFile().
2138  return false;
2139  }
2140  if (!init::StartLogging(args)) {
2141  // Detailed error printed inside StartLogging().
2142  return false;
2143  }
2144 
2145  LogPrintf("Using at most %i automatic connections (%i file descriptors "
2146  "available)\n",
2147  nMaxConnections, nFD);
2148 
2149  // Warn about relative -datadir path.
2150  if (args.IsArgSet("-datadir") &&
2151  !fs::PathFromString(args.GetArg("-datadir", "")).is_absolute()) {
2152  LogPrintf("Warning: relative datadir option '%s' specified, which will "
2153  "be interpreted relative to the current working directory "
2154  "'%s'. This is fragile, because if bitcoin is started in the "
2155  "future from a different location, it will be unable to "
2156  "locate the current data files. There could also be data "
2157  "loss if bitcoin is started while in a temporary "
2158  "directory.\n",
2159  args.GetArg("-datadir", ""),
2160  fs::PathToString(fs::current_path()));
2161  }
2162 
2165 
2166  int script_threads = args.GetIntArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
2167  if (script_threads <= 0) {
2168  // -par=0 means autodetect (number of cores - 1 script threads)
2169  // -par=-n means "leave n cores free" (number of cores - n - 1 script
2170  // threads)
2171  script_threads += GetNumCores();
2172  }
2173 
2174  // Subtract 1 because the main thread counts towards the par threads
2175  script_threads = std::max(script_threads - 1, 0);
2176 
2177  // Number of script-checking threads <= MAX_SCRIPTCHECK_THREADS
2178  script_threads = std::min(script_threads, MAX_SCRIPTCHECK_THREADS);
2179 
2180  LogPrintf("Script verification uses %d additional threads\n",
2181  script_threads);
2182  if (script_threads >= 1) {
2183  StartScriptCheckWorkerThreads(script_threads);
2184  }
2185 
2186  assert(!node.scheduler);
2187  node.scheduler = std::make_unique<CScheduler>();
2188 
2189  // Start the lightweight task scheduler thread
2190  node.scheduler->m_service_thread =
2191  std::thread(&util::TraceThread, "scheduler",
2192  [&] { node.scheduler->serviceQueue(); });
2193 
2194  // Gather some entropy once per minute.
2195  node.scheduler->scheduleEvery(
2196  [] {
2197  RandAddPeriodic();
2198  return true;
2199  },
2200  std::chrono::minutes{1});
2201 
2203 
2208  RegisterAllRPCCommands(config, rpcServer, tableRPC);
2209  for (const auto &client : node.chain_clients) {
2210  client->registerRpcs();
2211  }
2212 #if ENABLE_ZMQ
2214 #endif
2215 
2222  if (args.GetBoolArg("-server", false)) {
2223  uiInterface.InitMessage_connect(SetRPCWarmupStatus);
2224  if (!AppInitServers(config, httpRPCRequestProcessor, node)) {
2225  return InitError(
2226  _("Unable to start HTTP server. See debug log for details."));
2227  }
2228  }
2229 
2230  // Step 5: verify wallet database integrity
2231  for (const auto &client : node.chain_clients) {
2232  if (!client->verify()) {
2233  return false;
2234  }
2235  }
2236 
2237  // Step 6: network initialization
2238 
2239  // Note that we absolutely cannot open any actual connections
2240  // until the very end ("start node") as the UTXO/block state
2241  // is not yet setup and may end up being set up twice if we
2242  // need to reindex later.
2243 
2244  fListen = args.GetBoolArg("-listen", DEFAULT_LISTEN);
2245  fDiscover = args.GetBoolArg("-discover", true);
2246 
2247  {
2248  // Initialize addrman
2249  assert(!node.addrman);
2250 
2251  // Read asmap file if configured
2252  std::vector<bool> asmap;
2253  if (args.IsArgSet("-asmap")) {
2254  fs::path asmap_path = fs::PathFromString(args.GetArg("-asmap", ""));
2255  if (asmap_path.empty()) {
2257  }
2258  if (!asmap_path.is_absolute()) {
2259  asmap_path = args.GetDataDirNet() / asmap_path;
2260  }
2261  if (!fs::exists(asmap_path)) {
2262  InitError(strprintf(_("Could not find asmap file %s"),
2263  fs::quoted(fs::PathToString(asmap_path))));
2264  return false;
2265  }
2266  asmap = DecodeAsmap(asmap_path);
2267  if (asmap.size() == 0) {
2268  InitError(strprintf(_("Could not parse asmap file %s"),
2269  fs::quoted(fs::PathToString(asmap_path))));
2270  return false;
2271  }
2272  const uint256 asmap_version = SerializeHash(asmap);
2273  LogPrintf("Using asmap version %s for IP bucketing\n",
2274  asmap_version.ToString());
2275  } else {
2276  LogPrintf("Using /16 prefix for IP bucketing\n");
2277  }
2278 
2279  uiInterface.InitMessage(_("Loading P2P addresses...").translated);
2280  if (const auto error{
2281  LoadAddrman(chainparams, asmap, args, node.addrman)}) {
2282  return InitError(*error);
2283  }
2284  }
2285 
2286  assert(!node.banman);
2287  node.banman = std::make_unique<BanMan>(
2288  args.GetDataDirNet() / "banlist.dat", config.GetChainParams(),
2289  &uiInterface, args.GetIntArg("-bantime", DEFAULT_MISBEHAVING_BANTIME));
2290  assert(!node.connman);
2291  node.connman = std::make_unique<CConnman>(
2292  config, GetRand(std::numeric_limits<uint64_t>::max()),
2293  GetRand(std::numeric_limits<uint64_t>::max()), *node.addrman,
2294  args.GetBoolArg("-networkactive", true));
2295 
2296  // sanitize comments per BIP-0014, format user agent and check total size
2297  std::vector<std::string> uacomments;
2298  for (const std::string &cmt : args.GetArgs("-uacomment")) {
2299  if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT)) {
2300  return InitError(strprintf(
2301  _("User Agent comment (%s) contains unsafe characters."), cmt));
2302  }
2303  uacomments.push_back(cmt);
2304  }
2305  const std::string client_name = args.GetArg("-uaclientname", CLIENT_NAME);
2306  const std::string client_version =
2307  args.GetArg("-uaclientversion", FormatVersion(CLIENT_VERSION));
2308  if (client_name != SanitizeString(client_name, SAFE_CHARS_UA_COMMENT)) {
2309  return InitError(strprintf(
2310  _("-uaclientname (%s) contains invalid characters."), client_name));
2311  }
2312  if (client_version !=
2313  SanitizeString(client_version, SAFE_CHARS_UA_COMMENT)) {
2314  return InitError(
2315  strprintf(_("-uaclientversion (%s) contains invalid characters."),
2316  client_version));
2317  }
2318  const std::string strSubVersion =
2319  FormatUserAgent(client_name, client_version, uacomments);
2320  if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
2321  return InitError(strprintf(
2322  _("Total length of network version string (%i) exceeds maximum "
2323  "length (%i). Reduce the number or size of uacomments."),
2324  strSubVersion.size(), MAX_SUBVERSION_LENGTH));
2325  }
2326 
2327  if (args.IsArgSet("-onlynet")) {
2328  std::set<enum Network> nets;
2329  for (const std::string &snet : args.GetArgs("-onlynet")) {
2330  enum Network net = ParseNetwork(snet);
2331  if (net == NET_UNROUTABLE) {
2332  return InitError(strprintf(
2333  _("Unknown network specified in -onlynet: '%s'"), snet));
2334  }
2335  nets.insert(net);
2336  }
2337  for (int n = 0; n < NET_MAX; n++) {
2338  enum Network net = (enum Network)n;
2339  if (!nets.count(net)) {
2340  SetReachable(net, false);
2341  }
2342  }
2343  }
2344 
2345  // Check for host lookup allowed before parsing any network related
2346  // parameters
2347  fNameLookup = args.GetBoolArg("-dns", DEFAULT_NAME_LOOKUP);
2348 
2349  bool proxyRandomize =
2350  args.GetBoolArg("-proxyrandomize", DEFAULT_PROXYRANDOMIZE);
2351  // -proxy sets a proxy for all outgoing network traffic
2352  // -noproxy (or -proxy=0) as well as the empty string can be used to not set
2353  // a proxy, this is the default
2354  std::string proxyArg = args.GetArg("-proxy", "");
2355  SetReachable(NET_ONION, false);
2356  if (proxyArg != "" && proxyArg != "0") {
2357  CService proxyAddr;
2358  if (!Lookup(proxyArg, proxyAddr, 9050, fNameLookup)) {
2359  return InitError(strprintf(
2360  _("Invalid -proxy address or hostname: '%s'"), proxyArg));
2361  }
2362 
2363  proxyType addrProxy = proxyType(proxyAddr, proxyRandomize);
2364  if (!addrProxy.IsValid()) {
2365  return InitError(strprintf(
2366  _("Invalid -proxy address or hostname: '%s'"), proxyArg));
2367  }
2368 
2369  SetProxy(NET_IPV4, addrProxy);
2370  SetProxy(NET_IPV6, addrProxy);
2371  SetProxy(NET_ONION, addrProxy);
2372  SetNameProxy(addrProxy);
2373  // by default, -proxy sets onion as reachable, unless -noonion later
2374  SetReachable(NET_ONION, true);
2375  }
2376 
2377  // -onion can be used to set only a proxy for .onion, or override normal
2378  // proxy for .onion addresses.
2379  // -noonion (or -onion=0) disables connecting to .onion entirely. An empty
2380  // string is used to not override the onion proxy (in which case it defaults
2381  // to -proxy set above, or none)
2382  std::string onionArg = args.GetArg("-onion", "");
2383  if (onionArg != "") {
2384  if (onionArg == "0") {
2385  // Handle -noonion/-onion=0
2386  SetReachable(NET_ONION, false);
2387  } else {
2388  CService onionProxy;
2389  if (!Lookup(onionArg, onionProxy, 9050, fNameLookup)) {
2390  return InitError(strprintf(
2391  _("Invalid -onion address or hostname: '%s'"), onionArg));
2392  }
2393  proxyType addrOnion = proxyType(onionProxy, proxyRandomize);
2394  if (!addrOnion.IsValid()) {
2395  return InitError(strprintf(
2396  _("Invalid -onion address or hostname: '%s'"), onionArg));
2397  }
2398  SetProxy(NET_ONION, addrOnion);
2399  SetReachable(NET_ONION, true);
2400  }
2401  }
2402 
2403  for (const std::string &strAddr : args.GetArgs("-externalip")) {
2404  CService addrLocal;
2405  if (Lookup(strAddr, addrLocal, GetListenPort(), fNameLookup) &&
2406  addrLocal.IsValid()) {
2407  AddLocal(addrLocal, LOCAL_MANUAL);
2408  } else {
2409  return InitError(ResolveErrMsg("externalip", strAddr));
2410  }
2411  }
2412 
2413 #if ENABLE_ZMQ
2415 
2418  }
2419 #endif
2420 
2421  // Step 7: load block chain
2422 
2423  fReindex = args.GetBoolArg("-reindex", false);
2424  bool fReindexChainState = args.GetBoolArg("-reindex-chainstate", false);
2425 
2426  // cache size calculations
2427  CacheSizes cache_sizes =
2428  CalculateCacheSizes(args, g_enabled_filter_types.size());
2429 
2430  int64_t nMempoolSizeMax =
2431  args.GetIntArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
2432  LogPrintf("Cache configuration:\n");
2433  LogPrintf("* Using %.1f MiB for block index database\n",
2434  cache_sizes.block_tree_db * (1.0 / 1024 / 1024));
2435  if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
2436  LogPrintf("* Using %.1f MiB for transaction index database\n",
2437  cache_sizes.tx_index * (1.0 / 1024 / 1024));
2438  }
2439  for (BlockFilterType filter_type : g_enabled_filter_types) {
2440  LogPrintf("* Using %.1f MiB for %s block filter index database\n",
2441  cache_sizes.filter_index * (1.0 / 1024 / 1024),
2442  BlockFilterTypeName(filter_type));
2443  }
2444  LogPrintf("* Using %.1f MiB for chain state database\n",
2445  cache_sizes.coins_db * (1.0 / 1024 / 1024));
2446  LogPrintf("* Using %.1f MiB for in-memory UTXO set (plus up to %.1f MiB of "
2447  "unused mempool space)\n",
2448  cache_sizes.coins * (1.0 / 1024 / 1024),
2449  nMempoolSizeMax * (1.0 / 1024 / 1024));
2450 
2451  assert(!node.mempool);
2452  assert(!node.chainman);
2453  const int mempool_check_ratio = std::clamp<int>(
2454  args.GetIntArg("-checkmempool",
2455  chainparams.DefaultConsistencyChecks() ? 1 : 0),
2456  0, 1000000);
2457 
2458  for (bool fLoaded = false; !fLoaded && !ShutdownRequested();) {
2459  node.mempool = std::make_unique<CTxMemPool>(mempool_check_ratio);
2460 
2461  node.chainman = std::make_unique<ChainstateManager>();
2462  ChainstateManager &chainman = *node.chainman;
2463 
2464  const bool fReset = fReindex;
2465  bilingual_str strLoadError;
2466 
2467  uiInterface.InitMessage(_("Loading block index...").translated);
2468 
2469  const int64_t load_block_index_start_time = GetTimeMillis();
2470  std::optional<ChainstateLoadingError> rv;
2471 
2472  try {
2473  rv = LoadChainstate(
2474  fReset, chainman, Assert(node.mempool.get()), fPruneMode,
2475  chainparams.GetConsensus(), fReindexChainState,
2476  cache_sizes.block_tree_db, cache_sizes.coins_db,
2477  cache_sizes.coins, false, false, ShutdownRequested, []() {
2478  uiInterface.ThreadSafeMessageBox(
2479  _("Error reading from database, shutting down."), "",
2480  CClientUIInterface::MSG_ERROR);
2481  });
2482  } catch (const std::exception &e) {
2483  LogPrintf("%s\n", e.what());
2484  rv = ChainstateLoadingError::ERROR_GENERIC_BLOCKDB_OPEN_FAILED;
2485  }
2486 
2487  if (rv.has_value()) {
2488  switch (rv.value()) {
2489  case ChainstateLoadingError::ERROR_UPGRADING_BLOCK_DB:
2490  strLoadError = _("Error upgrading block index database");
2491  break;
2492  case ChainstateLoadingError::ERROR_LOADING_BLOCK_DB:
2493  strLoadError = _("Error loading block database");
2494  break;
2495  case ChainstateLoadingError::ERROR_BAD_GENESIS_BLOCK:
2496  // If the loaded chain has a wrong genesis, bail out
2497  // immediately (we're likely using a testnet datadir, or
2498  // the other way around).
2499  return InitError(_("Incorrect or no genesis block found. "
2500  "Wrong datadir for network?"));
2501  case ChainstateLoadingError::ERROR_PRUNED_NEEDS_REINDEX:
2502  strLoadError =
2503  _("You need to rebuild the database using -reindex to "
2504  "go back to unpruned mode. This will redownload the "
2505  "entire blockchain");
2506  break;
2507  case ChainstateLoadingError::ERROR_LOAD_GENESIS_BLOCK_FAILED:
2508  strLoadError = _("Error initializing block database");
2509  break;
2510  case ChainstateLoadingError::ERROR_CHAINSTATE_UPGRADE_FAILED:
2511  strLoadError = _("Error upgrading chainstate database");
2512  break;
2513  case ChainstateLoadingError::ERROR_REPLAYBLOCKS_FAILED:
2514  strLoadError =
2515  _("Unable to replay blocks. You will need to rebuild "
2516  "the database using -reindex-chainstate.");
2517  break;
2518  case ChainstateLoadingError::ERROR_LOADCHAINTIP_FAILED:
2519  strLoadError = _("Error initializing block database");
2520  break;
2521  case ChainstateLoadingError::ERROR_GENERIC_BLOCKDB_OPEN_FAILED:
2522  strLoadError = _("Error opening block database");
2523  break;
2524  case ChainstateLoadingError::SHUTDOWN_PROBED:
2525  break;
2526  }
2527  } else {
2528  std::optional<ChainstateLoadVerifyError> rv2;
2529  try {
2530  uiInterface.InitMessage(_("Verifying blocks…").translated);
2531 
2532  auto check_blocks =
2533  args.GetIntArg("-checkblocks", DEFAULT_CHECKBLOCKS);
2534  if (chainman.m_blockman.m_have_pruned &&
2535  check_blocks > MIN_BLOCKS_TO_KEEP) {
2536  LogPrintf("Prune: pruned datadir may not have more than %d "
2537  "blocks; only checking available blocks\n",
2539  }
2540 
2541  rv2 = VerifyLoadedChainstate(
2542  chainman, fReset, fReindexChainState, config, check_blocks,
2543  args.GetIntArg("-checklevel", DEFAULT_CHECKLEVEL),
2544  static_cast<int64_t (*)()>(GetTime));
2545  } catch (const std::exception &e) {
2546  LogPrintf("%s\n", e.what());
2547  rv2 = ChainstateLoadVerifyError::ERROR_GENERIC_FAILURE;
2548  }
2549 
2550  if (rv2.has_value()) {
2551  switch (rv2.value()) {
2552  case ChainstateLoadVerifyError::ERROR_BLOCK_FROM_FUTURE:
2553  strLoadError = _(
2554  "The block database contains a block which appears "
2555  "to be from the future. "
2556  "This may be due to your computer's date and time "
2557  "being set incorrectly. "
2558  "Only rebuild the block database if you are sure "
2559  "that your computer's date and time are correct");
2560  break;
2561  case ChainstateLoadVerifyError::ERROR_CORRUPTED_BLOCK_DB:
2562  strLoadError = _("Corrupted block database detected");
2563  break;
2564  case ChainstateLoadVerifyError::ERROR_GENERIC_FAILURE:
2565  strLoadError = _("Error opening block database");
2566  break;
2567  }
2568  } else {
2569  fLoaded = true;
2570  LogPrintf(" block index %15dms\n",
2571  GetTimeMillis() - load_block_index_start_time);
2572  }
2573  }
2574 
2575  if (!fLoaded && !ShutdownRequested()) {
2576  // first suggest a reindex
2577  if (!fReset) {
2578  bool fRet = uiInterface.ThreadSafeQuestion(
2579  strLoadError + Untranslated(".\n\n") +
2580  _("Do you want to rebuild the block database now?"),
2581  strLoadError.original +
2582  ".\nPlease restart with -reindex or "
2583  "-reindex-chainstate to recover.",
2584  "",
2587  if (fRet) {
2588  fReindex = true;
2589  AbortShutdown();
2590  } else {
2591  LogPrintf("Aborted block database rebuild. Exiting.\n");
2592  return false;
2593  }
2594  } else {
2595  return InitError(strLoadError);
2596  }
2597  }
2598  }
2599 
2600  // As LoadBlockIndex can take several minutes, it's possible the user
2601  // requested to kill the GUI during the last operation. If so, exit.
2602  // As the program has not fully started yet, Shutdown() is possibly
2603  // overkill.
2604  if (ShutdownRequested()) {
2605  LogPrintf("Shutdown requested. Exiting.\n");
2606  return false;
2607  }
2608 
2609  ChainstateManager &chainman = *Assert(node.chainman);
2610 
2611  assert(!node.peerman);
2612  node.peerman = PeerManager::make(
2613  chainparams, *node.connman, *node.addrman, node.banman.get(), chainman,
2614  *node.mempool, args.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY));
2615  RegisterValidationInterface(node.peerman.get());
2616 
2617  // Encoded addresses using cashaddr instead of base58.
2618  // We do this by default to avoid confusion with BTC addresses.
2619  config.SetCashAddrEncoding(args.GetBoolArg("-usecashaddr", true));
2620 
2621  // Step 7.5 (I guess ?): Initialize Avalanche.
2622  bilingual_str avalancheError;
2624  args, *node.chain, node.connman.get(), chainman, node.mempool.get(),
2625  *node.scheduler, avalancheError);
2626  if (!g_avalanche) {
2627  InitError(avalancheError);
2628  return false;
2629  }
2630 
2631  if (isAvalancheEnabled(args) &&
2632  g_avalanche->isAvalancheServiceAvailable()) {
2633  nLocalServices = ServiceFlags(nLocalServices | NODE_AVALANCHE);
2634  }
2635 
2636  // Step 8: load indexers
2637  if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
2638  if (const auto error{CheckLegacyTxindex(
2639  *Assert(chainman.m_blockman.m_block_tree_db))}) {
2640  return InitError(*error);
2641  }
2642 
2643  g_txindex =
2644  std::make_unique<TxIndex>(cache_sizes.tx_index, false, fReindex);
2645  g_txindex->Start(chainman.ActiveChainstate());
2646  }
2647 
2648  for (const auto &filter_type : g_enabled_filter_types) {
2649  InitBlockFilterIndex(filter_type, cache_sizes.filter_index, false,
2650  fReindex);
2651  GetBlockFilterIndex(filter_type)->Start(chainman.ActiveChainstate());
2652  }
2653 
2654  if (args.GetBoolArg("-coinstatsindex", DEFAULT_COINSTATSINDEX)) {
2655  g_coin_stats_index = std::make_unique<CoinStatsIndex>(
2656  /* cache size */ 0, false, fReindex);
2657  g_coin_stats_index->Start(chainman.ActiveChainstate());
2658  }
2659 
2660 #if ENABLE_CHRONIK
2661  if (args.GetBoolArg("-chronik", DEFAULT_CHRONIK)) {
2662  const bool fReindexChronik =
2663  fReindex || args.GetBoolArg("-chronikreindex", false);
2664  if (!chronik::Start(config, node, fReindexChronik)) {
2665  return false;
2666  }
2667  }
2668 #endif
2669 
2670  // Step 9: load wallet
2671  for (const auto &client : node.chain_clients) {
2672  if (!client->load()) {
2673  return false;
2674  }
2675  }
2676 
2677  // Step 10: data directory maintenance
2678 
2679  // if pruning, unset the service bit and perform the initial blockstore
2680  // prune after any wallet rescanning has taken place.
2681  if (fPruneMode) {
2682  LogPrintf("Unsetting NODE_NETWORK on prune mode\n");
2683  nLocalServices = ServiceFlags(nLocalServices & ~NODE_NETWORK);
2684  if (!fReindex) {
2685  LOCK(cs_main);
2686  for (Chainstate *chainstate : chainman.GetAll()) {
2687  uiInterface.InitMessage(_("Pruning blockstore...").translated);
2688  chainstate->PruneAndFlush();
2689  }
2690  }
2691  }
2692 
2693  // Step 11: import blocks
2694  if (!CheckDiskSpace(args.GetDataDirNet())) {
2695  InitError(
2696  strprintf(_("Error: Disk space is low for %s"),
2698  return false;
2699  }
2700  if (!CheckDiskSpace(args.GetBlocksDirPath())) {
2701  InitError(
2702  strprintf(_("Error: Disk space is low for %s"),
2704  return false;
2705  }
2706 
2707  // Either install a handler to notify us when genesis activates, or set
2708  // fHaveGenesis directly.
2709  // No locking, as this happens before any background thread is started.
2710  boost::signals2::connection block_notify_genesis_wait_connection;
2711  if (chainman.ActiveTip() == nullptr) {
2712  block_notify_genesis_wait_connection =
2713  uiInterface.NotifyBlockTip_connect(
2714  std::bind(BlockNotifyGenesisWait, std::placeholders::_2));
2715  } else {
2716  fHaveGenesis = true;
2717  }
2718 
2719 #if defined(HAVE_SYSTEM)
2720  const std::string block_notify = args.GetArg("-blocknotify", "");
2721  if (!block_notify.empty()) {
2722  uiInterface.NotifyBlockTip_connect([block_notify](
2723  SynchronizationState sync_state,
2724  const CBlockIndex *pBlockIndex) {
2725  if (sync_state != SynchronizationState::POST_INIT || !pBlockIndex) {
2726  return;
2727  }
2728  std::string command = block_notify;
2729  ReplaceAll(command, "%s", pBlockIndex->GetBlockHash().GetHex());
2730  std::thread t(runCommand, command);
2731  // thread runs free
2732  t.detach();
2733  });
2734  }
2735 #endif
2736 
2737  std::vector<fs::path> vImportFiles;
2738  for (const std::string &strFile : args.GetArgs("-loadblock")) {
2739  vImportFiles.push_back(fs::PathFromString(strFile));
2740  }
2741 
2742  chainman.m_load_block = std::thread(
2743  &util::TraceThread, "loadblk", [=, &config, &chainman, &args] {
2744  ThreadImport(config, chainman, vImportFiles, args);
2745  });
2746 
2747  // Wait for genesis block to be processed
2748  {
2750  // We previously could hang here if StartShutdown() is called prior to
2751  // ThreadImport getting started, so instead we just wait on a timer to
2752  // check ShutdownRequested() regularly.
2753  while (!fHaveGenesis && !ShutdownRequested()) {
2754  g_genesis_wait_cv.wait_for(lock, std::chrono::milliseconds(500));
2755  }
2756  block_notify_genesis_wait_connection.disconnect();
2757  }
2758 
2759  if (ShutdownRequested()) {
2760  return false;
2761  }
2762 
2763  // Step 12: start node
2764 
2765  int chain_active_height;
2766 
2768  {
2769  LOCK(cs_main);
2770  LogPrintf("block tree size = %u\n", chainman.BlockIndex().size());
2771  chain_active_height = chainman.ActiveChain().Height();
2772  if (tip_info) {
2773  tip_info->block_height = chain_active_height;
2774  tip_info->block_time =
2775  chainman.ActiveChain().Tip()
2776  ? chainman.ActiveChain().Tip()->GetBlockTime()
2779  Params().TxData(), chainman.ActiveChain().Tip());
2780  }
2781  if (tip_info && chainman.m_best_header) {
2782  tip_info->header_height = chainman.m_best_header->nHeight;
2783  tip_info->header_time = chainman.m_best_header->GetBlockTime();
2784  }
2785  }
2786  LogPrintf("nBestHeight = %d\n", chain_active_height);
2787  if (node.peerman) {
2788  node.peerman->SetBestHeight(chain_active_height);
2789  }
2790 
2791  Discover();
2792 
2793  // Map ports with UPnP or NAT-PMP.
2794  StartMapPort(args.GetBoolArg("-upnp", DEFAULT_UPNP),
2795  args.GetBoolArg("-natpmp", DEFAULT_NATPMP));
2796 
2797  CConnman::Options connOptions;
2798  connOptions.nLocalServices = nLocalServices;
2799  connOptions.nMaxConnections = nMaxConnections;
2800  connOptions.m_max_avalanche_outbound = std::min<int64_t>(
2802  ? args.GetIntArg("-maxavalancheoutbound",
2804  : 0,
2805  connOptions.nMaxConnections);
2806  connOptions.m_max_outbound_full_relay = std::min(
2808  connOptions.nMaxConnections - connOptions.m_max_avalanche_outbound);
2809  connOptions.m_max_outbound_block_relay = std::min(
2811  connOptions.nMaxConnections - connOptions.m_max_avalanche_outbound -
2812  connOptions.m_max_outbound_full_relay);
2813  connOptions.nMaxAddnode = MAX_ADDNODE_CONNECTIONS;
2814  connOptions.nMaxFeeler = MAX_FEELER_CONNECTIONS;
2815  connOptions.uiInterface = &uiInterface;
2816  connOptions.m_banman = node.banman.get();
2817  connOptions.m_msgproc.push_back(node.peerman.get());
2818  if (g_avalanche) {
2819  connOptions.m_msgproc.push_back(g_avalanche.get());
2820  }
2821  connOptions.nSendBufferMaxSize =
2822  1000 * args.GetIntArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER);
2823  connOptions.nReceiveFloodSize =
2824  1000 * args.GetIntArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER);
2825  connOptions.m_added_nodes = args.GetArgs("-addnode");
2826 
2827  connOptions.nMaxOutboundLimit =
2828  1024 * 1024 *
2829  args.GetIntArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET);
2830  connOptions.m_peer_connect_timeout = peer_connect_timeout;
2831 
2832  const auto BadPortWarning = [](const char *prefix, uint16_t port) {
2833  return strprintf(_("%s request to listen on port %u. This port is "
2834  "considered \"bad\" and "
2835  "thus it is unlikely that any Bitcoin ABC peers "
2836  "connect to it. See "
2837  "doc/p2p-bad-ports.md for details and a full list."),
2838  prefix, port);
2839  };
2840 
2841  for (const std::string &bind_arg : args.GetArgs("-bind")) {
2842  CService bind_addr;
2843  const size_t index = bind_arg.rfind('=');
2844  if (index == std::string::npos) {
2845  if (Lookup(bind_arg, bind_addr, GetListenPort(), false)) {
2846  connOptions.vBinds.push_back(bind_addr);
2847  if (IsBadPort(bind_addr.GetPort())) {
2848  InitWarning(BadPortWarning("-bind", bind_addr.GetPort()));
2849  }
2850  continue;
2851  }
2852  } else {
2853  const std::string network_type = bind_arg.substr(index + 1);
2854  if (network_type == "onion") {
2855  const std::string truncated_bind_arg =
2856  bind_arg.substr(0, index);
2857  if (Lookup(truncated_bind_arg, bind_addr,
2858  BaseParams().OnionServiceTargetPort(), false)) {
2859  connOptions.onion_binds.push_back(bind_addr);
2860  continue;
2861  }
2862  }
2863  }
2864  return InitError(ResolveErrMsg("bind", bind_arg));
2865  }
2866 
2867  for (const std::string &strBind : args.GetArgs("-whitebind")) {
2868  NetWhitebindPermissions whitebind;
2870  if (!NetWhitebindPermissions::TryParse(strBind, whitebind, error)) {
2871  return InitError(error);
2872  }
2873  connOptions.vWhiteBinds.push_back(whitebind);
2874  }
2875 
2876  // If the user did not specify -bind= or -whitebind= then we bind
2877  // on any address - 0.0.0.0 (IPv4) and :: (IPv6).
2878  connOptions.bind_on_any =
2879  args.GetArgs("-bind").empty() && args.GetArgs("-whitebind").empty();
2880 
2881  // Emit a warning if a bad port is given to -port= but only if -bind and
2882  // -whitebind are not given, because if they are, then -port= is ignored.
2883  if (connOptions.bind_on_any && args.IsArgSet("-port")) {
2884  const uint16_t port_arg = args.GetIntArg("-port", 0);
2885  if (IsBadPort(port_arg)) {
2886  InitWarning(BadPortWarning("-port", port_arg));
2887  }
2888  }
2889 
2890  CService onion_service_target;
2891  if (!connOptions.onion_binds.empty()) {
2892  onion_service_target = connOptions.onion_binds.front();
2893  } else {
2894  onion_service_target = DefaultOnionServiceTarget();
2895  connOptions.onion_binds.push_back(onion_service_target);
2896  }
2897 
2898  if (args.GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION)) {
2899  if (connOptions.onion_binds.size() > 1) {
2901  _("More than one onion bind address is provided. Using %s "
2902  "for the automatically created Tor onion service."),
2903  onion_service_target.ToStringIPPort()));
2904  }
2905  StartTorControl(onion_service_target);
2906  }
2907 
2908  for (const auto &net : args.GetArgs("-whitelist")) {
2909  NetWhitelistPermissions subnet;
2911  if (!NetWhitelistPermissions::TryParse(net, subnet, error)) {
2912  return InitError(error);
2913  }
2914  connOptions.vWhitelistedRange.push_back(subnet);
2915  }
2916 
2917  connOptions.vSeedNodes = args.GetArgs("-seednode");
2918 
2919  // Initiate outbound connections unless connect=0
2920  connOptions.m_use_addrman_outgoing = !args.IsArgSet("-connect");
2921  if (!connOptions.m_use_addrman_outgoing) {
2922  const auto connect = args.GetArgs("-connect");
2923  if (connect.size() != 1 || connect[0] != "0") {
2924  connOptions.m_specified_outgoing = connect;
2925  }
2926  }
2927 
2928  const std::string &i2psam_arg = args.GetArg("-i2psam", "");
2929  if (!i2psam_arg.empty()) {
2930  CService addr;
2931  if (!Lookup(i2psam_arg, addr, 7656, fNameLookup) || !addr.IsValid()) {
2932  return InitError(strprintf(
2933  _("Invalid -i2psam address or hostname: '%s'"), i2psam_arg));
2934  }
2935  SetReachable(NET_I2P, true);
2936  SetProxy(NET_I2P, proxyType{addr});
2937  } else {
2938  SetReachable(NET_I2P, false);
2939  }
2940 
2941  connOptions.m_i2p_accept_incoming =
2942  args.GetBoolArg("-i2pacceptincoming", true);
2943 
2944  if (!node.connman->Start(*node.scheduler, connOptions)) {
2945  return false;
2946  }
2947 
2948  // Step 13: finished
2949 
2950  // At this point, the RPC is "started", but still in warmup, which means it
2951  // cannot yet be called. Before we make it callable, we need to make sure
2952  // that the RPC's view of the best block is valid and consistent with
2953  // ChainstateManager's ActiveTip.
2954  //
2955  // If we do not do this, RPC's view of the best block will be height=0 and
2956  // hash=0x0. This will lead to erroroneous responses for things like
2957  // waitforblockheight.
2958  RPCNotifyBlockChange(chainman.ActiveTip());
2960 
2961  uiInterface.InitMessage(_("Done loading").translated);
2962 
2963  for (const auto &client : node.chain_clients) {
2964  client->start(*node.scheduler);
2965  }
2966 
2967  BanMan *banman = node.banman.get();
2968  node.scheduler->scheduleEvery(
2969  [banman] {
2970  banman->DumpBanlist();
2971  return true;
2972  },
2974 
2975  if (node.peerman) {
2976  node.peerman->StartScheduledTasks(*node.scheduler);
2977  }
2978 
2979  // Start Avalanche's event loop.
2980  g_avalanche->startEventLoop(*node.scheduler);
2981 
2982 #if HAVE_SYSTEM
2983  StartupNotify(args);
2984 #endif
2985 
2986  return true;
2987 }
std::optional< bilingual_str > LoadAddrman(const CChainParams &chainparams, const std::vector< bool > &asmap, const ArgsManager &args, std::unique_ptr< AddrMan > &addrman)
Returns an error string on failure.
Definition: addrdb.cpp:160
static constexpr int32_t DEFAULT_ADDRMAN_CONSISTENCY_CHECKS
Default for -checkaddrman.
Definition: addrman.h:28
arith_uint256 UintToArith256(const uint256 &a)
std::vector< bool > DecodeAsmap(fs::path path)
Read asmap from provided binary file.
Definition: asmap.cpp:293
bool isAvalancheEnabled(const ArgsManager &argsman)
Definition: avalanche.cpp:9
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
std::unique_ptr< avalanche::Processor > g_avalanche
Global avalanche instance.
Definition: processor.cpp:34
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:233
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.
RecursiveMutex cs_main
Global state.
Definition: validation.cpp:113
const CChainParams & Params()
Return the currently selected parameters.
std::unique_ptr< CChainParams > CreateChainParams(const std::string &chain)
Creates and returns a std::unique_ptr<CChainParams> of the chosen chain.
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...
#define Assert(val)
Identity function.
Definition: check.h:65
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: system.cpp:261
const fs::path & GetBlocksDirPath() const
Get blocks directory path.
Definition: system.cpp:403
@ NETWORK_ONLY
Definition: system.h:159
@ ALLOW_ANY
Definition: system.h:152
@ DEBUG_ONLY
Definition: system.h:153
@ ALLOW_INT
Definition: system.h:150
@ ALLOW_BOOL
Definition: system.h:149
@ ALLOW_STRING
Definition: system.h:151
@ SENSITIVE
Definition: system.h:161
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
Definition: system.cpp:472
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: system.cpp:482
const fs::path & GetDataDirNet() const
Get data directory path with appended network identifier.
Definition: system.h:259
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Definition: system.cpp:591
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:582
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn't already have a value.
Definition: system.cpp:618
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:601
void AddHiddenArgs(const std::vector< std::string > &args)
Add many hidden arguments.
Definition: system.cpp:671
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
Definition: system.cpp:649
const std::list< SectionInfo > GetUnrecognizedSections() const
Log warnings for unrecognized section names in the config file.
Definition: system.cpp:285
std::string GetChainName() const
Looks for -regtest, -testnet and returns the appropriate BIP70 chain name.
Definition: system.cpp:1045
std::atomic< bool > m_reopen_file
Definition: logging.h:109
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:381
void Start(Chainstate &active_chainstate)
Start initializes the sync state and registers the instance as a ValidationInterface so that it stays...
Definition: base.cpp:367
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:52
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: blockindex.h:26
int64_t GetBlockTime() const
Definition: blockindex.h:174
BlockHash GetBlockHash() const
Definition: blockindex.h:147
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: blockindex.h:39
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:157
int Height() const
Return the maximal height in the chain.
Definition: chain.h:193
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:74
bool DefaultConsistencyChecks() const
Default value for -checkmempool and -checkblockindex argument.
Definition: chainparams.h:101
std::string NetworkIDString() const
Return the BIP70 network string (main, test or regtest)
Definition: chainparams.h:121
bool RequireStandard() const
Policy: Filter transactions that do not match well-defined patterns.
Definition: chainparams.h:103
bool IsTestChain() const
If this chain is exclusively used for testing.
Definition: chainparams.h:105
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:86
const CBlock & GenesisBlock() const
Definition: chainparams.h:99
Fee rate in satoshis per kilobyte: Amount / kB.
Definition: feerate.h:21
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:544
std::string ToStringIPPort() const
uint16_t GetPort() const
static const int DEFAULT_ZMQ_SNDHWM
static CZMQNotificationInterface * Create()
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:646
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:1060
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:1203
Chainstate & ActiveChainstate() const
The most-work chain.
CBlockIndex * m_best_header
Best header we've seen so far (used for getheaders queries' starting points).
Definition: validation.h:1154
CBlockIndex * ActiveTip() const
Definition: validation.h:1201
CChain & ActiveChain() const
Definition: validation.h:1199
std::thread m_load_block
Definition: validation.h:1124
Chainstate &InitializeChainstate(CTxMemPool *mempool, const std::optional< BlockHash > &snapshot_blockhash=std::nullopt) LIFETIMEBOUND EXCLUSIVE_LOCKS_REQUIRED(std::vector< Chainstate * GetAll)()
Instantiate a new chainstate and assign it based upon whether it is from a snapshot.
Definition: validation.h:1178
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:1127
Definition: config.h:17
virtual uint64_t GetMaxBlockSize() const =0
virtual const CChainParams & GetChainParams() const =0
virtual bool SetMaxBlockSize(uint64_t maxBlockSize)=0
virtual void SetExcessUTXOCharge(Amount amt)=0
virtual void SetCashAddrEncoding(bool)=0
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(const CChainParams &chainparams, CConnman &connman, AddrMan &addrman, BanMan *banman, ChainstateManager &chainman, CTxMemPool &pool, bool ignore_incoming_txs)
Class for registering and managing all RPC calls.
Definition: server.h:39
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:200
std::string ToString() const
Definition: uint256.h:78
bool IsNull() const
Definition: uint256.h:30
std::string GetHex() const
Definition: uint256.cpp:16
std::string GetHex() const
Path class wrapper to prepare application code for transition from boost::filesystem library to std::...
Definition: fs.h:33
bool m_have_pruned
True if any block files have ever been pruned.
Definition: blockstorage.h:192
bool IsValid() const
Definition: netbase.h:38
256-bit opaque blob.
Definition: uint256.h:127
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 const uint64_t DEFAULT_MAX_BLOCK_SIZE
Default setting for maximum allowed size for a block, in bytes.
Definition: consensus.h:20
void SetupCurrencyUnitOptions(ArgsManager &argsman)
Definition: currencyunit.cpp:9
bilingual_str AmountErrMsg(const std::string &optname, const std::string &strValue)
Definition: error.cpp:51
bilingual_str ResolveErrMsg(const std::string &optname, const std::string &strBind)
Definition: error.cpp:42
uint256 SerializeHash(const T &obj, int nType=SER_GETHASH, int nVersion=PROTOCOL_VERSION)
Compute the 256-bit hash of an object's serialization.
Definition: hash.h:192
void InterruptHTTPRPC()
Interrupt HTTP RPC subsystem.
Definition: httprpc.cpp:470
void StopHTTPRPC()
Stop HTTP RPC subsystem.
Definition: httprpc.cpp:474
bool StartHTTPRPC(HTTPRPCRequestProcessor &httpRPCRequestProcessor)
Start HTTP RPC subsystem.
Definition: httprpc.cpp:449
void StartREST(const std::any &context)
Start HTTP REST subsystem.
Definition: rest.cpp:836
void StopREST()
Stop HTTP REST subsystem.
Definition: rest.cpp:848
void InterruptREST()
Interrupt RPC REST subsystem.
Definition: rest.cpp:846
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:133
static bool CreatePidFile(const ArgsManager &args)
Definition: init.cpp:140
static const bool DEFAULT_PROXYRANDOMIZE
Definition: init.cpp:116
void Interrupt(NodeContext &node)
Interrupt threads.
Definition: init.cpp:180
void InitLogging(const ArgsManager &args)
Initialize global loggers.
Definition: init.cpp:1632
bool AppInitLockDataDirectory()
Lock bitcoin data directory.
Definition: init.cpp:2106
void SetupServerArgs(NodeContext &node)
Register all arguments with the ArgsManager.
Definition: init.cpp:401
static bool AppInitServers(Config &config, HTTPRPCRequestProcessor &httpRPCRequestProcessor, NodeContext &node)
Definition: init.cpp:1473
#define MIN_CORE_FILEDESCRIPTORS
Definition: init.cpp:125
static bool fHaveGenesis
Definition: init.cpp:1448
void Shutdown(NodeContext &node)
Definition: init.cpp:204
static void HandleSIGTERM(int)
Signal handlers are very limited in what they are allowed to do.
Definition: init.cpp:363
static void OnRPCStarted()
Definition: init.cpp:389
static Mutex g_genesis_wait_mutex
Definition: init.cpp:1449
static void HandleSIGHUP(int)
Definition: init.cpp:367
static fs::path GetPidFile(const ArgsManager &args)
Definition: init.cpp:135
static std::condition_variable g_genesis_wait_cv
Definition: init.cpp:1450
bool AppInitMain(Config &config, RPCServer &rpcServer, HTTPRPCRequestProcessor &httpRPCRequestProcessor, NodeContext &node, interfaces::BlockAndHeaderTipInfo *tip_info)
Bitcoin main initialization.
Definition: init.cpp:2128
static constexpr bool DEFAULT_CHRONIK
Definition: init.cpp:118
bool AppInitBasicSetup(const ArgsManager &args)
Initialize bitcoin: Basic context setup.
Definition: init.cpp:1659
bool AppInitSanityChecks()
Initialization sanity checks: ecc init, sanity checks, dir lock.
Definition: init.cpp:2088
bool AppInitInterfaces(NodeContext &node)
Initialize node and wallet interface pointers.
Definition: init.cpp:2118
static const char * DEFAULT_ASMAP_FILENAME
Definition: init.cpp:128
void InitParameterInteraction(ArgsManager &args)
Parameter interaction: change current parameters depending on various rules.
Definition: init.cpp:1498
static void BlockNotifyGenesisWait(const CBlockIndex *pBlockIndex)
Definition: init.cpp:1452
static void OnRPCStopped()
Definition: init.cpp:394
static bool LockDataDirectory(bool probeOnly)
Definition: init.cpp:2072
static void registerSignalHandler(int signal, void(*handler)(int))
Definition: init.cpp:379
std::string LicenseInfo()
Returns licensing information (for -version)
Definition: init.cpp:1417
bool AppInitParameterInteraction(Config &config, const ArgsManager &args)
Initialization: parameter interaction.
Definition: init.cpp:1706
static const bool DEFAULT_REST_ENABLE
Definition: init.cpp:117
static boost::signals2::connection rpc_notify_block_change_connection
Definition: init.cpp:388
static void new_handler_terminate()
Definition: init.cpp:1648
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:19
#define LogPrint(category,...)
Definition: logging.h:208
#define LogPrintf(...)
Definition: logging.h:204
void StartMapPort(bool use_upnp, bool use_natpmp)
Definition: mapport.cpp:358
void StopMapPort()
Definition: mapport.cpp:364
void InterruptMapPort()
Definition: mapport.cpp:361
static constexpr bool DEFAULT_NATPMP
Definition: mapport.h:17
static constexpr bool DEFAULT_UPNP
Definition: mapport.h:11
static const unsigned int DEFAULT_DESCENDANT_SIZE_LIMIT
Default for -limitdescendantsize, maximum kilobytes of in-mempool descendants.
Definition: mempool.h:29
static constexpr unsigned int DEFAULT_ANCESTOR_SIZE_LIMIT
Default for -limitancestorsize, maximum kilobytes of tx + all in-mempool ancestors.
Definition: mempool.h:22
static constexpr unsigned int DEFAULT_DESCENDANT_LIMIT
Default for -limitdescendantcount, max number of in-mempool descendants.
Definition: mempool.h:24
static constexpr unsigned int DEFAULT_ANCESTOR_LIMIT
Default for -limitancestorcount, max number of in-mempool ancestors.
Definition: mempool.h:17
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:46
void OnStarted(std::function< void()> slot)
Definition: server.cpp:108
void OnStopped(std::function< void()> slot)
Definition: server.cpp:112
static constexpr Amount PROOF_DUST_THRESHOLD
Minimum amount per utxo.
Definition: proof.h:40
static auto quoted(const std::string &s)
Definition: fs.h:99
static bool exists(const path &p)
Definition: fs.h:94
static std::string PathToString(const path &path)
Convert path object to byte string.
Definition: fs.h:134
static path PathFromString(const std::string &string)
Convert byte string to path object.
Definition: fs.h:147
fs::ofstream ofstream
Definition: fs.h:247
std::string get_filesystem_error_message(const fs::filesystem_error &e)
Definition: fs.cpp:139
void AddLoggingArgs(ArgsManager &argsman)
Definition: common.cpp:64
void SetLoggingCategories(const ArgsManager &args)
Definition: common.cpp:160
bool SanityChecks()
Ensure a usable environment with all necessary library support.
Definition: common.cpp:42
void SetGlobals()
Definition: common.cpp:29
bool StartLogging(const ArgsManager &args)
Definition: common.cpp:188
void SetLoggingOptions(const ArgsManager &args)
Definition: common.cpp:139
void UnsetGlobals()
Definition: common.cpp:37
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:778
Definition: init.h:28
const CBlockIndex *GetFirstStoredBlock(const CBlockIndex *start_block) EXCLUSIVE_LOCKS_REQUIRED(voi CleanupBlockRevFiles)()
Find the first block that is not pruned.
Definition: blockstorage.h:204
bool fPruneMode
Pruning-related variables and constants.
ChainstateLoadVerifyError
Definition: chainstate.h:70
CacheSizes CalculateCacheSizes(const ArgsManager &args, size_t n_indexes)
Definition: caches.cpp:12
uint64_t nPruneTarget
Number of MiB of block files that we're trying to stay below.
static constexpr bool DEFAULT_STOPAFTERBLOCKIMPORT
Definition: blockstorage.h:37
void ThreadImport(const Config &config, ChainstateManager &chainman, std::vector< fs::path > vImportFiles, const ArgsManager &args)
std::optional< ChainstateLoadVerifyError > VerifyLoadedChainstate(ChainstateManager &chainman, bool fReset, bool fReindexChainState, const Config &config, unsigned int check_blocks, unsigned int check_level, std::function< int64_t()> get_unix_time_seconds)
Definition: chainstate.cpp:135
std::optional< ChainstateLoadingError > LoadChainstate(bool fReset, ChainstateManager &chainman, CTxMemPool *mempool, bool fPruneMode_, const Consensus::Params &consensus_params, bool fReindexChainState, int64_t nBlockTreeDBCache, int64_t nCoinDBCache, int64_t nCoinCacheUsage, bool block_tree_db_in_memory, bool coins_db_in_memory, std::function< bool()> shutdown_requested, std::function< void()> coins_error_cb)
This sequence can have 4 types of outcomes:
Definition: chainstate.cpp:14
std::atomic_bool fReindex
ChainstateLoadingError
Definition: chainstate.h:21
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:1111
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:134
bool fDiscover
Definition: net.cpp:123
bool fListen
Definition: net.cpp:124
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
Definition: net.cpp:278
bool AddLocal(const CService &addr, int nScore)
Definition: net.cpp:239
void Discover()
Definition: net.cpp:2773
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
Definition: net.h:91
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
Definition: net.h:67
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
Definition: net.h:74
static const size_t DEFAULT_MAXSENDBUFFER
Definition: net.h:105
static const int NUM_FDS_MESSAGE_CAPTURE
Number of file descriptors required for message capture.
Definition: net.h:99
static const bool DEFAULT_BLOCKSONLY
Default for blocks only.
Definition: net.h:95
static const bool DEFAULT_WHITELISTFORCERELAY
Default for -whitelistforcerelay.
Definition: net.h:55
static const bool DEFAULT_FORCEDNSSEED
Definition: net.h:101
static const bool DEFAULT_WHITELISTRELAY
Default for -whitelistrelay.
Definition: net.h:53
static constexpr uint64_t DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
Definition: net.h:93
static const size_t DEFAULT_MAXRECEIVEBUFFER
Definition: net.h:104
static const int DEFAULT_MAX_AVALANCHE_OUTBOUND_CONNECTIONS
Maximum number of avalanche enabled outgoing connections by default.
Definition: net.h:81
static const bool DEFAULT_FIXEDSEEDS
Definition: net.h:103
static const int MAX_FEELER_CONNECTIONS
Maximum number of feeler connections.
Definition: net.h:83
static const bool DEFAULT_LISTEN
-listen default
Definition: net.h:85
static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT
-peertimeout default
Definition: net.h:97
static const bool DEFAULT_DNSSEED
Definition: net.h:102
static const int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS
Maximum number of automatic outgoing nodes over which we'll relay everything (blocks,...
Definition: net.h:72
@ LOCAL_MANUAL
Definition: net.h:225
static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
Definition: net.h:76
const std::vector< std::string > NET_PERMISSIONS_DOC
static const unsigned int DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN
Default number of orphan+recently-replaced txn to keep around for block reconstruction.
static const unsigned int 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:12
bool fIsBareMultisigStd
Definition: settings.cpp:10
CFeeRate dustRelayFee
Definition: settings.cpp:11
static const 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:24
static const Amount DUST_RELAY_TX_FEE(1000 *SATOSHI)
Min feerate for defining dust.
static const 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 const unsigned int DEFAULT_BYTES_PER_SIGCHECK
Default for -bytespersigcheck .
Definition: policy.h:57
static const unsigned int DEFAULT_MAX_MEMPOOL_SIZE
Default for -maxmempool, maximum megabytes of mempool memory usage.
Definition: policy.h:48
static const bool DEFAULT_PERMIT_BAREMULTISIG
Default for -permitbaremultisig.
Definition: policy.h:59
static constexpr std::chrono::milliseconds AVALANCHE_DEFAULT_QUERY_TIMEOUT
How long before we consider that a query timed out.
Definition: processor.h:55
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:338
@ NODE_NETWORK_LIMITED
Definition: protocol.h:368
@ NODE_BLOOM
Definition: protocol.h:355
@ NODE_NETWORK
Definition: protocol.h:345
@ NODE_COMPACT_FILTERS
Definition: protocol.h:363
@ NODE_AVALANCHE
Definition: protocol.h:383
void RandAddPeriodic() noexcept
Gather entropy from various expensive sources, and feed them to the PRNG state.
Definition: random.cpp:640
uint64_t GetRand(uint64_t nMax) noexcept
Generate a uniform random integer in the range [0..range).
Definition: random.cpp:650
static void RegisterAllRPCCommands(const Config &config, RPCServer &rpcServer, CRPCTable &rpcTable)
Register all context-sensitive RPC commands.
Definition: register.h:38
const char * prefix
Definition: rest.cpp:821
bool(* handler)(Config &config, const std::any &context, HTTPRequest *req, const std::string &strReq)
Definition: rest.cpp:822
const char * name
Definition: rest.cpp:49
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:23
void InitScriptExecutionCache()
Initializes the script-execution cache.
Definition: scriptcache.cpp:76
static const unsigned int DEFAULT_MAX_SCRIPT_CACHE_SIZE
Definition: scriptcache.h:48
void SetRPCWarmupFinished()
Mark warmup as done.
Definition: server.cpp:391
void StartRPC()
Definition: server.cpp:346
void StopRPC()
Definition: server.cpp:363
void InterruptRPC()
Definition: server.cpp:352
void SetRPCWarmupStatus(const std::string &newStatus)
Set the RPC warmup status.
Definition: server.cpp:386
CRPCTable tableRPC
Definition: server.cpp:607
void RpcInterruptionPoint()
Throw JSONRPCError if RPC is not running.
Definition: server.cpp:380
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
void InitSignatureCache()
Definition: sigcache.cpp:78
static const unsigned int DEFAULT_MAX_SIG_CACHE_SIZE
Definition: sigcache.h:17
bool fAcceptDatacarrier
A data carrying output is an unspendable output containing data.
Definition: standard.cpp:15
static const unsigned int MAX_OP_RETURN_RELAY
Default setting for nMaxDatacarrierBytes.
Definition: standard.h:38
static const bool DEFAULT_ACCEPT_DATACARRIER
Definition: standard.h:19
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
bool IsHexNumber(const std::string &str)
Return true if the string is a hex number, optionally prefixed with "0x".
@ SAFE_CHARS_UA_COMMENT
BIP-0014 subset.
Definition: strencodings.h:24
void ReplaceAll(std::string &in_out, std::string_view search, std::string_view substitute)
Definition: string.cpp:9
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:46
Definition: amount.h:19
static constexpr Amount zero()
Definition: amount.h:32
static BlockHash fromHex(const std::string &str)
Definition: blockhash.h:17
int m_max_outbound_block_relay
Definition: net.h:920
unsigned int nReceiveFloodSize
Definition: net.h:928
int m_max_outbound_full_relay
Definition: net.h:919
std::vector< NetWhitebindPermissions > vWhiteBinds
Definition: net.h:933
uint64_t nMaxOutboundLimit
Definition: net.h:929
std::vector< NetWhitelistPermissions > vWhitelistedRange
Definition: net.h:932
CClientUIInterface * uiInterface
Definition: net.h:924
int m_max_avalanche_outbound
Definition: net.h:921
std::vector< CService > onion_binds
Definition: net.h:935
int nMaxFeeler
Definition: net.h:923
std::vector< std::string > m_specified_outgoing
Definition: net.h:940
int nMaxConnections
Definition: net.h:918
ServiceFlags nLocalServices
Definition: net.h:917
std::vector< std::string > m_added_nodes
Definition: net.h:941
int64_t m_peer_connect_timeout
Definition: net.h:930
std::vector< CService > vBinds
Definition: net.h:934
unsigned int nSendBufferMaxSize
Definition: net.h:927
bool m_i2p_accept_incoming
Definition: net.h:942
std::vector< std::string > vSeedNodes
Definition: net.h:931
BanMan * m_banman
Definition: net.h:926
bool m_use_addrman_outgoing
Definition: net.h:939
std::vector< NetEventsInterface * > m_msgproc
Definition: net.h:925
bool bind_on_any
True if the user did not specify -bind= or -whitebind= and thus we should bind on 0....
Definition: net.h:938
int nMaxAddnode
Definition: net.h:922
BlockHash defaultAssumeValid
Definition: params.h:82
uint256 nMinimumChainWork
Definition: params.h:81
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
std::string original
Definition: translation.h:18
Block and header tip information.
Definition: node.h:48
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
NodeContext struct containing references to chain state and connection state.
Definition: context.h:38
#define WAIT_LOCK(cs, name)
Definition: sync.h:251
#define LOCK(cs)
Definition: sync.h:243
#define TRY_LOCK(cs, name)
Definition: sync.h:249
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
Definition: system.cpp:766
fs::path AbsPathForConfigVal(const fs::path &path, bool net_specific)
Most paths passed as configuration arguments are treated as relative to the datadir if they are not a...
Definition: system.cpp:1383
const char *const BITCOIN_SETTINGS_FILENAME
Definition: system.cpp:73
std::string CopyrightHolders(const std::string &strPrefix)
Definition: system.cpp:1373
bool LockDirectory(const fs::path &directory, const std::string lockfile_name, bool probe_only)
Definition: system.cpp:87
bool DirIsWritable(const fs::path &directory)
Definition: system.cpp:126
bool SetupNetworking()
Definition: system.cpp:1356
int RaiseFileDescriptorLimit(int nMinFD)
This function tries to raise the file descriptor limit to the requested number.
Definition: system.cpp:1200
ArgsManager gArgs
Definition: system.cpp:75
bool CheckDiskSpace(const fs::path &dir, uint64_t additional_bytes)
Definition: system.cpp:140
const char *const BITCOIN_CONF_FILENAME
Definition: system.cpp:72
int GetNumCores()
Return the number of cores available on the current system.
Definition: system.cpp:1369
bool error(const char *fmt, const Args &...args)
Definition: system.h:45
int64_t GetTimeMillis()
Returns the system time (not mockable)
Definition: time.cpp:106
void SetMockTime(int64_t nMockTimeIn)
DEPRECATED Use SetMockTime with chrono type.
Definition: time.cpp:94
T GetTime()
Return system time (or mocked time, if set)
Definition: time.cpp:71
static const int64_t DEFAULT_MAX_TIME_ADJUSTMENT
Definition: timedata.h:13
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1201
CService DefaultOnionServiceTarget()
Definition: torcontrol.cpp:870
const std::string DEFAULT_TOR_CONTROL
Default control port.
Definition: torcontrol.cpp:39
void InterruptTorControl()
Definition: torcontrol.cpp:852
void StartTorControl(CService onion_service_target)
Definition: torcontrol.cpp:833
void StopTorControl()
Definition: torcontrol.cpp:862
static const bool DEFAULT_LISTEN_ONION
Definition: torcontrol.h:16
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:55
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:36
std::optional< bilingual_str > CheckLegacyTxindex(CBlockTreeDB &block_tree_db)
Definition: txdb.cpp:36
static constexpr int64_t MAX_DB_CACHE_MB
max. -dbcache (MiB)
Definition: txdb.h:32
static constexpr int64_t MIN_DB_CACHE_MB
min. -dbcache (MiB)
Definition: txdb.h:30
static constexpr int64_t DEFAULT_DB_BATCH_SIZE
-dbbatchsize default (bytes)
Definition: txdb.h:36
static constexpr int64_t DEFAULT_DB_CACHE_MB
-dbcache default (MiB)
Definition: txdb.h:34
std::unique_ptr< TxIndex > g_txindex
The global transaction index, used in GetTransaction. May be null.
Definition: txindex.cpp:17
CClientUIInterface uiInterface
void InitWarning(const bilingual_str &str)
Show warning message.
bool InitError(const bilingual_str &str)
Show error message.
uint256 uint256S(const char *str)
uint256 from const char *.
Definition: uint256.h:141
void StartScriptCheckWorkerThreads(int threads_num)
Run instances of script checking worker threads.
arith_uint256 nMinimumChainWork
Minimum work we will assume exists on some valid chain.
Definition: validation.cpp:124
bool fCheckBlockIndex
Definition: validation.cpp:119
std::condition_variable g_best_block_cv
Definition: validation.cpp:116
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...
bool DumpMempool(const CTxMemPool &pool)
Dump the mempool to disk.
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation)
Definition: validation.cpp:126
void StopScriptCheckWorkerThreads()
Stop all of the script checking worker threads.
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument 'checklevel'.
Definition: validation.cpp:92
BlockHash hashAssumeValid
Block hash whose ancestors we will assume to have valid scripts without checking them.
Definition: validation.cpp:123
bool fCheckpointsEnabled
Definition: validation.cpp:120
bool fRequireStandard
Definition: validation.cpp:118
int64_t nMaxTipAge
If the tip is older than this (in seconds), the node is considered to be in initial block download.
Definition: validation.cpp:121
assert(!tx.IsCoinBase())
static const bool DEFAULT_CHECKPOINTS_ENABLED
Definition: validation.h:86
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:118
static const unsigned int DEFAULT_CHECKLEVEL
Definition: validation.h:104
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:102
static const Amount DEFAULT_MIN_RELAY_TX_FEE_PER_KB(1000 *SATOSHI)
Default for -minrelaytxfee, minimum relay fee for transactions.
static const int MAX_SCRIPTCHECK_THREADS
Maximum number of dedicated script-checking threads allowed.
Definition: validation.h:82
static const Amount DEFAULT_UTXO_FEE
Default for -excessutxocharge for transactions transactions.
Definition: validation.h:75
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition: validation.h:121
static const int DEFAULT_SCRIPTCHECK_THREADS
-par default (number of script-checking threads, 0 = auto)
Definition: validation.h:84
static const char *const DEFAULT_BLOCKFILTERINDEX
Definition: validation.h:89
static const unsigned int DEFAULT_MEMPOOL_EXPIRY
Default for -mempoolexpiry, expiration time for mempool transactions in hours.
Definition: validation.h:80
static constexpr bool DEFAULT_COINSTATSINDEX
Definition: validation.h:88
static const int64_t DEFAULT_MAX_TIP_AGE
Definition: validation.h:85
static const signed int DEFAULT_CHECKBLOCKS
Definition: validation.h:103
static const bool DEFAULT_PERSIST_MEMPOOL
Default for -persistmempool.
Definition: validation.h:92
static const bool DEFAULT_PEERBLOOMFILTERS
Definition: validation.h:94
static const int DEFAULT_STOPATHEIGHT
Default for -stopatheight.
Definition: validation.h:97
static const bool DEFAULT_TXINDEX
Definition: validation.h:87
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
CZMQNotificationInterface * g_zmq_notification_interface
void RegisterZMQRPCCommands(CRPCTable &t)
Definition: zmqrpc.cpp:68