Bitcoin ABC  0.24.11
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 <amount.h>
14 #include <avalanche/avalanche.h>
15 #include <avalanche/processor.h>
16 #include <avalanche/proof.h> // For AVALANCHE_LEGACY_PROOF_DEFAULT
17 #include <avalanche/validation.h>
18 #include <banman.h>
19 #include <blockdb.h>
20 #include <blockfilter.h>
21 #include <chain.h>
22 #include <chainparams.h>
23 #include <checkpoints.h>
24 #include <compat/sanity.h>
25 #include <config.h>
26 #include <consensus/validation.h>
27 #include <currencyunit.h>
28 #include <flatfile.h>
29 #include <fs.h>
30 #include <hash.h>
31 #include <httprpc.h>
32 #include <httpserver.h>
33 #include <index/blockfilterindex.h>
34 #include <index/txindex.h>
35 #include <interfaces/chain.h>
36 #include <interfaces/node.h>
37 #include <key.h>
38 #include <miner.h>
39 #include <net.h>
40 #include <net_permissions.h>
41 #include <net_processing.h>
42 #include <netbase.h>
43 #include <network.h>
44 #include <node/context.h>
45 #include <node/ui_interface.h>
46 #include <policy/mempool.h>
47 #include <policy/policy.h>
48 #include <policy/settings.h>
49 #include <rpc/blockchain.h>
50 #include <rpc/register.h>
51 #include <rpc/server.h>
52 #include <rpc/util.h>
53 #include <scheduler.h>
54 #include <script/scriptcache.h>
55 #include <script/sigcache.h>
56 #include <script/standard.h>
57 #include <shutdown.h>
58 #include <sync.h>
59 #include <timedata.h>
60 #include <torcontrol.h>
61 #include <txdb.h>
62 #include <txmempool.h>
63 #include <util/asmap.h>
64 #include <util/check.h>
65 #include <util/moneystr.h>
66 #include <util/string.h>
67 #include <util/threadnames.h>
68 #include <util/translation.h>
69 #include <validation.h>
70 #include <validationinterface.h>
71 #include <walletinitinterface.h>
72 
73 #include <boost/algorithm/string/replace.hpp>
74 #include <boost/signals2/signal.hpp>
75 #include <boost/thread/thread.hpp>
76 
77 #if ENABLE_ZMQ
80 #include <zmq/zmqrpc.h>
81 #endif
82 
83 #ifndef WIN32
84 #include <attributes.h>
85 #include <cerrno>
86 #include <csignal>
87 #include <sys/stat.h>
88 #endif
89 #include <cstdint>
90 #include <cstdio>
91 #include <functional>
92 #include <set>
93 
94 static const bool DEFAULT_PROXYRANDOMIZE = true;
95 static const bool DEFAULT_REST_ENABLE = false;
96 static const bool DEFAULT_STOPAFTERBLOCKIMPORT = false;
97 
98 #ifdef WIN32
99 // Win32 LevelDB doesn't use filedescriptors, and the ones used for accessing
100 // block files don't count towards the fd_set size limit anyway.
101 #define MIN_CORE_FILEDESCRIPTORS 0
102 #else
103 #define MIN_CORE_FILEDESCRIPTORS 150
104 #endif
105 
106 static const char *DEFAULT_ASMAP_FILENAME = "ip_asn.map";
107 
111 static const char *BITCOIN_PID_FILENAME = "bitcoind.pid";
112 
113 static fs::path GetPidFile(const ArgsManager &args) {
114  return AbsPathForConfigVal(
116 }
117 
118 [[nodiscard]] static bool CreatePidFile(const ArgsManager &args) {
119  fsbridge::ofstream file{GetPidFile(args)};
120  if (file) {
121 #ifdef WIN32
122  tfm::format(file, "%d\n", GetCurrentProcessId());
123 #else
124  tfm::format(file, "%d\n", getpid());
125 #endif
126  return true;
127  } else {
128  return InitError(strprintf(_("Unable to create the PID file '%s': %s"),
130  std::strerror(errno)));
131  }
132 }
133 
135 //
136 // Shutdown
137 //
138 
139 //
140 // Thread management and startup/shutdown:
141 //
142 // The network-processing threads are all part of a thread group created by
143 // AppInit() or the Qt main() function.
144 //
145 // A clean exit happens when StartShutdown() or the SIGTERM signal handler sets
146 // fRequestShutdown, which makes main thread's WaitForShutdown() interrupts the
147 // thread group.
148 // And then, WaitForShutdown() makes all other on-going threads in the thread
149 // group join the main thread.
150 // Shutdown() is then called to clean up database connections, and stop other
151 // threads that should only be stopped after the main network-processing threads
152 // have exited.
153 //
154 // Shutdown for Qt is very similar, only it uses a QTimer to detect
155 // ShutdownRequested() getting set, and then does the normal Qt shutdown thing.
156 //
157 
158 static std::unique_ptr<ECCVerifyHandle> globalVerifyHandle;
159 
160 static std::thread g_load_block;
161 
162 static boost::thread_group threadGroup;
163 
164 void Interrupt(NodeContext &node) {
167  InterruptRPC();
168  InterruptREST();
171  if (g_avalanche) {
172  // Avalanche needs to be stopped before we interrupt the thread group as
173  // the scheduler will stop working then.
174  g_avalanche->stopEventLoop();
175  }
176  if (node.connman) {
177  node.connman->Interrupt();
178  }
179  if (g_txindex) {
180  g_txindex->Interrupt();
181  }
182  ForEachBlockFilterIndex([](BlockFilterIndex &index) { index.Interrupt(); });
183 }
184 
185 void Shutdown(NodeContext &node) {
186  static Mutex g_shutdown_mutex;
187  TRY_LOCK(g_shutdown_mutex, lock_shutdown);
188  if (!lock_shutdown) {
189  return;
190  }
191  LogPrintf("%s: In progress...\n", __func__);
192  Assert(node.args);
193 
198  util::ThreadRename("shutoff");
199  if (node.mempool) {
200  node.mempool->AddTransactionsUpdated(1);
201  }
202 
203  StopHTTPRPC();
204  StopREST();
205  StopRPC();
206  StopHTTPServer();
207  for (const auto &client : node.chain_clients) {
208  client->flush();
209  }
210  StopMapPort();
211 
212  // Because avalanche and the network depend on each other, it is important
213  // to shut them down in this order:
214  // 1. Stop avalanche event loop.
215  // 2. Shutdown network processing.
216  // 3. Destroy avalanche::Processor.
217  // 4. Destroy CConnman
218  if (g_avalanche) {
219  g_avalanche->stopEventLoop();
220  }
221 
222  // Because these depend on each-other, we make sure that neither can be
223  // using the other before destroying them.
224  if (node.peerman) {
226  }
227  // Follow the lock order requirements:
228  // * CheckForStaleTipAndEvictPeers locks cs_main before indirectly calling
229  // GetExtraFullOutboundCount which locks cs_vNodes.
230  // * ProcessMessage locks cs_main and g_cs_orphans before indirectly calling
231  // ForEachNode which locks cs_vNodes.
232  // * CConnman::Stop calls DeleteNode, which calls FinalizeNode, which locks
233  // cs_main and calls EraseOrphansFor, which locks g_cs_orphans.
234  //
235  // Thus the implicit locking order requirement is:
236  // (1) cs_main, (2) g_cs_orphans, (3) cs_vNodes.
237  if (node.connman) {
238  node.connman->StopThreads();
239  LOCK2(::cs_main, ::g_cs_orphans);
240  node.connman->StopNodes();
241  }
242 
243  StopTorControl();
244 
245  // After everything has been shut down, but before things get flushed, stop
246  // the CScheduler/checkqueue, threadGroup and load block thread.
247  if (node.scheduler) {
248  node.scheduler->stop();
249  }
250  if (g_load_block.joinable()) {
251  g_load_block.join();
252  }
253  threadGroup.interrupt_all();
254  threadGroup.join_all();
255 
256  // After the threads that potentially access these pointers have been
257  // stopped, destruct and reset all to nullptr.
258  node.peerman.reset();
259 
260  // Destroy various global instances
261  g_avalanche.reset();
262  node.connman.reset();
263  node.banman.reset();
264 
265  if (node.mempool && node.mempool->IsLoaded() &&
266  node.args->GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
267  DumpMempool(*node.mempool);
268  }
269 
270  // FlushStateToDisk generates a ChainStateFlushed callback, which we should
271  // avoid missing
272  if (node.chainman) {
273  LOCK(cs_main);
274  for (CChainState *chainstate : node.chainman->GetAll()) {
275  if (chainstate->CanFlushToDisk()) {
276  chainstate->ForceFlushStateToDisk();
277  }
278  }
279  }
280 
281  // After there are no more peers/RPC left to give us new data which may
282  // generate CValidationInterface callbacks, flush them...
284 
285  // Stop and delete all indexes only after flushing background callbacks.
286  if (g_txindex) {
287  g_txindex->Stop();
288  g_txindex.reset();
289  }
290  ForEachBlockFilterIndex([](BlockFilterIndex &index) { index.Stop(); });
292 
293  // Any future callbacks will be dropped. This should absolutely be safe - if
294  // missing a callback results in an unrecoverable situation, unclean
295  // shutdown would too. The only reason to do the above flushes is to let the
296  // wallet catch up with our current chain to avoid any strange pruning edge
297  // cases and make next startup faster by avoiding rescan.
298 
299  if (node.chainman) {
300  LOCK(cs_main);
301  for (CChainState *chainstate : node.chainman->GetAll()) {
302  if (chainstate->CanFlushToDisk()) {
303  chainstate->ForceFlushStateToDisk();
304  chainstate->ResetCoinsViews();
305  }
306  }
307  pblocktree.reset();
308  }
309  for (const auto &client : node.chain_clients) {
310  client->stop();
311  }
312 
313 #if ENABLE_ZMQ
318  }
319 #endif
320 
321  node.chain_clients.clear();
324  globalVerifyHandle.reset();
325  ECC_Stop();
326  node.mempool.reset();
327  node.chainman = nullptr;
328  node.scheduler.reset();
329 
330  try {
331  if (!fs::remove(GetPidFile(*node.args))) {
332  LogPrintf("%s: Unable to remove PID file: File does not exist\n",
333  __func__);
334  }
335  } catch (const fs::filesystem_error &e) {
336  LogPrintf("%s: Unable to remove PID file: %s\n", __func__,
338  }
339 
340  node.args = nullptr;
341  LogPrintf("%s: done\n", __func__);
342 }
343 
349 #ifndef WIN32
350 static void HandleSIGTERM(int) {
351  StartShutdown();
352 }
353 
354 static void HandleSIGHUP(int) {
355  LogInstance().m_reopen_file = true;
356 }
357 #else
358 static BOOL WINAPI consoleCtrlHandler(DWORD dwCtrlType) {
359  StartShutdown();
360  Sleep(INFINITE);
361  return true;
362 }
363 #endif
364 
365 #ifndef WIN32
366 static void registerSignalHandler(int signal, void (*handler)(int)) {
367  struct sigaction sa;
368  sa.sa_handler = handler;
369  sigemptyset(&sa.sa_mask);
370  sa.sa_flags = 0;
371  sigaction(signal, &sa, NULL);
372 }
373 #endif
374 
375 static boost::signals2::connection rpc_notify_block_change_connection;
376 static void OnRPCStarted() {
377  rpc_notify_block_change_connection = uiInterface.NotifyBlockTip_connect(
378  std::bind(RPCNotifyBlockChange, std::placeholders::_2));
379 }
380 
381 static void OnRPCStopped() {
383  RPCNotifyBlockChange(nullptr);
384  g_best_block_cv.notify_all();
385  LogPrint(BCLog::RPC, "RPC stopped.\n");
386 }
387 
389  assert(!node.args);
390  node.args = &gArgs;
391  ArgsManager &argsman = *node.args;
392 
393  SetupHelpOptions(argsman);
394  SetupCurrencyUnitOptions(argsman);
395  // server-only for now
396  argsman.AddArg("-help-debug",
397  "Print help message with debugging options and exit", false,
399 
400  const auto defaultBaseParams =
402  const auto testnetBaseParams =
404  const auto regtestBaseParams =
406  const auto defaultChainParams = CreateChainParams(CBaseChainParams::MAIN);
407  const auto testnetChainParams =
409  const auto regtestChainParams =
411 
412  // Hidden Options
413  std::vector<std::string> hidden_args = {
414  "-dbcrashratio", "-forcecompactdb", "-maxaddrtosend", "-parkdeepreorg",
415  "-automaticunparking", "-replayprotectionactivationtime",
416  "-enableminerfund",
417  // GUI args. These will be overwritten by SetupUIArgs for the GUI
418  "-allowselfsignedrootcertificates", "-choosedatadir", "-lang=<lang>",
419  "-min", "-resetguisettings", "-rootcertificates=<file>", "-splash",
420  "-uiplatform",
421  // TODO remove after the November 2020 upgrade
422  "-axionactivationtime"};
423 
424  // Set all of the args and their help
425  // When adding new options to the categories, please keep and ensure
426  // alphabetical ordering. Do not translate _(...) -help-debug options, Many
427  // technical terms, and only a very small audience, so is unnecessary stress
428  // to translators.
429  argsman.AddArg("-version", "Print version and exit", ArgsManager::ALLOW_ANY,
431 #if defined(HAVE_SYSTEM)
432  argsman.AddArg(
433  "-alertnotify=<cmd>",
434  "Execute command when a relevant alert is received or we see "
435  "a really long fork (%s in cmd is replaced by message)",
437 #endif
438  argsman.AddArg(
439  "-assumevalid=<hex>",
440  strprintf(
441  "If this block is in the chain assume that it and its ancestors "
442  "are valid and potentially skip their script verification (0 to "
443  "verify all, default: %s, testnet: %s)",
444  defaultChainParams->GetConsensus().defaultAssumeValid.GetHex(),
445  testnetChainParams->GetConsensus().defaultAssumeValid.GetHex()),
447  argsman.AddArg("-blocksdir=<dir>",
448  "Specify directory to hold blocks subdirectory for *.dat "
449  "files (default: <datadir>)",
451 #if defined(HAVE_SYSTEM)
452  argsman.AddArg("-blocknotify=<cmd>",
453  "Execute command when the best block changes (%s in cmd is "
454  "replaced by block hash)",
456 #endif
457  argsman.AddArg("-blockreconstructionextratxn=<n>",
458  strprintf("Extra transactions to keep in memory for compact "
459  "block reconstructions (default: %u)",
462  argsman.AddArg(
463  "-blocksonly",
464  strprintf("Whether to reject transactions from network peers. "
465  "Automatic broadcast and rebroadcast of any transactions "
466  "from inbound peers is disabled, unless the peer has the "
467  "'forcerelay' permission. RPC transactions are"
468  " not affected. (default: %u)",
471  argsman.AddArg(
472  "-conf=<file>",
473  strprintf("Specify path to read-only configuration file. Relative "
474  "paths will be prefixed by datadir location. (default: %s)",
477  argsman.AddArg("-datadir=<dir>", "Specify data directory",
479  argsman.AddArg(
480  "-dbbatchsize",
481  strprintf("Maximum database write batch size in bytes (default: %u)",
485  argsman.AddArg(
486  "-dbcache=<n>",
487  strprintf("Set database cache size in MiB (%d to %d, default: %d)",
490  argsman.AddArg(
491  "-debuglogfile=<file>",
492  strprintf("Specify location of debug log file. Relative paths "
493  "will be prefixed by a net-specific datadir "
494  "location. (0 to disable; default: %s)",
497  argsman.AddArg("-feefilter",
498  strprintf("Tell other nodes to filter invs to us by our "
499  "mempool min fee (default: %d)",
503  argsman.AddArg(
504  "-finalizationdelay=<n>",
505  strprintf("Set the minimum amount of time to wait between a "
506  "block header reception and the block finalization. "
507  "Unit is seconds (default: %d)",
510  argsman.AddArg(
511  "-includeconf=<file>",
512  "Specify additional configuration file, relative to the -datadir path "
513  "(only useable from configuration file, not command line)",
515  argsman.AddArg("-maxreorgdepth=<n>",
516  strprintf("Configure at what depth blocks are considered "
517  "final (default: %d). Use -1 to disable.",
520  argsman.AddArg("-loadblock=<file>",
521  "Imports blocks from external file on startup",
523  argsman.AddArg("-maxmempool=<n>",
524  strprintf("Keep the transaction memory pool below <n> "
525  "megabytes (default: %u)",
528  argsman.AddArg("-maxorphantx=<n>",
529  strprintf("Keep at most <n> unconnectable transactions in "
530  "memory (default: %u)",
533  argsman.AddArg("-mempoolexpiry=<n>",
534  strprintf("Do not keep transactions in the mempool longer "
535  "than <n> hours (default: %u)",
538  argsman.AddArg(
539  "-minimumchainwork=<hex>",
540  strprintf(
541  "Minimum work assumed to exist on a valid chain in hex "
542  "(default: %s, testnet: %s)",
543  defaultChainParams->GetConsensus().nMinimumChainWork.GetHex(),
544  testnetChainParams->GetConsensus().nMinimumChainWork.GetHex()),
547  argsman.AddArg(
548  "-par=<n>",
549  strprintf("Set the number of script verification threads (%u to %d, 0 "
550  "= auto, <0 = leave that many cores free, default: %d)",
554  argsman.AddArg("-persistmempool",
555  strprintf("Whether to save the mempool on shutdown and load "
556  "on restart (default: %u)",
559  argsman.AddArg(
560  "-pid=<file>",
561  strprintf("Specify pid file. Relative paths will be prefixed "
562  "by a net-specific datadir location. (default: %s)",
565  argsman.AddArg(
566  "-prune=<n>",
567  strprintf("Reduce storage requirements by enabling pruning (deleting) "
568  "of old blocks. This allows the pruneblockchain RPC to be "
569  "called to delete specific blocks, and enables automatic "
570  "pruning of old blocks if a target size in MiB is provided. "
571  "This mode is incompatible with -txindex and -rescan. "
572  "Warning: Reverting this setting requires re-downloading the "
573  "entire blockchain. (default: 0 = disable pruning blocks, 1 "
574  "= allow manual pruning via RPC, >=%u = automatically prune "
575  "block files to stay under the specified target size in MiB)",
576  MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024),
578  argsman.AddArg(
579  "-reindex-chainstate",
580  "Rebuild chain state from the currently indexed blocks. When "
581  "in pruning mode or if blocks on disk might be corrupted, use "
582  "full -reindex instead.",
584  argsman.AddArg(
585  "-reindex",
586  "Rebuild chain state and block index from the blk*.dat files on disk",
588  argsman.AddArg(
589  "-settings=<file>",
590  strprintf(
591  "Specify path to dynamic settings data file. Can be disabled with "
592  "-nosettings. File is written at runtime and not meant to be "
593  "edited by users (use %s instead for custom settings). Relative "
594  "paths will be prefixed by datadir location. (default: %s)",
597 #if HAVE_SYSTEM
598  argsman.AddArg("-startupnotify=<cmd>", "Execute command on startup.",
600 #endif
601 #ifndef WIN32
602  argsman.AddArg(
603  "-sysperms",
604  "Create new files with system default permissions, instead of umask "
605  "077 (only effective with disabled wallet functionality)",
607 #else
608  hidden_args.emplace_back("-sysperms");
609 #endif
610  argsman.AddArg("-txindex",
611  strprintf("Maintain a full transaction index, used by the "
612  "getrawtransaction rpc call (default: %d)",
615  argsman.AddArg(
616  "-blockfilterindex=<type>",
617  strprintf("Maintain an index of compact filters by block "
618  "(default: %s, values: %s).",
620  " If <type> is not supplied or if <type> = 1, indexes for "
621  "all known types are enabled.",
623  argsman.AddArg(
624  "-usecashaddr",
625  "Use Cash Address for destination encoding instead of base58 "
626  "(activate by default on Jan, 14)",
628 
629  argsman.AddArg(
630  "-addnode=<ip>",
631  "Add a node to connect to and attempt to keep the connection "
632  "open (see the `addnode` RPC command help for more info)",
635  argsman.AddArg("-asmap=<file>",
636  strprintf("Specify asn mapping used for bucketing of the "
637  "peers (default: %s). Relative paths will be "
638  "prefixed by the net-specific datadir location.",
641  argsman.AddArg("-bantime=<n>",
642  strprintf("Default duration (in seconds) of manually "
643  "configured bans (default: %u)",
646  argsman.AddArg(
647  "-bind=<addr>[:<port>][=onion]",
648  strprintf("Bind to given address and always listen on it (default: "
649  "0.0.0.0). Use [host]:port notation for IPv6. Append =onion "
650  "to tag any incoming connections to that address and port as "
651  "incoming Tor connections (default: 127.0.0.1:%u=onion, "
652  "testnet: 127.0.0.1:%u=onion, regtest: 127.0.0.1:%u=onion)",
653  defaultBaseParams->OnionServiceTargetPort(),
654  testnetBaseParams->OnionServiceTargetPort(),
655  regtestBaseParams->OnionServiceTargetPort()),
658  argsman.AddArg(
659  "-connect=<ip>",
660  "Connect only to the specified node(s); -connect=0 disables automatic "
661  "connections (the rules for this peer are the same as for -addnode)",
664  argsman.AddArg(
665  "-discover",
666  "Discover own IP addresses (default: 1 when listening and no "
667  "-externalip or -proxy)",
669  argsman.AddArg("-dns",
670  strprintf("Allow DNS lookups for -addnode, -seednode and "
671  "-connect (default: %d)",
674  argsman.AddArg(
675  "-dnsseed",
676  strprintf(
677  "Query for peer addresses via DNS lookup, if low on addresses "
678  "(default: %u unless -connect used)",
681  argsman.AddArg("-externalip=<ip>", "Specify your own public address",
683  argsman.AddArg(
684  "-fixedseeds",
685  strprintf(
686  "Allow fixed seeds if DNS seeds don't provide peers (default: %u)",
689  argsman.AddArg(
690  "-forcednsseed",
691  strprintf(
692  "Always query for peer addresses via DNS lookup (default: %d)",
695  argsman.AddArg("-overridednsseed",
696  "If set, only use the specified DNS seed when "
697  "querying for peer addresses via DNS lookup.",
699  argsman.AddArg(
700  "-listen",
701  "Accept connections from outside (default: 1 if no -proxy or -connect)",
703  argsman.AddArg(
704  "-listenonion",
705  strprintf("Automatically create Tor onion service (default: %d)",
708  argsman.AddArg(
709  "-maxconnections=<n>",
710  strprintf("Maintain at most <n> connections to peers. The effective "
711  "limit depends on system limitations and might be lower than "
712  "the specified value (default: %u)",
715  argsman.AddArg("-maxreceivebuffer=<n>",
716  strprintf("Maximum per-connection receive buffer, <n>*1000 "
717  "bytes (default: %u)",
720  argsman.AddArg(
721  "-maxsendbuffer=<n>",
722  strprintf(
723  "Maximum per-connection send buffer, <n>*1000 bytes (default: %u)",
726  argsman.AddArg(
727  "-maxtimeadjustment",
728  strprintf("Maximum allowed median peer time offset adjustment. Local "
729  "perspective of time may be influenced by peers forward or "
730  "backward by this amount. (default: %u seconds)",
733  argsman.AddArg("-onion=<ip:port>",
734  strprintf("Use separate SOCKS5 proxy to reach peers via Tor "
735  "onion services (default: %s)",
736  "-proxy"),
738  argsman.AddArg(
739  "-onlynet=<net>",
740  "Make outgoing connections only through network <net> (ipv4, ipv6 or "
741  "onion). Incoming connections are not affected by this option. This "
742  "option can be specified multiple times to allow multiple networks.",
744  argsman.AddArg("-peerbloomfilters",
745  strprintf("Support filtering of blocks and transaction with "
746  "bloom filters (default: %d)",
749  argsman.AddArg(
750  "-peerblockfilters",
751  strprintf(
752  "Serve compact block filters to peers per BIP 157 (default: %u)",
755  argsman.AddArg("-permitbaremultisig",
756  strprintf("Relay non-P2SH multisig (default: %d)",
759  argsman.AddArg("-port=<port>",
760  strprintf("Listen for connections on <port> (default: %u, "
761  "testnet: %u, regtest: %u)",
762  defaultChainParams->GetDefaultPort(),
763  testnetChainParams->GetDefaultPort(),
764  regtestChainParams->GetDefaultPort()),
767  argsman.AddArg("-proxy=<ip:port>", "Connect through SOCKS5 proxy",
769  argsman.AddArg(
770  "-proxyrandomize",
771  strprintf("Randomize credentials for every proxy connection. "
772  "This enables Tor stream isolation (default: %d)",
775  argsman.AddArg(
776  "-seednode=<ip>",
777  "Connect to a node to retrieve peer addresses, and disconnect",
779  gArgs.AddArg("-networkactive",
780  "Enable all P2P network activity (default: 1). Can be changed "
781  "by the setnetworkactive RPC command",
783  argsman.AddArg("-timeout=<n>",
784  strprintf("Specify connection timeout in milliseconds "
785  "(minimum: 1, default: %d)",
788  argsman.AddArg(
789  "-peertimeout=<n>",
790  strprintf("Specify p2p connection timeout in seconds. This option "
791  "determines the amount of time a peer may be inactive before "
792  "the connection to it is dropped. (minimum: 1, default: %d)",
795  argsman.AddArg(
796  "-torcontrol=<ip>:<port>",
797  strprintf(
798  "Tor control port to use if onion listening enabled (default: %s)",
801  argsman.AddArg("-torpassword=<pass>",
802  "Tor control port password (default: empty)",
805 #ifdef USE_UPNP
806 #if USE_UPNP
807  argsman.AddArg("-upnp",
808  "Use UPnP to map the listening port (default: 1 when "
809  "listening and no -proxy)",
811 #else
812  argsman.AddArg(
813  "-upnp",
814  strprintf("Use UPnP to map the listening port (default: %u)", 0),
816 #endif
817 #else
818  hidden_args.emplace_back("-upnp");
819 #endif
820  argsman.AddArg(
821  "-whitebind=<[permissions@]addr>",
822  "Bind to the given address and add permission flags to the peers "
823  "connecting to it."
824  "Use [host]:port notation for IPv6. Allowed permissions: " +
825  Join(NET_PERMISSIONS_DOC, ", ") +
826  ". "
827  "Specify multiple permissions separated by commas (default: "
828  "download,noban,mempool,relay). Can be specified multiple times.",
830 
831  argsman.AddArg("-whitelist=<[permissions@]IP address or network>",
832  "Add permission flags to the peers connecting from the "
833  "given IP address (e.g. 1.2.3.4) or CIDR-notated network "
834  "(e.g. 1.2.3.0/24). "
835  "Uses the same permissions as -whitebind. Can be specified "
836  "multiple times.",
838  argsman.AddArg(
839  "-maxuploadtarget=<n>",
840  strprintf("Tries to keep outbound traffic under the given target (in "
841  "MiB per 24h). Limit does not apply to peers with 'download' "
842  "permission. 0 = no limit (default: %d)",
845 
847 
848 #if ENABLE_ZMQ
849  argsman.AddArg("-zmqpubhashblock=<address>",
850  "Enable publish hash block in <address>",
852  argsman.AddArg("-zmqpubhashtx=<address>",
853  "Enable publish hash transaction in <address>",
855  argsman.AddArg("-zmqpubrawblock=<address>",
856  "Enable publish raw block in <address>",
858  argsman.AddArg("-zmqpubrawtx=<address>",
859  "Enable publish raw transaction in <address>",
861  argsman.AddArg("-zmqpubsequence=<address>",
862  "Enable publish hash block and tx sequence in <address>",
864  argsman.AddArg(
865  "-zmqpubhashblockhwm=<n>",
866  strprintf("Set publish hash block outbound message high water "
867  "mark (default: %d)",
870  argsman.AddArg(
871  "-zmqpubhashtxhwm=<n>",
872  strprintf("Set publish hash transaction outbound message high "
873  "water mark (default: %d)",
875  false, OptionsCategory::ZMQ);
876  argsman.AddArg(
877  "-zmqpubrawblockhwm=<n>",
878  strprintf("Set publish raw block outbound message high water "
879  "mark (default: %d)",
882  argsman.AddArg(
883  "-zmqpubrawtxhwm=<n>",
884  strprintf("Set publish raw transaction outbound message high "
885  "water mark (default: %d)",
888  argsman.AddArg("-zmqpubsequencehwm=<n>",
889  strprintf("Set publish hash sequence message high water mark"
890  " (default: %d)",
893 #else
894  hidden_args.emplace_back("-zmqpubhashblock=<address>");
895  hidden_args.emplace_back("-zmqpubhashtx=<address>");
896  hidden_args.emplace_back("-zmqpubrawblock=<address>");
897  hidden_args.emplace_back("-zmqpubrawtx=<address>");
898  hidden_args.emplace_back("-zmqpubsequence=<n>");
899  hidden_args.emplace_back("-zmqpubhashblockhwm=<n>");
900  hidden_args.emplace_back("-zmqpubhashtxhwm=<n>");
901  hidden_args.emplace_back("-zmqpubrawblockhwm=<n>");
902  hidden_args.emplace_back("-zmqpubrawtxhwm=<n>");
903  hidden_args.emplace_back("-zmqpubsequencehwm=<n>");
904 #endif
905 
906  argsman.AddArg(
907  "-checkblocks=<n>",
908  strprintf("How many blocks to check at startup (default: %u, 0 = all)",
912  argsman.AddArg("-checklevel=<n>",
913  strprintf("How thorough the block verification of "
914  "-checkblocks is: %s (0-4, default: %u)",
918  argsman.AddArg("-checkblockindex",
919  strprintf("Do a consistency check for the block tree, "
920  "chainstate, and other validation data structures "
921  "occasionally. (default: %u, regtest: %u)",
922  defaultChainParams->DefaultConsistencyChecks(),
923  regtestChainParams->DefaultConsistencyChecks()),
926  argsman.AddArg(
927  "-checkmempool=<n>",
928  strprintf(
929  "Run checks every <n> transactions (default: %u, regtest: %u)",
930  defaultChainParams->DefaultConsistencyChecks(),
931  regtestChainParams->DefaultConsistencyChecks()),
934  argsman.AddArg("-checkpoints",
935  strprintf("Only accept block chain matching built-in "
936  "checkpoints (default: %d)",
940  argsman.AddArg("-deprecatedrpc=<method>",
941  "Allows deprecated RPC method(s) to be used",
944  argsman.AddArg("-dropmessagestest=<n>",
945  "Randomly drop 1 of every <n> network messages",
948  argsman.AddArg(
949  "-stopafterblockimport",
950  strprintf("Stop running after importing blocks from disk (default: %d)",
954  argsman.AddArg("-stopatheight",
955  strprintf("Stop running after reaching the given height in "
956  "the main chain (default: %u)",
960  argsman.AddArg(
961  "-limitancestorcount=<n>",
962  strprintf("Do not accept transactions if number of in-mempool "
963  "ancestors is <n> or more (default: %u)",
967  argsman.AddArg(
968  "-limitancestorsize=<n>",
969  strprintf("Do not accept transactions whose size with all in-mempool "
970  "ancestors exceeds <n> kilobytes (default: %u)",
974  argsman.AddArg(
975  "-limitdescendantcount=<n>",
976  strprintf("Do not accept transactions if any ancestor would have <n> "
977  "or more in-mempool descendants (default: %u)",
981  argsman.AddArg(
982  "-limitdescendantsize=<n>",
983  strprintf("Do not accept transactions if any ancestor would have more "
984  "than <n> kilobytes of in-mempool descendants (default: %u).",
988  argsman.AddArg("-addrmantest", "Allows to test address relay on localhost",
991 
992  argsman.AddArg("-debug=<category>",
993  strprintf("Output debugging information (default: %u, "
994  "supplying <category> is optional)",
995  0) +
996  ". " +
997  "If <category> is not supplied or if <category> = 1, "
998  "output all debugging information. <category> can be: " +
999  LogInstance().LogCategoriesString() + ".",
1001  argsman.AddArg(
1002  "-debugexclude=<category>",
1003  strprintf("Exclude debugging information for a category. Can be used "
1004  "in conjunction with -debug=1 to output debug logs for all "
1005  "categories except one or more specified categories."),
1007  argsman.AddArg(
1008  "-logips",
1009  strprintf("Include IP addresses in debug output (default: %d)",
1010  DEFAULT_LOGIPS),
1012  argsman.AddArg(
1013  "-logtimestamps",
1014  strprintf("Prepend debug output with timestamp (default: %d)",
1017 #ifdef HAVE_THREAD_LOCAL
1018  argsman.AddArg(
1019  "-logthreadnames",
1020  strprintf(
1021  "Prepend debug output with name of the originating thread (only "
1022  "available on platforms supporting thread_local) (default: %u)",
1025 #else
1026  hidden_args.emplace_back("-logthreadnames");
1027 #endif
1028  argsman.AddArg(
1029  "-logtimemicros",
1030  strprintf("Add microsecond precision to debug timestamps (default: %d)",
1034  argsman.AddArg("-mocktime=<n>",
1035  "Replace actual time with " + UNIX_EPOCH_TIME +
1036  " (default: 0)",
1039  argsman.AddArg(
1040  "-maxsigcachesize=<n>",
1041  strprintf("Limit size of signature cache to <n> MiB (default: %u)",
1045  argsman.AddArg(
1046  "-maxscriptcachesize=<n>",
1047  strprintf("Limit size of script cache to <n> MiB (default: %u)",
1051  argsman.AddArg("-maxtipage=<n>",
1052  strprintf("Maximum tip age in seconds to consider node in "
1053  "initial block download (default: %u)",
1057 
1058  argsman.AddArg(
1059  "-printtoconsole",
1060  "Send trace/debug info to console instead of debug.log file (default: "
1061  "1 when no -daemon. To disable logging to file, set debuglogfile=0)",
1063  argsman.AddArg("-printpriority",
1064  strprintf("Log transaction priority and fee per kB when "
1065  "mining blocks (default: %d)",
1069  argsman.AddArg(
1070  "-shrinkdebugfile",
1071  "Shrink debug.log file on client startup (default: 1 when no -debug)",
1073 
1074  argsman.AddArg("-uacomment=<cmt>",
1075  "Append comment to the user agent string",
1077  argsman.AddArg("-uaclientname=<clientname>", "Set user agent client name",
1079  argsman.AddArg("-uaclientversion=<clientversion>",
1080  "Set user agent client version", ArgsManager::ALLOW_ANY,
1082 
1083  SetupChainParamsBaseOptions(argsman);
1084 
1085  argsman.AddArg(
1086  "-acceptnonstdtxn",
1087  strprintf(
1088  "Relay and mine \"non-standard\" transactions (%sdefault: %u)",
1089  "testnet/regtest only; ", defaultChainParams->RequireStandard()),
1092  argsman.AddArg("-excessiveblocksize=<n>",
1093  strprintf("Do not accept blocks larger than this limit, in "
1094  "bytes (default: %d)",
1098  const auto &ticker = Currency::get().ticker;
1099  argsman.AddArg(
1100  "-dustrelayfee=<amt>",
1101  strprintf("Fee rate (in %s/kB) used to define dust, the value of an "
1102  "output such that it will cost about 1/3 of its value in "
1103  "fees at this fee rate to spend it. (default: %s)",
1104  ticker, FormatMoney(DUST_RELAY_TX_FEE)),
1107 
1108  argsman.AddArg("-bytespersigop",
1109  strprintf("Equivalent bytes per sigop in transactions for "
1110  "relay and mining (default: %u)",
1113  argsman.AddArg(
1114  "-datacarrier",
1115  strprintf("Relay and mine data carrier transactions (default: %d)",
1118  argsman.AddArg(
1119  "-datacarriersize",
1120  strprintf("Maximum size of data in data carrier transactions "
1121  "we relay and mine (default: %u)",
1124  argsman.AddArg(
1125  "-minrelaytxfee=<amt>",
1126  strprintf("Fees (in %s/kB) smaller than this are rejected for "
1127  "relaying, mining and transaction creation (default: %s)",
1130  argsman.AddArg(
1131  "-whitelistrelay",
1132  strprintf("Add 'relay' permission to whitelisted inbound peers "
1133  "with default permissions. This will accept relayed "
1134  "transactions even when not relaying transactions "
1135  "(default: %d)",
1138  argsman.AddArg(
1139  "-whitelistforcerelay",
1140  strprintf("Add 'forcerelay' permission to whitelisted inbound peers"
1141  " with default permissions. This will relay transactions "
1142  "even if the transactions were already in the mempool "
1143  "(default: %d)",
1146 
1147  // Not sure this really belongs here, but it will do for now.
1148  // FIXME: This doesn't work anyways.
1149  argsman.AddArg("-excessutxocharge=<amt>",
1150  strprintf("Fees (in %s/kB) to charge per utxo created for "
1151  "relaying, and mining (default: %s)",
1152  ticker, FormatMoney(DEFAULT_UTXO_FEE)),
1155 
1156  argsman.AddArg("-blockmaxsize=<n>",
1157  strprintf("Set maximum block size in bytes (default: %d)",
1160  argsman.AddArg(
1161  "-blockmintxfee=<amt>",
1162  strprintf("Set lowest fee rate (in %s/kB) for transactions to "
1163  "be included in block creation. (default: %s)",
1166 
1167  argsman.AddArg("-blockversion=<n>",
1168  "Override block version to test forking scenarios",
1171 
1172  argsman.AddArg("-server", "Accept command line and JSON-RPC commands",
1174  argsman.AddArg("-rest",
1175  strprintf("Accept public REST requests (default: %d)",
1178  argsman.AddArg(
1179  "-rpcbind=<addr>[:port]",
1180  "Bind to given address to listen for JSON-RPC connections. Do not "
1181  "expose the RPC server to untrusted networks such as the public "
1182  "internet! This option is ignored unless -rpcallowip is also passed. "
1183  "Port is optional and overrides -rpcport. Use [host]:port notation "
1184  "for IPv6. This option can be specified multiple times (default: "
1185  "127.0.0.1 and ::1 i.e., localhost)",
1189  argsman.AddArg(
1190  "-rpccookiefile=<loc>",
1191  "Location of the auth cookie. Relative paths will be prefixed "
1192  "by a net-specific datadir location. (default: data dir)",
1194  argsman.AddArg("-rpcuser=<user>", "Username for JSON-RPC connections",
1197  argsman.AddArg("-rpcpassword=<pw>", "Password for JSON-RPC connections",
1200  argsman.AddArg(
1201  "-rpcwhitelist=<whitelist>",
1202  "Set a whitelist to filter incoming RPC calls for a specific user. The "
1203  "field <whitelist> comes in the format: <USERNAME>:<rpc 1>,<rpc "
1204  "2>,...,<rpc n>. If multiple whitelists are set for a given user, they "
1205  "are set-intersected. See -rpcwhitelistdefault documentation for "
1206  "information on default whitelist behavior.",
1208  argsman.AddArg(
1209  "-rpcwhitelistdefault",
1210  "Sets default behavior for rpc whitelisting. Unless "
1211  "rpcwhitelistdefault is set to 0, if any -rpcwhitelist is set, the rpc "
1212  "server acts as if all rpc users are subject to "
1213  "empty-unless-otherwise-specified whitelists. If rpcwhitelistdefault "
1214  "is set to 1 and no -rpcwhitelist is set, rpc server acts as if all "
1215  "rpc users are subject to empty whitelists.",
1217  argsman.AddArg(
1218  "-rpcauth=<userpw>",
1219  "Username and HMAC-SHA-256 hashed password for JSON-RPC connections. "
1220  "The field <userpw> comes in the format: <USERNAME>:<SALT>$<HASH>. A "
1221  "canonical python script is included in share/rpcauth. The client then "
1222  "connects normally using the rpcuser=<USERNAME>/rpcpassword=<PASSWORD> "
1223  "pair of arguments. This option can be specified multiple times",
1225  argsman.AddArg("-rpcport=<port>",
1226  strprintf("Listen for JSON-RPC connections on <port> "
1227  "(default: %u, testnet: %u, regtest: %u)",
1228  defaultBaseParams->RPCPort(),
1229  testnetBaseParams->RPCPort(),
1230  regtestBaseParams->RPCPort()),
1233  argsman.AddArg(
1234  "-rpcallowip=<ip>",
1235  "Allow JSON-RPC connections from specified source. Valid for "
1236  "<ip> are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. "
1237  "1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24). "
1238  "This option can be specified multiple times",
1240  argsman.AddArg(
1241  "-rpcthreads=<n>",
1242  strprintf(
1243  "Set the number of threads to service RPC calls (default: %d)",
1246  argsman.AddArg(
1247  "-rpccorsdomain=value",
1248  "Domain from which to accept cross origin requests (browser enforced)",
1250 
1251  argsman.AddArg("-rpcworkqueue=<n>",
1252  strprintf("Set the depth of the work queue to service RPC "
1253  "calls (default: %d)",
1257  argsman.AddArg("-rpcservertimeout=<n>",
1258  strprintf("Timeout during HTTP requests (default: %d)",
1262 
1263 #if HAVE_DECL_DAEMON
1264  argsman.AddArg("-daemon",
1265  "Run in the background as a daemon and accept commands",
1267 #else
1268  hidden_args.emplace_back("-daemon");
1269 #endif
1270 
1271  // Avalanche options.
1272  argsman.AddArg(
1273  "-enableavalanche",
1274  strprintf("Enable avalanche (default: %u)", AVALANCHE_DEFAULT_ENABLED),
1276  argsman.AddArg("-enableavalanchepeerdiscovery",
1277  strprintf("Enable avalanche peer discovery (default: %u)",
1280  argsman.AddArg(
1281  "-avacooldown",
1282  strprintf("Mandatory cooldown between two avapoll (default: %u)",
1285  argsman.AddArg(
1286  "-avadelegation",
1287  "Avalanche proof delegation to the master key used by this node "
1288  "(default: none). Should be used in conjunction with -avaproof and "
1289  "-avamasterkey",
1291  argsman.AddArg("-avaproof",
1292  "Avalanche proof to be used by this node (default: none)",
1294  argsman.AddArg(
1295  "-legacyavaproof",
1296  strprintf("Use the legacy avalanche proof format (default: %u)",
1299  argsman.AddArg("-avamasterkey",
1300  "Master key associated with the proof. If a proof is "
1301  "required, this is mandatory.",
1303  argsman.AddArg("-avasessionkey", "Avalanche session key (default: random)",
1305 
1306  // Add the hidden options
1307  argsman.AddHiddenArgs(hidden_args);
1308 }
1309 
1310 std::string LicenseInfo() {
1311  const std::string URL_SOURCE_CODE =
1312  "<https://github.com/Bitcoin-ABC/bitcoin-abc>";
1313  const std::string URL_WEBSITE = "<https://www.bitcoinabc.org>";
1314 
1315  return CopyrightHolders(strprintf(_("Copyright (C) %i-%i").translated, 2009,
1316  COPYRIGHT_YEAR) +
1317  " ") +
1318  "\n" + "\n" +
1319  strprintf(_("Please contribute if you find %s useful. "
1320  "Visit %s for further information about the software.")
1321  .translated,
1322  PACKAGE_NAME, URL_WEBSITE) +
1323  "\n" +
1324  strprintf(_("The source code is available from %s.").translated,
1325  URL_SOURCE_CODE) +
1326  "\n" + "\n" + _("This is experimental software.").translated + "\n" +
1327  strprintf(_("Distributed under the MIT software license, see the "
1328  "accompanying file %s or %s")
1329  .translated,
1330  "COPYING", "<https://opensource.org/licenses/MIT>") +
1331  "\n" + "\n" +
1332  strprintf(_("This product includes software developed by the "
1333  "OpenSSL Project for use in the OpenSSL Toolkit %s and "
1334  "cryptographic software written by Eric Young and UPnP "
1335  "software written by Thomas Bernard.")
1336  .translated,
1337  "<https://www.openssl.org>") +
1338  "\n";
1339 }
1340 
1341 static bool fHaveGenesis = false;
1343 static std::condition_variable g_genesis_wait_cv;
1344 
1345 static void BlockNotifyGenesisWait(const CBlockIndex *pBlockIndex) {
1346  if (pBlockIndex != nullptr) {
1347  {
1349  fHaveGenesis = true;
1350  }
1351  g_genesis_wait_cv.notify_all();
1352  }
1353 }
1354 
1357  assert(fImporting == false);
1358  fImporting = true;
1359  }
1360 
1362  assert(fImporting == true);
1363  fImporting = false;
1364  }
1365 };
1366 
1367 // If we're using -prune with -reindex, then delete block files that will be
1368 // ignored by the reindex. Since reindexing works by starting at block file 0
1369 // and looping until a blockfile is missing, do the same here to delete any
1370 // later block files after a gap. Also delete all rev files since they'll be
1371 // rewritten by the reindex anyway. This ensures that vinfoBlockFile is in sync
1372 // with what's actually on disk by the time we start downloading, so that
1373 // pruning works correctly.
1374 static void CleanupBlockRevFiles() {
1375  std::map<std::string, fs::path> mapBlockFiles;
1376 
1377  // Glob all blk?????.dat and rev?????.dat files from the blocks directory.
1378  // Remove the rev files immediately and insert the blk file paths into an
1379  // ordered map keyed by block file index.
1380  LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for "
1381  "-reindex with -prune\n");
1382  for (const auto &file : fs::directory_iterator{gArgs.GetBlocksDirPath()}) {
1383  const std::string path = fs::PathToString(file.path().filename());
1384  if (fs::is_regular_file(file) && path.length() == 12 &&
1385  path.substr(8, 4) == ".dat") {
1386  if (path.substr(0, 3) == "blk") {
1387  mapBlockFiles[path.substr(3, 5)] = file.path();
1388  } else if (path.substr(0, 3) == "rev") {
1389  remove(file.path());
1390  }
1391  }
1392  }
1393 
1394  // Remove all block files that aren't part of a contiguous set starting at
1395  // zero by walking the ordered map (keys are block file indices) by keeping
1396  // a separate counter. Once we hit a gap (or if 0 doesn't exist) start
1397  // removing block files.
1398  int contiguousCounter = 0;
1399  for (const auto &item : mapBlockFiles) {
1400  if (atoi(item.first) == contiguousCounter) {
1401  contiguousCounter++;
1402  continue;
1403  }
1404  remove(item.second);
1405  }
1406 }
1407 
1408 #if HAVE_SYSTEM
1409 static void StartupNotify(const ArgsManager &args) {
1410  std::string cmd = args.GetArg("-startupnotify", "");
1411  if (!cmd.empty()) {
1412  std::thread t(runCommand, cmd);
1413  // thread runs free
1414  t.detach();
1415  }
1416 }
1417 #endif
1418 
1419 static void ThreadImport(const Config &config, ChainstateManager &chainman,
1420  std::vector<fs::path> vImportFiles,
1421  const ArgsManager &args) {
1423 
1424  {
1425  const CChainParams &chainParams = config.GetChainParams();
1426 
1427  CImportingNow imp;
1428 
1429  // -reindex
1430  if (fReindex) {
1431  int nFile = 0;
1432  while (true) {
1433  FlatFilePos pos(nFile, 0);
1434  if (!fs::exists(GetBlockPosFilename(pos))) {
1435  // No block files left to reindex
1436  break;
1437  }
1438  FILE *file = OpenBlockFile(pos, true);
1439  if (!file) {
1440  // This error is logged in OpenBlockFile
1441  break;
1442  }
1443  LogPrintf("Reindexing block file blk%05u.dat...\n",
1444  (unsigned int)nFile);
1445  LoadExternalBlockFile(config, file, &pos);
1446  if (ShutdownRequested()) {
1447  LogPrintf("Shutdown requested. Exit %s\n", __func__);
1448  return;
1449  }
1450  nFile++;
1451  }
1452  pblocktree->WriteReindexing(false);
1453  fReindex = false;
1454  LogPrintf("Reindexing finished\n");
1455  // To avoid ending up in a situation without genesis block, re-try
1456  // initializing (no-op if reindexing worked):
1457  LoadGenesisBlock(chainParams);
1458  }
1459 
1460  // -loadblock=
1461  for (const fs::path &path : vImportFiles) {
1462  FILE *file = fsbridge::fopen(path, "rb");
1463  if (file) {
1464  LogPrintf("Importing blocks file %s...\n",
1465  fs::PathToString(path));
1466  LoadExternalBlockFile(config, file);
1467  if (ShutdownRequested()) {
1468  LogPrintf("Shutdown requested. Exit %s\n", __func__);
1469  return;
1470  }
1471  } else {
1472  LogPrintf("Warning: Could not open blocks file %s\n",
1473  fs::PathToString(path));
1474  }
1475  }
1476 
1477  // Reconsider blocks we know are valid. They may have been marked
1478  // invalid by, for instance, running an outdated version of the node
1479  // software.
1480  const MapCheckpoints &checkpoints =
1481  chainParams.Checkpoints().mapCheckpoints;
1482  for (const MapCheckpoints::value_type &i : checkpoints) {
1483  const BlockHash &hash = i.second;
1484 
1485  LOCK(cs_main);
1486  CBlockIndex *pblockindex = LookupBlockIndex(hash);
1487  if (pblockindex && !pblockindex->nStatus.isValid()) {
1488  LogPrintf("Reconsidering checkpointed block %s ...\n",
1489  hash.GetHex());
1490  ResetBlockFailureFlags(pblockindex);
1491  }
1492  }
1493 
1494  // scan for better chains in the block chain database, that are not yet
1495  // connected in the active best chain
1496 
1497  // We can't hold cs_main during ActivateBestChain even though we're
1498  // accessing the chainman unique_ptrs since ABC requires us not to be
1499  // holding cs_main, so retrieve the relevant pointers before the ABC
1500  // call.
1501  for (CChainState *chainstate :
1502  WITH_LOCK(::cs_main, return chainman.GetAll())) {
1503  BlockValidationState state;
1504  if (!chainstate->ActivateBestChain(config, state, nullptr)) {
1505  LogPrintf("Failed to connect best block (%s)\n",
1506  state.ToString());
1507  StartShutdown();
1508  return;
1509  }
1510  }
1511 
1512  if (args.GetBoolArg("-stopafterblockimport",
1514  LogPrintf("Stopping after block import\n");
1515  StartShutdown();
1516  return;
1517  }
1518  } // End scope of CImportingNow
1519  chainman.ActiveChainstate().LoadMempool(config, args);
1520 }
1521 
1526 static bool InitSanityCheck() {
1527  if (!ECC_InitSanityCheck()) {
1528  return InitError(Untranslated(
1529  "Elliptic curve cryptography sanity check failure. Aborting."));
1530  }
1531 
1532  if (!glibcxx_sanity_test()) {
1533  return false;
1534  }
1535 
1536  if (!Random_SanityCheck()) {
1537  return InitError(Untranslated(
1538  "OS cryptographic RNG sanity check failure. Aborting."));
1539  }
1540 
1541  return true;
1542 }
1543 
1544 static bool AppInitServers(Config &config,
1545  HTTPRPCRequestProcessor &httpRPCRequestProcessor,
1546  NodeContext &node) {
1547  const ArgsManager &args = *Assert(node.args);
1550  if (!InitHTTPServer(config)) {
1551  return false;
1552  }
1553 
1554  StartRPC();
1556 
1557  if (!StartHTTPRPC(httpRPCRequestProcessor)) {
1558  return false;
1559  }
1560  if (args.GetBoolArg("-rest", DEFAULT_REST_ENABLE)) {
1561  StartREST(httpRPCRequestProcessor.context);
1562  }
1563 
1564  StartHTTPServer();
1565  return true;
1566 }
1567 
1568 // Parameter interaction based on rules
1570  // when specifying an explicit binding address, you want to listen on it
1571  // even when -connect or -proxy is specified.
1572  if (args.IsArgSet("-bind")) {
1573  if (args.SoftSetBoolArg("-listen", true)) {
1574  LogPrintf(
1575  "%s: parameter interaction: -bind set -> setting -listen=1\n",
1576  __func__);
1577  }
1578  }
1579  if (args.IsArgSet("-whitebind")) {
1580  if (args.SoftSetBoolArg("-listen", true)) {
1581  LogPrintf("%s: parameter interaction: -whitebind set -> setting "
1582  "-listen=1\n",
1583  __func__);
1584  }
1585  }
1586 
1587  if (args.IsArgSet("-connect")) {
1588  // when only connecting to trusted nodes, do not seed via DNS, or listen
1589  // by default.
1590  if (args.SoftSetBoolArg("-dnsseed", false)) {
1591  LogPrintf("%s: parameter interaction: -connect set -> setting "
1592  "-dnsseed=0\n",
1593  __func__);
1594  }
1595  if (args.SoftSetBoolArg("-listen", false)) {
1596  LogPrintf("%s: parameter interaction: -connect set -> setting "
1597  "-listen=0\n",
1598  __func__);
1599  }
1600  }
1601 
1602  if (args.IsArgSet("-proxy")) {
1603  // to protect privacy, do not listen by default if a default proxy
1604  // server is specified.
1605  if (args.SoftSetBoolArg("-listen", false)) {
1606  LogPrintf(
1607  "%s: parameter interaction: -proxy set -> setting -listen=0\n",
1608  __func__);
1609  }
1610  // to protect privacy, do not use UPNP when a proxy is set. The user may
1611  // still specify -listen=1 to listen locally, so don't rely on this
1612  // happening through -listen below.
1613  if (args.SoftSetBoolArg("-upnp", false)) {
1614  LogPrintf(
1615  "%s: parameter interaction: -proxy set -> setting -upnp=0\n",
1616  __func__);
1617  }
1618  // to protect privacy, do not discover addresses by default
1619  if (args.SoftSetBoolArg("-discover", false)) {
1620  LogPrintf("%s: parameter interaction: -proxy set -> setting "
1621  "-discover=0\n",
1622  __func__);
1623  }
1624  }
1625 
1626  if (!args.GetBoolArg("-listen", DEFAULT_LISTEN)) {
1627  // do not map ports or try to retrieve public IP when not listening
1628  // (pointless)
1629  if (args.SoftSetBoolArg("-upnp", false)) {
1630  LogPrintf(
1631  "%s: parameter interaction: -listen=0 -> setting -upnp=0\n",
1632  __func__);
1633  }
1634  if (args.SoftSetBoolArg("-discover", false)) {
1635  LogPrintf(
1636  "%s: parameter interaction: -listen=0 -> setting -discover=0\n",
1637  __func__);
1638  }
1639  if (args.SoftSetBoolArg("-listenonion", false)) {
1640  LogPrintf("%s: parameter interaction: -listen=0 -> setting "
1641  "-listenonion=0\n",
1642  __func__);
1643  }
1644  }
1645 
1646  if (args.IsArgSet("-externalip")) {
1647  // if an explicit public IP is specified, do not try to find others
1648  if (args.SoftSetBoolArg("-discover", false)) {
1649  LogPrintf("%s: parameter interaction: -externalip set -> setting "
1650  "-discover=0\n",
1651  __func__);
1652  }
1653  }
1654 
1655  // disable whitelistrelay in blocksonly mode
1656  if (args.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)) {
1657  if (args.SoftSetBoolArg("-whitelistrelay", false)) {
1658  LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting "
1659  "-whitelistrelay=0\n",
1660  __func__);
1661  }
1662  }
1663 
1664  // Forcing relay from whitelisted hosts implies we will accept relays from
1665  // them in the first place.
1666  if (args.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
1667  if (args.SoftSetBoolArg("-whitelistrelay", true)) {
1668  LogPrintf("%s: parameter interaction: -whitelistforcerelay=1 -> "
1669  "setting -whitelistrelay=1\n",
1670  __func__);
1671  }
1672  }
1673 }
1674 
1681 void InitLogging(const ArgsManager &args) {
1682  LogInstance().m_print_to_file = !args.IsArgNegated("-debuglogfile");
1684  fs::PathFromString(args.GetArg("-debuglogfile", DEFAULT_DEBUGLOGFILE)));
1685 
1687  args.GetBoolArg("-printtoconsole", !args.GetBoolArg("-daemon", false));
1689  args.GetBoolArg("-logtimestamps", DEFAULT_LOGTIMESTAMPS);
1691  args.GetBoolArg("-logtimemicros", DEFAULT_LOGTIMEMICROS);
1692 #ifdef HAVE_THREAD_LOCAL
1694  args.GetBoolArg("-logthreadnames", DEFAULT_LOGTHREADNAMES);
1695 #endif
1696 
1697  fLogIPs = args.GetBoolArg("-logips", DEFAULT_LOGIPS);
1698 
1699  std::string version_string = FormatFullVersion();
1700 #ifdef DEBUG
1701  version_string += " (debug build)";
1702 #else
1703  version_string += " (release build)";
1704 #endif
1705  LogPrintf("%s version %s\n", CLIENT_NAME, version_string);
1706 }
1707 
1708 namespace { // Variables internal to initialization process only
1709 
1710 int nMaxConnections;
1711 int nUserMaxConnections;
1712 int nFD;
1714 int64_t peer_connect_timeout;
1715 std::set<BlockFilterType> g_enabled_filter_types;
1716 
1717 } // namespace
1718 
1719 [[noreturn]] static void new_handler_terminate() {
1720  // Rather than throwing std::bad-alloc if allocation fails, terminate
1721  // immediately to (try to) avoid chain corruption. Since LogPrintf may
1722  // itself allocate memory, set the handler directly to terminate first.
1723  std::set_new_handler(std::terminate);
1724  LogPrintf("Error: Out of memory. Terminating.\n");
1725 
1726  // The log was successful, terminate now.
1727  std::terminate();
1728 };
1729 
1731 // Step 1: setup
1732 #ifdef _MSC_VER
1733  // Turn off Microsoft heap dump noise
1734  _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
1735  _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, nullptr,
1736  OPEN_EXISTING, 0, 0));
1737  // Disable confusing "helpful" text message on abort, Ctrl-C
1738  _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
1739 #endif
1740 #ifdef WIN32
1741  // Enable Data Execution Prevention (DEP)
1742  SetProcessDEPPolicy(PROCESS_DEP_ENABLE);
1743 #endif
1744 
1745  if (!SetupNetworking()) {
1746  return InitError(Untranslated("Initializing networking failed"));
1747  }
1748 
1749 #ifndef WIN32
1750  if (!args.GetBoolArg("-sysperms", false)) {
1751  umask(077);
1752  }
1753 
1754  // Clean shutdown on SIGTERM
1757 
1758  // Reopen debug.log on SIGHUP
1760 
1761  // Ignore SIGPIPE, otherwise it will bring the daemon down if the client
1762  // closes unexpectedly
1763  signal(SIGPIPE, SIG_IGN);
1764 #else
1765  SetConsoleCtrlHandler(consoleCtrlHandler, true);
1766 #endif
1767 
1768  std::set_new_handler(new_handler_terminate);
1769 
1770  return true;
1771 }
1772 
1773 bool AppInitParameterInteraction(Config &config, const ArgsManager &args) {
1774  const CChainParams &chainparams = config.GetChainParams();
1775  // Step 2: parameter interactions
1776 
1777  // also see: InitParameterInteraction()
1778 
1779  // Error if network-specific options (-addnode, -connect, etc) are
1780  // specified in default section of config file, but not overridden
1781  // on the command line or in this network's section of the config file.
1782  std::string network = args.GetChainName();
1783  bilingual_str errors;
1784  for (const auto &arg : args.GetUnsuitableSectionOnlyArgs()) {
1785  errors += strprintf(_("Config setting for %s only applied on %s "
1786  "network when in [%s] section.") +
1787  Untranslated("\n"),
1788  arg, network, network);
1789  }
1790 
1791  if (!errors.empty()) {
1792  return InitError(errors);
1793  }
1794 
1795  // Warn if unrecognized section name are present in the config file.
1796  bilingual_str warnings;
1797  for (const auto &section : args.GetUnrecognizedSections()) {
1798  warnings += strprintf(Untranslated("%s:%i ") +
1799  _("Section [%s] is not recognized.") +
1800  Untranslated("\n"),
1801  section.m_file, section.m_line, section.m_name);
1802  }
1803 
1804  if (!warnings.empty()) {
1805  InitWarning(warnings);
1806  }
1807 
1808  if (!fs::is_directory(gArgs.GetBlocksDirPath())) {
1809  return InitError(
1810  strprintf(_("Specified blocks directory \"%s\" does not exist."),
1811  args.GetArg("-blocksdir", "")));
1812  }
1813 
1814  // parse and validate enabled filter types
1815  std::string blockfilterindex_value =
1816  args.GetArg("-blockfilterindex", DEFAULT_BLOCKFILTERINDEX);
1817  if (blockfilterindex_value == "" || blockfilterindex_value == "1") {
1818  g_enabled_filter_types = AllBlockFilterTypes();
1819  } else if (blockfilterindex_value != "0") {
1820  const std::vector<std::string> names =
1821  args.GetArgs("-blockfilterindex");
1822  for (const auto &name : names) {
1823  BlockFilterType filter_type;
1824  if (!BlockFilterTypeByName(name, filter_type)) {
1825  return InitError(
1826  strprintf(_("Unknown -blockfilterindex value %s."), name));
1827  }
1828  g_enabled_filter_types.insert(filter_type);
1829  }
1830  }
1831 
1832  // Signal NODE_COMPACT_FILTERS if peerblockfilters and basic filters index
1833  // are both enabled.
1834  if (gArgs.GetBoolArg("-peerblockfilters", DEFAULT_PEERBLOCKFILTERS)) {
1835  if (g_enabled_filter_types.count(BlockFilterType::BASIC) != 1) {
1836  return InitError(
1837  _("Cannot set -peerblockfilters without -blockfilterindex."));
1838  }
1839 
1840  nLocalServices = ServiceFlags(nLocalServices | NODE_COMPACT_FILTERS);
1841  }
1842 
1843  // if using block pruning, then disallow txindex
1844  if (args.GetArg("-prune", 0)) {
1845  if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
1846  return InitError(_("Prune mode is incompatible with -txindex."));
1847  }
1848  if (!g_enabled_filter_types.empty()) {
1849  return InitError(
1850  _("Prune mode is incompatible with -blockfilterindex."));
1851  }
1852  }
1853 
1854  // -bind and -whitebind can't be set when not listening
1855  size_t nUserBind =
1856  args.GetArgs("-bind").size() + args.GetArgs("-whitebind").size();
1857  if (nUserBind != 0 && !args.GetBoolArg("-listen", DEFAULT_LISTEN)) {
1858  return InitError(Untranslated(
1859  "Cannot set -bind or -whitebind together with -listen=0"));
1860  }
1861 
1862  // Make sure enough file descriptors are available
1863  int nBind = std::max(nUserBind, size_t(1));
1864  nUserMaxConnections =
1865  args.GetArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
1866  nMaxConnections = std::max(nUserMaxConnections, 0);
1867 
1868  // Trim requested connection counts, to fit into system limitations
1869  // <int> in std::min<int>(...) to work around FreeBSD compilation issue
1870  // described in #2695
1871  nFD = RaiseFileDescriptorLimit(nMaxConnections + nBind +
1874 #ifdef USE_POLL
1875  int fd_max = nFD;
1876 #else
1877  int fd_max = FD_SETSIZE;
1878 #endif
1879  nMaxConnections =
1880  std::max(std::min<int>(nMaxConnections, fd_max - nBind -
1883  0);
1884  if (nFD < MIN_CORE_FILEDESCRIPTORS) {
1885  return InitError(_("Not enough file descriptors available."));
1886  }
1887  nMaxConnections =
1889  nMaxConnections);
1890 
1891  if (nMaxConnections < nUserMaxConnections) {
1892  // Not categorizing as "Warning" because this is the normal behavior for
1893  // platforms using the select() interface for which FD_SETSIZE is
1894  // usually 1024.
1895  LogPrintf("Reducing -maxconnections from %d to %d, because of system "
1896  "limitations.\n",
1897  nUserMaxConnections, nMaxConnections);
1898  }
1899 
1900  // Step 3: parameter-to-internal-flags
1901  if (args.IsArgSet("-debug")) {
1902  // Special-case: if -debug=0/-nodebug is set, turn off debugging
1903  // messages
1904  const std::vector<std::string> &categories = args.GetArgs("-debug");
1905  if (std::none_of(
1906  categories.begin(), categories.end(),
1907  [](std::string cat) { return cat == "0" || cat == "none"; })) {
1908  for (const auto &cat : categories) {
1909  if (!LogInstance().EnableCategory(cat)) {
1910  InitWarning(
1911  strprintf(_("Unsupported logging category %s=%s."),
1912  "-debug", cat));
1913  }
1914  }
1915  }
1916  }
1917 
1918  // Now remove the logging categories which were explicitly excluded
1919  for (const std::string &cat : args.GetArgs("-debugexclude")) {
1920  if (!LogInstance().DisableCategory(cat)) {
1921  InitWarning(strprintf(_("Unsupported logging category %s=%s."),
1922  "-debugexclude", cat));
1923  }
1924  }
1925 
1926  fCheckBlockIndex = args.GetBoolArg("-checkblockindex",
1927  chainparams.DefaultConsistencyChecks());
1929  args.GetBoolArg("-checkpoints", DEFAULT_CHECKPOINTS_ENABLED);
1930  if (fCheckpointsEnabled) {
1931  LogPrintf("Checkpoints will be verified.\n");
1932  } else {
1933  LogPrintf("Skipping checkpoint verification.\n");
1934  }
1935 
1937  args.GetArg("-assumevalid",
1938  chainparams.GetConsensus().defaultAssumeValid.GetHex()));
1939  if (!hashAssumeValid.IsNull()) {
1940  LogPrintf("Assuming ancestors of block %s have valid signatures.\n",
1942  } else {
1943  LogPrintf("Validating signatures for all blocks.\n");
1944  }
1945 
1946  if (args.IsArgSet("-minimumchainwork")) {
1947  const std::string minChainWorkStr =
1948  args.GetArg("-minimumchainwork", "");
1949  if (!IsHexNumber(minChainWorkStr)) {
1950  return InitError(strprintf(
1951  Untranslated(
1952  "Invalid non-hex (%s) minimum chain work value specified"),
1953  minChainWorkStr));
1954  }
1955  nMinimumChainWork = UintToArith256(uint256S(minChainWorkStr));
1956  } else {
1959  }
1960  LogPrintf("Setting nMinimumChainWork=%s\n", nMinimumChainWork.GetHex());
1961  if (nMinimumChainWork <
1963  LogPrintf("Warning: nMinimumChainWork set below default value of %s\n",
1964  chainparams.GetConsensus().nMinimumChainWork.GetHex());
1965  }
1966 
1967  // mempool limits
1968  int64_t nMempoolSizeMax =
1969  args.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
1970  int64_t nMempoolSizeMin =
1971  args.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) *
1972  1000 * 40;
1973  if (nMempoolSizeMax < 0 || nMempoolSizeMax < nMempoolSizeMin) {
1974  return InitError(strprintf(_("-maxmempool must be at least %d MB"),
1975  std::ceil(nMempoolSizeMin / 1000000.0)));
1976  }
1977 
1978  // Configure excessive block size.
1979  const int64_t nProposedExcessiveBlockSize =
1980  args.GetArg("-excessiveblocksize", DEFAULT_MAX_BLOCK_SIZE);
1981  if (nProposedExcessiveBlockSize <= 0 ||
1982  !config.SetMaxBlockSize(nProposedExcessiveBlockSize)) {
1983  return InitError(
1984  _("Excessive block size must be > 1,000,000 bytes (1MB)"));
1985  }
1986 
1987  // Check blockmaxsize does not exceed maximum accepted block size.
1988  const int64_t nProposedMaxGeneratedBlockSize =
1989  args.GetArg("-blockmaxsize", DEFAULT_MAX_GENERATED_BLOCK_SIZE);
1990  if (nProposedMaxGeneratedBlockSize <= 0) {
1991  return InitError(_("Max generated block size must be greater than 0"));
1992  }
1993  if (uint64_t(nProposedMaxGeneratedBlockSize) > config.GetMaxBlockSize()) {
1994  return InitError(_("Max generated block size (blockmaxsize) cannot "
1995  "exceed the excessive block size "
1996  "(excessiveblocksize)"));
1997  }
1998 
1999  // block pruning; get the amount of disk space (in MiB) to allot for block &
2000  // undo files
2001  int64_t nPruneArg = args.GetArg("-prune", 0);
2002  if (nPruneArg < 0) {
2003  return InitError(
2004  _("Prune cannot be configured with a negative value."));
2005  }
2006  nPruneTarget = (uint64_t)nPruneArg * 1024 * 1024;
2007  if (nPruneArg == 1) {
2008  // manual pruning: -prune=1
2009  LogPrintf("Block pruning enabled. Use RPC call "
2010  "pruneblockchain(height) to manually prune block and undo "
2011  "files.\n");
2012  nPruneTarget = std::numeric_limits<uint64_t>::max();
2013  fPruneMode = true;
2014  } else if (nPruneTarget) {
2016  return InitError(
2017  strprintf(_("Prune configured below the minimum of %d MiB. "
2018  "Please use a higher number."),
2019  MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
2020  }
2021  LogPrintf("Prune configured to target %u MiB on disk for block and "
2022  "undo files.\n",
2023  nPruneTarget / 1024 / 1024);
2024  fPruneMode = true;
2025  }
2026 
2027  nConnectTimeout = args.GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT);
2028  if (nConnectTimeout <= 0) {
2030  }
2031 
2032  peer_connect_timeout =
2033  args.GetArg("-peertimeout", DEFAULT_PEER_CONNECT_TIMEOUT);
2034  if (peer_connect_timeout <= 0) {
2035  return InitError(Untranslated(
2036  "peertimeout cannot be configured with a negative value."));
2037  }
2038 
2039  // Obtain the amount to charge excess UTXO
2040  if (args.IsArgSet("-excessutxocharge")) {
2041  Amount n = Amount::zero();
2042  auto parsed = ParseMoney(args.GetArg("-excessutxocharge", ""), n);
2043  if (!parsed || Amount::zero() > n) {
2044  return InitError(AmountErrMsg(
2045  "excessutxocharge", args.GetArg("-excessutxocharge", "")));
2046  }
2047  config.SetExcessUTXOCharge(n);
2048  } else {
2050  }
2051 
2052  if (args.IsArgSet("-minrelaytxfee")) {
2053  Amount n = Amount::zero();
2054  auto parsed = ParseMoney(args.GetArg("-minrelaytxfee", ""), n);
2055  if (!parsed || n == Amount::zero()) {
2056  return InitError(AmountErrMsg("minrelaytxfee",
2057  args.GetArg("-minrelaytxfee", "")));
2058  }
2059  // High fee check is done afterward in CWallet::Create()
2061  }
2062 
2063  // Sanity check argument for min fee for including tx in block
2064  // TODO: Harmonize which arguments need sanity checking and where that
2065  // happens.
2066  if (args.IsArgSet("-blockmintxfee")) {
2067  Amount n = Amount::zero();
2068  if (!ParseMoney(args.GetArg("-blockmintxfee", ""), n)) {
2069  return InitError(AmountErrMsg("blockmintxfee",
2070  args.GetArg("-blockmintxfee", "")));
2071  }
2072  }
2073 
2074  // Feerate used to define dust. Shouldn't be changed lightly as old
2075  // implementations may inadvertently create non-standard transactions.
2076  if (args.IsArgSet("-dustrelayfee")) {
2077  Amount n = Amount::zero();
2078  auto parsed = ParseMoney(args.GetArg("-dustrelayfee", ""), n);
2079  if (!parsed || Amount::zero() == n) {
2080  return InitError(
2081  AmountErrMsg("dustrelayfee", args.GetArg("-dustrelayfee", "")));
2082  }
2083  dustRelayFee = CFeeRate(n);
2084  }
2085 
2087  !args.GetBoolArg("-acceptnonstdtxn", !chainparams.RequireStandard());
2088  if (!chainparams.IsTestChain() && !fRequireStandard) {
2089  return InitError(strprintf(
2090  Untranslated(
2091  "acceptnonstdtxn is not currently supported for %s chain"),
2092  chainparams.NetworkIDString()));
2093  }
2094  nBytesPerSigOp = args.GetArg("-bytespersigop", nBytesPerSigOp);
2095 
2097  return false;
2098  }
2099 
2101  args.GetBoolArg("-permitbaremultisig", DEFAULT_PERMIT_BAREMULTISIG);
2103  args.GetBoolArg("-datacarrier", DEFAULT_ACCEPT_DATACARRIER);
2104 
2105  // Option to startup with mocktime set (used for regression testing):
2106  SetMockTime(args.GetArg("-mocktime", 0)); // SetMockTime(0) is a no-op
2107 
2108  if (args.GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS)) {
2109  nLocalServices = ServiceFlags(nLocalServices | NODE_BLOOM);
2110  }
2111 
2112  nMaxTipAge = args.GetArg("-maxtipage", DEFAULT_MAX_TIP_AGE);
2113 
2114  if (args.IsArgSet("-proxy") && args.GetArg("-proxy", "").empty()) {
2115  return InitError(_(
2116  "No proxy server specified. Use -proxy=<ip> or -proxy=<ip:port>."));
2117  }
2118 
2119  return true;
2120 }
2121 
2122 static bool LockDataDirectory(bool probeOnly) {
2123  // Make sure only a single Bitcoin process is using the data directory.
2124  fs::path datadir = GetDataDir();
2125  if (!DirIsWritable(datadir)) {
2126  return InitError(strprintf(
2127  _("Cannot write to data directory '%s'; check permissions."),
2128  fs::PathToString(datadir)));
2129  }
2130  if (!LockDirectory(datadir, ".lock", probeOnly)) {
2131  return InitError(strprintf(_("Cannot obtain a lock on data directory "
2132  "%s. %s is probably already running."),
2133  fs::PathToString(datadir), PACKAGE_NAME));
2134  }
2135  return true;
2136 }
2137 
2139  // Step 4: sanity checks
2140 
2141  // Initialize elliptic curve code
2142  std::string sha256_algo = SHA256AutoDetect();
2143  LogPrintf("Using the '%s' SHA256 implementation\n", sha256_algo);
2144  RandomInit();
2145  ECC_Start();
2146  globalVerifyHandle.reset(new ECCVerifyHandle());
2147 
2148  // Sanity check
2149  if (!InitSanityCheck()) {
2150  return InitError(strprintf(
2151  _("Initialization sanity check failed. %s is shutting down."),
2152  PACKAGE_NAME));
2153  }
2154 
2155  // Probe the data directory lock to give an early error message, if possible
2156  // We cannot hold the data directory lock here, as the forking for daemon()
2157  // hasn't yet happened, and a fork will cause weird behavior to it.
2158  return LockDataDirectory(true);
2159 }
2160 
2162  // After daemonization get the data directory lock again and hold on to it
2163  // until exit. This creates a slight window for a race condition to happen,
2164  // however this condition is harmless: it will at most make us exit without
2165  // printing a message to console.
2166  if (!LockDataDirectory(false)) {
2167  // Detailed error printed inside LockDataDirectory
2168  return false;
2169  }
2170  return true;
2171 }
2172 
2174  node.chain = interfaces::MakeChain(node, Params());
2175  // Create client interfaces for wallets that are supposed to be loaded
2176  // according to -wallet and -disablewallet options. This only constructs
2177  // the interfaces, it doesn't load wallet data. Wallets actually get loaded
2178  // when load() and start() interface methods are called below.
2180  return true;
2181 }
2182 
2183 bool AppInitMain(Config &config, RPCServer &rpcServer,
2184  HTTPRPCRequestProcessor &httpRPCRequestProcessor,
2185  NodeContext &node,
2187  // Step 4a: application initialization
2188  const ArgsManager &args = *Assert(node.args);
2189  const CChainParams &chainparams = config.GetChainParams();
2190 
2191  if (!CreatePidFile(args)) {
2192  // Detailed error printed inside CreatePidFile().
2193  return false;
2194  }
2195 
2196  BCLog::Logger &logger = LogInstance();
2197  if (logger.m_print_to_file) {
2198  if (args.GetBoolArg("-shrinkdebugfile",
2199  logger.DefaultShrinkDebugFile())) {
2200  // Do this first since it both loads a bunch of debug.log into
2201  // memory, and because this needs to happen before any other
2202  // debug.log printing.
2203  logger.ShrinkDebugFile();
2204  }
2205  }
2206 
2207  if (!logger.StartLogging()) {
2208  return InitError(
2209  strprintf(Untranslated("Could not open debug log file %s"),
2210  fs::PathToString(logger.m_file_path)));
2211  }
2212 
2213  if (!logger.m_log_timestamps) {
2214  LogPrintf("Startup time: %s\n", FormatISO8601DateTime(GetTime()));
2215  }
2216  LogPrintf("Default data directory %s\n",
2218  LogPrintf("Using data directory %s\n", fs::PathToString(GetDataDir()));
2219 
2220  // Only log conf file usage message if conf file actually exists.
2221  fs::path config_file_path =
2222  GetConfigFile(args.GetArg("-conf", BITCOIN_CONF_FILENAME));
2223  if (fs::exists(config_file_path)) {
2224  LogPrintf("Config file: %s\n", fs::PathToString(config_file_path));
2225  } else if (args.IsArgSet("-conf")) {
2226  // Warn if no conf file exists at path provided by user
2227  InitWarning(
2228  strprintf(_("The specified config file %s does not exist\n"),
2229  fs::PathToString(config_file_path)));
2230  } else {
2231  // Not categorizing as "Warning" because it's the default behavior
2232  LogPrintf("Config file: %s (not found, skipping)\n",
2233  fs::PathToString(config_file_path));
2234  }
2235 
2236  // Log the config arguments to debug.log
2237  args.LogArgs();
2238 
2239  LogPrintf("Using at most %i automatic connections (%i file descriptors "
2240  "available)\n",
2241  nMaxConnections, nFD);
2242 
2243  // Warn about relative -datadir path.
2244  if (args.IsArgSet("-datadir") &&
2245  !fs::PathFromString(args.GetArg("-datadir", "")).is_absolute()) {
2246  LogPrintf("Warning: relative datadir option '%s' specified, which will "
2247  "be interpreted relative to the current working directory "
2248  "'%s'. This is fragile, because if bitcoin is started in the "
2249  "future from a different location, it will be unable to "
2250  "locate the current data files. There could also be data "
2251  "loss if bitcoin is started while in a temporary "
2252  "directory.\n",
2253  args.GetArg("-datadir", ""),
2254  fs::PathToString(fs::current_path()));
2255  }
2256 
2259 
2260  int script_threads = args.GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
2261  if (script_threads <= 0) {
2262  // -par=0 means autodetect (number of cores - 1 script threads)
2263  // -par=-n means "leave n cores free" (number of cores - n - 1 script
2264  // threads)
2265  script_threads += GetNumCores();
2266  }
2267 
2268  // Subtract 1 because the main thread counts towards the par threads
2269  script_threads = std::max(script_threads - 1, 0);
2270 
2271  // Number of script-checking threads <= MAX_SCRIPTCHECK_THREADS
2272  script_threads = std::min(script_threads, MAX_SCRIPTCHECK_THREADS);
2273 
2274  LogPrintf("Script verification uses %d additional threads\n",
2275  script_threads);
2276  if (script_threads >= 1) {
2277  for (int i = 0; i < script_threads; ++i) {
2278  threadGroup.create_thread([i]() { return ThreadScriptCheck(i); });
2279  }
2280  }
2281 
2282  assert(!node.scheduler);
2283  node.scheduler = std::make_unique<CScheduler>();
2284 
2285  // Start the lightweight task scheduler thread
2286  CScheduler::Function serviceLoop = [&node] {
2287  node.scheduler->serviceQueue();
2288  };
2289  threadGroup.create_thread(std::bind(&TraceThread<CScheduler::Function>,
2290  "scheduler", serviceLoop));
2291 
2292  // Gather some entropy once per minute.
2293  node.scheduler->scheduleEvery(
2294  [] {
2295  RandAddPeriodic();
2296  return true;
2297  },
2298  std::chrono::minutes{1});
2299 
2301 
2306  RegisterAllRPCCommands(config, rpcServer, tableRPC);
2307  for (const auto &client : node.chain_clients) {
2308  client->registerRpcs();
2309  }
2310 #if ENABLE_ZMQ
2312 #endif
2313 
2320  if (args.GetBoolArg("-server", false)) {
2321  uiInterface.InitMessage_connect(SetRPCWarmupStatus);
2322  if (!AppInitServers(config, httpRPCRequestProcessor, node)) {
2323  return InitError(
2324  _("Unable to start HTTP server. See debug log for details."));
2325  }
2326  }
2327 
2328  // Step 5: verify wallet database integrity
2329  for (const auto &client : node.chain_clients) {
2330  if (!client->verify()) {
2331  return false;
2332  }
2333  }
2334 
2335  // Step 6: network initialization
2336 
2337  // Note that we absolutely cannot open any actual connections
2338  // until the very end ("start node") as the UTXO/block state
2339  // is not yet setup and may end up being set up twice if we
2340  // need to reindex later.
2341 
2342  assert(!node.banman);
2343  node.banman = std::make_unique<BanMan>(
2344  GetDataDir() / "banlist.dat", config.GetChainParams(), &uiInterface,
2345  args.GetArg("-bantime", DEFAULT_MISBEHAVING_BANTIME));
2346  assert(!node.connman);
2347  node.connman = std::make_unique<CConnman>(
2348  config, GetRand(std::numeric_limits<uint64_t>::max()),
2349  GetRand(std::numeric_limits<uint64_t>::max()),
2350  gArgs.GetBoolArg("-networkactive", true));
2351 
2352  assert(!node.mempool);
2353  int check_ratio = std::min<int>(
2354  std::max<int>(
2355  args.GetArg("-checkmempool",
2356  chainparams.DefaultConsistencyChecks() ? 1 : 0),
2357  0),
2358  1000000);
2359  node.mempool = std::make_unique<CTxMemPool>(check_ratio);
2360 
2361  assert(!node.chainman);
2362  node.chainman = &g_chainman;
2363  ChainstateManager &chainman = *Assert(node.chainman);
2364 
2365  assert(!node.peerman);
2366  node.peerman =
2367  PeerManager::make(chainparams, *node.connman, node.banman.get(),
2368  *node.scheduler, chainman, *node.mempool,
2369  args.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY));
2371 
2372  // sanitize comments per BIP-0014, format user agent and check total size
2373  std::vector<std::string> uacomments;
2374  for (const std::string &cmt : args.GetArgs("-uacomment")) {
2375  if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT)) {
2376  return InitError(strprintf(
2377  _("User Agent comment (%s) contains unsafe characters."), cmt));
2378  }
2379  uacomments.push_back(cmt);
2380  }
2381  const std::string client_name = args.GetArg("-uaclientname", CLIENT_NAME);
2382  const std::string client_version =
2383  args.GetArg("-uaclientversion", FormatVersion(CLIENT_VERSION));
2384  if (client_name != SanitizeString(client_name, SAFE_CHARS_UA_COMMENT)) {
2385  return InitError(strprintf(
2386  _("-uaclientname (%s) contains invalid characters."), client_name));
2387  }
2388  if (client_version !=
2389  SanitizeString(client_version, SAFE_CHARS_UA_COMMENT)) {
2390  return InitError(
2391  strprintf(_("-uaclientversion (%s) contains invalid characters."),
2392  client_version));
2393  }
2394  const std::string strSubVersion =
2395  FormatUserAgent(client_name, client_version, uacomments);
2396  if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
2397  return InitError(strprintf(
2398  _("Total length of network version string (%i) exceeds maximum "
2399  "length (%i). Reduce the number or size of uacomments."),
2400  strSubVersion.size(), MAX_SUBVERSION_LENGTH));
2401  }
2402 
2403  if (args.IsArgSet("-onlynet")) {
2404  std::set<enum Network> nets;
2405  for (const std::string &snet : args.GetArgs("-onlynet")) {
2406  enum Network net = ParseNetwork(snet);
2407  if (net == NET_UNROUTABLE) {
2408  return InitError(strprintf(
2409  _("Unknown network specified in -onlynet: '%s'"), snet));
2410  }
2411  nets.insert(net);
2412  }
2413  for (int n = 0; n < NET_MAX; n++) {
2414  enum Network net = (enum Network)n;
2415  if (!nets.count(net)) {
2416  SetReachable(net, false);
2417  }
2418  }
2419  }
2420 
2421  // Check for host lookup allowed before parsing any network related
2422  // parameters
2423  fNameLookup = args.GetBoolArg("-dns", DEFAULT_NAME_LOOKUP);
2424 
2425  bool proxyRandomize =
2426  args.GetBoolArg("-proxyrandomize", DEFAULT_PROXYRANDOMIZE);
2427  // -proxy sets a proxy for all outgoing network traffic
2428  // -noproxy (or -proxy=0) as well as the empty string can be used to not set
2429  // a proxy, this is the default
2430  std::string proxyArg = args.GetArg("-proxy", "");
2431  SetReachable(NET_ONION, false);
2432  if (proxyArg != "" && proxyArg != "0") {
2433  CService proxyAddr;
2434  if (!Lookup(proxyArg, proxyAddr, 9050, fNameLookup)) {
2435  return InitError(strprintf(
2436  _("Invalid -proxy address or hostname: '%s'"), proxyArg));
2437  }
2438 
2439  proxyType addrProxy = proxyType(proxyAddr, proxyRandomize);
2440  if (!addrProxy.IsValid()) {
2441  return InitError(strprintf(
2442  _("Invalid -proxy address or hostname: '%s'"), proxyArg));
2443  }
2444 
2445  SetProxy(NET_IPV4, addrProxy);
2446  SetProxy(NET_IPV6, addrProxy);
2447  SetProxy(NET_ONION, addrProxy);
2448  SetNameProxy(addrProxy);
2449  // by default, -proxy sets onion as reachable, unless -noonion later
2450  SetReachable(NET_ONION, true);
2451  }
2452 
2453  // -onion can be used to set only a proxy for .onion, or override normal
2454  // proxy for .onion addresses.
2455  // -noonion (or -onion=0) disables connecting to .onion entirely. An empty
2456  // string is used to not override the onion proxy (in which case it defaults
2457  // to -proxy set above, or none)
2458  std::string onionArg = args.GetArg("-onion", "");
2459  if (onionArg != "") {
2460  if (onionArg == "0") {
2461  // Handle -noonion/-onion=0
2462  SetReachable(NET_ONION, false);
2463  } else {
2464  CService onionProxy;
2465  if (!Lookup(onionArg, onionProxy, 9050, fNameLookup)) {
2466  return InitError(strprintf(
2467  _("Invalid -onion address or hostname: '%s'"), onionArg));
2468  }
2469  proxyType addrOnion = proxyType(onionProxy, proxyRandomize);
2470  if (!addrOnion.IsValid()) {
2471  return InitError(strprintf(
2472  _("Invalid -onion address or hostname: '%s'"), onionArg));
2473  }
2474  SetProxy(NET_ONION, addrOnion);
2475  SetReachable(NET_ONION, true);
2476  }
2477  }
2478 
2479  fListen = args.GetBoolArg("-listen", DEFAULT_LISTEN);
2480  fDiscover = args.GetBoolArg("-discover", true);
2481 
2482  for (const std::string &strAddr : args.GetArgs("-externalip")) {
2483  CService addrLocal;
2484  if (Lookup(strAddr, addrLocal, GetListenPort(), fNameLookup) &&
2485  addrLocal.IsValid()) {
2486  AddLocal(addrLocal, LOCAL_MANUAL);
2487  } else {
2488  return InitError(ResolveErrMsg("externalip", strAddr));
2489  }
2490  }
2491 
2492  // Read asmap file if configured
2493  if (args.IsArgSet("-asmap")) {
2494  fs::path asmap_path = fs::PathFromString(args.GetArg("-asmap", ""));
2495  if (asmap_path.empty()) {
2497  }
2498  if (!asmap_path.is_absolute()) {
2499  asmap_path = GetDataDir() / asmap_path;
2500  }
2501  if (!fs::exists(asmap_path)) {
2502  InitError(strprintf(_("Could not find asmap file %s"),
2503  fs::quoted(fs::PathToString(asmap_path))));
2504  return false;
2505  }
2506  std::vector<bool> asmap = DecodeAsmap(asmap_path);
2507  if (asmap.size() == 0) {
2508  InitError(strprintf(_("Could not parse asmap file %s"),
2509  fs::quoted(fs::PathToString(asmap_path))));
2510  return false;
2511  }
2512  const uint256 asmap_version = SerializeHash(asmap);
2513  node.connman->SetAsmap(std::move(asmap));
2514  LogPrintf("Using asmap version %s for IP bucketing\n",
2515  asmap_version.ToString());
2516  } else {
2517  LogPrintf("Using /16 prefix for IP bucketing\n");
2518  }
2519 
2520 #if ENABLE_ZMQ
2522 
2525  }
2526 #endif
2527 
2528  // Step 6.5 (I guess ?): Initialize Avalanche.
2529  bilingual_str avalancheError;
2531  args, *node.chain, node.connman.get(), avalancheError);
2532  if (!g_avalanche) {
2533  InitError(avalancheError);
2534  return false;
2535  }
2536 
2537  if (isAvalancheEnabled(args) &&
2538  g_avalanche->isAvalancheServiceAvailable()) {
2539  nLocalServices = ServiceFlags(nLocalServices | NODE_AVALANCHE);
2540  }
2541 
2542  // Step 7: load block chain
2543 
2544  fReindex = args.GetBoolArg("-reindex", false);
2545  bool fReindexChainState = args.GetBoolArg("-reindex-chainstate", false);
2546 
2547  // cache size calculations
2548  int64_t nTotalCache = (args.GetArg("-dbcache", DEFAULT_DB_CACHE_MB) << 20);
2549  // total cache cannot be less than MIN_DB_CACHE_MB
2550  nTotalCache = std::max(nTotalCache, MIN_DB_CACHE_MB << 20);
2551  // total cache cannot be greater than MAX_DB_CACHE_MB
2552  nTotalCache = std::min(nTotalCache, MAX_DB_CACHE_MB << 20);
2553  int64_t nBlockTreeDBCache =
2554  std::min(nTotalCache / 8, MAX_BLOCK_DB_CACHE_MB << 20);
2555  nTotalCache -= nBlockTreeDBCache;
2556  int64_t nTxIndexCache =
2557  std::min(nTotalCache / 8, args.GetBoolArg("-txindex", DEFAULT_TXINDEX)
2558  ? MAX_TX_INDEX_CACHE_MB << 20
2559  : 0);
2560  nTotalCache -= nTxIndexCache;
2561  int64_t filter_index_cache = 0;
2562  if (!g_enabled_filter_types.empty()) {
2563  size_t n_indexes = g_enabled_filter_types.size();
2564  int64_t max_cache =
2565  std::min(nTotalCache / 8, MAX_FILTER_INDEX_CACHE_MB << 20);
2566  filter_index_cache = max_cache / n_indexes;
2567  nTotalCache -= filter_index_cache * n_indexes;
2568  }
2569  // use 25%-50% of the remainder for disk cache
2570  int64_t nCoinDBCache =
2571  std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23));
2572  // cap total coins db cache
2573  nCoinDBCache = std::min(nCoinDBCache, MAX_COINS_DB_CACHE_MB << 20);
2574  nTotalCache -= nCoinDBCache;
2575  // the rest goes to in-memory cache
2576  int64_t nCoinCacheUsage = nTotalCache;
2577  int64_t nMempoolSizeMax =
2578  args.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
2579  LogPrintf("Cache configuration:\n");
2580  LogPrintf("* Using %.1f MiB for block index database\n",
2581  nBlockTreeDBCache * (1.0 / 1024 / 1024));
2582  if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
2583  LogPrintf("* Using %.1f MiB for transaction index database\n",
2584  nTxIndexCache * (1.0 / 1024 / 1024));
2585  }
2586  for (BlockFilterType filter_type : g_enabled_filter_types) {
2587  LogPrintf("* Using %.1f MiB for %s block filter index database\n",
2588  filter_index_cache * (1.0 / 1024 / 1024),
2589  BlockFilterTypeName(filter_type));
2590  }
2591  LogPrintf("* Using %.1f MiB for chain state database\n",
2592  nCoinDBCache * (1.0 / 1024 / 1024));
2593  LogPrintf("* Using %.1f MiB for in-memory UTXO set (plus up to %.1f MiB of "
2594  "unused mempool space)\n",
2595  nCoinCacheUsage * (1.0 / 1024 / 1024),
2596  nMempoolSizeMax * (1.0 / 1024 / 1024));
2597 
2598  bool fLoaded = false;
2599  while (!fLoaded && !ShutdownRequested()) {
2600  const bool fReset = fReindex;
2601  auto is_coinsview_empty =
2602  [&](CChainState *chainstate) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
2603  return fReset || fReindexChainState ||
2604  chainstate->CoinsTip().GetBestBlock().IsNull();
2605  };
2606  bilingual_str strLoadError;
2607 
2608  uiInterface.InitMessage(_("Loading block index...").translated);
2609  do {
2610  bool failed_verification = false;
2611  const int64_t load_block_index_start_time = GetTimeMillis();
2612  try {
2613  LOCK(cs_main);
2614  chainman.InitializeChainstate(*Assert(node.mempool));
2615  chainman.m_total_coinstip_cache = nCoinCacheUsage;
2616  chainman.m_total_coinsdb_cache = nCoinDBCache;
2617 
2618  UnloadBlockIndex(node.mempool.get(), chainman);
2619 
2620  // new CBlockTreeDB tries to delete the existing file, which
2621  // fails if it's still open from the previous loop. Close it
2622  // first:
2623  pblocktree.reset();
2624  pblocktree.reset(
2625  new CBlockTreeDB(nBlockTreeDBCache, false, fReset));
2626 
2627  if (fReset) {
2628  pblocktree->WriteReindexing(true);
2629  // If we're reindexing in prune mode, wipe away unusable
2630  // block files and all undo data files
2631  if (fPruneMode) {
2633  }
2634  }
2635 
2636  const Consensus::Params &params = chainparams.GetConsensus();
2637 
2638  // If necessary, upgrade from older database format.
2639  // This is a no-op if we cleared the block tree db with -reindex
2640  // or -reindex-chainstate
2641  if (!pblocktree->Upgrade(params)) {
2642  strLoadError = _("Error upgrading block index database");
2643  break;
2644  }
2645 
2646  if (ShutdownRequested()) {
2647  break;
2648  }
2649 
2650  // LoadBlockIndex will load fHavePruned if we've ever removed a
2651  // block file from disk.
2652  // Note that it also sets fReindex based on the disk flag!
2653  // From here on out fReindex and fReset mean something
2654  // different!
2655  if (!chainman.LoadBlockIndex(params)) {
2656  if (ShutdownRequested()) {
2657  break;
2658  }
2659  strLoadError = _("Error loading block database");
2660  break;
2661  }
2662 
2663  // If the loaded chain has a wrong genesis, bail out immediately
2664  // (we're likely using a testnet datadir, or the other way
2665  // around).
2666  if (!chainman.BlockIndex().empty() &&
2668  return InitError(_("Incorrect or no genesis block found. "
2669  "Wrong datadir for network?"));
2670  }
2671 
2672  // Check for changed -prune state. What we are concerned about
2673  // is a user who has pruned blocks in the past, but is now
2674  // trying to run unpruned.
2675  if (fHavePruned && !fPruneMode) {
2676  strLoadError =
2677  _("You need to rebuild the database using -reindex to "
2678  "go back to unpruned mode. This will redownload the "
2679  "entire blockchain");
2680  break;
2681  }
2682 
2683  // At this point blocktree args are consistent with what's on
2684  // disk. If we're not mid-reindex (based on disk + args), add a
2685  // genesis block on disk (otherwise we use the one already on
2686  // disk).
2687  // This is called again in ThreadImport after the reindex
2688  // completes.
2689  if (!fReindex && !LoadGenesisBlock(chainparams)) {
2690  strLoadError = _("Error initializing block database");
2691  break;
2692  }
2693 
2694  // At this point we're either in reindex or we've loaded a
2695  // useful block tree into BlockIndex()!
2696 
2697  bool failed_chainstate_init = false;
2698 
2699  for (CChainState *chainstate : chainman.GetAll()) {
2700  chainstate->InitCoinsDB(
2701  /* cache_size_bytes */ nCoinDBCache,
2702  /* in_memory */ false,
2703  /* should_wipe */ fReset || fReindexChainState);
2704 
2705  chainstate->CoinsErrorCatcher().AddReadErrCallback([]() {
2706  uiInterface.ThreadSafeMessageBox(
2707  _("Error reading from database, shutting down."),
2709  });
2710 
2711  // If necessary, upgrade from older database format.
2712  // This is a no-op if we cleared the coinsviewdb with
2713  // -reindex or -reindex-chainstate
2714  if (!chainstate->CoinsDB().Upgrade()) {
2715  strLoadError = _("Error upgrading chainstate database");
2716  failed_chainstate_init = true;
2717  break;
2718  }
2719 
2720  // ReplayBlocks is a no-op if we cleared the coinsviewdb
2721  // with -reindex or -reindex-chainstate
2722  if (!chainstate->ReplayBlocks(params)) {
2723  strLoadError = _(
2724  "Unable to replay blocks. You will need to rebuild "
2725  "the database using -reindex-chainstate.");
2726  failed_chainstate_init = true;
2727  break;
2728  }
2729 
2730  // The on-disk coinsdb is now in a good state, create the
2731  // cache
2732  chainstate->InitCoinsCache(nCoinCacheUsage);
2733  assert(chainstate->CanFlushToDisk());
2734 
2735  if (!is_coinsview_empty(chainstate)) {
2736  // LoadChainTip initializes the chain based on
2737  // CoinsTip()'s best block
2738  if (!chainstate->LoadChainTip(chainparams)) {
2739  strLoadError =
2740  _("Error initializing block database");
2741  failed_chainstate_init = true;
2742  // out of the per-chainstate loop
2743  break;
2744  }
2745  assert(chainstate->m_chain.Tip() != nullptr);
2746  }
2747  }
2748 
2749  if (failed_chainstate_init) {
2750  // out of the chainstate activation do-while
2751  break;
2752  }
2753 
2754  for (CChainState *chainstate : chainman.GetAll()) {
2755  if (!is_coinsview_empty(chainstate)) {
2756  uiInterface.InitMessage(
2757  _("Verifying blocks...").translated);
2758  if (fHavePruned &&
2759  args.GetArg("-checkblocks", DEFAULT_CHECKBLOCKS) >
2761  LogPrintf(
2762  "Prune: pruned datadir may not have more than "
2763  "%d blocks; only checking available blocks\n",
2765  }
2766 
2767  const CBlockIndex *tip = chainstate->m_chain.Tip();
2768  RPCNotifyBlockChange(tip);
2769  if (tip &&
2770  tip->nTime > GetAdjustedTime() + 2 * 60 * 60) {
2771  strLoadError =
2772  _("The block database contains a block which "
2773  "appears to be from the future. "
2774  "This may be due to your computer's date and "
2775  "time being set incorrectly. "
2776  "Only rebuild the block database if you are "
2777  "sure that your computer's date and time are "
2778  "correct");
2779  failed_verification = true;
2780  break;
2781  }
2782 
2783  // Only verify the DB of the active chainstate. This is
2784  // fixed in later work when we allow VerifyDB to be
2785  // parameterized by chainstate.
2786  if (&::ChainstateActive() == chainstate &&
2787  !CVerifyDB().VerifyDB(
2788  config, &chainstate->CoinsDB(),
2789  args.GetArg("-checklevel", DEFAULT_CHECKLEVEL),
2790  args.GetArg("-checkblocks",
2791  DEFAULT_CHECKBLOCKS))) {
2792  strLoadError =
2793  _("Corrupted block database detected");
2794  failed_verification = true;
2795  break;
2796  }
2797  }
2798  }
2799  } catch (const std::exception &e) {
2800  LogPrintf("%s\n", e.what());
2801  strLoadError = _("Error opening block database");
2802  failed_verification = true;
2803  break;
2804  }
2805 
2806  if (!failed_verification) {
2807  fLoaded = true;
2808  LogPrintf(" block index %15dms\n",
2809  GetTimeMillis() - load_block_index_start_time);
2810  }
2811  } while (false);
2812 
2813  if (!fLoaded && !ShutdownRequested()) {
2814  // first suggest a reindex
2815  if (!fReset) {
2816  bool fRet = uiInterface.ThreadSafeQuestion(
2817  strLoadError + Untranslated(".\n\n") +
2818  _("Do you want to rebuild the block database now?"),
2819  strLoadError.original +
2820  ".\nPlease restart with -reindex or "
2821  "-reindex-chainstate to recover.",
2822  "",
2825  if (fRet) {
2826  fReindex = true;
2827  AbortShutdown();
2828  } else {
2829  LogPrintf("Aborted block database rebuild. Exiting.\n");
2830  return false;
2831  }
2832  } else {
2833  return InitError(strLoadError);
2834  }
2835  }
2836  }
2837 
2838  // As LoadBlockIndex can take several minutes, it's possible the user
2839  // requested to kill the GUI during the last operation. If so, exit.
2840  // As the program has not fully started yet, Shutdown() is possibly
2841  // overkill.
2842  if (ShutdownRequested()) {
2843  LogPrintf("Shutdown requested. Exiting.\n");
2844  return false;
2845  }
2846 
2847  // Encoded addresses using cashaddr instead of base58.
2848  // We do this by default to avoid confusion with BTC addresses.
2849  config.SetCashAddrEncoding(args.GetBoolArg("-usecashaddr", true));
2850 
2851  // Step 8: load indexers
2852  if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
2853  g_txindex = std::make_unique<TxIndex>(nTxIndexCache, false, fReindex);
2854  g_txindex->Start();
2855  }
2856 
2857  for (const auto &filter_type : g_enabled_filter_types) {
2858  InitBlockFilterIndex(filter_type, filter_index_cache, false, fReindex);
2859  GetBlockFilterIndex(filter_type)->Start();
2860  }
2861 
2862  // Step 9: load wallet
2863  for (const auto &client : node.chain_clients) {
2864  if (!client->load()) {
2865  return false;
2866  }
2867  }
2868 
2869  // Step 10: data directory maintenance
2870 
2871  // if pruning, unset the service bit and perform the initial blockstore
2872  // prune after any wallet rescanning has taken place.
2873  if (fPruneMode) {
2874  LogPrintf("Unsetting NODE_NETWORK on prune mode\n");
2875  nLocalServices = ServiceFlags(nLocalServices & ~NODE_NETWORK);
2876  if (!fReindex) {
2877  LOCK(cs_main);
2878  for (CChainState *chainstate : chainman.GetAll()) {
2879  uiInterface.InitMessage(_("Pruning blockstore...").translated);
2880  chainstate->PruneAndFlush();
2881  }
2882  }
2883  }
2884 
2885  // Step 11: import blocks
2886  if (!CheckDiskSpace(GetDataDir())) {
2887  InitError(strprintf(_("Error: Disk space is low for %s"),
2889  return false;
2890  }
2892  InitError(
2893  strprintf(_("Error: Disk space is low for %s"),
2895  return false;
2896  }
2897 
2898  // Either install a handler to notify us when genesis activates, or set
2899  // fHaveGenesis directly.
2900  // No locking, as this happens before any background thread is started.
2901  boost::signals2::connection block_notify_genesis_wait_connection;
2902  if (::ChainActive().Tip() == nullptr) {
2903  block_notify_genesis_wait_connection =
2904  uiInterface.NotifyBlockTip_connect(
2905  std::bind(BlockNotifyGenesisWait, std::placeholders::_2));
2906  } else {
2907  fHaveGenesis = true;
2908  }
2909 
2910 #if defined(HAVE_SYSTEM)
2911  const std::string block_notify = args.GetArg("-blocknotify", "");
2912  if (!block_notify.empty()) {
2913  uiInterface.NotifyBlockTip_connect([block_notify](
2914  SynchronizationState sync_state,
2915  const CBlockIndex *pBlockIndex) {
2916  if (sync_state != SynchronizationState::POST_INIT || !pBlockIndex) {
2917  return;
2918  }
2919  std::string command = block_notify;
2920  boost::replace_all(command, "%s",
2921  pBlockIndex->GetBlockHash().GetHex());
2922  std::thread t(runCommand, command);
2923  // thread runs free
2924  t.detach();
2925  });
2926  }
2927 #endif
2928 
2929  std::vector<fs::path> vImportFiles;
2930  for (const std::string &strFile : args.GetArgs("-loadblock")) {
2931  vImportFiles.push_back(fs::PathFromString(strFile));
2932  }
2933 
2934  g_load_block =
2935  std::thread(&TraceThread<std::function<void()>>, "loadblk",
2936  [=, &config, &chainman, &args] {
2937  ThreadImport(config, chainman, vImportFiles, args);
2938  });
2939 
2940  // Wait for genesis block to be processed
2941  {
2943  // We previously could hang here if StartShutdown() is called prior to
2944  // ThreadImport getting started, so instead we just wait on a timer to
2945  // check ShutdownRequested() regularly.
2946  while (!fHaveGenesis && !ShutdownRequested()) {
2947  g_genesis_wait_cv.wait_for(lock, std::chrono::milliseconds(500));
2948  }
2949  block_notify_genesis_wait_connection.disconnect();
2950  }
2951 
2952  if (ShutdownRequested()) {
2953  return false;
2954  }
2955 
2956  // Step 12: start node
2957 
2958  int chain_active_height;
2959 
2961  {
2962  LOCK(cs_main);
2963  LogPrintf("block tree size = %u\n", chainman.BlockIndex().size());
2964  chain_active_height = chainman.ActiveChain().Height();
2965  if (tip_info) {
2966  tip_info->block_height = chain_active_height;
2967  tip_info->block_time =
2968  chainman.ActiveChain().Tip()
2969  ? chainman.ActiveChain().Tip()->GetBlockTime()
2972  Params().TxData(), chainman.ActiveChain().Tip());
2973  }
2974  if (tip_info && ::pindexBestHeader) {
2977  }
2978  }
2979  LogPrintf("nBestHeight = %d\n", chain_active_height);
2980  if (node.peerman) {
2981  node.peerman->SetBestHeight(chain_active_height);
2982  }
2983 
2984  Discover();
2985 
2986  // Map ports with UPnP
2987  if (args.GetBoolArg("-upnp", DEFAULT_UPNP)) {
2988  StartMapPort();
2989  }
2990 
2991  CConnman::Options connOptions;
2992  connOptions.nLocalServices = nLocalServices;
2993  connOptions.nMaxConnections = nMaxConnections;
2994  connOptions.m_max_outbound_full_relay = std::min(
2996  connOptions.m_max_outbound_block_relay = std::min(
2998  connOptions.nMaxConnections - connOptions.m_max_outbound_full_relay);
2999  connOptions.nMaxAddnode = MAX_ADDNODE_CONNECTIONS;
3000  connOptions.nMaxFeeler = MAX_FEELER_CONNECTIONS;
3001  connOptions.uiInterface = &uiInterface;
3002  connOptions.m_banman = node.banman.get();
3003  connOptions.m_msgproc = node.peerman.get();
3004  connOptions.nSendBufferMaxSize =
3005  1000 * args.GetArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER);
3006  connOptions.nReceiveFloodSize =
3007  1000 * args.GetArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER);
3008  connOptions.m_added_nodes = args.GetArgs("-addnode");
3009 
3010  connOptions.nMaxOutboundLimit =
3011  1024 * 1024 *
3012  args.GetArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET);
3013  connOptions.m_peer_connect_timeout = peer_connect_timeout;
3014 
3015  for (const std::string &bind_arg : args.GetArgs("-bind")) {
3016  CService bind_addr;
3017  const size_t index = bind_arg.rfind('=');
3018  if (index == std::string::npos) {
3019  if (Lookup(bind_arg, bind_addr, GetListenPort(), false)) {
3020  connOptions.vBinds.push_back(bind_addr);
3021  continue;
3022  }
3023  } else {
3024  const std::string network_type = bind_arg.substr(index + 1);
3025  if (network_type == "onion") {
3026  const std::string truncated_bind_arg =
3027  bind_arg.substr(0, index);
3028  if (Lookup(truncated_bind_arg, bind_addr,
3029  BaseParams().OnionServiceTargetPort(), false)) {
3030  connOptions.onion_binds.push_back(bind_addr);
3031  continue;
3032  }
3033  }
3034  }
3035  return InitError(ResolveErrMsg("bind", bind_arg));
3036  }
3037 
3038  if (connOptions.onion_binds.empty()) {
3039  connOptions.onion_binds.push_back(DefaultOnionServiceTarget());
3040  }
3041 
3042  if (args.GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION)) {
3043  const auto bind_addr = connOptions.onion_binds.front();
3044  if (connOptions.onion_binds.size() > 1) {
3046  _("More than one onion bind address is provided. Using %s for "
3047  "the automatically created Tor onion service."),
3048  bind_addr.ToStringIPPort()));
3049  }
3050  StartTorControl(bind_addr);
3051  }
3052 
3053  for (const std::string &strBind : args.GetArgs("-whitebind")) {
3054  NetWhitebindPermissions whitebind;
3056  if (!NetWhitebindPermissions::TryParse(strBind, whitebind, error)) {
3057  return InitError(error);
3058  }
3059  connOptions.vWhiteBinds.push_back(whitebind);
3060  }
3061 
3062  for (const auto &net : args.GetArgs("-whitelist")) {
3063  NetWhitelistPermissions subnet;
3065  if (!NetWhitelistPermissions::TryParse(net, subnet, error)) {
3066  return InitError(error);
3067  }
3068  connOptions.vWhitelistedRange.push_back(subnet);
3069  }
3070 
3071  connOptions.vSeedNodes = args.GetArgs("-seednode");
3072 
3073  // Initiate outbound connections unless connect=0
3074  connOptions.m_use_addrman_outgoing = !args.IsArgSet("-connect");
3075  if (!connOptions.m_use_addrman_outgoing) {
3076  const auto connect = args.GetArgs("-connect");
3077  if (connect.size() != 1 || connect[0] != "0") {
3078  connOptions.m_specified_outgoing = connect;
3079  }
3080  }
3081  if (!node.connman->Start(*node.scheduler, connOptions)) {
3082  return false;
3083  }
3084 
3085  // Step 13: finished
3086 
3088  uiInterface.InitMessage(_("Done loading").translated);
3089 
3090  for (const auto &client : node.chain_clients) {
3091  client->start(*node.scheduler);
3092  }
3093 
3094  BanMan *banman = node.banman.get();
3095  node.scheduler->scheduleEvery(
3096  [banman] {
3097  banman->DumpBanlist();
3098  return true;
3099  },
3101 
3102  // Start Avalanche's event loop.
3103  g_avalanche->startEventLoop(*node.scheduler);
3104 
3105 #if HAVE_SYSTEM
3106  StartupNotify(args);
3107 #endif
3108 
3109  return true;
3110 }
DEFAULT_MAX_REORG_DEPTH
static const int DEFAULT_MAX_REORG_DEPTH
Default for -maxreorgdepth.
Definition: validation.h:99
MIN_DB_CACHE_MB
static constexpr int64_t MIN_DB_CACHE_MB
min. -dbcache (MiB)
Definition: txdb.h:29
CBlockIndex::GetBlockTime
int64_t GetBlockTime() const
Definition: blockindex.h:160
CopyrightHolders
std::string CopyrightHolders(const std::string &strPrefix)
Definition: system.cpp:1371
CreatePidFile
static bool CreatePidFile(const ArgsManager &args)
Definition: init.cpp:118
OpenBlockFile
FILE * OpenBlockFile(const FlatFilePos &pos, bool fReadOnly)
Open a block file (blk?????.dat).
Definition: blockdb.cpp:20
ArgsManager::LogArgs
void LogArgs() const
Log the config file options and the command line arguments, useful for troubleshooting.
Definition: system.cpp:1108
AppInitInterfaces
bool AppInitInterfaces(NodeContext &node)
Initialize node and wallet interface pointers.
Definition: init.cpp:2173
Config::GetMaxBlockSize
virtual uint64_t GetMaxBlockSize() const =0
LOCK2
#define LOCK2(cs1, cs2)
Definition: sync.h:244
ShutdownRequested
bool ShutdownRequested()
Definition: shutdown.cpp:18
CService
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:514
policy.h
DEFAULT_LOGTIMEMICROS
static const bool DEFAULT_LOGTIMEMICROS
Definition: logging.h:21
zmqabstractnotifier.h
g_wallet_init_interface
const WalletInitInterface & g_wallet_init_interface
Definition: init.cpp:40
BITCOIN_PID_FILENAME
static const char * BITCOIN_PID_FILENAME
The PID file facilities.
Definition: init.cpp:111
DirIsWritable
bool DirIsWritable(const fs::path &directory)
Definition: system.cpp:127
BlockFilterTypeName
const std::string & BlockFilterTypeName(BlockFilterType filter_type)
Get the human-readable name for a filter type.
Definition: blockfilter.cpp:175
CConnman::Options::vSeedNodes
std::vector< std::string > vSeedNodes
Definition: net.h:991
fLogIPs
bool fLogIPs
Definition: logging.cpp:12
BCLog::Logger::m_print_to_file
bool m_print_to_file
Definition: logging.h:94
ArgsManager::GetBoolArg
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:601
SerializeHash
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:175
fs::exists
static bool exists(const path &p)
Definition: fs.h:94
ArgsManager::AddHiddenArgs
void AddHiddenArgs(const std::vector< std::string > &args)
Add many hidden arguments.
Definition: system.cpp:671
ChainstateManager::BlockIndex
BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:1188
_
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:55
CChainState::LoadMempool
void LoadMempool(const Config &config, const ArgsManager &args)
Load the persisted mempool from disk.
Definition: validation.cpp:4819
StopMapPort
void StopMapPort()
Definition: net.cpp:1886
GetConfigFile
fs::path GetConfigFile(const std::string &confPath)
Definition: system.cpp:841
DEFAULT_DESCENDANT_LIMIT
static constexpr unsigned int DEFAULT_DESCENDANT_LIMIT
Default for -limitdescendantcount, max number of in-mempool descendants.
Definition: mempool.h:22
InterruptMapPort
void InterruptMapPort()
Definition: net.cpp:1883
DEFAULT_MIN_RELAY_TX_FEE_PER_KB
static const Amount DEFAULT_MIN_RELAY_TX_FEE_PER_KB(1000 *SATOSHI)
Default for -minrelaytxfee, minimum relay fee for transactions.
GetDataDir
const fs::path & GetDataDir(bool fNetSpecific)
Definition: system.cpp:831
StartMapPort
void StartMapPort()
Definition: net.cpp:1880
CClientUIInterface::BTN_ABORT
@ BTN_ABORT
Definition: ui_interface.h:44
DEFAULT_CHECKLEVEL
static const unsigned int DEFAULT_CHECKLEVEL
Definition: validation.h:113
proxyType::IsValid
bool IsValid() const
Definition: netbase.h:35
NET_UNROUTABLE
@ NET_UNROUTABLE
Addresses from these networks are not publicly routable on the global Internet.
Definition: netaddress.h:46
ParseNetwork
enum Network ParseNetwork(const std::string &net_in)
Definition: netbase.cpp:43
DEFAULT_MAX_GENERATED_BLOCK_SIZE
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
AbsPathForConfigVal
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:1381
CHECKLEVEL_DOC
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument 'checklevel'.
Definition: validation.cpp:69
CConnman::Options::nMaxAddnode
int nMaxAddnode
Definition: net.h:982
tinyformat::format
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
DEFAULT_PERSIST_MEMPOOL
static const bool DEFAULT_PERSIST_MEMPOOL
Default for -persistmempool.
Definition: validation.h:90
check.h
g_txindex
std::unique_ptr< TxIndex > g_txindex
The global transaction index, used in GetTransaction. May be null.
Definition: txindex.cpp:20
NET_IPV4
@ NET_IPV4
IPv4.
Definition: netaddress.h:49
CImportingNow::~CImportingNow
~CImportingNow()
Definition: init.cpp:1361
CBlockIndex::nTime
uint32_t nTime
Definition: blockindex.h:81
DecodeAsmap
std::vector< bool > DecodeAsmap(fs::path path)
Read asmap from provided binary file.
Definition: asmap.cpp:293
ChainstateManager::m_total_coinstip_cache
int64_t m_total_coinstip_cache
The total number of bytes available for us to use across all in-memory coins caches.
Definition: validation.h:1161
settings.h
fs.h
ChainActive
CChain & ChainActive()
Please prefer the identical ChainstateManager::ActiveChain.
Definition: validation.cpp:86
IsHexNumber
bool IsHexNumber(const std::string &str)
Return true if the string is a hex number, optionally prefixed with "0x".
Definition: strencodings.cpp:73
avalanche::Processor::MakeProcessor
static std::unique_ptr< Processor > MakeProcessor(const ArgsManager &argsman, interfaces::Chain &chain, CConnman *connman, bilingual_str &error)
Definition: processor.cpp:147
InitParameterInteraction
void InitParameterInteraction(ArgsManager &args)
Parameter interaction: change current parameters depending on various rules.
Definition: init.cpp:1569
OptionsCategory::RPC
@ RPC
BlockValidationState
Definition: validation.h:138
fsbridge::fopen
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:24
asmap.h
NodeContext::args
ArgsManager * args
Definition: context.h:44
MAX_COINS_DB_CACHE_MB
static constexpr int64_t MAX_COINS_DB_CACHE_MB
Max memory allocated to coin DB specific cache (MiB)
Definition: txdb.h:46
avalanche.h
DEFAULT_HTTP_WORKQUEUE
static const int DEFAULT_HTTP_WORKQUEUE
Definition: httpserver.h:13
CConnman::Options::vBinds
std::vector< CService > vBinds
Definition: net.h:994
CleanupBlockRevFiles
static void CleanupBlockRevFiles()
Definition: init.cpp:1374
SetupHelpOptions
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
Definition: system.cpp:760
OptionsCategory::AVALANCHE
@ AVALANCHE
base_uint::GetHex
std::string GetHex() const
Definition: arith_uint256.cpp:155
CZMQNotificationInterface::Create
static CZMQNotificationInterface * Create()
Definition: zmqnotificationinterface.cpp:29
ArgsManager::ALLOW_ANY
@ ALLOW_ANY
Definition: system.h:155
NET_PERMISSIONS_DOC
const std::vector< std::string > NET_PERMISSIONS_DOC
Definition: net_permissions.cpp:12
DEFAULT_MAX_TIME_ADJUSTMENT
static const int64_t DEFAULT_MAX_TIME_ADJUSTMENT
Definition: timedata.h:13
ArgsManager::SoftSetBoolArg
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn't already have a value.
Definition: system.cpp:618
uiInterface
CClientUIInterface uiInterface
Definition: ui_interface.cpp:12
InitLogging
void InitLogging(const ArgsManager &args)
Initialize global loggers.
Definition: init.cpp:1681
ChainstateManager::GetAll
CChainState &InitializeChainstate(CTxMemPool &mempool, const BlockHash &snapshot_blockhash=BlockHash()) EXCLUSIVE_LOCKS_REQUIRED(std::vector< CChainState * > GetAll()
Instantiate a new chainstate and assign it based upon whether it is from a snapshot.
Definition: validation.h:1180
nPruneTarget
uint64_t nPruneTarget
Number of MiB of block files that we're trying to stay below.
Definition: validation.cpp:116
NodeContext::mempool
std::unique_ptr< CTxMemPool > mempool
Definition: context.h:38
moneystr.h
sync.h
MAX_TX_INDEX_CACHE_MB
static constexpr int64_t MAX_TX_INDEX_CACHE_MB
Max memory allocated to block tree DB specific cache, if -txindex (MiB)
Definition: txdb.h:42
BCLog::Logger::StartLogging
bool StartLogging()
Start logging (and flush all buffered messages)
Definition: logging.cpp:39
blockfilterindex.h
zmqrpc.h
timedata.h
CConnman::Options::nMaxOutboundLimit
uint64_t nMaxOutboundLimit
Definition: net.h:989
CChainParams::IsTestChain
bool IsTestChain() const
If this chain is exclusively used for testing.
Definition: chainparams.h:70
fsbridge::get_filesystem_error_message
std::string get_filesystem_error_message(const fs::filesystem_error &e)
Definition: fs.cpp:131
string.h
atoi
int atoi(const std::string &str)
Definition: strencodings.cpp:477
InterruptRPC
void InterruptRPC()
Definition: server.cpp:349
bilingual_str
Bilingual messages:
Definition: translation.h:17
DEFAULT_STOPAFTERBLOCKIMPORT
static const bool DEFAULT_STOPAFTERBLOCKIMPORT
Definition: init.cpp:96
NET_MAX
@ NET_MAX
Dummy value to indicate the number of NET_* constants.
Definition: netaddress.h:68
MAX_SCRIPTCHECK_THREADS
static const int MAX_SCRIPTCHECK_THREADS
Maximum number of dedicated script-checking threads allowed.
Definition: validation.h:81
DEFAULT_MIN_FINALIZATION_DELAY
static const int64_t DEFAULT_MIN_FINALIZATION_DELAY
Default for -finalizationdelay This is the minimum time between a block header reception and the bloc...
Definition: validation.h:106
FormatVersion
std::string FormatVersion(int nVersion)
Definition: clientversion.cpp:47
AVALANCHE_DEFAULT_COOLDOWN
static constexpr size_t AVALANCHE_DEFAULT_COOLDOWN
Avalanche default cooldown in milliseconds.
Definition: avalanche.h:30
DEFAULT_MAX_PEER_CONNECTIONS
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
Definition: net.h:95
flatfile.h
SetupChainParamsBaseOptions
void SetupChainParamsBaseOptions(ArgsManager &argsman)
Set the arguments for chainparams.
Definition: chainparamsbase.cpp:17
ArgsManager::GetChainName
std::string GetChainName() const
Looks for -regtest, -testnet and returns the appropriate BIP70 chain name.
Definition: system.cpp:1043
WalletInitInterface::ParameterInteraction
virtual bool ParameterInteraction() const =0
Check wallet parameter interaction.
BlockFilterTypeByName
bool BlockFilterTypeByName(const std::string &name, BlockFilterType &filter_type)
Find a filter type by its human-readable name.
Definition: blockfilter.cpp:181
DEFAULT_LOGIPS
static const bool DEFAULT_LOGIPS
Definition: logging.h:22
ArgsManager::IsArgSet
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: system.cpp:482
CBlockIndex::nHeight
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: blockindex.h:36
AllBlockFilterTypes
const std::set< BlockFilterType > & AllBlockFilterTypes()
Get a list of known filter types.
Definition: blockfilter.cpp:192
WalletInitInterface::AddWalletOptions
virtual void AddWalletOptions(ArgsManager &argsman) const =0
Get wallet help string.
Sleep
static void Sleep(int nMilliSec)
Definition: util.h:13
StartTorControl
void StartTorControl(CService onion_service_target)
Definition: torcontrol.cpp:881
globalVerifyHandle
static std::unique_ptr< ECCVerifyHandle > globalVerifyHandle
Definition: init.cpp:158
validationinterface.h
AVALANCHE_DEFAULT_PEER_DISCOVERY_ENABLED
static constexpr bool AVALANCHE_DEFAULT_PEER_DISCOVERY_ENABLED
Is avalanche peer discovery enabled by default.
Definition: avalanche.h:25
nConnectTimeout
int nConnectTimeout
Definition: netbase.cpp:35
validation.h
InitScriptExecutionCache
void InitScriptExecutionCache()
Initializes the script-execution cache.
Definition: scriptcache.cpp:76
DEFAULT_MAXRECEIVEBUFFER
static const size_t DEFAULT_MAXRECEIVEBUFFER
Definition: net.h:106
node.h
BlockFilterIndex
BlockFilterIndex is used to store and retrieve block filters, hashes, and headers for a range of bloc...
Definition: blockfilterindex.h:30
DEFAULT_MEMPOOL_EXPIRY
static const unsigned int DEFAULT_MEMPOOL_EXPIRY
Default for -mempoolexpiry, expiration time for mempool transactions in hours.
Definition: validation.h:77
CConnman::Options::nLocalServices
ServiceFlags nLocalServices
Definition: net.h:978
CBaseChainParams::TESTNET
static const std::string TESTNET
Definition: chainparamsbase.h:22
ResolveErrMsg
bilingual_str ResolveErrMsg(const std::string &optname, const std::string &strBind)
Definition: error.cpp:42
InterruptTorControl
void InterruptTorControl()
Definition: torcontrol.cpp:899
DEFAULT_STOPATHEIGHT
static const int DEFAULT_STOPATHEIGHT
Default for -stopatheight.
Definition: validation.h:97
CChainParams
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:47
fs::quoted
static auto quoted(const std::string &s)
Definition: fs.h:99
ECC_InitSanityCheck
bool ECC_InitSanityCheck()
Check that required EC support is available at runtime.
Definition: key.cpp:427
minRelayTxFee
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation)
Definition: validation.cpp:122
HTTPRPCRequestProcessor
Definition: httprpc.h:17
OnRPCStarted
static void OnRPCStarted()
Definition: init.cpp:376
GetTime
int64_t GetTime()
DEPRECATED Use either GetSystemTimeInSeconds (not mockable) or GetTime<T> (mockable)
Definition: time.cpp:27
CConnman::Options::m_added_nodes
std::vector< std::string > m_added_nodes
Definition: net.h:998
DEFAULT_ANCESTOR_SIZE_LIMIT
static constexpr unsigned int DEFAULT_ANCESTOR_SIZE_LIMIT
Default for -limitancestorsize, maximum kilobytes of tx + all in-mempool ancestors.
Definition: mempool.h:20
WITH_LOCK
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:272
AVALANCHE_DEFAULT_LEGACY_PROOF
static constexpr bool AVALANCHE_DEFAULT_LEGACY_PROOF
Whether the legacy proof format should be used by default.
Definition: proof.h:32
NodeContext::rpc_interruption_point
std::function< void()> rpc_interruption_point
Definition: context.h:53
HandleSIGHUP
static void HandleSIGHUP(int)
Definition: init.cpp:354
DEFAULT_DB_CACHE_MB
static constexpr int64_t DEFAULT_DB_CACHE_MB
-dbcache default (MiB)
Definition: txdb.h:33
CChainParams::GetConsensus
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:59
glibcxx_sanity_test
bool glibcxx_sanity_test()
Definition: glibcxx_sanity.cpp:59
AnnotatedMixin< std::mutex >
threadGroup
static boost::thread_group threadGroup
Definition: init.cpp:162
ChainstateActive
CChainState & ChainstateActive()
Please prefer the identical ChainstateManager::ActiveChainstate.
Definition: validation.cpp:80
SAFE_CHARS_UA_COMMENT
@ SAFE_CHARS_UA_COMMENT
BIP-0014 subset.
Definition: strencodings.h:27
LicenseInfo
std::string LicenseInfo()
Returns licensing information (for -version)
Definition: init.cpp:1310
interfaces::BlockAndHeaderTipInfo
Block and header tip information.
Definition: node.h:46
HandleSIGTERM
static void HandleSIGTERM(int)
Signal handlers are very limited in what they are allowed to do.
Definition: init.cpp:350
SetupNetworking
bool SetupNetworking()
Definition: system.cpp:1354
SetupServerArgs
void SetupServerArgs(NodeContext &node)
Register all arguments with the ArgsManager.
Definition: init.cpp:388
ServiceFlags
ServiceFlags
nServices flags.
Definition: protocol.h:314
DEFAULT_FIXEDSEEDS
static const bool DEFAULT_FIXEDSEEDS
Definition: net.h:105
CBlockIndex::nStatus
BlockStatus nStatus
Verification status of this block. See enum BlockStatus.
Definition: blockindex.h:76
OptionsCategory::CONNECTION
@ CONNECTION
DEFAULT_LOGTIMESTAMPS
static const bool DEFAULT_LOGTIMESTAMPS
Definition: logging.h:23
NODE_NETWORK_LIMITED
@ NODE_NETWORK_LIMITED
Definition: protocol.h:344
DEFAULT_DESCENDANT_SIZE_LIMIT
static const unsigned int DEFAULT_DESCENDANT_SIZE_LIMIT
Default for -limitdescendantsize, maximum kilobytes of in-mempool descendants.
Definition: mempool.h:27
StopREST
void StopREST()
Stop HTTP REST subsystem.
Definition: rest.cpp:799
InterruptHTTPRPC
void InterruptHTTPRPC()
Interrupt HTTP RPC subsystem.
Definition: httprpc.cpp:469
TRY_LOCK
#define TRY_LOCK(cs, name)
Definition: sync.h:247
CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM
static const int DEFAULT_ZMQ_SNDHWM
Definition: zmqabstractnotifier.h:19
fDiscover
bool fDiscover
Definition: net.cpp:134
DUST_RELAY_TX_FEE
static const Amount DUST_RELAY_TX_FEE(1000 *SATOSHI)
Min feerate for defining dust.
CCheckpointData::mapCheckpoints
MapCheckpoints mapCheckpoints
Definition: chainparams.h:25
fs::PathToString
static std::string PathToString(const path &path)
Convert path object to byte string.
Definition: fs.h:134
NODE_NETWORK
@ NODE_NETWORK
Definition: protocol.h:321
MAX_DB_CACHE_MB
static constexpr int64_t MAX_DB_CACHE_MB
max. -dbcache (MiB)
Definition: txdb.h:31
MIN_BLOCKS_TO_KEEP
static const unsigned int MIN_BLOCKS_TO_KEEP
Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ChainActive().Tip() will not be pr...
Definition: validation.h:111
chainparams.h
chain.h
ChainstateManager::ActiveChainstate
CChainState & ActiveChainstate() const
The most-work chain.
Definition: validation.cpp:6053
ScheduleBatchPriority
void ScheduleBatchPriority()
On platforms that support it, tell the kernel the calling thread is CPU-intensive and non-interactive...
Definition: system.cpp:1388
OnRPCStopped
static void OnRPCStopped()
Definition: init.cpp:381
sanity.h
Network
Network
A network type.
Definition: netaddress.h:43
DEFAULT_MAX_SIG_CACHE_SIZE
static const unsigned int DEFAULT_MAX_SIG_CACHE_SIZE
Definition: sigcache.h:16
ThreadScriptCheck
void ThreadScriptCheck(int worker_num)
Run an instance of the script checking thread.
Definition: validation.cpp:1501
CChain::Tip
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:168
NODE_COMPACT_FILTERS
@ NODE_COMPACT_FILTERS
Definition: protocol.h:339
StartHTTPServer
void StartHTTPServer()
Start HTTP server.
Definition: httpserver.cpp:466
SetupCurrencyUnitOptions
void SetupCurrencyUnitOptions(ArgsManager &argsman)
Definition: currencyunit.cpp:9
context.h
ArgsManager::GetBlocksDirPath
const fs::path & GetBlocksDirPath()
Get blocks directory path.
Definition: system.cpp:404
g_genesis_wait_cv
static std::condition_variable g_genesis_wait_cv
Definition: init.cpp:1343
RPCServer
Class for registering and managing all RPC calls.
Definition: server.h:40
FormatISO8601DateTime
std::string FormatISO8601DateTime(int64_t nTime)
ISO 8601 formatting is preferred.
Definition: time.cpp:79
NodeContext::chain
std::unique_ptr< interfaces::Chain > chain
Definition: context.h:45
proxyType
Definition: netbase.h:28
GetRand
uint64_t GetRand(uint64_t nMax) noexcept
Generate a uniform random integer in the range [0..range).
Definition: random.cpp:650
MapCheckpoints
std::map< int, BlockHash > MapCheckpoints
Definition: chainparams.h:22
Assert
#define Assert(val)
Identity function.
Definition: check.h:56
rpc_notify_block_change_connection
static boost::signals2::connection rpc_notify_block_change_connection
Definition: init.cpp:375
fPruneMode
bool fPruneMode
True if we're running in -prune mode.
Definition: validation.cpp:112
CFeeRate
Fee rate in satoshis per kilobyte: Amount / kB.
Definition: feerate.h:21
g_avalanche
std::unique_ptr< avalanche::Processor > g_avalanche
Global avalanche instance.
Definition: processor.cpp:31
scheduler.h
fHavePruned
bool fHavePruned
Pruning-related variables and constants.
Definition: validation.cpp:111
bilingual_str::empty
bool empty() const
Definition: translation.h:27
CBlockIndex::GetBlockHash
BlockHash GetBlockHash() const
Definition: blockindex.h:133
DEFAULT_PEERBLOOMFILTERS
static const bool DEFAULT_PEERBLOOMFILTERS
Definition: validation.h:94
SHA256AutoDetect
std::string SHA256AutoDetect()
Autodetect the best available SHA256 implementation.
Definition: sha256.cpp:746
interfaces::BlockAndHeaderTipInfo::block_time
int64_t block_time
Definition: node.h:48
DEFAULT_MAX_ORPHAN_TRANSACTIONS
static const unsigned int DEFAULT_MAX_ORPHAN_TRANSACTIONS
Default for -maxorphantx, maximum number of orphan transactions kept in memory.
Definition: net_processing.h:28
BanMan::DumpBanlist
void DumpBanlist()
Definition: banman.cpp:49
DEFAULT_FEEFILTER
static const bool DEFAULT_FEEFILTER
Default for using fee filter.
Definition: validation.h:92
AppInitMain
bool AppInitMain(Config &config, RPCServer &rpcServer, HTTPRPCRequestProcessor &httpRPCRequestProcessor, NodeContext &node, interfaces::BlockAndHeaderTipInfo *tip_info)
Bitcoin main initialization.
Definition: init.cpp:2183
GetMainSignals
CMainSignals & GetMainSignals()
Definition: validationinterface.cpp:122
ValidationState::ToString
std::string ToString() const
Definition: validation.h:124
ChainstateManager::ActiveChain
CChain & ActiveChain() const
Definition: validation.h:1184
Amount::zero
static constexpr Amount zero()
Definition: amount.h:42
AmountErrMsg
bilingual_str AmountErrMsg(const std::string &optname, const std::string &strValue)
Definition: error.cpp:51
txmempool.h
DEFAULT_LISTEN_ONION
static const bool DEFAULT_LISTEN_ONION
Definition: torcontrol.h:16
shutdown.h
txindex.h
mempool.h
validation.h
BCLog::RPC
@ RPC
Definition: logging.h:45
BCLog::Logger::m_log_timestamps
bool m_log_timestamps
Definition: logging.h:96
NetWhitelistPermissions
Definition: net_permissions.h:72
fsbridge::ofstream
fs::ofstream ofstream
Definition: fs.h:235
Consensus::Params
Parameters that influence chain consensus.
Definition: params.h:59
Config
Definition: config.h:17
SetRPCWarmupFinished
void SetRPCWarmupFinished()
Mark warmup as done.
Definition: server.cpp:388
SetRPCWarmupStatus
void SetRPCWarmupStatus(const std::string &newStatus)
Set the RPC warmup status.
Definition: server.cpp:383
blockdb.h
ChainstateManager::LoadBlockIndex
bool LoadBlockIndex(const Consensus::Params &params) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Load the block tree and coins database from disk, initializing state if we're running with -reindex.
Definition: validation.cpp:5189
MAX_OUTBOUND_FULL_RELAY_CONNECTIONS
static const int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS
Maximum number of automatic outgoing nodes over which we'll relay everything (blocks,...
Definition: net.h:75
nMinimumChainWork
arith_uint256 nMinimumChainWork
Minimum work we will assume exists on some valid chain.
Definition: validation.cpp:120
BITCOIN_SETTINGS_FILENAME
const char *const BITCOIN_SETTINGS_FILENAME
Definition: system.cpp:74
BaseIndex::Stop
void Stop()
Stops the instance from staying in sync with blockchain updates.
Definition: base.cpp:321
TraceThread
void TraceThread(const char *name, Callable func)
Definition: system.h:467
banman.h
InitHTTPServer
bool InitHTTPServer(Config &config)
Initialize HTTP server.
Definition: httpserver.cpp:388
FormatUserAgent
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.
Definition: clientversion.cpp:66
DEFAULT_PEERBLOCKFILTERS
static const bool DEFAULT_PEERBLOCKFILTERS
Definition: net_processing.h:34
NODE_AVALANCHE
@ NODE_AVALANCHE
Definition: protocol.h:359
OptionsCategory::NODE_RELAY
@ NODE_RELAY
Untranslated
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:36
DEFAULT_MAXSENDBUFFER
static const size_t DEFAULT_MAXSENDBUFFER
Definition: net.h:107
BaseIndex::Start
void Start()
Start initializes the sync state and registers the instance as a ValidationInterface so that it stays...
Definition: base.cpp:308
blockfilter.h
LOCAL_MANUAL
@ LOCAL_MANUAL
Definition: net.h:234
Lookup
bool Lookup(const std::string &name, std::vector< CService > &vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
Resolve a service string to its corresponding service.
Definition: netbase.cpp:232
DEFAULT_TOR_CONTROL
const std::string DEFAULT_TOR_CONTROL
Default control port.
Definition: torcontrol.cpp:34
CScheduler::Function
std::function< void()> Function
Definition: scheduler.h:40
AVALANCHE_DEFAULT_ENABLED
static constexpr bool AVALANCHE_DEFAULT_ENABLED
Is avalanche enabled by default.
Definition: avalanche.h:20
CreateChainParams
std::unique_ptr< CChainParams > CreateChainParams(const std::string &chain)
Creates and returns a std::unique_ptr<CChainParams> of the chosen chain.
Definition: chainparams.cpp:513
ECC_Stop
void ECC_Stop()
Deinitialize the elliptic curve support.
Definition: key.cpp:451
GetDefaultDataDir
fs::path GetDefaultDataDir()
Definition: system.cpp:806
CImportingNow::CImportingNow
CImportingNow()
Definition: init.cpp:1356
ArgsManager::ALLOW_BOOL
@ ALLOW_BOOL
Definition: system.h:152
MAX_FILTER_INDEX_CACHE_MB
static constexpr int64_t MAX_FILTER_INDEX_CACHE_MB
Max memory allocated to all block filter index caches combined in MiB.
Definition: txdb.h:44
cs_main
RecursiveMutex cs_main
Global state.
Definition: validation.cpp:103
DEFAULT_MAX_SCRIPT_CACHE_SIZE
static const unsigned int DEFAULT_MAX_SCRIPT_CACHE_SIZE
Definition: scriptcache.h:48
CBlockHeader::GetBlockTime
int64_t GetBlockTime() const
Definition: block.h:52
ArgsManager::SENSITIVE
@ SENSITIVE
Definition: system.h:164
CConnman::Options::vWhitelistedRange
std::vector< NetWhitelistPermissions > vWhitelistedRange
Definition: net.h:992
interfaces::BlockAndHeaderTipInfo::block_height
int block_height
Definition: node.h:47
CLIENT_NAME
const std::string CLIENT_NAME
fs::path
Path class wrapper to prepare application code for transition from boost::filesystem library to std::...
Definition: fs.h:33
DEFAULT_PRINTPRIORITY
static const bool DEFAULT_PRINTPRIORITY
Definition: miner.h:28
FlatFilePos
Definition: flatfile.h:14
init.h
GetBlockPosFilename
fs::path GetBlockPosFilename(const FlatFilePos &pos)
Translation to a filesystem path.
Definition: blockdb.cpp:29
ArgsManager::DEBUG_ONLY
@ DEBUG_ONLY
Definition: system.h:156
DefaultOnionServiceTarget
CService DefaultOnionServiceTarget()
Definition: torcontrol.cpp:917
SetMockTime
void SetMockTime(int64_t nMockTimeIn)
For testing.
Definition: time.cpp:50
InitError
bool InitError(const bilingual_str &str)
Show error message.
Definition: ui_interface.cpp:96
DEFAULT_CHECKPOINTS_ENABLED
static const bool DEFAULT_CHECKPOINTS_ENABLED
Definition: validation.h:85
g_zmq_notification_interface
CZMQNotificationInterface * g_zmq_notification_interface
Definition: zmqnotificationinterface.cpp:207
fRequireStandard
bool fRequireStandard
Definition: validation.cpp:113
BCLog::Logger::ShrinkDebugFile
void ShrinkDebugFile()
Definition: logging.cpp:257
ArgsManager::AddArg
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
Definition: system.cpp:649
util::ThreadRename
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
CMainSignals::FlushBackgroundCallbacks
void FlushBackgroundCallbacks()
Call any remaining callbacks on the calling thread.
Definition: validationinterface.cpp:109
CImportingNow
Definition: init.cpp:1355
RegisterZMQRPCCommands
void RegisterZMQRPCCommands(CRPCTable &t)
Definition: zmqrpc.cpp:68
miner.h
DumpMempool
bool DumpMempool(const CTxMemPool &pool)
Dump the mempool to disk.
Definition: validation.cpp:5915
CBaseChainParams::REGTEST
static const std::string REGTEST
Definition: chainparamsbase.h:23
StopHTTPRPC
void StopHTTPRPC()
Stop HTTP RPC subsystem.
Definition: httprpc.cpp:473
tableRPC
CRPCTable tableRPC
Definition: server.cpp:604
DEFAULT_MAX_TIP_AGE
static const int64_t DEFAULT_MAX_TIP_AGE
Definition: validation.h:84
CConnman::Options::onion_binds
std::vector< CService > onion_binds
Definition: net.h:995
Currency::get
static const Currency & get()
Definition: amount.cpp:19
pindexBestHeader
CBlockIndex * pindexBestHeader
Best header we've seen so far (used for getheaders queries' starting points).
Definition: validation.cpp:105
BlockStatus::isValid
bool isValid(enum BlockValidity nUpTo=BlockValidity::TRANSACTIONS) const
Check whether this block index entry is valid up to the passed validity level.
Definition: blockstatus.h:94
SetReachable
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
Definition: net.cpp:291
DEFAULT_MAX_BLOCK_SIZE
static const uint64_t DEFAULT_MAX_BLOCK_SIZE
Default setting for maximum allowed size for a block, in bytes.
Definition: consensus.h:20
processor.h
BlockHash::fromHex
static BlockHash fromHex(const std::string &str)
Definition: blockhash.h:17
ArgsManager::GetUnsuitableSectionOnlyArgs
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:262
CheckDiskSpace
bool CheckDiskSpace(const fs::path &dir, uint64_t additional_bytes)
Definition: system.cpp:141
LoadExternalBlockFile
void LoadExternalBlockFile(const Config &config, FILE *fileIn, FlatFilePos *dbp)
Import blocks from an external file.
Definition: validation.cpp:5245
CBlockTreeDB
Access to the block database (blocks/index/)
Definition: txdb.h:105
CConnman::Options::m_peer_connect_timeout
int64_t m_peer_connect_timeout
Definition: net.h:990
g_chainman
ChainstateManager g_chainman
Definition: validation.cpp:78
RegisterAllRPCCommands
static void RegisterAllRPCCommands(const Config &config, RPCServer &rpcServer, CRPCTable &rpcTable)
Register all context-sensitive RPC commands.
Definition: register.h:43
ArgsManager::GetArg
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:582
NODE_BLOOM
@ NODE_BLOOM
Definition: protocol.h:331
OptionsCategory::OPTIONS
@ OPTIONS
base_blob::GetHex
std::string GetHex() const
Definition: uint256.cpp:16
standard.h
CChainParams::NetworkIDString
std::string NetworkIDString() const
Return the BIP70 network string (main, test or regtest)
Definition: chainparams.h:86
CConnman::Options::m_use_addrman_outgoing
bool m_use_addrman_outgoing
Definition: net.h:996
DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN
static const unsigned int DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN
Default number of orphan+recently-replaced txn to keep around for block reconstruction.
Definition: net_processing.h:33
NetWhitebindPermissions::TryParse
static bool TryParse(const std::string str, NetWhitebindPermissions &output, bilingual_str &error)
Definition: net_permissions.cpp:126
Interrupt
void Interrupt(NodeContext &node)
Interrupt threads.
Definition: init.cpp:164
CNetAddr::IsValid
bool IsValid() const
Definition: netaddress.cpp:441
CConnman::Options::m_max_outbound_block_relay
int m_max_outbound_block_relay
Definition: net.h:981
fNameLookup
bool fNameLookup
Definition: netbase.cpp:36
CreateBaseChainParams
std::unique_ptr< CBaseChainParams > CreateBaseChainParams(const std::string &chain)
Port numbers for incoming Tor connections (8334, 18334, 38334, 18445) have been chosen arbitrarily to...
Definition: chainparamsbase.cpp:46
BCLog::Logger::m_reopen_file
std::atomic< bool > m_reopen_file
Definition: logging.h:101
Consensus::Params::hashGenesisBlock
BlockHash hashGenesisBlock
Definition: params.h:60
Discover
void Discover()
Definition: net.cpp:2683
fs::PathFromString
static path PathFromString(const std::string &string)
Convert byte string to path object.
Definition: fs.h:147
bilingual_str::translated
std::string translated
Definition: translation.h:19
DEFAULT_ASMAP_FILENAME
static const char * DEFAULT_ASMAP_FILENAME
Definition: init.cpp:106
g_cs_orphans
RecursiveMutex g_cs_orphans
Guards orphan transactions and extra txs for compact blocks.
Definition: net_processing.cpp:290
CMainSignals::RegisterBackgroundSignalScheduler
void RegisterBackgroundSignalScheduler(CScheduler &scheduler)
Register a CScheduler to give callbacks which should run in the background (may only be called once)
Definition: validationinterface.cpp:100
DEFAULT_PROXYRANDOMIZE
static const bool DEFAULT_PROXYRANDOMIZE
Definition: init.cpp:94
DEFAULT_PERMIT_BAREMULTISIG
static const bool DEFAULT_PERMIT_BAREMULTISIG
Default for -permitbaremultisig.
Definition: policy.h:59
DUMP_BANS_INTERVAL
static constexpr std::chrono::minutes DUMP_BANS_INTERVAL
Definition: banman.h:22
base_blob::ToString
std::string ToString() const
Definition: uint256.h:78
CChainParams::GenesisBlock
const CBlock & GenesisBlock() const
Definition: chainparams.h:64
uint256
256-bit opaque blob.
Definition: uint256.h:127
uint256S
uint256 uint256S(const char *str)
uint256 from const char *.
Definition: uint256.h:141
new_handler_terminate
static void new_handler_terminate()
Definition: init.cpp:1719
fReindex
std::atomic_bool fReindex
CChainState
CChainState stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:745
MAX_FEELER_CONNECTIONS
static const int MAX_FEELER_CONNECTIONS
Maximum number of feeler connections.
Definition: net.h:81
walletinitinterface.h
AppInitSanityChecks
bool AppInitSanityChecks()
Initialization sanity checks: ecc init, sanity checks, dir lock.
Definition: init.cpp:2138
Amount
Definition: amount.h:19
LogPrint
#define LogPrint(category,...)
Definition: logging.h:193
CConnman::Options::nReceiveFloodSize
unsigned int nReceiveFloodSize
Definition: net.h:988
CMainSignals::UnregisterBackgroundSignalScheduler
void UnregisterBackgroundSignalScheduler()
Unregister a CScheduler to give callbacks which should run in the background - these callbacks will n...
Definition: validationinterface.cpp:105
zmqnotificationinterface.h
ListBlockFilterTypes
const std::string & ListBlockFilterTypes()
Get a comma-separated list of known filter type names.
Definition: blockfilter.cpp:205
GetNumCores
int GetNumCores()
Return the number of cores available on the current system.
Definition: system.cpp:1367
handler
bool(* handler)(Config &config, const util::Ref &context, HTTPRequest *req, const std::string &strReq)
Definition: rest.cpp:773
chain.h
DEFAULT_CONNECT_TIMEOUT
static const int DEFAULT_CONNECT_TIMEOUT
-timeout default
Definition: netbase.h:24
RandomInit
void RandomInit()
Initialize global RNG state and log any CPU features that are used.
Definition: random.cpp:785
net_processing.h
CConnman::Options
Definition: net.h:977
RPCServerSignals::OnStarted
void OnStarted(std::function< void()> slot)
Definition: server.cpp:108
UnregisterValidationInterface
void UnregisterValidationInterface(CValidationInterface *callbacks)
Unregister subscriber.
Definition: validationinterface.cpp:145
BlockFilterType::BASIC
@ BASIC
DEFAULT_BLOCK_MIN_TX_FEE_PER_KB
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...
CChain::Height
int Height() const
Return the maximal height in the chain.
Definition: chain.h:204
interfaces::BlockAndHeaderTipInfo::header_time
int64_t header_time
Definition: node.h:50
NodeContext::peerman
std::unique_ptr< PeerManager > peerman
Definition: context.h:39
CConnman::Options::nMaxConnections
int nMaxConnections
Definition: net.h:979
DEFAULT_MAX_UPLOAD_TARGET
static constexpr uint64_t DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
Definition: net.h:97
checkpoints.h
bilingual_str::original
std::string original
Definition: translation.h:18
BlockHash
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
CBaseChainParams::MAIN
static const std::string MAIN
BIP70 chain name strings (main, test or regtest)
Definition: chainparamsbase.h:21
BanMan
Definition: banman.h:58
CConnman::Options::nSendBufferMaxSize
unsigned int nSendBufferMaxSize
Definition: net.h:987
ChainstateManager
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:1099
OptionsCategory::ZMQ
@ ZMQ
attributes.h
g_genesis_wait_mutex
static Mutex g_genesis_wait_mutex
Definition: init.cpp:1342
CVerifyDB
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
Definition: validation.h:549
BCLog::Logger::m_file_path
fs::path m_file_path
Definition: logging.h:100
interfaces::BlockAndHeaderTipInfo::verification_progress
double verification_progress
Definition: node.h:51
DEFAULT_DNSSEED
static const bool DEFAULT_DNSSEED
Definition: net.h:104
name
const char * name
Definition: rest.cpp:43
nBytesPerSigOp
uint32_t nBytesPerSigOp
Definition: settings.cpp:12
ui_interface.h
NodeContext::chain_clients
std::vector< std::unique_ptr< interfaces::ChainClient > > chain_clients
List of all chain clients (wallet processes or other client) connected to node.
Definition: context.h:48
OptionsCategory::BLOCK_CREATION
@ BLOCK_CREATION
Config::SetMaxBlockSize
virtual bool SetMaxBlockSize(uint64_t maxBlockSize)=0
CConnman::Options::uiInterface
CClientUIInterface * uiInterface
Definition: net.h:984
DEFAULT_LOGTHREADNAMES
static const bool DEFAULT_LOGTHREADNAMES
Definition: logging.h:24
UnregisterAllValidationInterfaces
void UnregisterAllValidationInterfaces()
Unregister all subscribers.
Definition: validationinterface.cpp:151
DEFAULT_NAME_LOOKUP
static const int DEFAULT_NAME_LOOKUP
-dns default
Definition: netbase.h:26
InitSignatureCache
void InitSignatureCache()
Definition: sigcache.cpp:77
InitWarning
void InitWarning(const bilingual_str &str)
Show warning message.
Definition: ui_interface.cpp:101
Currency::ticker
std::string ticker
Definition: amount.h:160
SetProxy
bool SetProxy(enum Network net, const proxyType &addrProxy)
Definition: netbase.cpp:785
CLIENT_VERSION
static constexpr int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
Definition: clientversion.h:44
ECC_Start
void ECC_Start()
Initialize the elliptic curve support.
Definition: key.cpp:434
strprintf
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1201
CClientUIInterface::MSG_ERROR
@ MSG_ERROR
Definition: ui_interface.h:73
key.h
Join
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:36
fCheckpointsEnabled
bool fCheckpointsEnabled
Definition: validation.cpp:115
PeerManager::make
static std::unique_ptr< PeerManager > make(const CChainParams &chainparams, CConnman &connman, BanMan *banman, CScheduler &scheduler, ChainstateManager &chainman, CTxMemPool &pool, bool ignore_incoming_txs)
Definition: net_processing.cpp:1801
ArgsManager::IsArgNegated
bool IsArgNegated(const std::string &strArg) const
Return true if the argument was originally passed as a negated option, i.e.
Definition: system.cpp:578
httprpc.h
RPCNotifyBlockChange
void RPCNotifyBlockChange(const CBlockIndex *pindex)
Callback for when block tip changed.
Definition: blockchain.cpp:247
CConnman::Options::nMaxFeeler
int nMaxFeeler
Definition: net.h:983
GetAdjustedTime
int64_t GetAdjustedTime()
Definition: timedata.cpp:34
SanitizeString
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
Definition: strencodings.cpp:31
BCLog::Logger::DefaultShrinkDebugFile
bool DefaultShrinkDebugFile() const
Default for whether ShrinkDebugFile should be run.
Definition: logging.cpp:334
MAX_OP_RETURN_RELAY
static const unsigned int MAX_OP_RETURN_RELAY
Default setting for nMaxDatacarrierBytes.
Definition: standard.h:77
interfaces::BlockAndHeaderTipInfo::header_height
int header_height
Definition: node.h:49
MIN_DISK_SPACE_FOR_BLOCK_FILES
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:127
ResetBlockFailureFlags
void ResetBlockFailureFlags(CBlockIndex *pindex)
Remove invalidity status from a block and its descendants.
Definition: validation.cpp:3501
base_blob::IsNull
bool IsNull() const
Definition: uint256.h:30
InitSanityCheck
static bool InitSanityCheck()
Sanity checks Ensure that Bitcoin is running in a usable environment with all necessary library suppo...
Definition: init.cpp:1526
MAX_BLOCK_RELAY_ONLY_CONNECTIONS
static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
Definition: net.h:79
AppInitLockDataDirectory
bool AppInitLockDataDirectory()
Lock bitcoin data directory.
Definition: init.cpp:2161
SetNameProxy
bool SetNameProxy(const proxyType &addrProxy)
Set the name proxy to use for all connections to nodes specified by a hostname.
Definition: netbase.cpp:821
NodeContext::banman
std::unique_ptr< BanMan > banman
Definition: context.h:42
ECCVerifyHandle
Users of this module must hold an ECCVerifyHandle.
Definition: pubkey.h:228
AppInitBasicSetup
bool AppInitBasicSetup(ArgsManager &args)
Initialize bitcoin: Basic context setup.
Definition: init.cpp:1730
DEFAULT_WHITELISTRELAY
static const bool DEFAULT_WHITELISTRELAY
Default for -whitelistrelay.
Definition: net.h:51
StartREST
void StartREST(const util::Ref &context)
Start HTTP REST subsystem.
Definition: rest.cpp:787
ArgsManager
Definition: system.h:148
torcontrol.h
currencyunit.h
translation.h
CConnman::Options::m_msgproc
NetEventsInterface * m_msgproc
Definition: net.h:985
BaseParams
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
Definition: chainparamsbase.cpp:36
MAX_ADDNODE_CONNECTIONS
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
Definition: net.h:77
GetBlockFilterIndex
BlockFilterIndex * GetBlockFilterIndex(BlockFilterType filter_type)
Get a block filter index by type.
Definition: blockfilterindex.cpp:486
UintToArith256
arith_uint256 UintToArith256(const uint256 &a)
Definition: arith_uint256.cpp:256
EXCLUSIVE_LOCKS_REQUIRED
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:56
Config::GetChainParams
virtual const CChainParams & GetChainParams() const =0
BCLog::Logger::m_print_to_console
bool m_print_to_console
Definition: logging.h:93
ForEachBlockFilterIndex
void ForEachBlockFilterIndex(std::function< void(BlockFilterIndex &)> fn)
Iterate over all running block filter indexes, invoking fn on each.
Definition: blockfilterindex.cpp:491
pblocktree
std::unique_ptr< CBlockTreeDB > pblocktree
Global variable that points to the active block tree (protected by cs_main)
Definition: validation.cpp:176
LOCK
#define LOCK(cs)
Definition: sync.h:241
WalletInitInterface::Construct
virtual void Construct(NodeContext &node) const =0
Add wallets that should be opened to list of chain clients.
proof.h
DEFAULT_MISBEHAVING_BANTIME
static constexpr unsigned int DEFAULT_MISBEHAVING_BANTIME
Definition: banman.h:20
gArgs
ArgsManager gArgs
Definition: system.cpp:76
fCheckBlockIndex
bool fCheckBlockIndex
Definition: validation.cpp:114
BCLog::Logger
Definition: logging.h:64
GetPidFile
static fs::path GetPidFile(const ArgsManager &args)
Definition: init.cpp:113
RegisterValidationInterface
void RegisterValidationInterface(CValidationInterface *callbacks)
Register subscriber.
Definition: validationinterface.cpp:133
MIN_CORE_FILEDESCRIPTORS
#define MIN_CORE_FILEDESCRIPTORS
Definition: init.cpp:103
InterruptHTTPServer
void InterruptHTTPServer()
Interrupt HTTP server threads.
Definition: httpserver.cpp:478
NET_ONION
@ NET_ONION
TOR (v2 or v3)
Definition: netaddress.h:55
NodeContext::scheduler
std::unique_ptr< CScheduler > scheduler
Definition: context.h:52
CChainParams::Checkpoints
const CCheckpointData & Checkpoints() const
Definition: chainparams.h:93
CChainParams::RequireStandard
bool RequireStandard() const
Policy: Filter transactions that do not match well-defined patterns.
Definition: chainparams.h:68
FormatMoney
std::string FormatMoney(const Amount amt)
Money parsing/formatting utilities.
Definition: moneystr.cpp:12
Random_SanityCheck
bool Random_SanityCheck()
Check that OS randomness is available and returning the requested number of bytes.
Definition: random.cpp:705
nMaxTipAge
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:117
RPCServerSignals::OnStopped
void OnStopped(std::function< void()> slot)
Definition: server.cpp:112
network.h
BCLog::Logger::m_log_time_micros
bool m_log_time_micros
Definition: logging.h:97
ArgsManager::GetUnrecognizedSections
const std::list< SectionInfo > GetUnrecognizedSections() const
Log warnings for unrecognized section names in the config file.
Definition: system.cpp:286
LogInstance
BCLog::Logger & LogInstance()
Definition: logging.cpp:15
Params
const CChainParams & Params()
Return the currently selected parameters.
Definition: chainparams.cpp:508
DEFAULT_UTXO_FEE
static const Amount DEFAULT_UTXO_FEE
Default for -excessutxocharge for transactions transactions.
Definition: validation.h:72
fIsBareMultisigStd
bool fIsBareMultisigStd
Definition: settings.cpp:10
OptionsCategory::DEBUG_TEST
@ DEBUG_TEST
scriptcache.h
DEFAULT_DEBUGLOGFILE
const char *const DEFAULT_DEBUGLOGFILE
Definition: logging.cpp:13
HTTPRPCRequestProcessor::context
const util::Ref & context
Definition: httprpc.h:25
DEFAULT_BLOCKFILTERINDEX
static const char *const DEFAULT_BLOCKFILTERINDEX
Definition: validation.h:87
hash.h
CConnman::Options::m_specified_outgoing
std::vector< std::string > m_specified_outgoing
Definition: net.h:997
DEFAULT_PEER_CONNECT_TIMEOUT
static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT
-peertimeout default
Definition: net.h:101
AppInitParameterInteraction
bool AppInitParameterInteraction(Config &config, const ArgsManager &args)
Initialization: parameter interaction.
Definition: init.cpp:1773
LookupBlockIndex
CBlockIndex * LookupBlockIndex(const BlockHash &hash)
Definition: validation.cpp:150
ThreadImport
static void ThreadImport(const Config &config, ChainstateManager &chainman, std::vector< fs::path > vImportFiles, const ArgsManager &args)
Definition: init.cpp:1419
InterruptREST
void InterruptREST()
Interrupt RPC REST subsystem.
Definition: rest.cpp:797
BITCOIN_CONF_FILENAME
const char *const BITCOIN_CONF_FILENAME
Definition: system.cpp:73
fImporting
std::atomic_bool fImporting
register.h
RpcInterruptionPoint
void RpcInterruptionPoint()
Throw JSONRPCError if RPC is not running.
Definition: server.cpp:377
InitBlockFilterIndex
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.
Definition: blockfilterindex.cpp:497
BlockFilterType
BlockFilterType
Definition: blockfilter.h:88
NET_IPV6
@ NET_IPV6
IPv6.
Definition: netaddress.h:52
addrman.h
interfaces::MakeChain
std::unique_ptr< Chain > MakeChain(NodeContext &node, const CChainParams &params)
Return implementation of Chain interface.
Definition: chain.cpp:492
LockDataDirectory
static bool LockDataDirectory(bool probeOnly)
Definition: init.cpp:2122
config.h
DEFAULT_SCRIPTCHECK_THREADS
static const int DEFAULT_SCRIPTCHECK_THREADS
-par default (number of script-checking threads, 0 = auto)
Definition: validation.h:83
fHaveGenesis
static bool fHaveGenesis
Definition: init.cpp:1341
StartHTTPRPC
bool StartHTTPRPC(HTTPRPCRequestProcessor &httpRPCRequestProcessor)
Start HTTP RPC subsystem.
Definition: httprpc.cpp:448
hashAssumeValid
BlockHash hashAssumeValid
Block hash whose ancestors we will assume to have valid scripts without checking them.
Definition: validation.cpp:119
DEFAULT_BYTES_PER_SIGOP
static const unsigned int DEFAULT_BYTES_PER_SIGOP
Default for -bytespersigop .
Definition: policy.h:57
StartRPC
void StartRPC()
Definition: server.cpp:343
SynchronizationState
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition: validation.h:130
StopTorControl
void StopTorControl()
Definition: torcontrol.cpp:909
util.h
ChainstateManager::m_total_coinsdb_cache
int64_t m_total_coinsdb_cache
The total number of bytes available for us to use across all leveldb coins databases.
Definition: validation.h:1165
CConnman::Options::m_max_outbound_full_relay
int m_max_outbound_full_relay
Definition: net.h:980
netbase.h
DEFAULT_DB_BATCH_SIZE
static constexpr int64_t DEFAULT_DB_BATCH_SIZE
-dbbatchsize default (bytes)
Definition: txdb.h:35
DEFAULT_TXINDEX
static const bool DEFAULT_TXINDEX
Definition: validation.h:86
Consensus::Params::nMinimumChainWork
uint256 nMinimumChainWork
Definition: params.h:113
blockchain.h
httpserver.h
sigcache.h
MAX_BLOCK_DB_CACHE_MB
static constexpr int64_t MAX_BLOCK_DB_CACHE_MB
Max memory allocated to block tree DB specific cache, if no -txindex (MiB)
Definition: txdb.h:37
ArgsManager::GetArgs
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
Definition: system.cpp:473
FormatFullVersion
std::string FormatFullVersion()
Definition: clientversion.cpp:58
DEFAULT_WHITELISTFORCERELAY
static const bool DEFAULT_WHITELISTFORCERELAY
Default for -whitelistforcerelay.
Definition: net.h:53
DEFAULT_REST_ENABLE
static const bool DEFAULT_REST_ENABLE
Definition: init.cpp:95
error
bool error(const char *fmt, const Args &... args)
Definition: system.h:48
LoadGenesisBlock
bool LoadGenesisBlock(const CChainParams &chainparams)
Ensures we have a genesis block in the block tree, possibly writing one to disk.
Definition: validation.cpp:5241
DEFAULT_ANCESTOR_LIMIT
static constexpr unsigned int DEFAULT_ANCESTOR_LIMIT
Default for -limitancestorcount, max number of in-mempool ancestors.
Definition: mempool.h:15
ArgsManager::NETWORK_ONLY
@ NETWORK_ONLY
Definition: system.h:162
DEFAULT_UPNP
static const bool DEFAULT_UPNP
-upnp default
Definition: net.h:88
NodeContext::connman
std::unique_ptr< CConnman > connman
Definition: context.h:37
NodeContext
NodeContext struct containing references to chain state and connection state.
Definition: context.h:36
AppInitServers
static bool AppInitServers(Config &config, HTTPRPCRequestProcessor &httpRPCRequestProcessor, NodeContext &node)
Definition: init.cpp:1544
fListen
bool fListen
Definition: net.cpp:135
DEFAULT_BLOCKSONLY
static const bool DEFAULT_BLOCKSONLY
Default for blocks only.
Definition: net.h:99
server.h
UnloadBlockIndex
void UnloadBlockIndex(CTxMemPool *mempool, ChainstateManager &chainman)
Unload database information.
Definition: validation.cpp:5170
net.h
CBlockIndex
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: blockindex.h:23
GetListenPort
uint16_t GetListenPort()
Definition: net.cpp:145
RandAddPeriodic
void RandAddPeriodic() noexcept
Gather entropy from various expensive sources, and feed them to the PRNG state.
Definition: random.cpp:640
StopHTTPServer
void StopHTTPServer()
Stop HTTP server.
Definition: httpserver.cpp:489
g_load_block
static std::thread g_load_block
Definition: init.cpp:160
NetWhitebindPermissions
Definition: net_permissions.h:65
fAcceptDatacarrier
bool fAcceptDatacarrier
A data carrying output is an unspendable output containing data.
Definition: standard.cpp:15
StopRPC
void StopRPC()
Definition: server.cpp:360
NetWhitelistPermissions::TryParse
static bool TryParse(const std::string str, NetWhitelistPermissions &output, bilingual_str &error)
Definition: net_permissions.cpp:153
threadnames.h
amount.h
GuessVerificationProgress
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...
Definition: validation.cpp:5989
Config::SetExcessUTXOCharge
virtual void SetExcessUTXOCharge(Amount amt)=0
DEFAULT_HTTP_THREADS
static const int DEFAULT_HTTP_THREADS
Definition: httpserver.h:12
MAX_SUBVERSION_LENGTH
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
Definition: net.h:70
StartShutdown
void StartShutdown()
Definition: shutdown.cpp:12
LockDirectory
bool LockDirectory(const fs::path &directory, const std::string lockfile_name, bool probe_only)
Definition: system.cpp:88
CConnman::Options::vWhiteBinds
std::vector< NetWhitebindPermissions > vWhiteBinds
Definition: net.h:993
Consensus::Params::defaultAssumeValid
BlockHash defaultAssumeValid
Definition: params.h:114
LogPrintf
static void LogPrintf(const char *fmt, const Args &... args)
Definition: logging.h:175
AbortShutdown
void AbortShutdown()
Definition: shutdown.cpp:15
registerSignalHandler
static void registerSignalHandler(int signal, void(*handler)(int))
Definition: init.cpp:366
txdb.h
BlockNotifyGenesisWait
static void BlockNotifyGenesisWait(const CBlockIndex *pBlockIndex)
Definition: init.cpp:1345
RaiseFileDescriptorLimit
int RaiseFileDescriptorLimit(int nMinFD)
This function tries to raise the file descriptor limit to the requested number.
Definition: system.cpp:1198
Shutdown
void Shutdown(NodeContext &node)
Definition: init.cpp:185
DestroyAllBlockFilterIndexes
void DestroyAllBlockFilterIndexes()
Destroy all open block filter indexes.
Definition: blockfilterindex.cpp:509
GetTimeMillis
int64_t GetTimeMillis()
Returns the system time (not mockable)
Definition: time.cpp:59
UNIX_EPOCH_TIME
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:21
BCLog::Logger::m_log_threadnames
bool m_log_threadnames
Definition: logging.h:98
Config::SetCashAddrEncoding
virtual void SetCashAddrEncoding(bool)=0
SynchronizationState::POST_INIT
@ POST_INIT
dustRelayFee
CFeeRate dustRelayFee
Definition: settings.cpp:11
WAIT_LOCK
#define WAIT_LOCK(cs, name)
Definition: sync.h:249
DEFAULT_MAX_MEMPOOL_SIZE
static const unsigned int DEFAULT_MAX_MEMPOOL_SIZE
Default for -maxmempool, maximum megabytes of mempool memory usage.
Definition: policy.h:48
CConnman::Options::m_banman
BanMan * m_banman
Definition: net.h:986
DEFAULT_HTTP_SERVER_TIMEOUT
static const int DEFAULT_HTTP_SERVER_TIMEOUT
Definition: httpserver.h:14
DEFAULT_CHECKBLOCKS
static const signed int DEFAULT_CHECKBLOCKS
Definition: validation.h:112
ParseMoney
bool ParseMoney(const std::string &money_string, Amount &nRet)
Parse an amount denoted in full coins.
Definition: moneystr.cpp:36
net_permissions.h
DEFAULT_FORCEDNSSEED
static const bool DEFAULT_FORCEDNSSEED
Definition: net.h:103
DEFAULT_LISTEN
static const bool DEFAULT_LISTEN
-listen default
Definition: net.h:83
CChainParams::DefaultConsistencyChecks
bool DefaultConsistencyChecks() const
Default value for -checkmempool and -checkblockindex argument.
Definition: chainparams.h:66
DEFAULT_ACCEPT_DATACARRIER
static const bool DEFAULT_ACCEPT_DATACARRIER
Definition: standard.h:18
g_best_block_cv
std::condition_variable g_best_block_cv
Definition: validation.cpp:107
AddLocal
bool AddLocal(const CService &addr, int nScore)
Definition: net.cpp:253
isAvalancheEnabled
bool isAvalancheEnabled(const ArgsManager &argsman)
Definition: avalanche.cpp:9
NodeContext::chainman
ChainstateManager * chainman
Definition: context.h:41