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