Bitcoin ABC 0.30.12
P2P Digital Currency
init.cpp
Go to the documentation of this file.
1// Copyright (c) 2009-2010 Satoshi Nakamoto
2// Copyright (c) 2009-2018 The Bitcoin Core developers
3// Distributed under the MIT software license, see the accompanying
4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6#if defined(HAVE_CONFIG_H)
7#include <config/bitcoin-config.h>
8#endif
9
10#include <init.h>
11
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 May. 2025 upgrade
473 "-schumpeteractivationtime",
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 and -rescan. "
617 "Warning: Reverting this setting requires re-downloading the "
618 "entire blockchain. (default: 0 = disable pruning blocks, "
619 "1 = allow manual pruning via RPC, >=%u = automatically "
620 "prune block files to stay under the specified target size "
621 "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 argsman.AddArg(
751 "-chronikelectrummaxhistory",
752 strprintf("Largest tx history we are willing to serve. (default: %u)",
753 chronik::DEFAULT_ELECTRUM_MAX_HISTORY),
755#endif
756 argsman.AddArg(
757 "-blockfilterindex=<type>",
758 strprintf("Maintain an index of compact filters by block "
759 "(default: %s, values: %s).",
761 " If <type> is not supplied or if <type> = 1, indexes for "
762 "all known types are enabled.",
764 argsman.AddArg(
765 "-usecashaddr",
766 "Use Cash Address for destination encoding instead of base58 "
767 "(activate by default on Jan, 14)",
769
770 argsman.AddArg(
771 "-addnode=<ip>",
772 "Add a node to connect to and attempt to keep the connection "
773 "open (see the `addnode` RPC command help for more info)",
776 argsman.AddArg("-asmap=<file>",
777 strprintf("Specify asn mapping used for bucketing of the "
778 "peers (default: %s). Relative paths will be "
779 "prefixed by the net-specific datadir location.",
782 argsman.AddArg("-bantime=<n>",
783 strprintf("Default duration (in seconds) of manually "
784 "configured bans (default: %u)",
787 argsman.AddArg(
788 "-bind=<addr>[:<port>][=onion]",
789 strprintf("Bind to given address and always listen on it (default: "
790 "0.0.0.0). Use [host]:port notation for IPv6. Append =onion "
791 "to tag any incoming connections to that address and port as "
792 "incoming Tor connections (default: 127.0.0.1:%u=onion, "
793 "testnet: 127.0.0.1:%u=onion, regtest: 127.0.0.1:%u=onion)",
794 defaultBaseParams->OnionServiceTargetPort(),
795 testnetBaseParams->OnionServiceTargetPort(),
796 regtestBaseParams->OnionServiceTargetPort()),
799 argsman.AddArg(
800 "-connect=<ip>",
801 "Connect only to the specified node(s); -connect=0 disables automatic "
802 "connections (the rules for this peer are the same as for -addnode)",
805 argsman.AddArg(
806 "-discover",
807 "Discover own IP addresses (default: 1 when listening and no "
808 "-externalip or -proxy)",
810 argsman.AddArg("-dns",
811 strprintf("Allow DNS lookups for -addnode, -seednode and "
812 "-connect (default: %d)",
815 argsman.AddArg(
816 "-dnsseed",
817 strprintf(
818 "Query for peer addresses via DNS lookup, if low on addresses "
819 "(default: %u unless -connect used)",
822 argsman.AddArg("-externalip=<ip>", "Specify your own public address",
824 argsman.AddArg(
825 "-fixedseeds",
826 strprintf(
827 "Allow fixed seeds if DNS seeds don't provide peers (default: %u)",
830 argsman.AddArg(
831 "-forcednsseed",
832 strprintf(
833 "Always query for peer addresses via DNS lookup (default: %d)",
836 argsman.AddArg("-overridednsseed",
837 "If set, only use the specified DNS seed when "
838 "querying for peer addresses via DNS lookup.",
840 argsman.AddArg(
841 "-listen",
842 "Accept connections from outside (default: 1 if no -proxy or -connect)",
844 argsman.AddArg(
845 "-listenonion",
846 strprintf("Automatically create Tor onion service (default: %d)",
849 argsman.AddArg(
850 "-maxconnections=<n>",
851 strprintf("Maintain at most <n> connections to peers. The effective "
852 "limit depends on system limitations and might be lower than "
853 "the specified value (default: %u)",
856 argsman.AddArg("-maxreceivebuffer=<n>",
857 strprintf("Maximum per-connection receive buffer, <n>*1000 "
858 "bytes (default: %u)",
861 argsman.AddArg(
862 "-maxsendbuffer=<n>",
863 strprintf(
864 "Maximum per-connection send buffer, <n>*1000 bytes (default: %u)",
867 argsman.AddArg(
868 "-maxtimeadjustment",
869 strprintf("Maximum allowed median peer time offset adjustment. Local "
870 "perspective of time may be influenced by peers forward or "
871 "backward by this amount. (default: %u seconds)",
874 argsman.AddArg("-onion=<ip:port>",
875 strprintf("Use separate SOCKS5 proxy to reach peers via Tor "
876 "onion services (default: %s)",
877 "-proxy"),
879 argsman.AddArg("-i2psam=<ip:port>",
880 "I2P SAM proxy to reach I2P peers and accept I2P "
881 "connections (default: none)",
883 argsman.AddArg(
884 "-i2pacceptincoming",
885 "If set and -i2psam is also set then incoming I2P connections are "
886 "accepted via the SAM proxy. If this is not set but -i2psam is set "
887 "then only outgoing connections will be made to the I2P network. "
888 "Ignored if -i2psam is not set. Listening for incoming I2P connections "
889 "is done through the SAM proxy, not by binding to a local address and "
890 "port (default: 1)",
892
893 argsman.AddArg(
894 "-onlynet=<net>",
895 "Make outgoing connections only through network <net> (" +
896 Join(GetNetworkNames(), ", ") +
897 "). Incoming connections are not affected by this option. This "
898 "option can be specified multiple times to allow multiple "
899 "networks. Warning: if it is used with non-onion networks "
900 "and the -onion or -proxy option is set, then outbound onion "
901 "connections will still be made; use -noonion or -onion=0 to "
902 "disable outbound onion connections in this case",
904 argsman.AddArg("-peerbloomfilters",
905 strprintf("Support filtering of blocks and transaction with "
906 "bloom filters (default: %d)",
909 argsman.AddArg(
910 "-peerblockfilters",
911 strprintf(
912 "Serve compact block filters to peers per BIP 157 (default: %u)",
915 argsman.AddArg("-permitbaremultisig",
916 strprintf("Relay non-P2SH multisig (default: %d)",
919 // TODO: remove the sentence "Nodes not using ... incoming connections."
920 // once the changes from https://github.com/bitcoin/bitcoin/pull/23542 have
921 // become widespread.
922 argsman.AddArg("-port=<port>",
923 strprintf("Listen for connections on <port>. Nodes not "
924 "using the default ports (default: %u, "
925 "testnet: %u, regtest: %u) are unlikely to get "
926 "incoming connections. Not relevant for I2P (see "
927 "doc/i2p.md).",
928 defaultChainParams->GetDefaultPort(),
929 testnetChainParams->GetDefaultPort(),
930 regtestChainParams->GetDefaultPort()),
933 argsman.AddArg("-proxy=<ip:port>", "Connect through SOCKS5 proxy",
935 argsman.AddArg(
936 "-proxyrandomize",
937 strprintf("Randomize credentials for every proxy connection. "
938 "This enables Tor stream isolation (default: %d)",
941 argsman.AddArg(
942 "-seednode=<ip>",
943 "Connect to a node to retrieve peer addresses, and disconnect",
945 argsman.AddArg(
946 "-networkactive",
947 "Enable all P2P network activity (default: 1). Can be changed "
948 "by the setnetworkactive RPC command",
950 argsman.AddArg("-timeout=<n>",
951 strprintf("Specify connection timeout in milliseconds "
952 "(minimum: 1, default: %d)",
955 argsman.AddArg(
956 "-peertimeout=<n>",
957 strprintf("Specify p2p connection timeout in seconds. This option "
958 "determines the amount of time a peer may be inactive before "
959 "the connection to it is dropped. (minimum: 1, default: %d)",
962 argsman.AddArg(
963 "-torcontrol=<ip>:<port>",
964 strprintf(
965 "Tor control port to use if onion listening enabled (default: %s)",
968 argsman.AddArg("-torpassword=<pass>",
969 "Tor control port password (default: empty)",
972#ifdef USE_UPNP
973#if USE_UPNP
974 argsman.AddArg("-upnp",
975 "Use UPnP to map the listening port (default: 1 when "
976 "listening and no -proxy)",
978#else
979 argsman.AddArg(
980 "-upnp",
981 strprintf("Use UPnP to map the listening port (default: %u)", 0),
983#endif
984#else
985 hidden_args.emplace_back("-upnp");
986#endif
987#ifdef USE_NATPMP
988 argsman.AddArg(
989 "-natpmp",
990 strprintf("Use NAT-PMP to map the listening port (default: %s)",
991 DEFAULT_NATPMP ? "1 when listening and no -proxy" : "0"),
993#else
994 hidden_args.emplace_back("-natpmp");
995#endif // USE_NATPMP
996 argsman.AddArg(
997 "-whitebind=<[permissions@]addr>",
998 "Bind to the given address and add permission flags to the peers "
999 "connecting to it."
1000 "Use [host]:port notation for IPv6. Allowed permissions: " +
1001 Join(NET_PERMISSIONS_DOC, ", ") +
1002 ". "
1003 "Specify multiple permissions separated by commas (default: "
1004 "download,noban,mempool,relay). Can be specified multiple times.",
1006
1007 argsman.AddArg("-whitelist=<[permissions@]IP address or network>",
1008 "Add permission flags to the peers using the given "
1009 "IP address (e.g. 1.2.3.4) or CIDR-notated network "
1010 "(e.g. 1.2.3.0/24). "
1011 "Uses the same permissions as -whitebind. "
1012 "Additional flags \"in\" and \"out\" control whether "
1013 "permissions apply to incoming connections and/or manual "
1014 "(default: incoming only). "
1015 "Can be specified multiple times.",
1017 argsman.AddArg(
1018 "-maxuploadtarget=<n>",
1019 strprintf("Tries to keep outbound traffic under the given target (in "
1020 "MiB per 24h). Limit does not apply to peers with 'download' "
1021 "permission. 0 = no limit (default: %d)",
1024
1026
1027#if ENABLE_ZMQ
1028 argsman.AddArg("-zmqpubhashblock=<address>",
1029 "Enable publish hash block in <address>",
1031 argsman.AddArg("-zmqpubhashtx=<address>",
1032 "Enable publish hash transaction in <address>",
1034 argsman.AddArg("-zmqpubrawblock=<address>",
1035 "Enable publish raw block in <address>",
1037 argsman.AddArg("-zmqpubrawtx=<address>",
1038 "Enable publish raw transaction in <address>",
1040 argsman.AddArg("-zmqpubsequence=<address>",
1041 "Enable publish hash block and tx sequence in <address>",
1043 argsman.AddArg(
1044 "-zmqpubhashblockhwm=<n>",
1045 strprintf("Set publish hash block outbound message high water "
1046 "mark (default: %d)",
1049 argsman.AddArg(
1050 "-zmqpubhashtxhwm=<n>",
1051 strprintf("Set publish hash transaction outbound message high "
1052 "water mark (default: %d)",
1054 false, OptionsCategory::ZMQ);
1055 argsman.AddArg(
1056 "-zmqpubrawblockhwm=<n>",
1057 strprintf("Set publish raw block outbound message high water "
1058 "mark (default: %d)",
1061 argsman.AddArg(
1062 "-zmqpubrawtxhwm=<n>",
1063 strprintf("Set publish raw transaction outbound message high "
1064 "water mark (default: %d)",
1067 argsman.AddArg("-zmqpubsequencehwm=<n>",
1068 strprintf("Set publish hash sequence message high water mark"
1069 " (default: %d)",
1072#else
1073 hidden_args.emplace_back("-zmqpubhashblock=<address>");
1074 hidden_args.emplace_back("-zmqpubhashtx=<address>");
1075 hidden_args.emplace_back("-zmqpubrawblock=<address>");
1076 hidden_args.emplace_back("-zmqpubrawtx=<address>");
1077 hidden_args.emplace_back("-zmqpubsequence=<n>");
1078 hidden_args.emplace_back("-zmqpubhashblockhwm=<n>");
1079 hidden_args.emplace_back("-zmqpubhashtxhwm=<n>");
1080 hidden_args.emplace_back("-zmqpubrawblockhwm=<n>");
1081 hidden_args.emplace_back("-zmqpubrawtxhwm=<n>");
1082 hidden_args.emplace_back("-zmqpubsequencehwm=<n>");
1083#endif
1084
1085 argsman.AddArg(
1086 "-checkblocks=<n>",
1087 strprintf("How many blocks to check at startup (default: %u, 0 = all)",
1091 argsman.AddArg("-checklevel=<n>",
1092 strprintf("How thorough the block verification of "
1093 "-checkblocks is: %s (0-4, default: %u)",
1097 argsman.AddArg("-checkblockindex",
1098 strprintf("Do a consistency check for the block tree, "
1099 "chainstate, and other validation data structures "
1100 "occasionally. (default: %u, regtest: %u)",
1101 defaultChainParams->DefaultConsistencyChecks(),
1102 regtestChainParams->DefaultConsistencyChecks()),
1105 argsman.AddArg("-checkaddrman=<n>",
1106 strprintf("Run addrman consistency checks every <n> "
1107 "operations. Use 0 to disable. (default: %u)",
1111 argsman.AddArg(
1112 "-checkmempool=<n>",
1113 strprintf("Run mempool consistency checks every <n> transactions. Use "
1114 "0 to disable. (default: %u, regtest: %u)",
1115 defaultChainParams->DefaultConsistencyChecks(),
1116 regtestChainParams->DefaultConsistencyChecks()),
1119 argsman.AddArg("-checkpoints",
1120 strprintf("Only accept block chain matching built-in "
1121 "checkpoints (default: %d)",
1125 argsman.AddArg("-deprecatedrpc=<method>",
1126 "Allows deprecated RPC method(s) to be used",
1129 argsman.AddArg(
1130 "-stopafterblockimport",
1131 strprintf("Stop running after importing blocks from disk (default: %d)",
1135 argsman.AddArg("-stopatheight",
1136 strprintf("Stop running after reaching the given height in "
1137 "the main chain (default: %u)",
1141 argsman.AddArg("-addrmantest", "Allows to test address relay on localhost",
1144 argsman.AddArg("-capturemessages", "Capture all P2P messages to disk",
1147 argsman.AddArg("-mocktime=<n>",
1148 "Replace actual time with " + UNIX_EPOCH_TIME +
1149 " (default: 0)",
1152 argsman.AddArg(
1153 "-maxsigcachesize=<n>",
1154 strprintf("Limit size of signature cache to <n> MiB (default: %u)",
1158 argsman.AddArg(
1159 "-maxscriptcachesize=<n>",
1160 strprintf("Limit size of script cache to <n> MiB (default: %u)",
1164 argsman.AddArg("-maxtipage=<n>",
1165 strprintf("Maximum tip age in seconds to consider node in "
1166 "initial block download (default: %u)",
1167 Ticks<std::chrono::seconds>(DEFAULT_MAX_TIP_AGE)),
1170
1171 argsman.AddArg("-uacomment=<cmt>",
1172 "Append comment to the user agent string",
1174 argsman.AddArg("-uaclientname=<clientname>", "Set user agent client name",
1176 argsman.AddArg("-uaclientversion=<clientversion>",
1177 "Set user agent client version", ArgsManager::ALLOW_ANY,
1179
1181
1182 argsman.AddArg(
1183 "-acceptnonstdtxn",
1184 strprintf(
1185 "Relay and mine \"non-standard\" transactions (%sdefault: %u)",
1186 "testnet/regtest only; ", defaultChainParams->RequireStandard()),
1189 argsman.AddArg("-excessiveblocksize=<n>",
1190 strprintf("Do not accept blocks larger than this limit, in "
1191 "bytes (default: %d)",
1195 const auto &ticker = Currency::get().ticker;
1196 argsman.AddArg(
1197 "-dustrelayfee=<amt>",
1198 strprintf("Fee rate (in %s/kB) used to define dust, the value of an "
1199 "output such that it will cost about 1/3 of its value in "
1200 "fees at this fee rate to spend it. (default: %s)",
1204
1205 argsman.AddArg(
1206 "-bytespersigcheck",
1207 strprintf("Equivalent bytes per sigCheck in transactions for relay and "
1208 "mining (default: %u).",
1211 argsman.AddArg(
1212 "-bytespersigop",
1213 strprintf("DEPRECATED: Equivalent bytes per sigCheck in transactions "
1214 "for relay and mining (default: %u). This has been "
1215 "deprecated since v0.26.8 and will be removed in the future, "
1216 "please use -bytespersigcheck instead.",
1219 argsman.AddArg(
1220 "-datacarrier",
1221 strprintf("Relay and mine data carrier transactions (default: %d)",
1224 argsman.AddArg(
1225 "-datacarriersize",
1226 strprintf("Maximum size of data in data carrier transactions "
1227 "we relay and mine (default: %u)",
1230 argsman.AddArg(
1231 "-minrelaytxfee=<amt>",
1232 strprintf("Fees (in %s/kB) smaller than this are rejected for "
1233 "relaying, mining and transaction creation (default: %s)",
1236 argsman.AddArg(
1237 "-whitelistrelay",
1238 strprintf("Add 'relay' permission to whitelisted peers "
1239 "with default permissions. This will accept relayed "
1240 "transactions even when not relaying transactions "
1241 "(default: %d)",
1244 argsman.AddArg(
1245 "-whitelistforcerelay",
1246 strprintf("Add 'forcerelay' permission to whitelisted peers "
1247 "with default permissions. This will relay transactions "
1248 "even if the transactions were already in the mempool "
1249 "(default: %d)",
1252
1253 argsman.AddArg("-blockmaxsize=<n>",
1254 strprintf("Set maximum block size in bytes (default: %d)",
1257 argsman.AddArg(
1258 "-blockmintxfee=<amt>",
1259 strprintf("Set lowest fee rate (in %s/kB) for transactions to "
1260 "be included in block creation. (default: %s)",
1263 argsman.AddArg("-simplegbt",
1264 "Use a simplified getblocktemplate output (default: 0)",
1266
1267 argsman.AddArg("-blockversion=<n>",
1268 "Override block version to test forking scenarios",
1271
1272 argsman.AddArg("-server", "Accept command line and JSON-RPC commands",
1274 argsman.AddArg("-rest",
1275 strprintf("Accept public REST requests (default: %d)",
1278 argsman.AddArg(
1279 "-rpcbind=<addr>[:port]",
1280 "Bind to given address to listen for JSON-RPC connections. Do not "
1281 "expose the RPC server to untrusted networks such as the public "
1282 "internet! This option is ignored unless -rpcallowip is also passed. "
1283 "Port is optional and overrides -rpcport. Use [host]:port notation "
1284 "for IPv6. This option can be specified multiple times (default: "
1285 "127.0.0.1 and ::1 i.e., localhost)",
1289 argsman.AddArg(
1290 "-rpcdoccheck",
1291 strprintf("Throw a non-fatal error at runtime if the documentation for "
1292 "an RPC is incorrect (default: %u)",
1295 argsman.AddArg(
1296 "-rpccookiefile=<loc>",
1297 "Location of the auth cookie. Relative paths will be prefixed "
1298 "by a net-specific datadir location. (default: data dir)",
1300 argsman.AddArg("-rpcuser=<user>", "Username for JSON-RPC connections",
1303 argsman.AddArg("-rpcpassword=<pw>", "Password for JSON-RPC connections",
1306 argsman.AddArg(
1307 "-rpcwhitelist=<whitelist>",
1308 "Set a whitelist to filter incoming RPC calls for a specific user. The "
1309 "field <whitelist> comes in the format: <USERNAME>:<rpc 1>,<rpc "
1310 "2>,...,<rpc n>. If multiple whitelists are set for a given user, they "
1311 "are set-intersected. See -rpcwhitelistdefault documentation for "
1312 "information on default whitelist behavior.",
1314 argsman.AddArg(
1315 "-rpcwhitelistdefault",
1316 "Sets default behavior for rpc whitelisting. Unless "
1317 "rpcwhitelistdefault is set to 0, if any -rpcwhitelist is set, the rpc "
1318 "server acts as if all rpc users are subject to "
1319 "empty-unless-otherwise-specified whitelists. If rpcwhitelistdefault "
1320 "is set to 1 and no -rpcwhitelist is set, rpc server acts as if all "
1321 "rpc users are subject to empty whitelists.",
1323 argsman.AddArg(
1324 "-rpcauth=<userpw>",
1325 "Username and HMAC-SHA-256 hashed password for JSON-RPC connections. "
1326 "The field <userpw> comes in the format: <USERNAME>:<SALT>$<HASH>. A "
1327 "canonical python script is included in share/rpcauth. The client then "
1328 "connects normally using the rpcuser=<USERNAME>/rpcpassword=<PASSWORD> "
1329 "pair of arguments. This option can be specified multiple times",
1331 argsman.AddArg("-rpcport=<port>",
1332 strprintf("Listen for JSON-RPC connections on <port> "
1333 "(default: %u, testnet: %u, regtest: %u)",
1334 defaultBaseParams->RPCPort(),
1335 testnetBaseParams->RPCPort(),
1336 regtestBaseParams->RPCPort()),
1339 argsman.AddArg(
1340 "-rpcallowip=<ip>",
1341 "Allow JSON-RPC connections from specified source. Valid for "
1342 "<ip> are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. "
1343 "1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24). "
1344 "This option can be specified multiple times",
1346 argsman.AddArg(
1347 "-rpcthreads=<n>",
1348 strprintf(
1349 "Set the number of threads to service RPC calls (default: %d)",
1352 argsman.AddArg(
1353 "-rpccorsdomain=value",
1354 "Domain from which to accept cross origin requests (browser enforced)",
1356
1357 argsman.AddArg("-rpcworkqueue=<n>",
1358 strprintf("Set the depth of the work queue to service RPC "
1359 "calls (default: %d)",
1363 argsman.AddArg("-rpcservertimeout=<n>",
1364 strprintf("Timeout during HTTP requests (default: %d)",
1368
1369#if HAVE_DECL_FORK
1370 argsman.AddArg("-daemon",
1371 strprintf("Run in the background as a daemon and accept "
1372 "commands (default: %d)",
1375 argsman.AddArg("-daemonwait",
1376 strprintf("Wait for initialization to be finished before "
1377 "exiting. This implies -daemon (default: %d)",
1380#else
1381 hidden_args.emplace_back("-daemon");
1382 hidden_args.emplace_back("-daemonwait");
1383#endif
1384
1385 // Avalanche options.
1386 argsman.AddArg("-avalanche",
1387 strprintf("Enable the avalanche feature (default: %u)",
1390 argsman.AddArg(
1391 "-avalanchestakingrewards",
1392 strprintf("Enable the avalanche staking rewards feature (default: %u, "
1393 "testnet: %u, regtest: %u)",
1394 defaultChainParams->GetConsensus().enableStakingRewards,
1395 testnetChainParams->GetConsensus().enableStakingRewards,
1396 regtestChainParams->GetConsensus().enableStakingRewards),
1398 argsman.AddArg("-avalancheconflictingproofcooldown",
1399 strprintf("Mandatory cooldown before a proof conflicting "
1400 "with an already registered one can be considered "
1401 "in seconds (default: %u)",
1404 argsman.AddArg("-avalanchepeerreplacementcooldown",
1405 strprintf("Mandatory cooldown before a peer can be replaced "
1406 "in seconds (default: %u)",
1409 argsman.AddArg(
1410 "-avaminquorumstake",
1411 strprintf(
1412 "Minimum amount of known stake for a usable quorum (default: %s)",
1415 argsman.AddArg(
1416 "-avaminquorumconnectedstakeratio",
1417 strprintf("Minimum proportion of known stake we"
1418 " need nodes for to have a usable quorum (default: %s). "
1419 "This parameter is parsed with a maximum precision of "
1420 "0.000001.",
1423 argsman.AddArg(
1424 "-avaminavaproofsnodecount",
1425 strprintf("Minimum number of node that needs to send us an avaproofs"
1426 " message before we consider we have a usable quorum"
1427 " (default: %s)",
1430 argsman.AddArg(
1431 "-avastalevotethreshold",
1432 strprintf("Number of avalanche votes before a voted item goes stale "
1433 "when voting confidence is low (default: %u)",
1436 argsman.AddArg(
1437 "-avastalevotefactor",
1438 strprintf(
1439 "Factor affecting the number of avalanche votes before a voted "
1440 "item goes stale when voting confidence is high (default: %u)",
1443 argsman.AddArg("-avacooldown",
1444 strprintf("Mandatory cooldown between two avapoll in "
1445 "milliseconds (default: %u)",
1448 argsman.AddArg(
1449 "-avatimeout",
1450 strprintf("Avalanche query timeout in milliseconds (default: %u)",
1453 argsman.AddArg(
1454 "-avadelegation",
1455 "Avalanche proof delegation to the master key used by this node "
1456 "(default: none). Should be used in conjunction with -avaproof and "
1457 "-avamasterkey",
1459 argsman.AddArg("-avaproof",
1460 "Avalanche proof to be used by this node (default: none)",
1462 argsman.AddArg(
1463 "-avaproofstakeutxoconfirmations",
1464 strprintf(
1465 "Minimum number of confirmations before a stake utxo is mature"
1466 " enough to be included into a proof. Utxos in the mempool are not "
1467 "accepted (i.e this value must be greater than 0) (default: %s)",
1470 argsman.AddArg("-avaproofstakeutxodustthreshold",
1471 strprintf("Minimum value each stake utxo must have to be "
1472 "considered valid (default: %s)",
1475 argsman.AddArg("-avamasterkey",
1476 "Master key associated with the proof. If a proof is "
1477 "required, this is mandatory.",
1480 argsman.AddArg("-avasessionkey", "Avalanche session key (default: random)",
1483 argsman.AddArg("-enablertt",
1484 strprintf("Whether to enforce Real Time Targeting via "
1485 "Avalanche, default (%u)",
1488 argsman.AddArg(
1489 "-maxavalancheoutbound",
1490 strprintf(
1491 "Set the maximum number of avalanche outbound peers to connect to. "
1492 "Note that this option takes precedence over the -maxconnections "
1493 "option (default: %u).",
1496 argsman.AddArg(
1497 "-persistavapeers",
1498 strprintf("Whether to save the avalanche peers upon shutdown and load "
1499 "them upon startup (default: %u).",
1502
1503 hidden_args.emplace_back("-avalanchepreconsensus");
1504 hidden_args.emplace_back("-avalanchestakingpreconsensus");
1505
1506 // Add the hidden options
1507 argsman.AddHiddenArgs(hidden_args);
1508}
1509
1510static bool fHaveGenesis = false;
1512static std::condition_variable g_genesis_wait_cv;
1513
1514static void BlockNotifyGenesisWait(const CBlockIndex *pBlockIndex) {
1515 if (pBlockIndex != nullptr) {
1516 {
1518 fHaveGenesis = true;
1519 }
1520 g_genesis_wait_cv.notify_all();
1521 }
1522}
1523
1524#if HAVE_SYSTEM
1525static void StartupNotify(const ArgsManager &args) {
1526 std::string cmd = args.GetArg("-startupnotify", "");
1527 if (!cmd.empty()) {
1528 std::thread t(runCommand, cmd);
1529 // thread runs free
1530 t.detach();
1531 }
1532}
1533#endif
1534
1535static bool AppInitServers(Config &config,
1536 HTTPRPCRequestProcessor &httpRPCRequestProcessor,
1537 NodeContext &node) {
1538 const ArgsManager &args = *Assert(node.args);
1541 if (!InitHTTPServer(config)) {
1542 return false;
1543 }
1544
1545 StartRPC();
1546 node.rpc_interruption_point = RpcInterruptionPoint;
1547
1548 if (!StartHTTPRPC(httpRPCRequestProcessor)) {
1549 return false;
1550 }
1551 if (args.GetBoolArg("-rest", DEFAULT_REST_ENABLE)) {
1552 StartREST(&node);
1553 }
1554
1556 return true;
1557}
1558
1559// Parameter interaction based on rules
1561 // when specifying an explicit binding address, you want to listen on it
1562 // even when -connect or -proxy is specified.
1563 if (args.IsArgSet("-bind")) {
1564 if (args.SoftSetBoolArg("-listen", true)) {
1565 LogPrintf(
1566 "%s: parameter interaction: -bind set -> setting -listen=1\n",
1567 __func__);
1568 }
1569 }
1570 if (args.IsArgSet("-whitebind")) {
1571 if (args.SoftSetBoolArg("-listen", true)) {
1572 LogPrintf("%s: parameter interaction: -whitebind set -> setting "
1573 "-listen=1\n",
1574 __func__);
1575 }
1576 }
1577
1578 if (args.IsArgSet("-connect")) {
1579 // when only connecting to trusted nodes, do not seed via DNS, or listen
1580 // by default.
1581 if (args.SoftSetBoolArg("-dnsseed", false)) {
1582 LogPrintf("%s: parameter interaction: -connect set -> setting "
1583 "-dnsseed=0\n",
1584 __func__);
1585 }
1586 if (args.SoftSetBoolArg("-listen", false)) {
1587 LogPrintf("%s: parameter interaction: -connect set -> setting "
1588 "-listen=0\n",
1589 __func__);
1590 }
1591 }
1592
1593 if (args.IsArgSet("-proxy")) {
1594 // to protect privacy, do not listen by default if a default proxy
1595 // server is specified.
1596 if (args.SoftSetBoolArg("-listen", false)) {
1597 LogPrintf(
1598 "%s: parameter interaction: -proxy set -> setting -listen=0\n",
1599 __func__);
1600 }
1601 // to protect privacy, do not map ports when a proxy is set. The user
1602 // may still specify -listen=1 to listen locally, so don't rely on this
1603 // happening through -listen below.
1604 if (args.SoftSetBoolArg("-upnp", false)) {
1605 LogPrintf(
1606 "%s: parameter interaction: -proxy set -> setting -upnp=0\n",
1607 __func__);
1608 }
1609 if (args.SoftSetBoolArg("-natpmp", false)) {
1610 LogPrintf(
1611 "%s: parameter interaction: -proxy set -> setting -natpmp=0\n",
1612 __func__);
1613 }
1614 // to protect privacy, do not discover addresses by default
1615 if (args.SoftSetBoolArg("-discover", false)) {
1616 LogPrintf("%s: parameter interaction: -proxy set -> setting "
1617 "-discover=0\n",
1618 __func__);
1619 }
1620 }
1621
1622 if (!args.GetBoolArg("-listen", DEFAULT_LISTEN)) {
1623 // do not map ports or try to retrieve public IP when not listening
1624 // (pointless)
1625 if (args.SoftSetBoolArg("-upnp", false)) {
1626 LogPrintf(
1627 "%s: parameter interaction: -listen=0 -> setting -upnp=0\n",
1628 __func__);
1629 }
1630 if (args.SoftSetBoolArg("-natpmp", false)) {
1631 LogPrintf(
1632 "%s: parameter interaction: -listen=0 -> setting -natpmp=0\n",
1633 __func__);
1634 }
1635 if (args.SoftSetBoolArg("-discover", false)) {
1636 LogPrintf(
1637 "%s: parameter interaction: -listen=0 -> setting -discover=0\n",
1638 __func__);
1639 }
1640 if (args.SoftSetBoolArg("-listenonion", false)) {
1641 LogPrintf("%s: parameter interaction: -listen=0 -> setting "
1642 "-listenonion=0\n",
1643 __func__);
1644 }
1645 if (args.SoftSetBoolArg("-i2pacceptincoming", false)) {
1646 LogPrintf("%s: parameter interaction: -listen=0 -> setting "
1647 "-i2pacceptincoming=0\n",
1648 __func__);
1649 }
1650 }
1651
1652 if (args.IsArgSet("-externalip")) {
1653 // if an explicit public IP is specified, do not try to find others
1654 if (args.SoftSetBoolArg("-discover", false)) {
1655 LogPrintf("%s: parameter interaction: -externalip set -> setting "
1656 "-discover=0\n",
1657 __func__);
1658 }
1659 }
1660
1661 // disable whitelistrelay in blocksonly mode
1662 if (args.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)) {
1663 if (args.SoftSetBoolArg("-whitelistrelay", false)) {
1664 LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting "
1665 "-whitelistrelay=0\n",
1666 __func__);
1667 }
1668 }
1669
1670 // Forcing relay from whitelisted hosts implies we will accept relays from
1671 // them in the first place.
1672 if (args.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
1673 if (args.SoftSetBoolArg("-whitelistrelay", true)) {
1674 LogPrintf("%s: parameter interaction: -whitelistforcerelay=1 -> "
1675 "setting -whitelistrelay=1\n",
1676 __func__);
1677 }
1678 }
1679
1680 // If avalanche is set, soft set all the feature flags accordingly.
1681 if (args.IsArgSet("-avalanche")) {
1682 const bool fAvalanche =
1683 args.GetBoolArg("-avalanche", AVALANCHE_DEFAULT_ENABLED);
1684 args.SoftSetBoolArg("-automaticunparking", !fAvalanche);
1685 }
1686}
1687
1694void InitLogging(const ArgsManager &args) {
1697}
1698
1699namespace { // Variables internal to initialization process only
1700
1701int nMaxConnections;
1702int nUserMaxConnections;
1703int nFD;
1705int64_t peer_connect_timeout;
1706std::set<BlockFilterType> g_enabled_filter_types;
1707
1708} // namespace
1709
1710[[noreturn]] static void new_handler_terminate() {
1711 // Rather than throwing std::bad-alloc if allocation fails, terminate
1712 // immediately to (try to) avoid chain corruption. Since LogPrintf may
1713 // itself allocate memory, set the handler directly to terminate first.
1714 std::set_new_handler(std::terminate);
1715 LogPrintf("Error: Out of memory. Terminating.\n");
1716
1717 // The log was successful, terminate now.
1718 std::terminate();
1719};
1720
1722// Step 1: setup
1723#ifdef _MSC_VER
1724 // Turn off Microsoft heap dump noise
1725 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
1726 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, nullptr,
1727 OPEN_EXISTING, 0, 0));
1728 // Disable confusing "helpful" text message on abort, Ctrl-C
1729 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
1730#endif
1731#ifdef WIN32
1732 // Enable Data Execution Prevention (DEP)
1733 SetProcessDEPPolicy(PROCESS_DEP_ENABLE);
1734#endif
1735 if (!InitShutdownState()) {
1736 return InitError(
1737 Untranslated("Initializing wait-for-shutdown state failed."));
1738 }
1739
1740 if (!SetupNetworking()) {
1741 return InitError(Untranslated("Initializing networking failed"));
1742 }
1743
1744#ifndef WIN32
1745 if (!args.GetBoolArg("-sysperms", false)) {
1746 umask(077);
1747 }
1748
1749 // Clean shutdown on SIGTERM
1752
1753 // Reopen debug.log on SIGHUP
1755
1756 // Ignore SIGPIPE, otherwise it will bring the daemon down if the client
1757 // closes unexpectedly
1758 signal(SIGPIPE, SIG_IGN);
1759#else
1760 SetConsoleCtrlHandler(consoleCtrlHandler, true);
1761#endif
1762
1763 std::set_new_handler(new_handler_terminate);
1764
1765 return true;
1766}
1767
1769 const CChainParams &chainparams = config.GetChainParams();
1770 // Step 2: parameter interactions
1771
1772 // also see: InitParameterInteraction()
1773
1774 // Error if network-specific options (-addnode, -connect, etc) are
1775 // specified in default section of config file, but not overridden
1776 // on the command line or in this network's section of the config file.
1777 std::string network = args.GetChainName();
1778 bilingual_str errors;
1779 for (const auto &arg : args.GetUnsuitableSectionOnlyArgs()) {
1780 errors += strprintf(_("Config setting for %s only applied on %s "
1781 "network when in [%s] section.") +
1782 Untranslated("\n"),
1783 arg, network, network);
1784 }
1785
1786 if (!errors.empty()) {
1787 return InitError(errors);
1788 }
1789
1790 // Warn if unrecognized section name are present in the config file.
1791 bilingual_str warnings;
1792 for (const auto &section : args.GetUnrecognizedSections()) {
1793 warnings += strprintf(Untranslated("%s:%i ") +
1794 _("Section [%s] is not recognized.") +
1795 Untranslated("\n"),
1796 section.m_file, section.m_line, section.m_name);
1797 }
1798
1799 if (!warnings.empty()) {
1800 InitWarning(warnings);
1801 }
1802
1803 if (!fs::is_directory(args.GetBlocksDirPath())) {
1804 return InitError(
1805 strprintf(_("Specified blocks directory \"%s\" does not exist."),
1806 args.GetArg("-blocksdir", "")));
1807 }
1808
1809 // parse and validate enabled filter types
1810 std::string blockfilterindex_value =
1811 args.GetArg("-blockfilterindex", DEFAULT_BLOCKFILTERINDEX);
1812 if (blockfilterindex_value == "" || blockfilterindex_value == "1") {
1813 g_enabled_filter_types = AllBlockFilterTypes();
1814 } else if (blockfilterindex_value != "0") {
1815 const std::vector<std::string> names =
1816 args.GetArgs("-blockfilterindex");
1817 for (const auto &name : names) {
1818 BlockFilterType filter_type;
1819 if (!BlockFilterTypeByName(name, filter_type)) {
1820 return InitError(
1821 strprintf(_("Unknown -blockfilterindex value %s."), name));
1822 }
1823 g_enabled_filter_types.insert(filter_type);
1824 }
1825 }
1826
1827 // Signal NODE_COMPACT_FILTERS if peerblockfilters and basic filters index
1828 // are both enabled.
1829 if (args.GetBoolArg("-peerblockfilters", DEFAULT_PEERBLOCKFILTERS)) {
1830 if (g_enabled_filter_types.count(BlockFilterType::BASIC) != 1) {
1831 return InitError(
1832 _("Cannot set -peerblockfilters without -blockfilterindex."));
1833 }
1834
1835 nLocalServices = ServiceFlags(nLocalServices | NODE_COMPACT_FILTERS);
1836 }
1837
1838 if (args.GetIntArg("-prune", 0)) {
1839 if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
1840 return InitError(_("Prune mode is incompatible with -txindex."));
1841 }
1842 if (args.GetBoolArg("-reindex-chainstate", false)) {
1843 return InitError(
1844 _("Prune mode is incompatible with -reindex-chainstate. Use "
1845 "full -reindex instead."));
1846 }
1847 if (args.GetBoolArg("-chronik", DEFAULT_CHRONIK)) {
1848 return InitError(_("Prune mode is incompatible with -chronik."));
1849 }
1850 }
1851
1852 // -bind and -whitebind can't be set when not listening
1853 size_t nUserBind =
1854 args.GetArgs("-bind").size() + args.GetArgs("-whitebind").size();
1855 if (nUserBind != 0 && !args.GetBoolArg("-listen", DEFAULT_LISTEN)) {
1856 return InitError(Untranslated(
1857 "Cannot set -bind or -whitebind together with -listen=0"));
1858 }
1859
1860 // Make sure enough file descriptors are available
1861 int nBind = std::max(nUserBind, size_t(1));
1862 nUserMaxConnections =
1863 args.GetIntArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
1864 nMaxConnections = std::max(nUserMaxConnections, 0);
1865
1866 // -maxavalancheoutbound takes precedence over -maxconnections
1867 const int maxAvalancheOutbound = args.GetIntArg(
1868 "-maxavalancheoutbound", DEFAULT_MAX_AVALANCHE_OUTBOUND_CONNECTIONS);
1869 const bool fAvalanche =
1870 args.GetBoolArg("-avalanche", AVALANCHE_DEFAULT_ENABLED);
1871 if (fAvalanche && maxAvalancheOutbound > nMaxConnections) {
1872 nMaxConnections = std::max(maxAvalancheOutbound, nMaxConnections);
1873 // Indicate the value set by the user
1874 LogPrintf("Increasing -maxconnections from %d to %d to comply with "
1875 "-maxavalancheoutbound\n",
1876 nUserMaxConnections, nMaxConnections);
1877 }
1878
1879 // Trim requested connection counts, to fit into system limitations
1880 // <int> in std::min<int>(...) to work around FreeBSD compilation issue
1881 // described in #2695
1883 nMaxConnections + nBind + MIN_CORE_FILEDESCRIPTORS +
1885#ifdef USE_POLL
1886 int fd_max = nFD;
1887#else
1888 int fd_max = FD_SETSIZE;
1889#endif
1890 nMaxConnections = std::max(
1891 std::min<int>(nMaxConnections,
1892 fd_max - nBind - MIN_CORE_FILEDESCRIPTORS -
1894 0);
1895 if (nFD < MIN_CORE_FILEDESCRIPTORS) {
1896 return InitError(_("Not enough file descriptors available."));
1897 }
1898 nMaxConnections =
1900 nMaxConnections);
1901
1902 if (nMaxConnections < nUserMaxConnections) {
1903 // Not categorizing as "Warning" because this is the normal behavior for
1904 // platforms using the select() interface for which FD_SETSIZE is
1905 // usually 1024.
1906 LogPrintf("Reducing -maxconnections from %d to %d, because of system "
1907 "limitations.\n",
1908 nUserMaxConnections, nMaxConnections);
1909 }
1910
1911 // Step 3: parameter-to-internal-flags
1913
1914 // Configure excessive block size.
1915 const int64_t nProposedExcessiveBlockSize =
1916 args.GetIntArg("-excessiveblocksize", DEFAULT_MAX_BLOCK_SIZE);
1917 if (nProposedExcessiveBlockSize <= 0 ||
1918 !config.SetMaxBlockSize(nProposedExcessiveBlockSize)) {
1919 return InitError(
1920 _("Excessive block size must be > 1,000,000 bytes (1MB)"));
1921 }
1922
1923 // Check blockmaxsize does not exceed maximum accepted block size.
1924 const int64_t nProposedMaxGeneratedBlockSize =
1925 args.GetIntArg("-blockmaxsize", DEFAULT_MAX_GENERATED_BLOCK_SIZE);
1926 if (nProposedMaxGeneratedBlockSize <= 0) {
1927 return InitError(_("Max generated block size must be greater than 0"));
1928 }
1929 if (uint64_t(nProposedMaxGeneratedBlockSize) > config.GetMaxBlockSize()) {
1930 return InitError(_("Max generated block size (blockmaxsize) cannot "
1931 "exceed the excessive block size "
1932 "(excessiveblocksize)"));
1933 }
1934
1936 if (nConnectTimeout <= 0) {
1938 }
1939
1940 peer_connect_timeout =
1941 args.GetIntArg("-peertimeout", DEFAULT_PEER_CONNECT_TIMEOUT);
1942 if (peer_connect_timeout <= 0) {
1943 return InitError(Untranslated(
1944 "peertimeout cannot be configured with a negative value."));
1945 }
1946
1947 // Sanity check argument for min fee for including tx in block
1948 // TODO: Harmonize which arguments need sanity checking and where that
1949 // happens.
1950 if (args.IsArgSet("-blockmintxfee")) {
1951 Amount n = Amount::zero();
1952 if (!ParseMoney(args.GetArg("-blockmintxfee", ""), n)) {
1953 return InitError(AmountErrMsg("blockmintxfee",
1954 args.GetArg("-blockmintxfee", "")));
1955 }
1956 }
1957
1959 args.IsArgSet("-bytespersigcheck")
1960 ? args.GetIntArg("-bytespersigcheck", nBytesPerSigCheck)
1961 : args.GetIntArg("-bytespersigop", nBytesPerSigCheck);
1962
1964 return false;
1965 }
1966
1967 // Option to startup with mocktime set (used for regression testing):
1968 SetMockTime(args.GetIntArg("-mocktime", 0)); // SetMockTime(0) is a no-op
1969
1970 if (args.GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS)) {
1971 nLocalServices = ServiceFlags(nLocalServices | NODE_BLOOM);
1972 }
1973
1974 if (args.IsArgSet("-proxy") && args.GetArg("-proxy", "").empty()) {
1975 return InitError(_(
1976 "No proxy server specified. Use -proxy=<ip> or -proxy=<ip:port>."));
1977 }
1978
1979 // Avalanche parameters
1980 const int64_t stakeUtxoMinConfirmations =
1981 args.GetIntArg("-avaproofstakeutxoconfirmations",
1983
1984 if (!chainparams.IsTestChain() &&
1985 stakeUtxoMinConfirmations !=
1987 return InitError(_("Avalanche stake UTXO minimum confirmations can "
1988 "only be set on test chains."));
1989 }
1990
1991 if (stakeUtxoMinConfirmations <= 0) {
1992 return InitError(_("Avalanche stake UTXO minimum confirmations must be "
1993 "a positive integer."));
1994 }
1995
1996 if (args.IsArgSet("-avaproofstakeutxodustthreshold")) {
1997 Amount amount = Amount::zero();
1998 auto parsed = ParseMoney(
1999 args.GetArg("-avaproofstakeutxodustthreshold", ""), amount);
2000 if (!parsed || Amount::zero() == amount) {
2001 return InitError(AmountErrMsg(
2002 "avaproofstakeutxodustthreshold",
2003 args.GetArg("-avaproofstakeutxodustthreshold", "")));
2004 }
2005
2006 if (!chainparams.IsTestChain() &&
2008 return InitError(_("Avalanche stake UTXO dust threshold can "
2009 "only be set on test chains."));
2010 }
2011 }
2012
2013 // This is a staking node
2014 if (fAvalanche && args.IsArgSet("-avaproof")) {
2015 if (!args.GetBoolArg("-listen", true)) {
2016 return InitError(_("Running a staking node requires accepting "
2017 "inbound connections. Please enable -listen."));
2018 }
2019 if (args.IsArgSet("-proxy")) {
2020 return InitError(_("Running a staking node behind a proxy is not "
2021 "supported. Please disable -proxy."));
2022 }
2023 if (args.IsArgSet("-i2psam")) {
2024 return InitError(_("Running a staking node behind I2P is not "
2025 "supported. Please disable -i2psam."));
2026 }
2027 if (args.IsArgSet("-onlynet")) {
2028 return InitError(
2029 _("Restricting the outbound network is not supported when "
2030 "running a staking node. Please disable -onlynet."));
2031 }
2032 }
2033
2034 // Also report errors from parsing before daemonization
2035 {
2036 KernelNotifications notifications{};
2037 ChainstateManager::Options chainman_opts_dummy{
2038 .config = config,
2039 .datadir = args.GetDataDirNet(),
2040 .notifications = notifications,
2041 };
2042 if (const auto error{ApplyArgsManOptions(args, chainman_opts_dummy)}) {
2043 return InitError(*error);
2044 }
2045 BlockManager::Options blockman_opts_dummy{
2046 .chainparams = chainman_opts_dummy.config.GetChainParams(),
2047 .blocks_dir = args.GetBlocksDirPath(),
2048 };
2049 if (const auto error{ApplyArgsManOptions(args, blockman_opts_dummy)}) {
2050 return InitError(*error);
2051 }
2052 }
2053
2054 return true;
2055}
2056
2057static bool LockDataDirectory(bool probeOnly) {
2058 // Make sure only a single Bitcoin process is using the data directory.
2059 fs::path datadir = gArgs.GetDataDirNet();
2060 if (!DirIsWritable(datadir)) {
2061 return InitError(strprintf(
2062 _("Cannot write to data directory '%s'; check permissions."),
2063 fs::PathToString(datadir)));
2064 }
2065 if (!LockDirectory(datadir, ".lock", probeOnly)) {
2066 return InitError(strprintf(_("Cannot obtain a lock on data directory "
2067 "%s. %s is probably already running."),
2068 fs::PathToString(datadir), PACKAGE_NAME));
2069 }
2070 return true;
2071}
2072
2074 // Step 4: sanity checks
2075
2077
2078 // Sanity check
2079 if (!init::SanityChecks()) {
2080 return InitError(strprintf(
2081 _("Initialization sanity check failed. %s is shutting down."),
2082 PACKAGE_NAME));
2083 }
2084
2085 // Probe the data directory lock to give an early error message, if possible
2086 // We cannot hold the data directory lock here, as the forking for daemon()
2087 // hasn't yet happened, and a fork will cause weird behavior to it.
2088 return LockDataDirectory(true);
2089}
2090
2092 // After daemonization get the data directory lock again and hold on to it
2093 // until exit. This creates a slight window for a race condition to happen,
2094 // however this condition is harmless: it will at most make us exit without
2095 // printing a message to console.
2096 if (!LockDataDirectory(false)) {
2097 // Detailed error printed inside LockDataDirectory
2098 return false;
2099 }
2100 return true;
2101}
2102
2105 // Create client interfaces for wallets that are supposed to be loaded
2106 // according to -wallet and -disablewallet options. This only constructs
2107 // the interfaces, it doesn't load wallet data. Wallets actually get loaded
2108 // when load() and start() interface methods are called below.
2110 return true;
2111}
2112
2113bool AppInitMain(Config &config, RPCServer &rpcServer,
2114 HTTPRPCRequestProcessor &httpRPCRequestProcessor,
2117 // Step 4a: application initialization
2118 const ArgsManager &args = *Assert(node.args);
2119 const CChainParams &chainparams = config.GetChainParams();
2120
2121 if (!CreatePidFile(args)) {
2122 // Detailed error printed inside CreatePidFile().
2123 return false;
2124 }
2125 if (!init::StartLogging(args)) {
2126 // Detailed error printed inside StartLogging().
2127 return false;
2128 }
2129
2130 LogPrintf("Using at most %i automatic connections (%i file descriptors "
2131 "available)\n",
2132 nMaxConnections, nFD);
2133
2134 // Warn about relative -datadir path.
2135 if (args.IsArgSet("-datadir") &&
2136 !args.GetPathArg("-datadir").is_absolute()) {
2137 LogPrintf("Warning: relative datadir option '%s' specified, which will "
2138 "be interpreted relative to the current working directory "
2139 "'%s'. This is fragile, because if bitcoin is started in the "
2140 "future from a different location, it will be unable to "
2141 "locate the current data files. There could also be data "
2142 "loss if bitcoin is started while in a temporary "
2143 "directory.\n",
2144 args.GetArg("-datadir", ""),
2145 fs::PathToString(fs::current_path()));
2146 }
2147
2148 ValidationCacheSizes validation_cache_sizes{};
2149 ApplyArgsManOptions(args, validation_cache_sizes);
2150
2151 if (!InitSignatureCache(validation_cache_sizes.signature_cache_bytes)) {
2152 return InitError(strprintf(
2153 _("Unable to allocate memory for -maxsigcachesize: '%s' MiB"),
2154 args.GetIntArg("-maxsigcachesize",
2156 }
2158 validation_cache_sizes.script_execution_cache_bytes)) {
2159 return InitError(strprintf(
2160 _("Unable to allocate memory for -maxscriptcachesize: '%s' MiB"),
2161 args.GetIntArg("-maxscriptcachesize",
2163 }
2164
2165 int script_threads = args.GetIntArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
2166 if (script_threads <= 0) {
2167 // -par=0 means autodetect (number of cores - 1 script threads)
2168 // -par=-n means "leave n cores free" (number of cores - n - 1 script
2169 // threads)
2170 script_threads += GetNumCores();
2171 }
2172
2173 // Subtract 1 because the main thread counts towards the par threads
2174 script_threads = std::max(script_threads - 1, 0);
2175
2176 // Number of script-checking threads <= MAX_SCRIPTCHECK_THREADS
2177 script_threads = std::min(script_threads, MAX_SCRIPTCHECK_THREADS);
2178
2179 LogPrintf("Script verification uses %d additional threads\n",
2180 script_threads);
2181 if (script_threads >= 1) {
2182 StartScriptCheckWorkerThreads(script_threads);
2183 }
2184
2185 assert(!node.scheduler);
2186 node.scheduler = std::make_unique<CScheduler>();
2187
2188 // Start the lightweight task scheduler thread
2189 node.scheduler->m_service_thread =
2190 std::thread(&util::TraceThread, "scheduler",
2191 [&] { node.scheduler->serviceQueue(); });
2192
2193 // Gather some entropy once per minute.
2194 node.scheduler->scheduleEvery(
2195 [] {
2197 return true;
2198 },
2199 std::chrono::minutes{1});
2200
2202
2207 RegisterAllRPCCommands(config, rpcServer, tableRPC);
2208 for (const auto &client : node.chain_clients) {
2209 client->registerRpcs();
2210 }
2211#if ENABLE_ZMQ
2213#endif
2214
2221 if (args.GetBoolArg("-server", false)) {
2222 uiInterface.InitMessage_connect(SetRPCWarmupStatus);
2223 if (!AppInitServers(config, httpRPCRequestProcessor, node)) {
2224 return InitError(
2225 _("Unable to start HTTP server. See debug log for details."));
2226 }
2227 }
2228
2229 // Step 5: verify wallet database integrity
2230 for (const auto &client : node.chain_clients) {
2231 if (!client->verify()) {
2232 return false;
2233 }
2234 }
2235
2236 // Step 6: network initialization
2237
2238 // Note that we absolutely cannot open any actual connections
2239 // until the very end ("start node") as the UTXO/block state
2240 // is not yet setup and may end up being set up twice if we
2241 // need to reindex later.
2242
2243 fListen = args.GetBoolArg("-listen", DEFAULT_LISTEN);
2244 fDiscover = args.GetBoolArg("-discover", true);
2245
2246 {
2247 // Initialize addrman
2248 assert(!node.addrman);
2249
2250 // Read asmap file if configured
2251 std::vector<bool> asmap;
2252 if (args.IsArgSet("-asmap")) {
2253 fs::path asmap_path =
2254 args.GetPathArg("-asmap", DEFAULT_ASMAP_FILENAME);
2255 if (!asmap_path.is_absolute()) {
2256 asmap_path = args.GetDataDirNet() / asmap_path;
2257 }
2258 if (!fs::exists(asmap_path)) {
2259 InitError(strprintf(_("Could not find asmap file %s"),
2260 fs::quoted(fs::PathToString(asmap_path))));
2261 return false;
2262 }
2263 asmap = DecodeAsmap(asmap_path);
2264 if (asmap.size() == 0) {
2265 InitError(strprintf(_("Could not parse asmap file %s"),
2266 fs::quoted(fs::PathToString(asmap_path))));
2267 return false;
2268 }
2269 const uint256 asmap_version = (HashWriter{} << asmap).GetHash();
2270 LogPrintf("Using asmap version %s for IP bucketing\n",
2271 asmap_version.ToString());
2272 } else {
2273 LogPrintf("Using /16 prefix for IP bucketing\n");
2274 }
2275
2276 uiInterface.InitMessage(_("Loading P2P addresses...").translated);
2277 auto addrman{LoadAddrman(chainparams, asmap, args)};
2278 if (!addrman) {
2279 return InitError(util::ErrorString(addrman));
2280 }
2281 node.addrman = std::move(*addrman);
2282 }
2283
2284 assert(!node.banman);
2285 node.banman = std::make_unique<BanMan>(
2286 args.GetDataDirNet() / "banlist.dat", config.GetChainParams(),
2288 assert(!node.connman);
2289 node.connman = std::make_unique<CConnman>(
2290 config, GetRand<uint64_t>(), GetRand<uint64_t>(), *node.addrman,
2291 args.GetBoolArg("-networkactive", true));
2292
2293 // sanitize comments per BIP-0014, format user agent and check total size
2294 std::vector<std::string> uacomments;
2295 for (const std::string &cmt : args.GetArgs("-uacomment")) {
2296 if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT)) {
2297 return InitError(strprintf(
2298 _("User Agent comment (%s) contains unsafe characters."), cmt));
2299 }
2300 uacomments.push_back(cmt);
2301 }
2302 const std::string client_name = args.GetArg("-uaclientname", CLIENT_NAME);
2303 const std::string client_version =
2304 args.GetArg("-uaclientversion", FormatVersion(CLIENT_VERSION));
2305 if (client_name != SanitizeString(client_name, SAFE_CHARS_UA_COMMENT)) {
2306 return InitError(strprintf(
2307 _("-uaclientname (%s) contains invalid characters."), client_name));
2308 }
2309 if (client_version !=
2310 SanitizeString(client_version, SAFE_CHARS_UA_COMMENT)) {
2311 return InitError(
2312 strprintf(_("-uaclientversion (%s) contains invalid characters."),
2313 client_version));
2314 }
2315 const std::string strSubVersion =
2316 FormatUserAgent(client_name, client_version, uacomments);
2317 if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
2318 return InitError(strprintf(
2319 _("Total length of network version string (%i) exceeds maximum "
2320 "length (%i). Reduce the number or size of uacomments."),
2321 strSubVersion.size(), MAX_SUBVERSION_LENGTH));
2322 }
2323
2324 if (args.IsArgSet("-onlynet")) {
2325 std::set<enum Network> nets;
2326 for (const std::string &snet : args.GetArgs("-onlynet")) {
2327 enum Network net = ParseNetwork(snet);
2328 if (net == NET_UNROUTABLE) {
2329 return InitError(strprintf(
2330 _("Unknown network specified in -onlynet: '%s'"), snet));
2331 }
2332 nets.insert(net);
2333 }
2334 for (int n = 0; n < NET_MAX; n++) {
2335 enum Network net = (enum Network)n;
2336 if (!nets.count(net)) {
2337 SetReachable(net, false);
2338 }
2339 }
2340 }
2341
2342 // Check for host lookup allowed before parsing any network related
2343 // parameters
2345
2346 bool proxyRandomize =
2347 args.GetBoolArg("-proxyrandomize", DEFAULT_PROXYRANDOMIZE);
2348 // -proxy sets a proxy for all outgoing network traffic
2349 // -noproxy (or -proxy=0) as well as the empty string can be used to not set
2350 // a proxy, this is the default
2351 std::string proxyArg = args.GetArg("-proxy", "");
2352 SetReachable(NET_ONION, false);
2353 if (proxyArg != "" && proxyArg != "0") {
2354 CService proxyAddr;
2355 if (!Lookup(proxyArg, proxyAddr, 9050, fNameLookup)) {
2356 return InitError(strprintf(
2357 _("Invalid -proxy address or hostname: '%s'"), proxyArg));
2358 }
2359
2360 proxyType addrProxy = proxyType(proxyAddr, proxyRandomize);
2361 if (!addrProxy.IsValid()) {
2362 return InitError(strprintf(
2363 _("Invalid -proxy address or hostname: '%s'"), proxyArg));
2364 }
2365
2366 SetProxy(NET_IPV4, addrProxy);
2367 SetProxy(NET_IPV6, addrProxy);
2368 SetProxy(NET_ONION, addrProxy);
2369 SetNameProxy(addrProxy);
2370 // by default, -proxy sets onion as reachable, unless -noonion later
2371 SetReachable(NET_ONION, true);
2372 }
2373
2374 // -onion can be used to set only a proxy for .onion, or override normal
2375 // proxy for .onion addresses.
2376 // -noonion (or -onion=0) disables connecting to .onion entirely. An empty
2377 // string is used to not override the onion proxy (in which case it defaults
2378 // to -proxy set above, or none)
2379 std::string onionArg = args.GetArg("-onion", "");
2380 if (onionArg != "") {
2381 if (onionArg == "0") {
2382 // Handle -noonion/-onion=0
2383 SetReachable(NET_ONION, false);
2384 } else {
2385 CService onionProxy;
2386 if (!Lookup(onionArg, onionProxy, 9050, fNameLookup)) {
2387 return InitError(strprintf(
2388 _("Invalid -onion address or hostname: '%s'"), onionArg));
2389 }
2390 proxyType addrOnion = proxyType(onionProxy, proxyRandomize);
2391 if (!addrOnion.IsValid()) {
2392 return InitError(strprintf(
2393 _("Invalid -onion address or hostname: '%s'"), onionArg));
2394 }
2395 SetProxy(NET_ONION, addrOnion);
2396 SetReachable(NET_ONION, true);
2397 }
2398 }
2399
2400 for (const std::string &strAddr : args.GetArgs("-externalip")) {
2401 CService addrLocal;
2402 if (Lookup(strAddr, addrLocal, GetListenPort(), fNameLookup) &&
2403 addrLocal.IsValid()) {
2404 AddLocal(addrLocal, LOCAL_MANUAL);
2405 } else {
2406 return InitError(ResolveErrMsg("externalip", strAddr));
2407 }
2408 }
2409
2410#if ENABLE_ZMQ
2412 [&chainman = node.chainman](CBlock &block, const CBlockIndex &index) {
2413 assert(chainman);
2414 return chainman->m_blockman.ReadBlockFromDisk(block, index);
2415 });
2416
2419 }
2420#endif
2421
2422 // Step 7: load block chain
2423
2424 node.notifications = std::make_unique<KernelNotifications>();
2425 fReindex = args.GetBoolArg("-reindex", false);
2426 bool fReindexChainState = args.GetBoolArg("-reindex-chainstate", false);
2427
2428 ChainstateManager::Options chainman_opts{
2429 .config = config,
2430 .datadir = args.GetDataDirNet(),
2431 .adjusted_time_callback = GetAdjustedTime,
2432 .notifications = *node.notifications,
2433 };
2434 // no error can happen, already checked in AppInitParameterInteraction
2435 Assert(!ApplyArgsManOptions(args, chainman_opts));
2436
2437 if (chainman_opts.checkpoints_enabled) {
2438 LogPrintf("Checkpoints will be verified.\n");
2439 } else {
2440 LogPrintf("Skipping checkpoint verification.\n");
2441 }
2442
2443 BlockManager::Options blockman_opts{
2444 .chainparams = chainman_opts.config.GetChainParams(),
2445 .blocks_dir = args.GetBlocksDirPath(),
2446 };
2447 // no error can happen, already checked in AppInitParameterInteraction
2448 Assert(!ApplyArgsManOptions(args, blockman_opts));
2449
2450 // cache size calculations
2451 CacheSizes cache_sizes =
2452 CalculateCacheSizes(args, g_enabled_filter_types.size());
2453
2454 LogPrintf("Cache configuration:\n");
2455 LogPrintf("* Using %.1f MiB for block index database\n",
2456 cache_sizes.block_tree_db * (1.0 / 1024 / 1024));
2457 if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
2458 LogPrintf("* Using %.1f MiB for transaction index database\n",
2459 cache_sizes.tx_index * (1.0 / 1024 / 1024));
2460 }
2461 for (BlockFilterType filter_type : g_enabled_filter_types) {
2462 LogPrintf("* Using %.1f MiB for %s block filter index database\n",
2463 cache_sizes.filter_index * (1.0 / 1024 / 1024),
2464 BlockFilterTypeName(filter_type));
2465 }
2466 LogPrintf("* Using %.1f MiB for chain state database\n",
2467 cache_sizes.coins_db * (1.0 / 1024 / 1024));
2468
2469 assert(!node.mempool);
2470 assert(!node.chainman);
2471
2472 CTxMemPool::Options mempool_opts{
2473 .check_ratio = chainparams.DefaultConsistencyChecks() ? 1 : 0,
2474 };
2475 if (const auto err{ApplyArgsManOptions(args, chainparams, mempool_opts)}) {
2476 return InitError(*err);
2477 }
2478 mempool_opts.check_ratio =
2479 std::clamp<int>(mempool_opts.check_ratio, 0, 1'000'000);
2480
2481 // FIXME: this legacy limit comes from the DEFAULT_DESCENDANT_SIZE_LIMIT
2482 // (101) that was enforced before the wellington activation. While it's
2483 // still a good idea to have some minimum mempool size, using this value as
2484 // a threshold is no longer relevant.
2485 int64_t nMempoolSizeMin = 101 * 1000 * 40;
2486 if (mempool_opts.max_size_bytes < 0 ||
2487 (!chainparams.IsTestChain() &&
2488 mempool_opts.max_size_bytes < nMempoolSizeMin)) {
2489 return InitError(strprintf(_("-maxmempool must be at least %d MB"),
2490 std::ceil(nMempoolSizeMin / 1000000.0)));
2491 }
2492 LogPrintf("* Using %.1f MiB for in-memory UTXO set (plus up to %.1f MiB of "
2493 "unused mempool space)\n",
2494 cache_sizes.coins * (1.0 / 1024 / 1024),
2495 mempool_opts.max_size_bytes * (1.0 / 1024 / 1024));
2496
2497 for (bool fLoaded = false; !fLoaded && !ShutdownRequested();) {
2498 node.mempool = std::make_unique<CTxMemPool>(mempool_opts);
2499
2500 node.chainman =
2501 std::make_unique<ChainstateManager>(chainman_opts, blockman_opts);
2502 ChainstateManager &chainman = *node.chainman;
2503
2505 options.mempool = Assert(node.mempool.get());
2506 options.reindex = node::fReindex;
2507 options.reindex_chainstate = fReindexChainState;
2508 options.prune = chainman.m_blockman.IsPruneMode();
2509 options.check_blocks =
2510 args.GetIntArg("-checkblocks", DEFAULT_CHECKBLOCKS);
2511 options.check_level = args.GetIntArg("-checklevel", DEFAULT_CHECKLEVEL);
2513 args.IsArgSet("-checkblocks") || args.IsArgSet("-checklevel");
2515 options.coins_error_cb = [] {
2516 uiInterface.ThreadSafeMessageBox(
2517 _("Error reading from database, shutting down."), "",
2519 };
2520
2521 uiInterface.InitMessage(_("Loading block index...").translated);
2522
2523 const int64_t load_block_index_start_time = GetTimeMillis();
2524 auto catch_exceptions = [](auto &&f) {
2525 try {
2526 return f();
2527 } catch (const std::exception &e) {
2528 LogPrintf("%s\n", e.what());
2529 return std::make_tuple(node::ChainstateLoadStatus::FAILURE,
2530 _("Error opening block database"));
2531 }
2532 };
2533 auto [status, error] = catch_exceptions(
2534 [&] { return LoadChainstate(chainman, cache_sizes, options); });
2536 uiInterface.InitMessage(_("Verifying blocks...").translated);
2537 if (chainman.m_blockman.m_have_pruned &&
2538 options.check_blocks > MIN_BLOCKS_TO_KEEP) {
2540 "pruned datadir may not have more than %d "
2541 "blocks; only checking available blocks\n",
2543 }
2544 std::tie(status, error) = catch_exceptions(
2545 [&] { return VerifyLoadedChainstate(chainman, options); });
2547 WITH_LOCK(cs_main, return node.chainman->LoadRecentHeadersTime(
2548 node.chainman->m_options.datadir /
2550 fLoaded = true;
2551 LogPrintf(" block index %15dms\n",
2552 GetTimeMillis() - load_block_index_start_time);
2553 }
2554 }
2555
2558 status ==
2560 return InitError(error);
2561 }
2562
2563 if (!fLoaded && !ShutdownRequested()) {
2564 // first suggest a reindex
2565 if (!options.reindex) {
2566 bool fRet = uiInterface.ThreadSafeQuestion(
2567 error + Untranslated(".\n\n") +
2568 _("Do you want to rebuild the block database now?"),
2569 error.original + ".\nPlease restart with -reindex or "
2570 "-reindex-chainstate to recover.",
2571 "",
2574 if (fRet) {
2575 fReindex = true;
2576 AbortShutdown();
2577 } else {
2578 LogPrintf("Aborted block database rebuild. Exiting.\n");
2579 return false;
2580 }
2581 } else {
2582 return InitError(error);
2583 }
2584 }
2585 }
2586
2587 // As LoadBlockIndex can take several minutes, it's possible the user
2588 // requested to kill the GUI during the last operation. If so, exit.
2589 // As the program has not fully started yet, Shutdown() is possibly
2590 // overkill.
2591 if (ShutdownRequested()) {
2592 LogPrintf("Shutdown requested. Exiting.\n");
2593 return false;
2594 }
2595
2596 ChainstateManager &chainman = *Assert(node.chainman);
2597
2598 if (args.GetBoolArg("-avalanche", AVALANCHE_DEFAULT_ENABLED)) {
2599 // Initialize Avalanche.
2600 bilingual_str avalancheError;
2602 args, *node.chain, node.connman.get(), chainman, node.mempool.get(),
2603 *node.scheduler, avalancheError);
2604 if (!node.avalanche) {
2605 InitError(avalancheError);
2606 return false;
2607 }
2608
2609 if (node.avalanche->isAvalancheServiceAvailable()) {
2610 nLocalServices = ServiceFlags(nLocalServices | NODE_AVALANCHE);
2611 }
2612 }
2613
2614 PeerManager::Options peerman_opts{};
2615 ApplyArgsManOptions(args, peerman_opts);
2616
2617 assert(!node.peerman);
2618 node.peerman = PeerManager::make(*node.connman, *node.addrman,
2619 node.banman.get(), chainman, *node.mempool,
2620 node.avalanche.get(), peerman_opts);
2621 RegisterValidationInterface(node.peerman.get());
2622
2623 // Encoded addresses using cashaddr instead of base58.
2624 // We do this by default to avoid confusion with BTC addresses.
2625 config.SetCashAddrEncoding(args.GetBoolArg("-usecashaddr", true));
2626
2627 // Step 8: load indexers
2628 if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
2629 auto result{
2631 chainman.m_blockman.m_block_tree_db)))};
2632 if (!result) {
2633 return InitError(util::ErrorString(result));
2634 }
2635
2636 g_txindex =
2637 std::make_unique<TxIndex>(cache_sizes.tx_index, false, fReindex);
2638 if (!g_txindex->Start(chainman.ActiveChainstate())) {
2639 return false;
2640 }
2641 }
2642
2643 for (const auto &filter_type : g_enabled_filter_types) {
2644 InitBlockFilterIndex(filter_type, cache_sizes.filter_index, false,
2645 fReindex);
2646 if (!GetBlockFilterIndex(filter_type)
2647 ->Start(chainman.ActiveChainstate())) {
2648 return false;
2649 }
2650 }
2651
2652 if (args.GetBoolArg("-coinstatsindex", DEFAULT_COINSTATSINDEX)) {
2653 g_coin_stats_index = std::make_unique<CoinStatsIndex>(
2654 /* cache size */ 0, false, fReindex);
2655 if (!g_coin_stats_index->Start(chainman.ActiveChainstate())) {
2656 return false;
2657 }
2658 }
2659
2660#if ENABLE_CHRONIK
2661 if (args.GetBoolArg("-chronik", DEFAULT_CHRONIK)) {
2662 const bool fReindexChronik =
2663 fReindex || args.GetBoolArg("-chronikreindex", false);
2664 if (!chronik::Start(args, config, node, fReindexChronik)) {
2665 return false;
2666 }
2667 }
2668#endif
2669
2670 // Step 9: load wallet
2671 for (const auto &client : node.chain_clients) {
2672 if (!client->load()) {
2673 return false;
2674 }
2675 }
2676
2677 // Step 10: data directory maintenance
2678
2679 // if pruning, unset the service bit and perform the initial blockstore
2680 // prune after any wallet rescanning has taken place.
2681 if (chainman.m_blockman.IsPruneMode()) {
2682 LogPrintf("Unsetting NODE_NETWORK on prune mode\n");
2683 nLocalServices = ServiceFlags(nLocalServices & ~NODE_NETWORK);
2684 if (!fReindex) {
2685 LOCK(cs_main);
2686 for (Chainstate *chainstate : chainman.GetAll()) {
2687 uiInterface.InitMessage(_("Pruning blockstore...").translated);
2688 chainstate->PruneAndFlush();
2689 }
2690 }
2691 }
2692
2693 // Step 11: import blocks
2694 if (!CheckDiskSpace(args.GetDataDirNet())) {
2695 InitError(
2696 strprintf(_("Error: Disk space is low for %s"),
2698 return false;
2699 }
2700 if (!CheckDiskSpace(args.GetBlocksDirPath())) {
2701 InitError(
2702 strprintf(_("Error: Disk space is low for %s"),
2704 return false;
2705 }
2706
2707 // Either install a handler to notify us when genesis activates, or set
2708 // fHaveGenesis directly.
2709 // No locking, as this happens before any background thread is started.
2710 boost::signals2::connection block_notify_genesis_wait_connection;
2711 if (WITH_LOCK(chainman.GetMutex(),
2712 return chainman.ActiveChain().Tip() == nullptr)) {
2713 block_notify_genesis_wait_connection =
2714 uiInterface.NotifyBlockTip_connect(
2715 std::bind(BlockNotifyGenesisWait, std::placeholders::_2));
2716 } else {
2717 fHaveGenesis = true;
2718 }
2719
2720#if defined(HAVE_SYSTEM)
2721 const std::string block_notify = args.GetArg("-blocknotify", "");
2722 if (!block_notify.empty()) {
2723 uiInterface.NotifyBlockTip_connect([block_notify](
2724 SynchronizationState sync_state,
2725 const CBlockIndex *pBlockIndex) {
2726 if (sync_state != SynchronizationState::POST_INIT || !pBlockIndex) {
2727 return;
2728 }
2729 std::string command = block_notify;
2730 ReplaceAll(command, "%s", pBlockIndex->GetBlockHash().GetHex());
2731 std::thread t(runCommand, command);
2732 // thread runs free
2733 t.detach();
2734 });
2735 }
2736#endif
2737
2738 std::vector<fs::path> vImportFiles;
2739 for (const std::string &strFile : args.GetArgs("-loadblock")) {
2740 vImportFiles.push_back(fs::PathFromString(strFile));
2741 }
2742
2743 avalanche::Processor *const avalanche = node.avalanche.get();
2744 chainman.m_load_block =
2745 std::thread(&util::TraceThread, "loadblk", [=, &chainman, &args] {
2746 ThreadImport(chainman, avalanche, vImportFiles,
2747 ShouldPersistMempool(args) ? MempoolPath(args)
2748 : fs::path{});
2749 });
2750
2751 // Wait for genesis block to be processed
2752 {
2754 // We previously could hang here if StartShutdown() is called prior to
2755 // ThreadImport getting started, so instead we just wait on a timer to
2756 // check ShutdownRequested() regularly.
2757 while (!fHaveGenesis && !ShutdownRequested()) {
2758 g_genesis_wait_cv.wait_for(lock, std::chrono::milliseconds(500));
2759 }
2760 block_notify_genesis_wait_connection.disconnect();
2761 }
2762
2763 if (ShutdownRequested()) {
2764 return false;
2765 }
2766
2767 // Step 12: start node
2768
2769 int chain_active_height;
2770
2772 {
2773 LOCK(cs_main);
2774 LogPrintf("block tree size = %u\n", chainman.BlockIndex().size());
2775 chain_active_height = chainman.ActiveChain().Height();
2776 if (tip_info) {
2777 tip_info->block_height = chain_active_height;
2778 tip_info->block_time =
2779 chainman.ActiveChain().Tip()
2780 ? chainman.ActiveChain().Tip()->GetBlockTime()
2781 : chainman.GetParams().GenesisBlock().GetBlockTime();
2783 chainman.GetParams().TxData(), chainman.ActiveChain().Tip());
2784 }
2785 if (tip_info && chainman.m_best_header) {
2786 tip_info->header_height = chainman.m_best_header->nHeight;
2787 tip_info->header_time = chainman.m_best_header->GetBlockTime();
2788 }
2789 }
2790 LogPrintf("nBestHeight = %d\n", chain_active_height);
2791 if (node.peerman) {
2792 node.peerman->SetBestHeight(chain_active_height);
2793 }
2794
2795 // Map ports with UPnP or NAT-PMP.
2796 StartMapPort(args.GetBoolArg("-upnp", DEFAULT_UPNP),
2797 args.GetBoolArg("-natpmp", DEFAULT_NATPMP));
2798
2799 CConnman::Options connOptions;
2800 connOptions.nLocalServices = nLocalServices;
2801 connOptions.nMaxConnections = nMaxConnections;
2802 connOptions.m_max_avalanche_outbound =
2803 node.avalanche
2804 ? args.GetIntArg("-maxavalancheoutbound",
2806 : 0;
2807 connOptions.m_max_outbound_full_relay = std::min(
2809 connOptions.nMaxConnections - connOptions.m_max_avalanche_outbound);
2810 connOptions.m_max_outbound_block_relay = std::min(
2812 connOptions.nMaxConnections - connOptions.m_max_avalanche_outbound -
2813 connOptions.m_max_outbound_full_relay);
2815 connOptions.nMaxFeeler = MAX_FEELER_CONNECTIONS;
2816 connOptions.uiInterface = &uiInterface;
2817 connOptions.m_banman = node.banman.get();
2818 connOptions.m_msgproc.push_back(node.peerman.get());
2819 if (node.avalanche) {
2820 connOptions.m_msgproc.push_back(node.avalanche.get());
2821 }
2822 connOptions.nSendBufferMaxSize =
2823 1000 * args.GetIntArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER);
2824 connOptions.nReceiveFloodSize =
2825 1000 * args.GetIntArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER);
2826 connOptions.m_added_nodes = args.GetArgs("-addnode");
2827
2828 connOptions.nMaxOutboundLimit =
2829 1024 * 1024 *
2830 args.GetIntArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET);
2831 connOptions.m_peer_connect_timeout = peer_connect_timeout;
2832 connOptions.whitelist_forcerelay =
2833 args.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY);
2834 connOptions.whitelist_relay =
2835 args.GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY);
2836
2837 // Port to bind to if `-bind=addr` is provided without a `:port` suffix.
2838 const uint16_t default_bind_port = static_cast<uint16_t>(
2839 args.GetIntArg("-port", config.GetChainParams().GetDefaultPort()));
2840
2841 const auto BadPortWarning = [](const char *prefix, uint16_t port) {
2842 return strprintf(_("%s request to listen on port %u. This port is "
2843 "considered \"bad\" and "
2844 "thus it is unlikely that any Bitcoin ABC peers "
2845 "connect to it. See "
2846 "doc/p2p-bad-ports.md for details and a full list."),
2847 prefix, port);
2848 };
2849
2850 for (const std::string &bind_arg : args.GetArgs("-bind")) {
2851 CService bind_addr;
2852 const size_t index = bind_arg.rfind('=');
2853 if (index == std::string::npos) {
2854 if (Lookup(bind_arg, bind_addr, default_bind_port,
2855 /*fAllowLookup=*/false)) {
2856 connOptions.vBinds.push_back(bind_addr);
2857 if (IsBadPort(bind_addr.GetPort())) {
2858 InitWarning(BadPortWarning("-bind", bind_addr.GetPort()));
2859 }
2860 continue;
2861 }
2862 } else {
2863 const std::string network_type = bind_arg.substr(index + 1);
2864 if (network_type == "onion") {
2865 const std::string truncated_bind_arg =
2866 bind_arg.substr(0, index);
2867 if (Lookup(truncated_bind_arg, bind_addr,
2868 BaseParams().OnionServiceTargetPort(), false)) {
2869 connOptions.onion_binds.push_back(bind_addr);
2870 continue;
2871 }
2872 }
2873 }
2874 return InitError(ResolveErrMsg("bind", bind_arg));
2875 }
2876
2877 for (const std::string &strBind : args.GetArgs("-whitebind")) {
2878 NetWhitebindPermissions whitebind;
2880 if (!NetWhitebindPermissions::TryParse(strBind, whitebind, error)) {
2881 return InitError(error);
2882 }
2883 connOptions.vWhiteBinds.push_back(whitebind);
2884 }
2885
2886 // If the user did not specify -bind= or -whitebind= then we bind
2887 // on any address - 0.0.0.0 (IPv4) and :: (IPv6).
2888 connOptions.bind_on_any =
2889 args.GetArgs("-bind").empty() && args.GetArgs("-whitebind").empty();
2890
2891 // Emit a warning if a bad port is given to -port= but only if -bind and
2892 // -whitebind are not given, because if they are, then -port= is ignored.
2893 if (connOptions.bind_on_any && args.IsArgSet("-port")) {
2894 const uint16_t port_arg = args.GetIntArg("-port", 0);
2895 if (IsBadPort(port_arg)) {
2896 InitWarning(BadPortWarning("-port", port_arg));
2897 }
2898 }
2899
2900 CService onion_service_target;
2901 if (!connOptions.onion_binds.empty()) {
2902 onion_service_target = connOptions.onion_binds.front();
2903 } else if (!connOptions.vBinds.empty()) {
2904 onion_service_target = connOptions.vBinds.front();
2905 } else {
2906 onion_service_target = DefaultOnionServiceTarget();
2907 connOptions.onion_binds.push_back(onion_service_target);
2908 }
2909
2910 if (args.GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION)) {
2911 if (connOptions.onion_binds.size() > 1) {
2913 _("More than one onion bind address is provided. Using %s "
2914 "for the automatically created Tor onion service."),
2915 onion_service_target.ToStringIPPort()));
2916 }
2917 StartTorControl(onion_service_target);
2918 }
2919
2920 if (connOptions.bind_on_any) {
2921 // Only add all IP addresses of the machine if we would be listening on
2922 // any address - 0.0.0.0 (IPv4) and :: (IPv6).
2923 Discover();
2924 }
2925
2926 for (const auto &net : args.GetArgs("-whitelist")) {
2928 ConnectionDirection connection_direction;
2930 if (!NetWhitelistPermissions::TryParse(net, subnet,
2931 connection_direction, error)) {
2932 return InitError(error);
2933 }
2934 if (connection_direction & ConnectionDirection::In) {
2935 connOptions.vWhitelistedRangeIncoming.push_back(subnet);
2936 }
2937 if (connection_direction & ConnectionDirection::Out) {
2938 connOptions.vWhitelistedRangeOutgoing.push_back(subnet);
2939 }
2940 }
2941
2942 connOptions.vSeedNodes = args.GetArgs("-seednode");
2943
2944 // Initiate outbound connections unless connect=0
2945 connOptions.m_use_addrman_outgoing = !args.IsArgSet("-connect");
2946 if (!connOptions.m_use_addrman_outgoing) {
2947 const auto connect = args.GetArgs("-connect");
2948 if (connect.size() != 1 || connect[0] != "0") {
2949 connOptions.m_specified_outgoing = connect;
2950 }
2951 }
2952
2953 const std::string &i2psam_arg = args.GetArg("-i2psam", "");
2954 if (!i2psam_arg.empty()) {
2955 CService addr;
2956 if (!Lookup(i2psam_arg, addr, 7656, fNameLookup) || !addr.IsValid()) {
2957 return InitError(strprintf(
2958 _("Invalid -i2psam address or hostname: '%s'"), i2psam_arg));
2959 }
2960 SetReachable(NET_I2P, true);
2961 SetProxy(NET_I2P, proxyType{addr});
2962 } else {
2963 SetReachable(NET_I2P, false);
2964 }
2965
2966 connOptions.m_i2p_accept_incoming =
2967 args.GetBoolArg("-i2pacceptincoming", true);
2968
2969 if (!node.connman->Start(*node.scheduler, connOptions)) {
2970 return false;
2971 }
2972
2973 // Step 13: finished
2974
2975 // At this point, the RPC is "started", but still in warmup, which means it
2976 // cannot yet be called. Before we make it callable, we need to make sure
2977 // that the RPC's view of the best block is valid and consistent with
2978 // ChainstateManager's active tip.
2979 //
2980 // If we do not do this, RPC's view of the best block will be height=0 and
2981 // hash=0x0. This will lead to erroroneous responses for things like
2982 // waitforblockheight.
2984 WITH_LOCK(chainman.GetMutex(), return chainman.ActiveTip()));
2986
2987 uiInterface.InitMessage(_("Done loading").translated);
2988
2989 for (const auto &client : node.chain_clients) {
2990 client->start(*node.scheduler);
2991 }
2992
2993 BanMan *banman = node.banman.get();
2994 node.scheduler->scheduleEvery(
2995 [banman] {
2996 banman->DumpBanlist();
2997 return true;
2998 },
3000
3001 // Start Avalanche's event loop.
3002 if (node.avalanche) {
3003 node.avalanche->startEventLoop(*node.scheduler);
3004 }
3005
3006 if (node.peerman) {
3007 node.peerman->StartScheduledTasks(*node.scheduler);
3008 }
3009
3010#if HAVE_SYSTEM
3011 StartupNotify(args);
3012#endif
3013
3014 return true;
3015}
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:85
const CBlock & GenesisBlock() const
Definition: chainparams.h:110
bool DefaultConsistencyChecks() const
Default value for -checkmempool and -checkblockindex argument.
Definition: chainparams.h:112
const ChainTxData & TxData() const
Definition: chainparams.h:152
bool IsTestChain() const
If this chain is exclusively used for testing.
Definition: chainparams.h:116
uint16_t GetDefaultPort() const
Definition: chainparams.h:100
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:1140
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:1407
SnapshotCompletionResult MaybeCompleteSnapshotValidation(std::function< void(bilingual_str)> shutdown_fnc=[](bilingual_str msg) { AbortNode(msg.original, msg);}) EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex *GetSnapshotBaseBlock() const EXCLUSIVE_LOCKS_REQUIRED(Chainstate ActiveChainstate)() const
Once the background validation chainstate has reached the height which is the base of the UTXO snapsh...
Definition: validation.h:1383
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
Definition: validation.h:1265
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1390
const CChainParams & GetParams() const
Definition: validation.h:1227
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1384
std::thread m_load_block
Definition: validation.h:1270
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(std::vector< Chainstate * GetAll)()
Instantiate a new chainstate.
Definition: validation.h:1347
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:1273
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:222
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:73
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:275
bool IsPruneMode() const
Whether running in -prune mode.
Definition: blockstorage.h:246
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:1694
bool AppInitLockDataDirectory()
Lock bitcoin data directory.
Definition: init.cpp:2091
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:1535
#define MIN_CORE_FILEDESCRIPTORS
Definition: init.cpp:144
static bool fHaveGenesis
Definition: init.cpp:1510
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:1511
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:1512
bool AppInitMain(Config &config, RPCServer &rpcServer, HTTPRPCRequestProcessor &httpRPCRequestProcessor, NodeContext &node, interfaces::BlockAndHeaderTipInfo *tip_info)
Bitcoin main initialization.
Definition: init.cpp:2113
static constexpr bool DEFAULT_CHRONIK
Definition: init.cpp:137
bool AppInitBasicSetup(const ArgsManager &args)
Initialize bitcoin: Basic context setup.
Definition: init.cpp:1721
bool AppInitSanityChecks()
Initialization sanity checks: ecc init, sanity checks, dir lock.
Definition: init.cpp:2073
bool AppInitInterfaces(NodeContext &node)
Initialize node and wallet interface pointers.
Definition: init.cpp:2103
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:1560
static void BlockNotifyGenesisWait(const CBlockIndex *pBlockIndex)
Definition: init.cpp:1514
static void OnRPCStopped()
Definition: init.cpp:418
static bool LockDataDirectory(bool probeOnly)
Definition: init.cpp:2057
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:1768
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:1710
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:798
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:271
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:65
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