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