Bitcoin ABC 0.33.8
P2P Digital Currency
init.cpp
Go to the documentation of this file.
1// Copyright (c) 2009-2010 Satoshi Nakamoto
2// Copyright (c) 2009-2018 The Bitcoin Core developers
3// Distributed under the MIT software license, see the accompanying
4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6#if defined(HAVE_CONFIG_H)
7#include <config/bitcoin-config.h>
8#endif
9
10#include <init.h>
11
12#include <kernel/checks.h>
14
15#include <addrman.h>
16#include <avalanche/avalanche.h>
17#include <avalanche/processor.h>
18#include <avalanche/proof.h> // For AVALANCHE_LEGACY_PROOF_DEFAULT
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 <chainparamsbase.h>
26#include <clientversion.h>
27#include <common/args.h>
28#include <common/messages.h>
29#include <config.h>
30#include <consensus/amount.h>
31#include <currencyunit.h>
32#include <flatfile.h>
33#include <hash.h>
34#include <httprpc.h>
35#include <httpserver.h>
38#include <index/txindex.h>
39#include <init/common.h>
40#include <interfaces/chain.h>
41#include <interfaces/node.h>
42#include <kernel/caches.h>
43#include <mapport.h>
44#include <mempool_args.h>
45#include <net.h>
46#include <net_permissions.h>
47#include <net_processing.h>
48#include <netbase.h>
50#include <node/blockstorage.h>
51#include <node/caches.h>
52#include <node/chainstate.h>
54#include <node/context.h>
57#include <node/miner.h>
58#include <node/peerman_args.h>
59#include <node/ui_interface.h>
60#include <policy/block/rtt.h>
61#include <policy/policy.h>
62#include <policy/settings.h>
63#include <rpc/blockchain.h>
64#include <rpc/register.h>
65#include <rpc/server.h>
66#include <rpc/util.h>
67#include <scheduler.h>
68#include <script/scriptcache.h>
69#include <script/sigcache.h>
70#include <script/standard.h>
71#include <shutdown.h>
72#include <sync.h>
73#include <timedata.h>
74#include <torcontrol.h>
75#include <txdb.h>
76#include <txmempool.h>
77#include <util/asmap.h>
78#include <util/chaintype.h>
79#include <util/check.h>
80#include <util/fs.h>
81#include <util/fs_helpers.h>
82#include <util/moneystr.h>
83#include <util/string.h>
84#include <util/syserror.h>
85#include <util/thread.h>
86#include <util/threadnames.h>
87#include <util/translation.h>
88#include <validation.h>
89#include <validationinterface.h>
90#include <walletinitinterface.h>
91
92#include <boost/signals2/signal.hpp>
93
94#if ENABLE_CHRONIK
95#include <chronik-cpp/chronik.h>
96#endif
97
98#if ENABLE_ZMQ
101#include <zmq/zmqrpc.h>
102#endif
103
104#ifndef WIN32
105#include <cerrno>
106#include <csignal>
107#include <sys/stat.h>
108#endif
109#include <algorithm>
110#include <condition_variable>
111#include <cstdint>
112#include <cstdio>
113#include <fstream>
114#include <functional>
115#include <set>
116#include <string>
117#include <thread>
118#include <vector>
119
123
126
131using node::fReindex;
139using util::Join;
140using util::ReplaceAll;
141
142static const bool DEFAULT_PROXYRANDOMIZE = true;
143static const bool DEFAULT_REST_ENABLE = false;
144static constexpr bool DEFAULT_CHRONIK = false;
145static constexpr bool DEFAULT_USEASHADDR = true;
146
147#ifdef WIN32
148// Win32 LevelDB doesn't use filedescriptors, and the ones used for accessing
149// block files don't count towards the fd_set size limit anyway.
150#define MIN_CORE_FILEDESCRIPTORS 0
151#else
152#define MIN_CORE_FILEDESCRIPTORS 150
153#endif
154
155static const char *DEFAULT_ASMAP_FILENAME = "ip_asn.map";
156
157static const std::string HEADERS_TIME_FILE_NAME{"headerstime.dat"};
158
162static const char *BITCOIN_PID_FILENAME = "bitcoind.pid";
163
164static fs::path GetPidFile(const ArgsManager &args) {
165 return AbsPathForConfigVal(args,
166 args.GetPathArg("-pid", BITCOIN_PID_FILENAME));
167}
168
169[[nodiscard]] static bool CreatePidFile(const ArgsManager &args) {
170 std::ofstream file{GetPidFile(args)};
171 if (file) {
172#ifdef WIN32
173 tfm::format(file, "%d\n", GetCurrentProcessId());
174#else
175 tfm::format(file, "%d\n", getpid());
176#endif
177 return true;
178 } else {
179 return InitError(strprintf(_("Unable to create the PID file '%s': %s"),
181 SysErrorString(errno)));
182 }
183}
184
186//
187// Shutdown
188//
189
190//
191// Thread management and startup/shutdown:
192//
193// The network-processing threads are all part of a thread group created by
194// AppInit() or the Qt main() function.
195//
196// A clean exit happens when StartShutdown() or the SIGTERM signal handler sets
197// fRequestShutdown, which makes main thread's WaitForShutdown() interrupts the
198// thread group.
199// And then, WaitForShutdown() makes all other on-going threads in the thread
200// group join the main thread.
201// Shutdown() is then called to clean up database connections, and stop other
202// threads that should only be stopped after the main network-processing threads
203// have exited.
204//
205// Shutdown for Qt is very similar, only it uses a QTimer to detect
206// ShutdownRequested() getting set, and then does the normal Qt shutdown thing.
207//
208
212 InterruptRPC();
216 if (node.avalanche) {
217 // Avalanche needs to be stopped before we interrupt the thread group as
218 // the scheduler will stop working then.
219 node.avalanche->stopEventLoop();
220 }
221 if (node.connman) {
222 node.connman->Interrupt();
223 }
224 if (g_txindex) {
225 g_txindex->Interrupt();
226 }
227 ForEachBlockFilterIndex([](BlockFilterIndex &index) { index.Interrupt(); });
228 if (g_coin_stats_index) {
229 g_coin_stats_index->Interrupt();
230 }
231}
232
234 static Mutex g_shutdown_mutex;
235 TRY_LOCK(g_shutdown_mutex, lock_shutdown);
236 if (!lock_shutdown) {
237 return;
238 }
239 LogPrintf("%s: In progress...\n", __func__);
240 Assert(node.args);
241
246 util::ThreadRename("shutoff");
247 if (node.mempool) {
248 node.mempool->AddTransactionsUpdated(1);
249 }
250
251 StopHTTPRPC();
252 StopREST();
253 StopRPC();
255 for (const auto &client : node.chain_clients) {
256 client->flush();
257 }
258 StopMapPort();
259
260 // Because avalanche and the network depend on each other, it is important
261 // to shut them down in this order:
262 // 1. Stop avalanche event loop.
263 // 2. Shutdown network processing.
264 // 3. Destroy avalanche::Processor.
265 // 4. Destroy CConnman
266 if (node.avalanche) {
267 node.avalanche->stopEventLoop();
268 }
269
270 // Because these depend on each-other, we make sure that neither can be
271 // using the other before destroying them.
272 if (node.peerman) {
273 UnregisterValidationInterface(node.peerman.get());
274 }
275 if (node.connman) {
276 node.connman->Stop();
277 }
278
280
281 // After everything has been shut down, but before things get flushed, stop
282 // the CScheduler/checkqueue, scheduler and load block thread.
283 if (node.scheduler) {
284 node.scheduler->stop();
285 }
286 if (node.chainman && node.chainman->m_thread_load.joinable()) {
287 node.chainman->m_thread_load.join();
288 }
290
291 // After the threads that potentially access these pointers have been
292 // stopped, destruct and reset all to nullptr.
293 node.peerman.reset();
294
295 // Destroy various global instances
296 node.avalanche.reset();
297 node.connman.reset();
298 node.banman.reset();
299 node.addrman.reset();
300
301 if (node.mempool && node.mempool->GetLoadTried() &&
302 ShouldPersistMempool(*node.args)) {
303 DumpMempool(*node.mempool, MempoolPath(*node.args));
304 }
305
306 // FlushStateToDisk generates a ChainStateFlushed callback, which we should
307 // avoid missing
308 if (node.chainman) {
309 LOCK(cs_main);
310 for (Chainstate *chainstate : node.chainman->GetAll()) {
311 if (chainstate->CanFlushToDisk()) {
312 chainstate->ForceFlushStateToDisk();
313 }
314 }
315 }
316
317 // After there are no more peers/RPC left to give us new data which may
318 // generate CValidationInterface callbacks, flush them...
320
321#if ENABLE_CHRONIK
322 if (node.args->GetBoolArg("-chronik", DEFAULT_CHRONIK)) {
323 chronik::Stop();
324 }
325#endif
326
327 // Stop and delete all indexes only after flushing background callbacks.
328 if (g_txindex) {
329 g_txindex->Stop();
330 g_txindex.reset();
331 }
332 if (g_coin_stats_index) {
333 g_coin_stats_index->Stop();
334 g_coin_stats_index.reset();
335 }
336 ForEachBlockFilterIndex([](BlockFilterIndex &index) { index.Stop(); });
338
339 // Any future callbacks will be dropped. This should absolutely be safe - if
340 // missing a callback results in an unrecoverable situation, unclean
341 // shutdown would too. The only reason to do the above flushes is to let the
342 // wallet catch up with our current chain to avoid any strange pruning edge
343 // cases and make next startup faster by avoiding rescan.
344
345 if (node.chainman) {
346 LOCK(cs_main);
347 for (Chainstate *chainstate : node.chainman->GetAll()) {
348 if (chainstate->CanFlushToDisk()) {
349 chainstate->ForceFlushStateToDisk();
350 chainstate->ResetCoinsViews();
351 }
352 }
353
354 node.chainman->DumpRecentHeadersTime(node.chainman->m_options.datadir /
356 }
357 for (const auto &client : node.chain_clients) {
358 client->stop();
359 }
360
361#if ENABLE_ZMQ
365 }
366#endif
367
368 node.chain_clients.clear();
371 node.kernel.reset();
372 node.mempool.reset();
373 node.chainman.reset();
374 node.scheduler.reset();
375
376 try {
377 if (!fs::remove(GetPidFile(*node.args))) {
378 LogPrintf("%s: Unable to remove PID file: File does not exist\n",
379 __func__);
380 }
381 } catch (const fs::filesystem_error &e) {
382 LogPrintf("%s: Unable to remove PID file: %s\n", __func__,
384 }
385
386 LogPrintf("%s: done\n", __func__);
387}
388
394#ifndef WIN32
395static void HandleSIGTERM(int) {
397}
398
399static void HandleSIGHUP(int) {
400 LogInstance().m_reopen_file = true;
401}
402#else
403static BOOL WINAPI consoleCtrlHandler(DWORD dwCtrlType) {
405 Sleep(INFINITE);
406 return true;
407}
408#endif
409
410#ifndef WIN32
411static void registerSignalHandler(int signal, void (*handler)(int)) {
412 struct sigaction sa;
413 sa.sa_handler = handler;
414 sigemptyset(&sa.sa_mask);
415 sa.sa_flags = 0;
416 sigaction(signal, &sa, NULL);
417}
418#endif
419
420static boost::signals2::connection rpc_notify_block_change_connection;
421static void OnRPCStarted() {
422 rpc_notify_block_change_connection = uiInterface.NotifyBlockTip_connect(
423 std::bind(RPCNotifyBlockChange, std::placeholders::_2));
424}
425
426static void OnRPCStopped() {
428 RPCNotifyBlockChange(nullptr);
429 g_best_block_cv.notify_all();
430 LogPrint(BCLog::RPC, "RPC stopped.\n");
431}
432
434 assert(!node.args);
435 node.args = &gArgs;
436 ArgsManager &argsman = *node.args;
437
438 SetupHelpOptions(argsman);
440 // server-only for now
441 argsman.AddArg("-help-debug",
442 "Print help message with debugging options and exit", false,
444
445 init::AddLoggingArgs(argsman);
446
447 const auto defaultBaseParams = CreateBaseChainParams(ChainType::MAIN);
448 const auto testnetBaseParams = CreateBaseChainParams(ChainType::TESTNET);
449 const auto regtestBaseParams = CreateBaseChainParams(ChainType::REGTEST);
450 const auto defaultChainParams = CreateChainParams(argsman, ChainType::MAIN);
451 const auto testnetChainParams =
453 const auto regtestChainParams =
455
456 // Hidden Options
457 std::vector<std::string> hidden_args = {
458 "-dbcrashratio",
459 "-forcecompactdb",
460 "-maxaddrtosend",
461 "-parkdeepreorg",
462 "-automaticunparking",
463 "-replayprotectionactivationtime",
464 "-enableminerfund",
465 "-chronikallowpause",
466 "-chronikcors",
467 // GUI args. These will be overwritten by SetupUIArgs for the GUI
468 "-allowselfsignedrootcertificates",
469 "-choosedatadir",
470 "-lang=<lang>",
471 "-min",
472 "-resetguisettings",
473 "-rootcertificates=<file>",
474 "-splash",
475 "-uiplatform",
476 // TODO remove after the May 2026 upgrade
477 "-obolenskyactivationtime",
478 };
479
480 // Set all of the args and their help
481 // When adding new options to the categories, please keep and ensure
482 // alphabetical ordering. Do not translate _(...) -help-debug options, Many
483 // technical terms, and only a very small audience, so is unnecessary stress
484 // to translators.
485 argsman.AddArg("-version", "Print version and exit", ArgsManager::ALLOW_ANY,
487#if defined(HAVE_SYSTEM)
488 argsman.AddArg(
489 "-alertnotify=<cmd>",
490 "Execute command when a relevant alert is received or we see "
491 "a really long fork (%s in cmd is replaced by message)",
493#endif
494 argsman.AddArg(
495 "-assumevalid=<hex>",
496 strprintf(
497 "If this block is in the chain assume that it and its ancestors "
498 "are valid and potentially skip their script verification (0 to "
499 "verify all, default: %s, testnet: %s)",
500 defaultChainParams->GetConsensus().defaultAssumeValid.GetHex(),
501 testnetChainParams->GetConsensus().defaultAssumeValid.GetHex()),
503 argsman.AddArg("-blocksdir=<dir>",
504 "Specify directory to hold blocks subdirectory for *.dat "
505 "files (default: <datadir>)",
507 argsman.AddArg("-fastprune",
508 "Use smaller block files and lower minimum prune height for "
509 "testing purposes",
512#if defined(HAVE_SYSTEM)
513 argsman.AddArg("-blocknotify=<cmd>",
514 "Execute command when the best block changes (%s in cmd is "
515 "replaced by block hash)",
517#endif
518 argsman.AddArg("-blockreconstructionextratxn=<n>",
519 strprintf("Extra transactions to keep in memory for compact "
520 "block reconstructions (default: %u)",
523 argsman.AddArg(
524 "-blocksonly",
525 strprintf("Whether to reject transactions from network peers. "
526 "Disables automatic broadcast and rebroadcast of "
527 "transactions, unless the source peer has the "
528 "'forcerelay' permission. RPC transactions are"
529 " not affected. (default: %u)",
532 argsman.AddArg("-coinstatsindex",
533 strprintf("Maintain coinstats index used by the "
534 "gettxoutsetinfo RPC (default: %u)",
537 argsman.AddArg(
538 "-conf=<file>",
539 strprintf("Specify path to read-only configuration file. Relative "
540 "paths will be prefixed by datadir location. (default: %s)",
543 argsman.AddArg("-datadir=<dir>", "Specify data directory",
545 argsman.AddArg(
546 "-dbbatchsize",
547 strprintf("Maximum database write batch size in bytes (default: %u)",
551 argsman.AddArg("-dbcache=<n>",
552 strprintf("Maximum database cache size <n> MiB (minimum %d, "
553 "default: %d). Make sure you have enough RAM. In "
554 "addition, unused memory allocated to the mempool "
555 "is shared with this cache (see -maxmempool).",
556 MIN_DB_CACHE >> 20, DEFAULT_DB_CACHE >> 20),
558 argsman.AddArg(
559 "-includeconf=<file>",
560 "Specify additional configuration file, relative to the -datadir path "
561 "(only useable from configuration file, not command line)",
563 argsman.AddArg("-allowignoredconf",
564 strprintf("For backwards compatibility, treat an unused %s "
565 "file in the datadir as a warning, not an error.",
568 argsman.AddArg("-loadblock=<file>",
569 "Imports blocks from external file on startup",
571 argsman.AddArg("-maxmempool=<n>",
572 strprintf("Keep the transaction memory pool below <n> "
573 "megabytes (default: %u)",
576 argsman.AddArg("-maxorphantx=<n>",
577 strprintf("Keep at most <n> unconnectable transactions in "
578 "memory (default: %u)",
581 argsman.AddArg("-mempoolexpiry=<n>",
582 strprintf("Do not keep transactions in the mempool longer "
583 "than <n> hours (default: %u)",
586 argsman.AddArg(
587 "-minimumchainwork=<hex>",
588 strprintf(
589 "Minimum work assumed to exist on a valid chain in hex "
590 "(default: %s, testnet: %s)",
591 defaultChainParams->GetConsensus().nMinimumChainWork.GetHex(),
592 testnetChainParams->GetConsensus().nMinimumChainWork.GetHex()),
595 argsman.AddArg(
596 "-par=<n>",
597 strprintf("Set the number of script verification threads (0 = auto, "
598 "up to %d, <0 = leave that many cores free, default: %d)",
601 argsman.AddArg("-persistmempool",
602 strprintf("Whether to save the mempool on shutdown and load "
603 "on restart (default: %u)",
606 argsman.AddArg(
607 "-persistrecentheaderstime",
608 strprintf(
609 "Whether the node stores the recent headers reception time to a "
610 "file and load it upon startup. This is intended for mining nodes "
611 "to overestimate the real time target upon restart (default: %u)",
614 argsman.AddArg(
615 "-pid=<file>",
616 strprintf("Specify pid file. Relative paths will be prefixed "
617 "by a net-specific datadir location. (default: %s)",
620 argsman.AddArg(
621 "-prune=<n>",
622 strprintf("Reduce storage requirements by enabling pruning (deleting) "
623 "of old blocks. This allows the pruneblockchain RPC to be "
624 "called to delete specific blocks and enables automatic "
625 "pruning of old blocks if a target size in MiB is provided. "
626 "This mode is incompatible with -txindex and -rescan. "
627 "Warning: Reverting this setting requires re-downloading the "
628 "entire blockchain. (default: 0 = disable pruning blocks, "
629 "1 = allow manual pruning via RPC, >=%u = automatically "
630 "prune block files to stay under the specified target size "
631 "in MiB)",
632 MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024),
634 argsman.AddArg(
635 "-reindex-chainstate",
636 "Rebuild chain state from the currently indexed blocks. When "
637 "in pruning mode or if blocks on disk might be corrupted, use "
638 "full -reindex instead.",
640 argsman.AddArg(
641 "-reindex",
642 "Rebuild chain state and block index from the blk*.dat files on disk."
643 " This will also rebuild active optional indexes.",
645 argsman.AddArg(
646 "-settings=<file>",
647 strprintf(
648 "Specify path to dynamic settings data file. Can be disabled with "
649 "-nosettings. File is written at runtime and not meant to be "
650 "edited by users (use %s instead for custom settings). Relative "
651 "paths will be prefixed by datadir location. (default: %s)",
654#if HAVE_SYSTEM
655 argsman.AddArg("-startupnotify=<cmd>", "Execute command on startup.",
657#endif
658#ifndef WIN32
659 argsman.AddArg(
660 "-sysperms",
661 "Create new files with system default permissions, instead of umask "
662 "077 (only effective with disabled wallet functionality)",
664#else
665 hidden_args.emplace_back("-sysperms");
666#endif
667 argsman.AddArg("-txindex",
668 strprintf("Maintain a full transaction index, used by the "
669 "getrawtransaction rpc call (default: %d)",
672#if ENABLE_CHRONIK
673 argsman.AddArg(
674 "-chronik",
675 strprintf("Enable the Chronik indexer, which can be read via a "
676 "dedicated HTTP/Protobuf interface (default: %d)",
679 argsman.AddArg(
680 "-chronikbind=<addr>[:port]",
681 strprintf(
682 "Bind the Chronik indexer to the given address to listen for "
683 "HTTP/Protobuf connections to access the index. Unlike the "
684 "JSON-RPC, it's ok to have this publicly exposed on the internet. "
685 "This option can be specified multiple times (default: %s; default "
686 "port: %u, testnet: %u, regtest: %u)",
687 Join(chronik::DEFAULT_BINDS, ", "),
688 defaultBaseParams->ChronikPort(), testnetBaseParams->ChronikPort(),
689 regtestBaseParams->ChronikPort()),
693 argsman.AddArg("-chroniktokenindex",
694 "Enable token indexing in Chronik (default: 1)",
696 argsman.AddArg("-chroniklokadidindex",
697 "Enable LOKAD ID indexing in Chronik (default: 1)",
699 argsman.AddArg("-chronikreindex",
700 "Reindex the Chronik indexer from genesis, but leave the "
701 "other indexes untouched",
703 argsman.AddArg(
704 "-chroniktxnumcachebuckets",
705 strprintf(
706 "Tuning param of the TxNumCache, specifies how many buckets "
707 "to use on the belt. Caution against setting this too high, "
708 "it may slow down indexing. Set to 0 to disable. (default: %d)",
709 chronik::DEFAULT_TX_NUM_CACHE_BUCKETS),
712 argsman.AddArg(
713 "-chroniktxnumcachebucketsize",
714 strprintf(
715 "Tuning param of the TxNumCache, specifies the size of each bucket "
716 "on the belt. Unlike the number of buckets, this may be increased "
717 "without much danger of slowing the indexer down. The total cache "
718 "size will be `num_buckets * bucket_size * 40B`, so by default the "
719 "cache will require %dkB of memory. (default: %d)",
720 chronik::DEFAULT_TX_NUM_CACHE_BUCKETS *
721 chronik::DEFAULT_TX_NUM_CACHE_BUCKET_SIZE * 40 / 1000,
722 chronik::DEFAULT_TX_NUM_CACHE_BUCKET_SIZE),
725 argsman.AddArg("-chronikperfstats",
726 "Output some performance statistics (e.g. num cache hits, "
727 "seconds spent) into a <datadir>/perf folder. (default: 0)",
729 argsman.AddArg("-chronikscripthashindex",
730 "Enable the scripthash index for the Chronik indexer "
731 "(default: 1 if chronikelectrumbind is set, 0 otherwise) ",
733 argsman.AddArg(
734 "-chronikelectrumbind=<addr>[:port][:t|s|w|y]",
735 strprintf(
736 "Bind the Chronik Electrum interface to the given "
737 "address:port:protocol. If not set, the Electrum interface will "
738 "not start. This option can be specified multiple times. The "
739 "protocol is selected by a single letter, where 't' means TCP, 's' "
740 "means TLS, 'w' means WS and 'y' means WSS. If TLS and/or WSS is "
741 "selected, the certificate chain and private key must both be "
742 "passed (see -chronikelectrumcert and -chronikelectrumprivkey "
743 "(default: disabled; default port: %u, testnet: %u, regtest: %u; "
744 "default protocol: TLS)",
745 defaultBaseParams->ChronikElectrumPort(),
746 testnetBaseParams->ChronikElectrumPort(),
747 regtestBaseParams->ChronikElectrumPort()),
751 argsman.AddArg(
752 "-chronikelectrumcert",
753 "Path to the certificate file to be used by the Chronik Electrum "
754 "server when the TLS protocol is selected. The file should contain "
755 "the whole certificate chain (typically a .pem file). If used the "
756 "-chronikelectrumprivkey must be set as well.",
760 argsman.AddArg(
761 "-chronikelectrumprivkey",
762 "Path to the private key file to be used by the Chronik Electrum "
763 "server when the TLS protocol is selected. If used the "
764 "-chronikelectrumcert must be set as well.",
768 argsman.AddArg(
769 "-chronikelectrumurl",
770 "The URL to advertise to the Electrum peers. This needs to be set to "
771 "the server public URL to instruct the other Electrum peers that they "
772 "don't have to drop the connection. See the 'hosts' key in "
773 "https://electrum-cash-protocol.readthedocs.io/en/latest/"
774 "protocol-methods.html#server.features (default: 127.0.0.1).",
778 argsman.AddArg(
779 "-chronikelectrummaxhistory",
780 strprintf("Largest tx history we are willing to serve. (default: %u)",
781 chronik::DEFAULT_ELECTRUM_MAX_HISTORY),
784 argsman.AddArg(
785 "-chronikelectrumdonationaddress",
786 strprintf(
787 "The server donation address. No checks are done on the server "
788 "side to ensure this is a valid eCash address, it is just relayed "
789 "to clients verbatim as a text string (%u characters maximum).",
790 chronik::MAX_LENGTH_DONATION_ADDRESS),
793 argsman.AddArg(
794 "-chronikelectrumpeersvalidationinterval",
795 strprintf(
796 "The peers submitted via the Chronik Electrum server.add_peer "
797 "endpoint are periodically checked for validity and are only "
798 "returned after they passed the validation. This option controls "
799 "the interval duration between successive peers validation "
800 "processes in seconds (default: %u). Setting this value to 0 "
801 "disables the peer validation completely.",
802 std::chrono::duration_cast<std::chrono::seconds>(
803 chronik::DEFAULT_ELECTRUM_PEER_VALIDATION_INTERVAL)
804 .count()),
807#endif
808 argsman.AddArg(
809 "-blockfilterindex=<type>",
810 strprintf("Maintain an index of compact filters by block "
811 "(default: %s, values: %s).",
813 " If <type> is not supplied or if <type> = 1, indexes for "
814 "all known types are enabled.",
816 argsman.AddArg(
817 "-usecashaddr",
818 strprintf("Use Cash Address for destination encoding instead of legacy "
819 "base58 addresses (default: %d)",
822
823 argsman.AddArg(
824 "-addnode=<ip>",
825 "Add a node to connect to and attempt to keep the connection "
826 "open (see the `addnode` RPC command help for more info)",
829 argsman.AddArg("-asmap=<file>",
830 strprintf("Specify asn mapping used for bucketing of the "
831 "peers (default: %s). Relative paths will be "
832 "prefixed by the net-specific datadir location.",
835 argsman.AddArg("-bantime=<n>",
836 strprintf("Default duration (in seconds) of manually "
837 "configured bans (default: %u)",
840 argsman.AddArg(
841 "-bind=<addr>[:<port>][=onion]",
842 strprintf("Bind to given address and always listen on it (default: "
843 "0.0.0.0). Use [host]:port notation for IPv6. Append =onion "
844 "to tag any incoming connections to that address and port as "
845 "incoming Tor connections (default: 127.0.0.1:%u=onion, "
846 "testnet: 127.0.0.1:%u=onion, regtest: 127.0.0.1:%u=onion)",
847 defaultBaseParams->OnionServiceTargetPort(),
848 testnetBaseParams->OnionServiceTargetPort(),
849 regtestBaseParams->OnionServiceTargetPort()),
852 argsman.AddArg(
853 "-connect=<ip>",
854 "Connect only to the specified node(s); -noconnect disables automatic "
855 "connections (the rules for this peer are the same as for -addnode)",
858 argsman.AddArg(
859 "-discover",
860 "Discover own IP addresses (default: 1 when listening and no "
861 "-externalip or -proxy)",
863 argsman.AddArg("-dns",
864 strprintf("Allow DNS lookups for -addnode, -seednode and "
865 "-connect (default: %d)",
868 argsman.AddArg(
869 "-dnsseed",
870 strprintf(
871 "Query for peer addresses via DNS lookup, if low on addresses "
872 "(default: %u unless -connect used)",
875 argsman.AddArg("-externalip=<ip>", "Specify your own public address",
877 argsman.AddArg(
878 "-fixedseeds",
879 strprintf(
880 "Allow fixed seeds if DNS seeds don't provide peers (default: %u)",
883 argsman.AddArg(
884 "-forcednsseed",
885 strprintf(
886 "Always query for peer addresses via DNS lookup (default: %d)",
889 argsman.AddArg("-overridednsseed",
890 "If set, only use the specified DNS seed when "
891 "querying for peer addresses via DNS lookup.",
893 argsman.AddArg(
894 "-listen",
895 "Accept connections from outside (default: 1 if no -proxy or -connect)",
897 argsman.AddArg(
898 "-listenonion",
899 strprintf("Automatically create Tor onion service (default: %d)",
902 argsman.AddArg(
903 "-maxconnections=<n>",
904 strprintf("Maintain at most <n> connections to peers. The effective "
905 "limit depends on system limitations and might be lower than "
906 "the specified value (default: %u)",
909 argsman.AddArg("-maxreceivebuffer=<n>",
910 strprintf("Maximum per-connection receive buffer, <n>*1000 "
911 "bytes (default: %u)",
914 argsman.AddArg(
915 "-maxsendbuffer=<n>",
916 strprintf(
917 "Maximum per-connection send buffer, <n>*1000 bytes (default: %u)",
920 argsman.AddArg(
921 "-maxtimeadjustment",
922 strprintf("Maximum allowed median peer time offset adjustment. Local "
923 "perspective of time may be influenced by peers forward or "
924 "backward by this amount. (default: %u seconds)",
927#if HAVE_SOCKADDR_UN
928 argsman.AddArg("-onion=<ip:port|path>",
929 "Use separate SOCKS5 proxy to reach peers via Tor onion "
930 "services, set -noonion to disable (default: -proxy). May "
931 "be a local file path prefixed with 'unix:'.",
933#else
934 argsman.AddArg(
935 "-onion=<ip:port>",
936 strprintf("Use separate SOCKS5 proxy to reach peers via Tor "
937 "onion services, set -noonion to disable (default: %s)",
938 "-proxy"),
940#endif
941 argsman.AddArg("-i2psam=<ip:port>",
942 "I2P SAM proxy to reach I2P peers and accept I2P "
943 "connections (default: none)",
945 argsman.AddArg(
946 "-i2pacceptincoming",
947 "If set and -i2psam is also set then incoming I2P connections are "
948 "accepted via the SAM proxy. If this is not set but -i2psam is set "
949 "then only outgoing connections will be made to the I2P network. "
950 "Ignored if -i2psam is not set. Listening for incoming I2P connections "
951 "is done through the SAM proxy, not by binding to a local address and "
952 "port (default: 1)",
954
955 argsman.AddArg(
956 "-onlynet=<net>",
957 "Make outgoing connections only through network <net> (" +
958 Join(GetNetworkNames(), ", ") +
959 "). Incoming connections are not affected by this option. This "
960 "option can be specified multiple times to allow multiple "
961 "networks.",
963 argsman.AddArg("-peerbloomfilters",
964 strprintf("Support filtering of blocks and transaction with "
965 "bloom filters (default: %d)",
968 argsman.AddArg(
969 "-peerblockfilters",
970 strprintf(
971 "Serve compact block filters to peers per BIP 157 (default: %u)",
974 argsman.AddArg("-permitbaremultisig",
975 strprintf("Relay non-P2SH multisig (default: %d)",
978 // TODO: remove the sentence "Nodes not using ... incoming connections."
979 // once the changes from https://github.com/bitcoin/bitcoin/pull/23542 have
980 // become widespread.
981 argsman.AddArg("-port=<port>",
982 strprintf("Listen for connections on <port>. Nodes not "
983 "using the default ports (default: %u, "
984 "testnet: %u, regtest: %u) are unlikely to get "
985 "incoming connections. Not relevant for I2P (see "
986 "doc/i2p.md).",
987 defaultChainParams->GetDefaultPort(),
988 testnetChainParams->GetDefaultPort(),
989 regtestChainParams->GetDefaultPort()),
992#if HAVE_SOCKADDR_UN
993 argsman.AddArg("-proxy=<ip:port|path>",
994 "Connect through SOCKS5 proxy, set -noproxy to disable "
995 "(default: disabled). May be a local file path prefixed "
996 "with 'unix:' if the proxy supports it.",
999#else
1000 argsman.AddArg("-proxy=<ip:port>",
1001 "Connect through SOCKS5 proxy, set -noproxy to disable "
1002 "(default: disabled)",
1005#endif
1006 argsman.AddArg(
1007 "-proxyrandomize",
1008 strprintf("Randomize credentials for every proxy connection. "
1009 "This enables Tor stream isolation (default: %d)",
1012 argsman.AddArg(
1013 "-seednode=<ip>",
1014 "Connect to a node to retrieve peer addresses, and disconnect",
1016 argsman.AddArg(
1017 "-networkactive",
1018 "Enable all P2P network activity (default: 1). Can be changed "
1019 "by the setnetworkactive RPC command",
1021 argsman.AddArg("-timeout=<n>",
1022 strprintf("Specify connection timeout in milliseconds "
1023 "(minimum: 1, default: %d)",
1026 argsman.AddArg(
1027 "-peertimeout=<n>",
1028 strprintf("Specify p2p connection timeout in seconds. This option "
1029 "determines the amount of time a peer may be inactive before "
1030 "the connection to it is dropped. (minimum: 1, default: %d)",
1033 argsman.AddArg(
1034 "-torcontrol=<ip>:<port>",
1035 strprintf(
1036 "Tor control port to use if onion listening enabled (default: %s)",
1039 argsman.AddArg("-torpassword=<pass>",
1040 "Tor control port password (default: empty)",
1043 // UPnP support was dropped. We keep `-upnp` as a hidden arg to display a
1044 // more user friendly error when set. TODO: remove (here and below) for
1045 // 0.34.0.
1046 argsman.AddArg("-upnp", "", ArgsManager::ALLOW_ANY,
1048 argsman.AddArg(
1049 "-natpmp",
1050 strprintf("Use PCP or NAT-PMP to map the listening port (default: %u)",
1053 argsman.AddArg(
1054 "-whitebind=<[permissions@]addr>",
1055 "Bind to the given address and add permission flags to the peers "
1056 "connecting to it."
1057 "Use [host]:port notation for IPv6. Allowed permissions: " +
1058 Join(NET_PERMISSIONS_DOC, ", ") +
1059 ". "
1060 "Specify multiple permissions separated by commas (default: "
1061 "download,noban,mempool,relay). Can be specified multiple times.",
1063
1064 argsman.AddArg("-whitelist=<[permissions@]IP address or network>",
1065 "Add permission flags to the peers using the given "
1066 "IP address (e.g. 1.2.3.4) or CIDR-notated network "
1067 "(e.g. 1.2.3.0/24). "
1068 "Uses the same permissions as -whitebind. "
1069 "Additional flags \"in\" and \"out\" control whether "
1070 "permissions apply to incoming connections and/or manual "
1071 "(default: incoming only). "
1072 "Can be specified multiple times.",
1074 argsman.AddArg(
1075 "-maxuploadtarget=<n>",
1076 strprintf("Tries to keep outbound traffic under the given target (in "
1077 "MiB per 24h). Limit does not apply to peers with 'download' "
1078 "permission. 0 = no limit (default: %d)",
1081
1083
1084#if ENABLE_ZMQ
1085 argsman.AddArg("-zmqpubhashblock=<address>",
1086 "Enable publish hash block in <address>",
1088 argsman.AddArg("-zmqpubhashtx=<address>",
1089 "Enable publish hash transaction in <address>",
1091 argsman.AddArg("-zmqpubrawblock=<address>",
1092 "Enable publish raw block in <address>",
1094 argsman.AddArg("-zmqpubrawtx=<address>",
1095 "Enable publish raw transaction in <address>",
1097 argsman.AddArg("-zmqpubsequence=<address>",
1098 "Enable publish hash block and tx sequence in <address>",
1100 argsman.AddArg(
1101 "-zmqpubhashblockhwm=<n>",
1102 strprintf("Set publish hash block outbound message high water "
1103 "mark (default: %d)",
1106 argsman.AddArg(
1107 "-zmqpubhashtxhwm=<n>",
1108 strprintf("Set publish hash transaction outbound message high "
1109 "water mark (default: %d)",
1111 false, OptionsCategory::ZMQ);
1112 argsman.AddArg(
1113 "-zmqpubrawblockhwm=<n>",
1114 strprintf("Set publish raw block outbound message high water "
1115 "mark (default: %d)",
1118 argsman.AddArg(
1119 "-zmqpubrawtxhwm=<n>",
1120 strprintf("Set publish raw transaction outbound message high "
1121 "water mark (default: %d)",
1124 argsman.AddArg("-zmqpubsequencehwm=<n>",
1125 strprintf("Set publish hash sequence message high water mark"
1126 " (default: %d)",
1129#else
1130 hidden_args.emplace_back("-zmqpubhashblock=<address>");
1131 hidden_args.emplace_back("-zmqpubhashtx=<address>");
1132 hidden_args.emplace_back("-zmqpubrawblock=<address>");
1133 hidden_args.emplace_back("-zmqpubrawtx=<address>");
1134 hidden_args.emplace_back("-zmqpubsequence=<n>");
1135 hidden_args.emplace_back("-zmqpubhashblockhwm=<n>");
1136 hidden_args.emplace_back("-zmqpubhashtxhwm=<n>");
1137 hidden_args.emplace_back("-zmqpubrawblockhwm=<n>");
1138 hidden_args.emplace_back("-zmqpubrawtxhwm=<n>");
1139 hidden_args.emplace_back("-zmqpubsequencehwm=<n>");
1140#endif
1141
1142 argsman.AddArg(
1143 "-checkblocks=<n>",
1144 strprintf("How many blocks to check at startup (default: %u, 0 = all)",
1148 argsman.AddArg("-checklevel=<n>",
1149 strprintf("How thorough the block verification of "
1150 "-checkblocks is: %s (0-4, default: %u)",
1154 argsman.AddArg("-checkblockindex",
1155 strprintf("Do a consistency check for the block tree, "
1156 "chainstate, and other validation data structures "
1157 "occasionally. (default: %u, regtest: %u)",
1158 defaultChainParams->DefaultConsistencyChecks(),
1159 regtestChainParams->DefaultConsistencyChecks()),
1162 argsman.AddArg("-checkaddrman=<n>",
1163 strprintf("Run addrman consistency checks every <n> "
1164 "operations. Use 0 to disable. (default: %u)",
1168 argsman.AddArg(
1169 "-checkmempool=<n>",
1170 strprintf("Run mempool consistency checks every <n> transactions. Use "
1171 "0 to disable. (default: %u, regtest: %u)",
1172 defaultChainParams->DefaultConsistencyChecks(),
1173 regtestChainParams->DefaultConsistencyChecks()),
1176 argsman.AddArg("-checkpoints",
1177 strprintf("Only accept block chain matching built-in "
1178 "checkpoints (default: %d)",
1182 argsman.AddArg("-deprecatedrpc=<method>",
1183 "Allows deprecated RPC method(s) to be used",
1186 argsman.AddArg(
1187 "-stopafterblockimport",
1188 strprintf("Stop running after importing blocks from disk (default: %d)",
1192 argsman.AddArg("-stopatheight",
1193 strprintf("Stop running after reaching the given height in "
1194 "the main chain (default: %u)",
1198 argsman.AddArg("-addrmantest", "Allows to test address relay on localhost",
1201 argsman.AddArg("-capturemessages", "Capture all P2P messages to disk",
1204 argsman.AddArg("-mocktime=<n>",
1205 "Replace actual time with " + UNIX_EPOCH_TIME +
1206 " (default: 0)",
1209 argsman.AddArg(
1210 "-maxsigcachesize=<n>",
1211 strprintf("Limit size of signature cache to <n> MiB (default: %u)",
1215 argsman.AddArg(
1216 "-maxscriptcachesize=<n>",
1217 strprintf("Limit size of script cache to <n> MiB (default: %u)",
1221 argsman.AddArg("-maxtipage=<n>",
1222 strprintf("Maximum tip age in seconds to consider node in "
1223 "initial block download (default: %u)",
1224 Ticks<std::chrono::seconds>(DEFAULT_MAX_TIP_AGE)),
1227
1228 argsman.AddArg("-uacomment=<cmt>",
1229 "Append comment to the user agent string",
1231 argsman.AddArg("-uaclientname=<clientname>", "Set user agent client name",
1233 argsman.AddArg("-uaclientversion=<clientversion>",
1234 "Set user agent client version", ArgsManager::ALLOW_ANY,
1236
1238
1239 argsman.AddArg(
1240 "-acceptnonstdtxn",
1241 strprintf(
1242 "Relay and mine \"non-standard\" transactions (%sdefault: %u)",
1243 "testnet/regtest only; ", defaultChainParams->RequireStandard()),
1246 argsman.AddArg("-excessiveblocksize=<n>",
1247 strprintf("Do not accept blocks larger than this limit, in "
1248 "bytes (default: %d)",
1252 const auto &ticker = Currency::get().ticker;
1253 argsman.AddArg(
1254 "-dustrelayfee=<amt>",
1255 strprintf("Fee rate (in %s/kB) used to define dust, the value of an "
1256 "output such that it will cost about 1/3 of its value in "
1257 "fees at this fee rate to spend it. (default: %s)",
1261
1262 argsman.AddArg(
1263 "-bytespersigcheck",
1264 strprintf("Equivalent bytes per sigCheck in transactions for relay and "
1265 "mining (default: %u).",
1268 argsman.AddArg(
1269 "-bytespersigop",
1270 strprintf("DEPRECATED: Equivalent bytes per sigCheck in transactions "
1271 "for relay and mining (default: %u). This has been "
1272 "deprecated since v0.26.8 and will be removed in the future, "
1273 "please use -bytespersigcheck instead.",
1276 argsman.AddArg(
1277 "-datacarrier",
1278 strprintf("Relay and mine data carrier transactions (default: %d)",
1281 argsman.AddArg(
1282 "-datacarriersize",
1283 strprintf("Maximum size of data in data carrier transactions "
1284 "we relay and mine (default: %u)",
1287 argsman.AddArg(
1288 "-minrelaytxfee=<amt>",
1289 strprintf("Fees (in %s/kB) smaller than this are rejected for "
1290 "relaying, mining and transaction creation (default: %s)",
1293 argsman.AddArg(
1294 "-whitelistrelay",
1295 strprintf("Add 'relay' permission to whitelisted peers "
1296 "with default permissions. This will accept relayed "
1297 "transactions even when not relaying transactions "
1298 "(default: %d)",
1301 argsman.AddArg(
1302 "-whitelistforcerelay",
1303 strprintf("Add 'forcerelay' permission to whitelisted peers "
1304 "with default permissions. This will relay transactions "
1305 "even if the transactions were already in the mempool "
1306 "(default: %d)",
1309
1310 argsman.AddArg("-blockmaxsize=<n>",
1311 strprintf("Set maximum block size in bytes (default: %d)",
1314 argsman.AddArg(
1315 "-blockmintxfee=<amt>",
1316 strprintf("Set lowest fee rate (in %s/kB) for transactions to "
1317 "be included in block creation. (default: %s)",
1320 argsman.AddArg("-simplegbt",
1321 "Use a simplified getblocktemplate output (default: 0)",
1323
1324 argsman.AddArg("-blockversion=<n>",
1325 "Override block version to test forking scenarios",
1328
1329 argsman.AddArg("-server", "Accept command line and JSON-RPC commands",
1331 argsman.AddArg("-rest",
1332 strprintf("Accept public REST requests (default: %d)",
1335 argsman.AddArg(
1336 "-rpcbind=<addr>[:port]",
1337 "Bind to given address to listen for JSON-RPC connections. Do not "
1338 "expose the RPC server to untrusted networks such as the public "
1339 "internet! This option is ignored unless -rpcallowip is also passed. "
1340 "Port is optional and overrides -rpcport. Use [host]:port notation "
1341 "for IPv6. This option can be specified multiple times (default: "
1342 "127.0.0.1 and ::1 i.e., localhost)",
1346 argsman.AddArg(
1347 "-rpcdoccheck",
1348 strprintf("Throw a non-fatal error at runtime if the documentation for "
1349 "an RPC is incorrect (default: %u)",
1352 argsman.AddArg(
1353 "-rpccookiefile=<loc>",
1354 "Location of the auth cookie. Relative paths will be prefixed "
1355 "by a net-specific datadir location. (default: data dir)",
1357 argsman.AddArg("-rpcuser=<user>", "Username for JSON-RPC connections",
1360 argsman.AddArg("-rpcpassword=<pw>", "Password for JSON-RPC connections",
1363 argsman.AddArg(
1364 "-rpcwhitelist=<whitelist>",
1365 "Set a whitelist to filter incoming RPC calls for a specific user. The "
1366 "field <whitelist> comes in the format: <USERNAME>:<rpc 1>,<rpc "
1367 "2>,...,<rpc n>. If multiple whitelists are set for a given user, they "
1368 "are set-intersected. See -rpcwhitelistdefault documentation for "
1369 "information on default whitelist behavior.",
1371 argsman.AddArg(
1372 "-rpcwhitelistdefault",
1373 "Sets default behavior for rpc whitelisting. Unless "
1374 "rpcwhitelistdefault is set to 0, if any -rpcwhitelist is set, the rpc "
1375 "server acts as if all rpc users are subject to "
1376 "empty-unless-otherwise-specified whitelists. If rpcwhitelistdefault "
1377 "is set to 1 and no -rpcwhitelist is set, rpc server acts as if all "
1378 "rpc users are subject to empty whitelists.",
1380 argsman.AddArg(
1381 "-rpcauth=<userpw>",
1382 "Username and HMAC-SHA-256 hashed password for JSON-RPC connections. "
1383 "The field <userpw> comes in the format: <USERNAME>:<SALT>$<HASH>. A "
1384 "canonical python script is included in share/rpcauth. The client then "
1385 "connects normally using the rpcuser=<USERNAME>/rpcpassword=<PASSWORD> "
1386 "pair of arguments. This option can be specified multiple times",
1388 argsman.AddArg("-rpcport=<port>",
1389 strprintf("Listen for JSON-RPC connections on <port> "
1390 "(default: %u, testnet: %u, regtest: %u)",
1391 defaultBaseParams->RPCPort(),
1392 testnetBaseParams->RPCPort(),
1393 regtestBaseParams->RPCPort()),
1396 argsman.AddArg(
1397 "-rpcallowip=<ip>",
1398 "Allow JSON-RPC connections from specified source. Valid for "
1399 "<ip> are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. "
1400 "1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24). "
1401 "This option can be specified multiple times",
1403 argsman.AddArg(
1404 "-rpcthreads=<n>",
1405 strprintf(
1406 "Set the number of threads to service RPC calls (default: %d)",
1409 argsman.AddArg(
1410 "-rpccorsdomain=value",
1411 "Domain from which to accept cross origin requests (browser enforced)",
1413
1414 argsman.AddArg("-rpcworkqueue=<n>",
1415 strprintf("Set the depth of the work queue to service RPC "
1416 "calls (default: %d)",
1420 argsman.AddArg("-rpcservertimeout=<n>",
1421 strprintf("Timeout during HTTP requests (default: %d)",
1425
1426#if HAVE_DECL_FORK
1427 argsman.AddArg("-daemon",
1428 strprintf("Run in the background as a daemon and accept "
1429 "commands (default: %d)",
1432 argsman.AddArg("-daemonwait",
1433 strprintf("Wait for initialization to be finished before "
1434 "exiting. This implies -daemon (default: %d)",
1437#else
1438 hidden_args.emplace_back("-daemon");
1439 hidden_args.emplace_back("-daemonwait");
1440#endif
1441
1442 // Avalanche options.
1443 argsman.AddArg("-avalanche",
1444 strprintf("Enable the avalanche feature (default: %u)",
1447 argsman.AddArg(
1448 "-avalanchestakingrewards",
1449 strprintf("Enable the avalanche staking rewards feature (default: %u, "
1450 "testnet: %u, regtest: %u)",
1451 defaultChainParams->GetConsensus().enableStakingRewards,
1452 testnetChainParams->GetConsensus().enableStakingRewards,
1453 regtestChainParams->GetConsensus().enableStakingRewards),
1455 argsman.AddArg("-avalanchestakingpreconsensus",
1456 strprintf("Enable the avalanche staking rewards "
1457 "preconsensus feature (default: %u)",
1460 argsman.AddArg(
1461 "-avalanchepreconsensus",
1462 strprintf("Enable the avalanche preconsensus feature (default: %u)",
1465 argsman.AddArg("-avalanchepreconsensusmining",
1466 strprintf("Enable mining only the avalanche finalized "
1467 "transactions (default: %u)",
1470 argsman.AddArg("-avalancheconflictingproofcooldown",
1471 strprintf("Mandatory cooldown before a proof conflicting "
1472 "with an already registered one can be considered "
1473 "in seconds (default: %u)",
1477 argsman.AddArg("-avalanchepeerreplacementcooldown",
1478 strprintf("Mandatory cooldown before a peer can be replaced "
1479 "in seconds (default: %u)",
1483 argsman.AddArg(
1484 "-avaminquorumstake",
1485 strprintf(
1486 "Minimum amount of known stake for a usable quorum (default: %s)",
1489 argsman.AddArg(
1490 "-avaminquorumconnectedstakeratio",
1491 strprintf("Minimum proportion of known stake we"
1492 " need nodes for to have a usable quorum (default: %s). "
1493 "This parameter is parsed with a maximum precision of "
1494 "0.000001.",
1498 argsman.AddArg(
1499 "-avaminavaproofsnodecount",
1500 strprintf("Minimum number of node that needs to send us an avaproofs"
1501 " message before we consider we have a usable quorum"
1502 " (default: %s)",
1506 argsman.AddArg(
1507 "-avastalevotethreshold",
1508 strprintf("Number of avalanche votes before a voted item goes stale "
1509 "when voting confidence is low (default: %u)",
1513 argsman.AddArg(
1514 "-avastalevotefactor",
1515 strprintf(
1516 "Factor affecting the number of avalanche votes before a voted "
1517 "item goes stale when voting confidence is high (default: %u)",
1521 argsman.AddArg("-avacooldown",
1522 strprintf("Mandatory cooldown between two avapoll in "
1523 "milliseconds (default: %u)",
1526 argsman.AddArg(
1527 "-avatimeout",
1528 strprintf("Avalanche query timeout in milliseconds (default: %u)",
1531 argsman.AddArg(
1532 "-avamaxelementpoll",
1533 strprintf("Maximum number of elements to include and accept in an "
1534 "avapoll (default: %u)",
1537 argsman.AddArg(
1538 "-avadelegation",
1539 "Avalanche proof delegation to the master key used by this node "
1540 "(default: none). Should be used in conjunction with -avaproof and "
1541 "-avamasterkey",
1543 argsman.AddArg("-avaproof",
1544 "Avalanche proof to be used by this node (default: none)",
1546 argsman.AddArg(
1547 "-avaproofstakeutxoconfirmations",
1548 strprintf(
1549 "Minimum number of confirmations before a stake utxo is mature"
1550 " enough to be included into a proof. Utxos in the mempool are not "
1551 "accepted (i.e this value must be greater than 0) (default: %s)",
1555 argsman.AddArg("-avaproofstakeutxodustthreshold",
1556 strprintf("Minimum value each stake utxo must have to be "
1557 "considered valid (default: %s)",
1560 argsman.AddArg("-avamasterkey",
1561 "Master key associated with the proof. If a proof is "
1562 "required, this is mandatory.",
1565 argsman.AddArg("-avasessionkey", "Avalanche session key (default: random)",
1568 argsman.AddArg("-enablertt",
1569 strprintf("Whether to enforce Real Time Targeting via "
1570 "Avalanche, default (%u)",
1573 argsman.AddArg(
1574 "-maxavalancheoutbound",
1575 strprintf(
1576 "Set the maximum number of avalanche outbound peers to connect to. "
1577 "Note that this option takes precedence over the -maxconnections "
1578 "option (default: %u).",
1582 argsman.AddArg(
1583 "-persistavapeers",
1584 strprintf("Whether to save the avalanche peers upon shutdown and load "
1585 "them upon startup (default: %u).",
1588
1589 // Add the hidden options
1590 argsman.AddHiddenArgs(hidden_args);
1591}
1592
1593static bool fHaveGenesis = false;
1595static std::condition_variable g_genesis_wait_cv;
1596
1597static void BlockNotifyGenesisWait(const CBlockIndex *pBlockIndex) {
1598 if (pBlockIndex != nullptr) {
1599 {
1601 fHaveGenesis = true;
1602 }
1603 g_genesis_wait_cv.notify_all();
1604 }
1605}
1606
1607#if HAVE_SYSTEM
1608static void StartupNotify(const ArgsManager &args) {
1609 std::string cmd = args.GetArg("-startupnotify", "");
1610 if (!cmd.empty()) {
1611 std::thread t(runCommand, cmd);
1612 // thread runs free
1613 t.detach();
1614 }
1615}
1616#endif
1617
1618static bool AppInitServers(Config &config,
1619 HTTPRPCRequestProcessor &httpRPCRequestProcessor,
1620 NodeContext &node) {
1621 const ArgsManager &args = *Assert(node.args);
1624 if (!InitHTTPServer(config)) {
1625 return false;
1626 }
1627
1628 StartRPC();
1629 node.rpc_interruption_point = RpcInterruptionPoint;
1630
1631 if (!StartHTTPRPC(httpRPCRequestProcessor)) {
1632 return false;
1633 }
1634 if (args.GetBoolArg("-rest", DEFAULT_REST_ENABLE)) {
1635 StartREST(&node);
1636 }
1637
1639 return true;
1640}
1641
1642// Parameter interaction based on rules
1644 // when specifying an explicit binding address, you want to listen on it
1645 // even when -connect or -proxy is specified.
1646 if (args.IsArgSet("-bind")) {
1647 if (args.SoftSetBoolArg("-listen", true)) {
1648 LogPrintf(
1649 "%s: parameter interaction: -bind set -> setting -listen=1\n",
1650 __func__);
1651 }
1652 }
1653 if (args.IsArgSet("-whitebind")) {
1654 if (args.SoftSetBoolArg("-listen", true)) {
1655 LogPrintf("%s: parameter interaction: -whitebind set -> setting "
1656 "-listen=1\n",
1657 __func__);
1658 }
1659 }
1660
1661 if (args.IsArgSet("-connect")) {
1662 // when only connecting to trusted nodes, do not seed via DNS, or listen
1663 // by default.
1664 if (args.SoftSetBoolArg("-dnsseed", false)) {
1665 LogPrintf("%s: parameter interaction: -connect set -> setting "
1666 "-dnsseed=0\n",
1667 __func__);
1668 }
1669 if (args.SoftSetBoolArg("-listen", false)) {
1670 LogPrintf("%s: parameter interaction: -connect set -> setting "
1671 "-listen=0\n",
1672 __func__);
1673 }
1674 }
1675
1676 if (args.IsArgSet("-proxy")) {
1677 // to protect privacy, do not listen by default if a default proxy
1678 // server is specified.
1679 if (args.SoftSetBoolArg("-listen", false)) {
1680 LogPrintf(
1681 "%s: parameter interaction: -proxy set -> setting -listen=0\n",
1682 __func__);
1683 }
1684 // to protect privacy, do not map ports when a proxy is set. The user
1685 // may still specify -listen=1 to listen locally, so don't rely on this
1686 // happening through -listen below.
1687 if (args.SoftSetBoolArg("-natpmp", false)) {
1688 LogPrintf(
1689 "%s: parameter interaction: -proxy set -> setting -natpmp=0\n",
1690 __func__);
1691 }
1692 // to protect privacy, do not discover addresses by default
1693 if (args.SoftSetBoolArg("-discover", false)) {
1694 LogPrintf("%s: parameter interaction: -proxy set -> setting "
1695 "-discover=0\n",
1696 __func__);
1697 }
1698 }
1699
1700 if (!args.GetBoolArg("-listen", DEFAULT_LISTEN)) {
1701 // do not map ports or try to retrieve public IP when not listening
1702 // (pointless)
1703 if (args.SoftSetBoolArg("-natpmp", false)) {
1704 LogPrintf(
1705 "%s: parameter interaction: -listen=0 -> setting -natpmp=0\n",
1706 __func__);
1707 }
1708 if (args.SoftSetBoolArg("-discover", false)) {
1709 LogPrintf(
1710 "%s: parameter interaction: -listen=0 -> setting -discover=0\n",
1711 __func__);
1712 }
1713 if (args.SoftSetBoolArg("-listenonion", false)) {
1714 LogPrintf("%s: parameter interaction: -listen=0 -> setting "
1715 "-listenonion=0\n",
1716 __func__);
1717 }
1718 if (args.SoftSetBoolArg("-i2pacceptincoming", false)) {
1719 LogPrintf("%s: parameter interaction: -listen=0 -> setting "
1720 "-i2pacceptincoming=0\n",
1721 __func__);
1722 }
1723 }
1724
1725 if (args.IsArgSet("-externalip")) {
1726 // if an explicit public IP is specified, do not try to find others
1727 if (args.SoftSetBoolArg("-discover", false)) {
1728 LogPrintf("%s: parameter interaction: -externalip set -> setting "
1729 "-discover=0\n",
1730 __func__);
1731 }
1732 }
1733
1734 // disable whitelistrelay in blocksonly mode
1735 if (args.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)) {
1736 if (args.SoftSetBoolArg("-whitelistrelay", false)) {
1737 LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting "
1738 "-whitelistrelay=0\n",
1739 __func__);
1740 }
1741 }
1742
1743 // Forcing relay from whitelisted hosts implies we will accept relays from
1744 // them in the first place.
1745 if (args.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
1746 if (args.SoftSetBoolArg("-whitelistrelay", true)) {
1747 LogPrintf("%s: parameter interaction: -whitelistforcerelay=1 -> "
1748 "setting -whitelistrelay=1\n",
1749 __func__);
1750 }
1751 }
1752
1753 // If avalanche is set, soft set all the feature flags accordingly.
1754 if (args.IsArgSet("-avalanche")) {
1755 const bool fAvalanche =
1756 args.GetBoolArg("-avalanche", AVALANCHE_DEFAULT_ENABLED);
1757 args.SoftSetBoolArg("-automaticunparking", !fAvalanche);
1758 }
1759}
1760
1767void InitLogging(const ArgsManager &args) {
1770}
1771
1772namespace { // Variables internal to initialization process only
1773
1774int nMaxConnections;
1775int nUserMaxConnections;
1776int nFD;
1778int64_t peer_connect_timeout;
1779std::set<BlockFilterType> g_enabled_filter_types;
1780
1781} // namespace
1782
1783[[noreturn]] static void new_handler_terminate() {
1784 // Rather than throwing std::bad-alloc if allocation fails, terminate
1785 // immediately to (try to) avoid chain corruption. Since LogPrintf may
1786 // itself allocate memory, set the handler directly to terminate first.
1787 std::set_new_handler(std::terminate);
1788 LogPrintf("Error: Out of memory. Terminating.\n");
1789
1790 // The log was successful, terminate now.
1791 std::terminate();
1792};
1793
1794bool AppInitBasicSetup(const ArgsManager &args, std::atomic<int> &exit_status) {
1795// Step 1: setup
1796#ifdef _MSC_VER
1797 // Turn off Microsoft heap dump noise
1798 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
1799 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, nullptr,
1800 OPEN_EXISTING, 0, 0));
1801 // Disable confusing "helpful" text message on abort, Ctrl-C
1802 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
1803#endif
1804#ifdef WIN32
1805 // Enable Data Execution Prevention (DEP)
1806 SetProcessDEPPolicy(PROCESS_DEP_ENABLE);
1807#endif
1808 if (!SetupNetworking()) {
1809 return InitError(Untranslated("Initializing networking failed"));
1810 }
1811
1812#ifndef WIN32
1813 if (!args.GetBoolArg("-sysperms", false)) {
1814 umask(077);
1815 }
1816
1817 // Clean shutdown on SIGTERM
1820
1821 // Reopen debug.log on SIGHUP
1823
1824 // Ignore SIGPIPE, otherwise it will bring the daemon down if the client
1825 // closes unexpectedly
1826 signal(SIGPIPE, SIG_IGN);
1827#else
1828 SetConsoleCtrlHandler(consoleCtrlHandler, true);
1829#endif
1830
1831 std::set_new_handler(new_handler_terminate);
1832
1833 return true;
1834}
1835
1837 const CChainParams &chainparams = config.GetChainParams();
1838 // Step 2: parameter interactions
1839
1840 // also see: InitParameterInteraction()
1841
1842 // Error if network-specific options (-addnode, -connect, etc) are
1843 // specified in default section of config file, but not overridden
1844 // on the command line or in this chain's section of the config file.
1845 ChainType chain = args.GetChainType();
1846 bilingual_str errors;
1847 for (const auto &arg : args.GetUnsuitableSectionOnlyArgs()) {
1848 errors +=
1849 strprintf(_("Config setting for %s only applied on %s "
1850 "network when in [%s] section.") +
1851 Untranslated("\n"),
1852 arg, ChainTypeToString(chain), ChainTypeToString(chain));
1853 }
1854
1855 if (!errors.empty()) {
1856 return InitError(errors);
1857 }
1858
1859 // Warn if unrecognized section name are present in the config file.
1860 bilingual_str warnings;
1861 for (const auto &section : args.GetUnrecognizedSections()) {
1862 warnings += strprintf(Untranslated("%s:%i ") +
1863 _("Section [%s] is not recognized.") +
1864 Untranslated("\n"),
1865 section.m_file, section.m_line, section.m_name);
1866 }
1867
1868 if (!warnings.empty()) {
1869 InitWarning(warnings);
1870 }
1871
1872 if (!fs::is_directory(args.GetBlocksDirPath())) {
1873 return InitError(
1874 strprintf(_("Specified blocks directory \"%s\" does not exist."),
1875 args.GetArg("-blocksdir", "")));
1876 }
1877
1878 // parse and validate enabled filter types
1879 std::string blockfilterindex_value =
1880 args.GetArg("-blockfilterindex", DEFAULT_BLOCKFILTERINDEX);
1881 if (blockfilterindex_value == "" || blockfilterindex_value == "1") {
1882 g_enabled_filter_types = AllBlockFilterTypes();
1883 } else if (blockfilterindex_value != "0") {
1884 const std::vector<std::string> names =
1885 args.GetArgs("-blockfilterindex");
1886 for (const auto &name : names) {
1887 BlockFilterType filter_type;
1888 if (!BlockFilterTypeByName(name, filter_type)) {
1889 return InitError(
1890 strprintf(_("Unknown -blockfilterindex value %s."), name));
1891 }
1892 g_enabled_filter_types.insert(filter_type);
1893 }
1894 }
1895
1896 // Signal NODE_COMPACT_FILTERS if peerblockfilters and basic filters index
1897 // are both enabled.
1898 if (args.GetBoolArg("-peerblockfilters", DEFAULT_PEERBLOCKFILTERS)) {
1899 if (g_enabled_filter_types.count(BlockFilterType::BASIC) != 1) {
1900 return InitError(
1901 _("Cannot set -peerblockfilters without -blockfilterindex."));
1902 }
1903
1904 nLocalServices = ServiceFlags(nLocalServices | NODE_COMPACT_FILTERS);
1905 }
1906
1907 if (args.GetIntArg("-prune", 0)) {
1908 if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
1909 return InitError(_("Prune mode is incompatible with -txindex."));
1910 }
1911 if (args.GetBoolArg("-reindex-chainstate", false)) {
1912 return InitError(
1913 _("Prune mode is incompatible with -reindex-chainstate. Use "
1914 "full -reindex instead."));
1915 }
1916 if (args.GetBoolArg("-chronik", DEFAULT_CHRONIK)) {
1917 return InitError(_("Prune mode is incompatible with -chronik."));
1918 }
1919 }
1920
1921 // -bind and -whitebind can't be set when not listening
1922 size_t nUserBind =
1923 args.GetArgs("-bind").size() + args.GetArgs("-whitebind").size();
1924 if (nUserBind != 0 && !args.GetBoolArg("-listen", DEFAULT_LISTEN)) {
1925 return InitError(Untranslated(
1926 "Cannot set -bind or -whitebind together with -listen=0"));
1927 }
1928
1929 // Make sure enough file descriptors are available
1930 int nBind = std::max(nUserBind, size_t(1));
1931 nUserMaxConnections =
1932 args.GetIntArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
1933 nMaxConnections = std::max(nUserMaxConnections, 0);
1934
1935 // -maxavalancheoutbound takes precedence over -maxconnections
1936 const int maxAvalancheOutbound = args.GetIntArg(
1937 "-maxavalancheoutbound", DEFAULT_MAX_AVALANCHE_OUTBOUND_CONNECTIONS);
1938 const bool fAvalanche =
1939 args.GetBoolArg("-avalanche", AVALANCHE_DEFAULT_ENABLED);
1940 if (fAvalanche && maxAvalancheOutbound > nMaxConnections) {
1941 nMaxConnections = std::max(maxAvalancheOutbound, nMaxConnections);
1942 // Indicate the value set by the user
1943 LogPrintf("Increasing -maxconnections from %d to %d to comply with "
1944 "-maxavalancheoutbound\n",
1945 nUserMaxConnections, nMaxConnections);
1946 }
1947
1948 // Trim requested connection counts, to fit into system limitations
1949 // <int> in std::min<int>(...) to work around FreeBSD compilation issue
1950 // described in #2695
1952 nMaxConnections + nBind + MIN_CORE_FILEDESCRIPTORS +
1954#ifdef USE_POLL
1955 int fd_max = nFD;
1956#else
1957 int fd_max = FD_SETSIZE;
1958#endif
1959 nMaxConnections = std::max(
1960 std::min<int>(nMaxConnections,
1961 fd_max - nBind - MIN_CORE_FILEDESCRIPTORS -
1963 0);
1964 if (nFD < MIN_CORE_FILEDESCRIPTORS) {
1965 return InitError(_("Not enough file descriptors available."));
1966 }
1967 nMaxConnections =
1969 nMaxConnections);
1970
1971 if (nMaxConnections < nUserMaxConnections) {
1972 // Not categorizing as "Warning" because this is the normal behavior for
1973 // platforms using the select() interface for which FD_SETSIZE is
1974 // usually 1024.
1975 LogPrintf("Reducing -maxconnections from %d to %d, because of system "
1976 "limitations.\n",
1977 nUserMaxConnections, nMaxConnections);
1978 }
1979
1980 // Step 3: parameter-to-internal-flags
1983
1984 // Configure excessive block size.
1985 const int64_t nProposedExcessiveBlockSize =
1986 args.GetIntArg("-excessiveblocksize", DEFAULT_MAX_BLOCK_SIZE);
1987 if (nProposedExcessiveBlockSize <= 0 ||
1988 !config.SetMaxBlockSize(nProposedExcessiveBlockSize)) {
1989 return InitError(
1990 _("Excessive block size must be > 1,000,000 bytes (1MB)"));
1991 }
1992
1993 // Check blockmaxsize does not exceed maximum accepted block size.
1994 const int64_t nProposedMaxGeneratedBlockSize =
1995 args.GetIntArg("-blockmaxsize", DEFAULT_MAX_GENERATED_BLOCK_SIZE);
1996 if (nProposedMaxGeneratedBlockSize <= 0) {
1997 return InitError(_("Max generated block size must be greater than 0"));
1998 }
1999 if (uint64_t(nProposedMaxGeneratedBlockSize) > config.GetMaxBlockSize()) {
2000 return InitError(_("Max generated block size (blockmaxsize) cannot "
2001 "exceed the excessive block size "
2002 "(excessiveblocksize)"));
2003 }
2004
2006 if (nConnectTimeout <= 0) {
2008 }
2009
2010 peer_connect_timeout =
2011 args.GetIntArg("-peertimeout", DEFAULT_PEER_CONNECT_TIMEOUT);
2012 if (peer_connect_timeout <= 0) {
2013 return InitError(Untranslated(
2014 "peertimeout cannot be configured with a negative value."));
2015 }
2016
2017 // Sanity check argument for min fee for including tx in block
2018 // TODO: Harmonize which arguments need sanity checking and where that
2019 // happens.
2020 if (args.IsArgSet("-blockmintxfee")) {
2021 Amount n = Amount::zero();
2022 if (!ParseMoney(args.GetArg("-blockmintxfee", ""), n)) {
2023 return InitError(AmountErrMsg("blockmintxfee",
2024 args.GetArg("-blockmintxfee", "")));
2025 }
2026 }
2027
2029 args.IsArgSet("-bytespersigcheck")
2030 ? args.GetIntArg("-bytespersigcheck", nBytesPerSigCheck)
2031 : args.GetIntArg("-bytespersigop", nBytesPerSigCheck);
2032
2034 return false;
2035 }
2036
2037 // Option to startup with mocktime set (used for regression testing):
2038 SetMockTime(args.GetIntArg("-mocktime", 0)); // SetMockTime(0) is a no-op
2039
2040 if (args.GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS)) {
2041 nLocalServices = ServiceFlags(nLocalServices | NODE_BLOOM);
2042 }
2043
2044 // Avalanche parameters
2045 const int64_t stakeUtxoMinConfirmations =
2046 args.GetIntArg("-avaproofstakeutxoconfirmations",
2048
2049 if (!chainparams.IsTestChain() &&
2050 stakeUtxoMinConfirmations !=
2052 return InitError(_("Avalanche stake UTXO minimum confirmations can "
2053 "only be set on test chains."));
2054 }
2055
2056 if (stakeUtxoMinConfirmations <= 0) {
2057 return InitError(_("Avalanche stake UTXO minimum confirmations must be "
2058 "a positive integer."));
2059 }
2060
2061 if (args.IsArgSet("-avaproofstakeutxodustthreshold")) {
2062 Amount amount = Amount::zero();
2063 auto parsed = ParseMoney(
2064 args.GetArg("-avaproofstakeutxodustthreshold", ""), amount);
2065 if (!parsed || Amount::zero() == amount) {
2066 return InitError(AmountErrMsg(
2067 "avaproofstakeutxodustthreshold",
2068 args.GetArg("-avaproofstakeutxodustthreshold", "")));
2069 }
2070
2071 if (!chainparams.IsTestChain() &&
2073 return InitError(_("Avalanche stake UTXO dust threshold can "
2074 "only be set on test chains."));
2075 }
2076 }
2077
2078 // This is a staking node
2079 if (fAvalanche && args.IsArgSet("-avaproof")) {
2080 if (!args.GetBoolArg("-listen", true)) {
2081 return InitError(_("Running a staking node requires accepting "
2082 "inbound connections. Please enable -listen."));
2083 }
2084 if (args.IsArgSet("-proxy")) {
2085 return InitError(_("Running a staking node behind a proxy is not "
2086 "supported. Please disable -proxy."));
2087 }
2088 if (args.IsArgSet("-i2psam")) {
2089 return InitError(_("Running a staking node behind I2P is not "
2090 "supported. Please disable -i2psam."));
2091 }
2092 if (args.IsArgSet("-onlynet")) {
2093 return InitError(
2094 _("Restricting the outbound network is not supported when "
2095 "running a staking node. Please disable -onlynet."));
2096 }
2097 }
2098
2099 // Also report errors from parsing before daemonization
2100 {
2101 kernel::Notifications notifications{};
2102 ChainstateManager::Options chainman_opts_dummy{
2103 .config = config,
2104 .datadir = args.GetDataDirNet(),
2105 .notifications = notifications,
2106 };
2107 if (const auto error{ApplyArgsManOptions(args, chainman_opts_dummy)}) {
2108 return InitError(*error);
2109 }
2110 BlockManager::Options blockman_opts_dummy{
2111 .chainparams = chainman_opts_dummy.config.GetChainParams(),
2112 .blocks_dir = args.GetBlocksDirPath(),
2113 .notifications = chainman_opts_dummy.notifications,
2114 };
2115 if (const auto error{ApplyArgsManOptions(args, blockman_opts_dummy)}) {
2116 return InitError(*error);
2117 }
2118 }
2119
2120 return true;
2121}
2122
2123static bool LockDataDirectory(bool probeOnly) {
2124 // Make sure only a single Bitcoin process is using the data directory.
2125 const fs::path &datadir = gArgs.GetDataDirNet();
2126 switch (util::LockDirectory(datadir, ".lock", probeOnly)) {
2128 return InitError(
2129 strprintf(_("Cannot obtain a lock on data directory %s. %s is "
2130 "probably already running."),
2131 fs::PathToString(datadir), PACKAGE_NAME));
2133 return true;
2135 return InitError(strprintf(
2136 _("Cannot write to data directory '%s'; check permissions."),
2137 fs::PathToString(datadir)));
2138 } // no default case, so the compiler can warn about missing cases
2139 assert(false);
2140}
2141
2143 // Step 4: sanity checks
2144 auto result{kernel::SanityChecks(kernel)};
2145 if (!result) {
2147 return InitError(strprintf(
2148 _("Initialization sanity check failed. %s is shutting down."),
2149 PACKAGE_NAME));
2150 }
2151
2152 // Probe the data directory lock to give an early error message, if possible
2153 // We cannot hold the data directory lock here, as the forking for daemon()
2154 // hasn't yet happened, and a fork will cause weird behavior to it.
2155 return LockDataDirectory(true);
2156}
2157
2159 // After daemonization get the data directory lock again and hold on to it
2160 // until exit. This creates a slight window for a race condition to happen,
2161 // however this condition is harmless: it will at most make us exit without
2162 // printing a message to console.
2163 if (!LockDataDirectory(false)) {
2164 // Detailed error printed inside LockDataDirectory
2165 return false;
2166 }
2167 return true;
2168}
2169
2172 // Create client interfaces for wallets that are supposed to be loaded
2173 // according to -wallet and -disablewallet options. This only constructs
2174 // the interfaces, it doesn't load wallet data. Wallets actually get loaded
2175 // when load() and start() interface methods are called below.
2177 return true;
2178}
2179
2180bool AppInitMain(Config &config, RPCServer &rpcServer,
2181 HTTPRPCRequestProcessor &httpRPCRequestProcessor,
2184 // Step 4a: application initialization
2185 const ArgsManager &args = *Assert(node.args);
2186 const CChainParams &chainparams = config.GetChainParams();
2187
2188 if (!CreatePidFile(args)) {
2189 // Detailed error printed inside CreatePidFile().
2190 return false;
2191 }
2192 if (!init::StartLogging(args)) {
2193 // Detailed error printed inside StartLogging().
2194 return false;
2195 }
2196
2197 LogPrintf("Using at most %i automatic connections (%i file descriptors "
2198 "available)\n",
2199 nMaxConnections, nFD);
2200
2201 // Warn about relative -datadir path.
2202 if (args.IsArgSet("-datadir") &&
2203 !args.GetPathArg("-datadir").is_absolute()) {
2204 LogPrintf("Warning: relative datadir option '%s' specified, which will "
2205 "be interpreted relative to the current working directory "
2206 "'%s'. This is fragile, because if bitcoin is started in the "
2207 "future from a different location, it will be unable to "
2208 "locate the current data files. There could also be data "
2209 "loss if bitcoin is started while in a temporary "
2210 "directory.\n",
2211 args.GetArg("-datadir", ""),
2212 fs::PathToString(fs::current_path()));
2213 }
2214
2215 int script_threads = args.GetIntArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
2216 if (script_threads <= 0) {
2217 // -par=0 means autodetect (number of cores - 1 script threads)
2218 // -par=-n means "leave n cores free" (number of cores - n - 1 script
2219 // threads)
2220 script_threads += GetNumCores();
2221 }
2222
2223 // Subtract 1 because the main thread counts towards the par threads
2224 script_threads = std::max(script_threads - 1, 0);
2225
2226 // Number of script-checking threads <= MAX_SCRIPTCHECK_THREADS
2227 script_threads = std::min(script_threads, MAX_SCRIPTCHECK_THREADS);
2228
2229 LogPrintf("Script verification uses %d additional threads\n",
2230 script_threads);
2231 if (script_threads >= 1) {
2232 StartScriptCheckWorkerThreads(script_threads);
2233 }
2234
2235 assert(!node.scheduler);
2236 node.scheduler = std::make_unique<CScheduler>();
2237 auto &scheduler = *node.scheduler;
2238
2239 // Start the lightweight task scheduler thread
2240 node.scheduler->m_service_thread =
2241 std::thread(&util::TraceThread, "scheduler",
2242 [&] { node.scheduler->serviceQueue(); });
2243
2244 // Gather some entropy once per minute.
2245 node.scheduler->scheduleEvery(
2246 [] {
2248 return true;
2249 },
2250 std::chrono::minutes{1});
2251
2252 if (args.GetBoolArg("-logratelimit", BCLog::DEFAULT_LOGRATELIMIT)) {
2254 [&scheduler](auto func, auto window) {
2255 scheduler.scheduleEvery(std::move(func), window);
2256 },
2258 } else {
2259 LogInfo("Log rate limiting disabled\n");
2260 }
2261
2262 // Check disk space every 5 minutes to avoid db corruption.
2263 node.scheduler->scheduleEvery(
2264 [&args] {
2265 constexpr uint64_t min_disk_space = 250_MiB;
2266 if (!CheckDiskSpace(args.GetBlocksDirPath(), min_disk_space)) {
2267 LogPrintf("Shutting down due to lack of disk space!\n");
2268 StartShutdown();
2269 }
2270 return true;
2271 },
2272 std::chrono::minutes{5});
2273
2275
2280 RegisterAllRPCCommands(config, rpcServer, tableRPC);
2281 for (const auto &client : node.chain_clients) {
2282 client->registerRpcs();
2283 }
2284#if ENABLE_ZMQ
2286#endif
2287
2294 if (args.GetBoolArg("-server", false)) {
2295 uiInterface.InitMessage_connect(SetRPCWarmupStatus);
2296 if (!AppInitServers(config, httpRPCRequestProcessor, node)) {
2297 return InitError(
2298 _("Unable to start HTTP server. See debug log for details."));
2299 }
2300 }
2301
2302 // Step 5: verify wallet database integrity
2303 for (const auto &client : node.chain_clients) {
2304 if (!client->verify()) {
2305 return false;
2306 }
2307 }
2308
2309 // Step 6: network initialization
2310
2311 // Note that we absolutely cannot open any actual connections
2312 // until the very end ("start node") as the UTXO/block state
2313 // is not yet setup and may end up being set up twice if we
2314 // need to reindex later.
2315
2316 fListen = args.GetBoolArg("-listen", DEFAULT_LISTEN);
2317 fDiscover = args.GetBoolArg("-discover", true);
2318
2319 {
2320 // Initialize addrman
2321 assert(!node.addrman);
2322
2323 // Read asmap file if configured
2324 std::vector<bool> asmap;
2325 if (args.IsArgSet("-asmap")) {
2326 fs::path asmap_path =
2327 args.GetPathArg("-asmap", DEFAULT_ASMAP_FILENAME);
2328 if (!asmap_path.is_absolute()) {
2329 asmap_path = args.GetDataDirNet() / asmap_path;
2330 }
2331 if (!fs::exists(asmap_path)) {
2332 InitError(strprintf(_("Could not find asmap file %s"),
2333 fs::quoted(fs::PathToString(asmap_path))));
2334 return false;
2335 }
2336 asmap = DecodeAsmap(asmap_path);
2337 if (asmap.size() == 0) {
2338 InitError(strprintf(_("Could not parse asmap file %s"),
2339 fs::quoted(fs::PathToString(asmap_path))));
2340 return false;
2341 }
2342 const uint256 asmap_version = (HashWriter{} << asmap).GetHash();
2343 LogPrintf("Using asmap version %s for IP bucketing\n",
2344 asmap_version.ToString());
2345 } else {
2346 LogPrintf("Using /16 prefix for IP bucketing\n");
2347 }
2348
2349 uiInterface.InitMessage(_("Loading P2P addresses...").translated);
2350 auto addrman{LoadAddrman(chainparams, asmap, args)};
2351 if (!addrman) {
2352 return InitError(util::ErrorString(addrman));
2353 }
2354 node.addrman = std::move(*addrman);
2355 }
2356
2358 assert(!node.banman);
2359 node.banman = std::make_unique<BanMan>(
2360 args.GetDataDirNet() / "banlist", config.GetChainParams(), &uiInterface,
2361 args.GetIntArg("-bantime", DEFAULT_MISBEHAVING_BANTIME));
2362 assert(!node.connman);
2363 node.connman = std::make_unique<CConnman>(
2364 config, rng.rand64(), rng.rand64(), *node.addrman,
2365 args.GetBoolArg("-networkactive", true));
2366
2367 // Check port numbers
2368 for (const std::string port_option : {
2369 "-port",
2370 "-rpcport",
2371 }) {
2372 if (args.IsArgSet(port_option)) {
2373 const std::string port = args.GetArg(port_option, "");
2374 uint16_t n;
2375 if (!ParseUInt16(port, &n) || n == 0) {
2376 return InitError(InvalidPortErrMsg(port_option, port));
2377 }
2378 }
2379 }
2380
2381 for (const std::string port_option : {
2382 "-i2psam",
2383 "-onion",
2384 "-proxy",
2385 "-rpcbind",
2386 "-torcontrol",
2387 "-whitebind",
2388 "-zmqpubhashblock",
2389 "-zmqpubhashtx",
2390 "-zmqpubrawblock",
2391 "-zmqpubrawtx",
2392 "-zmqpubsequence",
2393 }) {
2394 for (const std::string &socket_addr : args.GetArgs(port_option)) {
2395 std::string host_out;
2396 uint16_t port_out{0};
2397 if (!SplitHostPort(socket_addr, port_out, host_out)) {
2398#if HAVE_SOCKADDR_UN
2399 // Allow unix domain sockets for -proxy and -onion e.g.
2400 // unix:/some/file/path
2401 if ((port_option != "-proxy" && port_option != "-onion") ||
2402 socket_addr.find(ADDR_PREFIX_UNIX) != 0) {
2403 return InitError(
2404 InvalidPortErrMsg(port_option, socket_addr));
2405 }
2406#else
2407 return InitError(InvalidPortErrMsg(port_option, socket_addr));
2408#endif
2409 }
2410 }
2411 }
2412
2413 for (const std::string &socket_addr : args.GetArgs("-bind")) {
2414 std::string host_out;
2415 uint16_t port_out{0};
2416 std::string bind_socket_addr =
2417 socket_addr.substr(0, socket_addr.rfind('='));
2418 if (!SplitHostPort(bind_socket_addr, port_out, host_out)) {
2419 return InitError(InvalidPortErrMsg("-bind", socket_addr));
2420 }
2421 }
2422
2423 // sanitize comments per BIP-0014, format user agent and check total size
2424 std::vector<std::string> uacomments;
2425 for (const std::string &cmt : args.GetArgs("-uacomment")) {
2426 if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT)) {
2427 return InitError(strprintf(
2428 _("User Agent comment (%s) contains unsafe characters."), cmt));
2429 }
2430 uacomments.push_back(cmt);
2431 }
2432 const std::string client_name = args.GetArg("-uaclientname", CLIENT_NAME);
2433 const std::string client_version =
2434 args.GetArg("-uaclientversion", FormatVersion(CLIENT_VERSION));
2435 if (client_name != SanitizeString(client_name, SAFE_CHARS_UA_COMMENT)) {
2436 return InitError(strprintf(
2437 _("-uaclientname (%s) contains invalid characters."), client_name));
2438 }
2439 if (client_version !=
2440 SanitizeString(client_version, SAFE_CHARS_UA_COMMENT)) {
2441 return InitError(
2442 strprintf(_("-uaclientversion (%s) contains invalid characters."),
2443 client_version));
2444 }
2445 const std::string strSubVersion =
2446 FormatUserAgent(client_name, client_version, uacomments);
2447 if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
2448 return InitError(strprintf(
2449 _("Total length of network version string (%i) exceeds maximum "
2450 "length (%i). Reduce the number or size of uacomments."),
2451 strSubVersion.size(), MAX_SUBVERSION_LENGTH));
2452 }
2453
2454 if (args.IsArgSet("-onlynet")) {
2455 std::set<enum Network> nets;
2456 for (const std::string &snet : args.GetArgs("-onlynet")) {
2457 enum Network net = ParseNetwork(snet);
2458 if (net == NET_UNROUTABLE) {
2459 return InitError(strprintf(
2460 _("Unknown network specified in -onlynet: '%s'"), snet));
2461 }
2462 nets.insert(net);
2463 }
2464 for (int n = 0; n < NET_MAX; n++) {
2465 enum Network net = (enum Network)n;
2466 assert(IsReachable(net));
2467 if (!nets.count(net)) {
2468 SetReachable(net, false);
2469 }
2470 }
2471 }
2472
2473 // Check for host lookup allowed before parsing any network related
2474 // parameters
2476
2477 Proxy onion_proxy;
2478
2479 bool proxyRandomize =
2480 args.GetBoolArg("-proxyrandomize", DEFAULT_PROXYRANDOMIZE);
2481 // -proxy sets a proxy for all outgoing network traffic
2482 // -noproxy (or -proxy=0) as well as the empty string can be used to not set
2483 // a proxy, this is the default
2484 std::string proxyArg = args.GetArg("-proxy", "");
2485 if (proxyArg != "" && proxyArg != "0") {
2486 Proxy addrProxy;
2487 if (IsUnixSocketPath(proxyArg)) {
2488 addrProxy = Proxy(proxyArg, proxyRandomize);
2489 } else {
2490 const std::optional<CService> proxyAddr{
2491 Lookup(proxyArg, 9050, fNameLookup)};
2492 if (!proxyAddr.has_value()) {
2493 return InitError(strprintf(
2494 _("Invalid -proxy address or hostname: '%s'"), proxyArg));
2495 }
2496
2497 addrProxy = Proxy(proxyAddr.value(), proxyRandomize);
2498 }
2499
2500 if (!addrProxy.IsValid()) {
2501 return InitError(strprintf(
2502 _("Invalid -proxy address or hostname: '%s'"), proxyArg));
2503 }
2504
2505 SetProxy(NET_IPV4, addrProxy);
2506 SetProxy(NET_IPV6, addrProxy);
2507 SetNameProxy(addrProxy);
2508 onion_proxy = addrProxy;
2509 }
2510
2511 const bool onlynet_used_with_onion{args.IsArgSet("-onlynet") &&
2513
2514 // -onion can be used to set only a proxy for .onion, or override normal
2515 // proxy for .onion addresses.
2516 // -noonion (or -onion=0) disables connecting to .onion entirely. An empty
2517 // string is used to not override the onion proxy (in which case it defaults
2518 // to -proxy set above, or none)
2519 std::string onionArg = args.GetArg("-onion", "");
2520 if (onionArg != "") {
2521 if (onionArg == "0") {
2522 // Handle -noonion/-onion=0
2523 onion_proxy = Proxy{};
2524 if (onlynet_used_with_onion) {
2525 return InitError(_("Outbound connections restricted to Tor "
2526 "(-onlynet=onion) but the proxy for "
2527 "reaching the Tor network is explicitly "
2528 "forbidden: -onion=0"));
2529 }
2530 } else {
2531 if (IsUnixSocketPath(onionArg)) {
2532 onion_proxy = Proxy(onionArg, proxyRandomize);
2533 } else {
2534 const std::optional<CService> addr{
2535 Lookup(onionArg, 9050, fNameLookup)};
2536 if (!addr.has_value() || !addr->IsValid()) {
2537 return InitError(
2538 strprintf(_("Invalid -onion address or hostname: '%s'"),
2539 onionArg));
2540 }
2541
2542 onion_proxy = Proxy(addr.value(), proxyRandomize);
2543 }
2544 }
2545 }
2546
2547 if (onion_proxy.IsValid()) {
2548 SetProxy(NET_ONION, onion_proxy);
2549 } else {
2550 // If -listenonion is set, then we will (try to) connect to the Tor
2551 // control port later from the torcontrol thread and may retrieve the
2552 // onion proxy from there.
2553 const bool listenonion_disabled{
2554 !args.GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION)};
2555 if (onlynet_used_with_onion && listenonion_disabled) {
2556 return InitError(_("Outbound connections restricted to Tor "
2557 "(-onlynet=onion) but the proxy for "
2558 "reaching the Tor network is not provided: none "
2559 "of -proxy, -onion or "
2560 "-listenonion is given"));
2561 }
2562 SetReachable(NET_ONION, false);
2563 }
2564
2565 for (const std::string &strAddr : args.GetArgs("-externalip")) {
2566 const std::optional<CService> addrLocal{
2567 Lookup(strAddr, GetListenPort(), fNameLookup)};
2568 if (addrLocal.has_value() && addrLocal->IsValid()) {
2569 AddLocal(addrLocal.value(), LOCAL_MANUAL);
2570 } else {
2571 return InitError(ResolveErrMsg("externalip", strAddr));
2572 }
2573 }
2574
2575#if ENABLE_ZMQ
2577 [&chainman = node.chainman](CBlock &block, const CBlockIndex &index) {
2578 assert(chainman);
2579 return chainman->m_blockman.ReadBlock(block, index);
2580 });
2581
2584 }
2585#endif
2586
2587 // Step 7: load block chain
2588
2589 node.notifications =
2590 std::make_unique<KernelNotifications>(node.exit_status);
2591 fReindex = args.GetBoolArg("-reindex", false);
2592 bool fReindexChainState = args.GetBoolArg("-reindex-chainstate", false);
2593
2594 ChainstateManager::Options chainman_opts{
2595 .config = config,
2596 .datadir = args.GetDataDirNet(),
2597 .adjusted_time_callback = GetAdjustedTime,
2598 .notifications = *node.notifications,
2599 };
2600 // no error can happen, already checked in AppInitParameterInteraction
2601 Assert(!ApplyArgsManOptions(args, chainman_opts));
2602
2603 if (chainman_opts.checkpoints_enabled) {
2604 LogPrintf("Checkpoints will be verified.\n");
2605 } else {
2606 LogPrintf("Skipping checkpoint verification.\n");
2607 }
2608
2609 BlockManager::Options blockman_opts{
2610 .chainparams = chainman_opts.config.GetChainParams(),
2611 .blocks_dir = args.GetBlocksDirPath(),
2612 .notifications = chainman_opts.notifications,
2613 };
2614 // no error can happen, already checked in AppInitParameterInteraction
2615 Assert(!ApplyArgsManOptions(args, blockman_opts));
2616
2617 // cache size calculations
2618 const auto [index_cache_sizes, kernel_cache_sizes] =
2619 CalculateCacheSizes(args, g_enabled_filter_types.size());
2620
2621 LogInfo("Cache configuration:\n");
2622 LogInfo("* Using %.1f MiB for block index database\n",
2623 kernel_cache_sizes.block_tree_db * (1.0 / 1024 / 1024));
2624 if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
2625 LogInfo("* Using %.1f MiB for transaction index database\n",
2626 index_cache_sizes.tx_index * (1.0 / 1024 / 1024));
2627 }
2628 for (BlockFilterType filter_type : g_enabled_filter_types) {
2629 LogInfo("* Using %.1f MiB for %s block filter index database\n",
2630 index_cache_sizes.filter_index * (1.0 / 1024 / 1024),
2631 BlockFilterTypeName(filter_type));
2632 }
2633 LogInfo("* Using %.1f MiB for chain state database\n",
2634 kernel_cache_sizes.coins_db * (1.0 / 1024 / 1024));
2635
2636 assert(!node.mempool);
2637 assert(!node.chainman);
2638
2639 CTxMemPool::Options mempool_opts{
2640 .check_ratio = chainparams.DefaultConsistencyChecks() ? 1 : 0,
2641 };
2642 if (const auto err{ApplyArgsManOptions(args, chainparams, mempool_opts)}) {
2643 return InitError(*err);
2644 }
2645 mempool_opts.check_ratio =
2646 std::clamp<int>(mempool_opts.check_ratio, 0, 1'000'000);
2647
2648 // FIXME: this legacy limit comes from the DEFAULT_DESCENDANT_SIZE_LIMIT
2649 // (101) that was enforced before the wellington activation. While it's
2650 // still a good idea to have some minimum mempool size, using this value as
2651 // a threshold is no longer relevant.
2652 int64_t nMempoolSizeMin = 101 * 1000 * 40;
2653 if (mempool_opts.max_size_bytes < 0 ||
2654 (!chainparams.IsTestChain() &&
2655 mempool_opts.max_size_bytes < nMempoolSizeMin)) {
2656 return InitError(strprintf(_("-maxmempool must be at least %d MB"),
2657 std::ceil(nMempoolSizeMin / 1000000.0)));
2658 }
2659 LogInfo("* Using %.1f MiB for in-memory UTXO set (plus up to %.1f MiB of "
2660 "unused mempool space)\n",
2661 kernel_cache_sizes.coins * (1.0 / 1024 / 1024),
2662 mempool_opts.max_size_bytes * (1.0 / 1024 / 1024));
2663
2664 for (bool fLoaded = false; !fLoaded && !ShutdownRequested();) {
2665 node.mempool = std::make_unique<CTxMemPool>(config, mempool_opts);
2666
2667 node.chainman = std::make_unique<ChainstateManager>(
2668 node.kernel->interrupt, chainman_opts, blockman_opts);
2669 ChainstateManager &chainman = *node.chainman;
2670
2671 // This is defined and set here instead of inline in validation.h to
2672 // avoid a hard dependency between validation and index/base, since the
2673 // latter is not in libbitcoinkernel.
2674 chainman.snapshot_download_completed = [&node]() {
2675 if (!node.chainman->m_blockman.IsPruneMode()) {
2676 LogPrintf("[snapshot] re-enabling NODE_NETWORK services\n");
2677 node.connman->AddLocalServices(NODE_NETWORK);
2678 }
2679
2680 LogPrintf("[snapshot] restarting indexes\n");
2681
2682 // Drain the validation interface queue to ensure that the old
2683 // indexes don't have any pending work.
2685
2686 for (auto *index : node.indexes) {
2687 index->Interrupt();
2688 index->Stop();
2689 if (!(index->Init() && index->StartBackgroundSync())) {
2690 LogPrintf("[snapshot] WARNING failed to restart index %s "
2691 "on snapshot chain\n",
2692 index->GetName());
2693 }
2694 }
2695 };
2696
2698 options.mempool = Assert(node.mempool.get());
2699 options.reindex = node::fReindex;
2700 options.reindex_chainstate = fReindexChainState;
2701 options.prune = chainman.m_blockman.IsPruneMode();
2702 options.check_blocks =
2703 args.GetIntArg("-checkblocks", DEFAULT_CHECKBLOCKS);
2704 options.check_level = args.GetIntArg("-checklevel", DEFAULT_CHECKLEVEL);
2706 args.IsArgSet("-checkblocks") || args.IsArgSet("-checklevel");
2708 options.coins_error_cb = [] {
2709 uiInterface.ThreadSafeMessageBox(
2710 _("Error reading from database, shutting down."), "",
2712 };
2713
2714 uiInterface.InitMessage(_("Loading block index...").translated);
2715
2716 const int64_t load_block_index_start_time = GetTimeMillis();
2717 auto catch_exceptions = [](auto &&f) {
2718 try {
2719 return f();
2720 } catch (const std::exception &e) {
2721 LogPrintf("%s\n", e.what());
2722 return std::make_tuple(node::ChainstateLoadStatus::FAILURE,
2723 _("Error opening block database"));
2724 }
2725 };
2726 auto [status, error] =
2727 catch_exceptions([&, &kernel_cache_sizes_ = kernel_cache_sizes] {
2728 return LoadChainstate(chainman, kernel_cache_sizes_, options);
2729 });
2731 uiInterface.InitMessage(_("Verifying blocks...").translated);
2732 if (chainman.m_blockman.m_have_pruned &&
2733 options.check_blocks > MIN_BLOCKS_TO_KEEP) {
2734 LogWarning("pruned datadir may not have more than %d "
2735 "blocks; only checking available blocks\n",
2737 }
2738 std::tie(status, error) = catch_exceptions(
2739 [&] { return VerifyLoadedChainstate(chainman, options); });
2741 WITH_LOCK(cs_main, return node.chainman->LoadRecentHeadersTime(
2742 node.chainman->m_options.datadir /
2744 fLoaded = true;
2745 LogPrintf(" block index %15dms\n",
2746 GetTimeMillis() - load_block_index_start_time);
2747 }
2748 }
2749
2752 status ==
2754 return InitError(error);
2755 }
2756
2757 if (!fLoaded && !ShutdownRequested()) {
2758 // first suggest a reindex
2759 if (!options.reindex) {
2760 bool fRet = uiInterface.ThreadSafeQuestion(
2761 error + Untranslated(".\n\n") +
2762 _("Do you want to rebuild the block database now?"),
2763 error.original + ".\nPlease restart with -reindex or "
2764 "-reindex-chainstate to recover.",
2765 "",
2768 if (fRet) {
2769 fReindex = true;
2770 AbortShutdown();
2771 } else {
2772 LogPrintf("Aborted block database rebuild. Exiting.\n");
2773 return false;
2774 }
2775 } else {
2776 return InitError(error);
2777 }
2778 }
2779 }
2780
2781 // As LoadBlockIndex can take several minutes, it's possible the user
2782 // requested to kill the GUI during the last operation. If so, exit.
2783 // As the program has not fully started yet, Shutdown() is possibly
2784 // overkill.
2785 if (ShutdownRequested()) {
2786 LogPrintf("Shutdown requested. Exiting.\n");
2787 return false;
2788 }
2789
2790 ChainstateManager &chainman = *Assert(node.chainman);
2791
2792 if (args.GetBoolArg("-avalanche", AVALANCHE_DEFAULT_ENABLED)) {
2793 // Initialize Avalanche.
2794 bilingual_str avalancheError;
2796 args, *node.chain, node.connman.get(), chainman, node.mempool.get(),
2797 *node.scheduler, avalancheError);
2798 if (!node.avalanche) {
2799 InitError(avalancheError);
2800 return false;
2801 }
2802
2803 if (node.avalanche->isAvalancheServiceAvailable()) {
2804 nLocalServices = ServiceFlags(nLocalServices | NODE_AVALANCHE);
2805 }
2806 }
2807
2808 PeerManager::Options peerman_opts{};
2809 ApplyArgsManOptions(args, peerman_opts);
2810
2811 assert(!node.peerman);
2812 node.peerman = PeerManager::make(*node.connman, *node.addrman,
2813 node.banman.get(), chainman, *node.mempool,
2814 node.avalanche.get(), peerman_opts);
2815 RegisterValidationInterface(node.peerman.get());
2816
2817 // Encoded addresses using cashaddr instead of base58.
2818 // We do this by default to avoid confusion with BTC addresses.
2819 config.SetCashAddrEncoding(
2820 args.GetBoolArg("-usecashaddr", DEFAULT_USEASHADDR));
2821
2822 // Step 8: load indexers
2823
2824 if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
2825 auto result{
2827 chainman.m_blockman.m_block_tree_db)))};
2828 if (!result) {
2829 return InitError(util::ErrorString(result));
2830 }
2831
2832 g_txindex = std::make_unique<TxIndex>(
2833 interfaces::MakeChain(node, Params()), index_cache_sizes.tx_index,
2834 false, fReindex);
2835 node.indexes.emplace_back(g_txindex.get());
2836 }
2837
2838 for (const auto &filter_type : g_enabled_filter_types) {
2840 [&] { return interfaces::MakeChain(node, Params()); }, filter_type,
2841 index_cache_sizes.filter_index, false, fReindex);
2842 node.indexes.emplace_back(GetBlockFilterIndex(filter_type));
2843 }
2844
2845 if (args.GetBoolArg("-coinstatsindex", DEFAULT_COINSTATSINDEX)) {
2846 g_coin_stats_index = std::make_unique<CoinStatsIndex>(
2847 interfaces::MakeChain(node, Params()), /* cache size */ 0, false,
2848 fReindex);
2849 node.indexes.emplace_back(g_coin_stats_index.get());
2850 }
2851
2852 // Init indexes
2853 for (auto index : node.indexes) {
2854 if (!index->Init()) {
2855 return false;
2856 }
2857 }
2858
2859 const bool background_sync_in_progress{WITH_LOCK(
2860 chainman.GetMutex(), return chainman.BackgroundSyncInProgress())};
2861#if ENABLE_CHRONIK
2862 if (args.GetBoolArg("-chronik", DEFAULT_CHRONIK)) {
2863 if (background_sync_in_progress) {
2864 return InitError(
2865 _("Assumeutxo is incompatible with -chronik. Wait for "
2866 "background sync to complete before enabling Chronik."));
2867 }
2868
2869 const bool fReindexChronik =
2870 fReindex || args.GetBoolArg("-chronikreindex", false);
2871 if (!chronik::Start(args, config, node, fReindexChronik)) {
2872 return false;
2873 }
2874 }
2875#endif
2876
2877 // Step 9: load wallet
2878 for (const auto &client : node.chain_clients) {
2879 if (!client->load()) {
2880 return false;
2881 }
2882 }
2883
2884 // Step 10: data directory maintenance
2885
2886 // if pruning, perform the initial blockstore prune
2887 // after any wallet rescanning has taken place.
2888 if (chainman.m_blockman.IsPruneMode()) {
2889 if (!fReindex) {
2890 LOCK(cs_main);
2891 for (Chainstate *chainstate : chainman.GetAll()) {
2892 uiInterface.InitMessage(_("Pruning blockstore...").translated);
2893 chainstate->PruneAndFlush();
2894 }
2895 }
2896 } else {
2897 // Prior to setting NODE_NETWORK, check if we can provide historical
2898 // blocks.
2899 if (!background_sync_in_progress) {
2900 LogPrintf("Setting NODE_NETWORK on non-prune mode\n");
2901 nLocalServices = ServiceFlags(nLocalServices | NODE_NETWORK);
2902 } else {
2903 LogPrintf("Running node in NODE_NETWORK_LIMITED mode until "
2904 "snapshot background sync completes\n");
2905 }
2906 }
2907
2908 // Step 11: import blocks
2909 if (!CheckDiskSpace(args.GetDataDirNet())) {
2910 InitError(
2911 strprintf(_("Error: Disk space is low for %s"),
2913 return false;
2914 }
2915 if (!CheckDiskSpace(args.GetBlocksDirPath())) {
2916 InitError(
2917 strprintf(_("Error: Disk space is low for %s"),
2919 return false;
2920 }
2921
2922 // Either install a handler to notify us when genesis activates, or set
2923 // fHaveGenesis directly.
2924 // No locking, as this happens before any background thread is started.
2925 boost::signals2::connection block_notify_genesis_wait_connection;
2926 if (WITH_LOCK(chainman.GetMutex(),
2927 return chainman.ActiveChain().Tip() == nullptr)) {
2928 block_notify_genesis_wait_connection =
2929 uiInterface.NotifyBlockTip_connect(
2930 std::bind(BlockNotifyGenesisWait, std::placeholders::_2));
2931 } else {
2932 fHaveGenesis = true;
2933 }
2934
2935#if defined(HAVE_SYSTEM)
2936 const std::string block_notify = args.GetArg("-blocknotify", "");
2937 if (!block_notify.empty()) {
2938 uiInterface.NotifyBlockTip_connect([block_notify](
2939 SynchronizationState sync_state,
2940 const CBlockIndex *pBlockIndex) {
2941 if (sync_state != SynchronizationState::POST_INIT || !pBlockIndex) {
2942 return;
2943 }
2944 std::string command = block_notify;
2945 ReplaceAll(command, "%s", pBlockIndex->GetBlockHash().GetHex());
2946 std::thread t(runCommand, command);
2947 // thread runs free
2948 t.detach();
2949 });
2950 }
2951#endif
2952
2953 std::vector<fs::path> vImportFiles;
2954 for (const std::string &strFile : args.GetArgs("-loadblock")) {
2955 vImportFiles.push_back(fs::PathFromString(strFile));
2956 }
2957
2958 avalanche::Processor *const avalanche = node.avalanche.get();
2959 chainman.m_thread_load = std::thread(
2960 &util::TraceThread, "initload", [=, &chainman, &args, &node] {
2961 // Import blocks
2962 ImportBlocks(chainman, avalanche, vImportFiles);
2963 // Start indexes initial sync
2965 bilingual_str err_str =
2966 _("Failed to start indexes, shutting down..");
2967 chainman.GetNotifications().fatalError(err_str.original,
2968 err_str);
2969 return;
2970 }
2971 // Load mempool from disk
2972 chainman.ActiveChainstate().LoadMempool(
2973 ShouldPersistMempool(args) ? MempoolPath(args) : fs::path{});
2974 });
2975
2976 // Wait for genesis block to be processed
2977 {
2979 // We previously could hang here if StartShutdown() is called prior to
2980 // ImportBlocks getting started, so instead we just wait on a timer to
2981 // check ShutdownRequested() regularly.
2982 while (!fHaveGenesis && !ShutdownRequested()) {
2983 g_genesis_wait_cv.wait_for(lock, std::chrono::milliseconds(500));
2984 }
2985 block_notify_genesis_wait_connection.disconnect();
2986 }
2987
2988 if (ShutdownRequested()) {
2989 return false;
2990 }
2991
2992 // Step 12: start node
2993
2994 int chain_active_height;
2995
2997 {
2998 LOCK(cs_main);
2999 LogPrintf("block tree size = %u\n", chainman.BlockIndex().size());
3000 chain_active_height = chainman.ActiveChain().Height();
3001 if (tip_info) {
3002 tip_info->block_height = chain_active_height;
3003 tip_info->block_time =
3004 chainman.ActiveChain().Tip()
3005 ? chainman.ActiveChain().Tip()->GetBlockTime()
3006 : chainman.GetParams().GenesisBlock().GetBlockTime();
3008 chainman.GetParams().TxData(), chainman.ActiveChain().Tip());
3009 }
3010 if (tip_info && chainman.m_best_header) {
3011 tip_info->header_height = chainman.m_best_header->nHeight;
3012 tip_info->header_time = chainman.m_best_header->GetBlockTime();
3013 }
3014 }
3015 LogPrintf("nBestHeight = %d\n", chain_active_height);
3016 if (node.peerman) {
3017 node.peerman->SetBestHeight(chain_active_height);
3018 }
3019
3020 // Map ports with NAT-PMP
3021 StartMapPort(args.GetBoolArg("-natpmp", DEFAULT_NATPMP));
3022
3023 CConnman::Options connOptions;
3024 connOptions.nLocalServices = nLocalServices;
3025 connOptions.nMaxConnections = nMaxConnections;
3026 connOptions.m_max_avalanche_outbound =
3027 node.avalanche
3028 ? args.GetIntArg("-maxavalancheoutbound",
3030 : 0;
3031 connOptions.m_max_outbound_full_relay = std::min(
3033 connOptions.nMaxConnections - connOptions.m_max_avalanche_outbound);
3034 connOptions.m_max_outbound_block_relay = std::min(
3036 connOptions.nMaxConnections - connOptions.m_max_avalanche_outbound -
3037 connOptions.m_max_outbound_full_relay);
3039 connOptions.nMaxFeeler = MAX_FEELER_CONNECTIONS;
3040 connOptions.uiInterface = &uiInterface;
3041 connOptions.m_banman = node.banman.get();
3042 connOptions.m_msgproc.push_back(node.peerman.get());
3043 if (node.avalanche) {
3044 connOptions.m_msgproc.push_back(node.avalanche.get());
3045 }
3046 connOptions.nSendBufferMaxSize =
3047 1000 * args.GetIntArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER);
3048 connOptions.nReceiveFloodSize =
3049 1000 * args.GetIntArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER);
3050 connOptions.m_added_nodes = args.GetArgs("-addnode");
3051
3052 connOptions.nMaxOutboundLimit =
3053 1024 * 1024 *
3054 args.GetIntArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET);
3055 connOptions.m_peer_connect_timeout = peer_connect_timeout;
3056 connOptions.whitelist_forcerelay =
3057 args.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY);
3058 connOptions.whitelist_relay =
3059 args.GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY);
3060
3061 // Port to bind to if `-bind=addr` is provided without a `:port` suffix.
3062 const uint16_t default_bind_port = static_cast<uint16_t>(
3063 args.GetIntArg("-port", config.GetChainParams().GetDefaultPort()));
3064
3065 const auto BadPortWarning = [](const char *prefix, uint16_t port) {
3066 return strprintf(_("%s request to listen on port %u. This port is "
3067 "considered \"bad\" and "
3068 "thus it is unlikely that any Bitcoin ABC peers "
3069 "connect to it. See "
3070 "doc/p2p-bad-ports.md for details and a full list."),
3071 prefix, port);
3072 };
3073
3074 for (const std::string &bind_arg : args.GetArgs("-bind")) {
3075 std::optional<CService> bind_addr;
3076 const size_t index = bind_arg.rfind('=');
3077 if (index == std::string::npos) {
3078 bind_addr =
3079 Lookup(bind_arg, default_bind_port, /*fAllowLookup=*/false);
3080 if (bind_addr.has_value()) {
3081 connOptions.vBinds.push_back(bind_addr.value());
3082 if (IsBadPort(bind_addr.value().GetPort())) {
3084 BadPortWarning("-bind", bind_addr.value().GetPort()));
3085 }
3086 continue;
3087 }
3088 } else {
3089 const std::string network_type = bind_arg.substr(index + 1);
3090 if (network_type == "onion") {
3091 const std::string truncated_bind_arg =
3092 bind_arg.substr(0, index);
3093 bind_addr =
3094 Lookup(truncated_bind_arg,
3095 BaseParams().OnionServiceTargetPort(), false);
3096 if (bind_addr.has_value()) {
3097 connOptions.onion_binds.push_back(bind_addr.value());
3098 continue;
3099 }
3100 }
3101 }
3102 return InitError(ResolveErrMsg("bind", bind_arg));
3103 }
3104
3105 for (const std::string &strBind : args.GetArgs("-whitebind")) {
3106 NetWhitebindPermissions whitebind;
3107 bilingual_str error;
3108 if (!NetWhitebindPermissions::TryParse(strBind, whitebind, error)) {
3109 return InitError(error);
3110 }
3111 connOptions.vWhiteBinds.push_back(whitebind);
3112 }
3113
3114 // If the user did not specify -bind= or -whitebind= then we bind
3115 // on any address - 0.0.0.0 (IPv4) and :: (IPv6).
3116 connOptions.bind_on_any =
3117 args.GetArgs("-bind").empty() && args.GetArgs("-whitebind").empty();
3118
3119 // Emit a warning if a bad port is given to -port= but only if -bind and
3120 // -whitebind are not given, because if they are, then -port= is ignored.
3121 if (connOptions.bind_on_any && args.IsArgSet("-port")) {
3122 const uint16_t port_arg = args.GetIntArg("-port", 0);
3123 if (IsBadPort(port_arg)) {
3124 InitWarning(BadPortWarning("-port", port_arg));
3125 }
3126 }
3127
3128 CService onion_service_target;
3129 if (!connOptions.onion_binds.empty()) {
3130 onion_service_target = connOptions.onion_binds.front();
3131 } else if (!connOptions.vBinds.empty()) {
3132 onion_service_target = connOptions.vBinds.front();
3133 } else {
3134 onion_service_target = DefaultOnionServiceTarget();
3135 connOptions.onion_binds.push_back(onion_service_target);
3136 }
3137
3138 if (args.GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION)) {
3139 if (connOptions.onion_binds.size() > 1) {
3141 _("More than one onion bind address is provided. Using %s "
3142 "for the automatically created Tor onion service."),
3143 onion_service_target.ToStringAddrPort()));
3144 }
3145 StartTorControl(onion_service_target);
3146 }
3147
3148 if (connOptions.bind_on_any) {
3149 // Only add all IP addresses of the machine if we would be listening on
3150 // any address - 0.0.0.0 (IPv4) and :: (IPv6).
3151 Discover();
3152 }
3153
3154 for (const auto &net : args.GetArgs("-whitelist")) {
3156 ConnectionDirection connection_direction;
3157 bilingual_str error;
3158 if (!NetWhitelistPermissions::TryParse(net, subnet,
3159 connection_direction, error)) {
3160 return InitError(error);
3161 }
3162 if (connection_direction & ConnectionDirection::In) {
3163 connOptions.vWhitelistedRangeIncoming.push_back(subnet);
3164 }
3165 if (connection_direction & ConnectionDirection::Out) {
3166 connOptions.vWhitelistedRangeOutgoing.push_back(subnet);
3167 }
3168 }
3169
3170 connOptions.vSeedNodes = args.GetArgs("-seednode");
3171
3172 // Initiate outbound connections unless connect=0
3173 connOptions.m_use_addrman_outgoing = !args.IsArgSet("-connect");
3174 if (!connOptions.m_use_addrman_outgoing) {
3175 const auto connect = args.GetArgs("-connect");
3176 if (connect.size() != 1 || connect[0] != "0") {
3177 connOptions.m_specified_outgoing = connect;
3178 }
3179 }
3180
3181 const std::string &i2psam_arg = args.GetArg("-i2psam", "");
3182 if (!i2psam_arg.empty()) {
3183 const std::optional<CService> addr{
3184 Lookup(i2psam_arg, 7656, fNameLookup)};
3185 if (!addr.has_value() || !addr->IsValid()) {
3186 return InitError(strprintf(
3187 _("Invalid -i2psam address or hostname: '%s'"), i2psam_arg));
3188 }
3189 SetProxy(NET_I2P, Proxy{addr.value()});
3190 } else {
3191 SetReachable(NET_I2P, false);
3192 }
3193
3194 connOptions.m_i2p_accept_incoming =
3195 args.GetBoolArg("-i2pacceptincoming", true);
3196
3197 if (!node.connman->Start(*node.scheduler, connOptions)) {
3198 return false;
3199 }
3200
3201 // Step 13: finished
3202
3203 // At this point, the RPC is "started", but still in warmup, which means it
3204 // cannot yet be called. Before we make it callable, we need to make sure
3205 // that the RPC's view of the best block is valid and consistent with
3206 // ChainstateManager's active tip.
3207 //
3208 // If we do not do this, RPC's view of the best block will be height=0 and
3209 // hash=0x0. This will lead to erroroneous responses for things like
3210 // waitforblockheight.
3212 WITH_LOCK(chainman.GetMutex(), return chainman.ActiveTip()));
3214
3215 uiInterface.InitMessage(_("Done loading").translated);
3216
3217 for (const auto &client : node.chain_clients) {
3218 client->start(*node.scheduler);
3219 }
3220
3221 BanMan *banman = node.banman.get();
3222 node.scheduler->scheduleEvery(
3223 [banman] {
3224 banman->DumpBanlist();
3225 return true;
3226 },
3228
3229 // Start Avalanche's event loop.
3230 if (node.avalanche) {
3231 node.avalanche->startEventLoop(*node.scheduler);
3232 }
3233
3234 if (node.peerman) {
3235 node.peerman->StartScheduledTasks(*node.scheduler);
3236 }
3237
3238#if HAVE_SYSTEM
3239 StartupNotify(args);
3240#endif
3241
3242 return true;
3243}
3244
3246 // Find the oldest block among all indexes.
3247 // This block is used to verify that we have the required blocks' data
3248 // stored on disk, starting from that point up to the current tip.
3249 // indexes_start_block='nullptr' means "start from height 0".
3250 std::optional<const CBlockIndex *> indexes_start_block;
3251 std::string older_index_name;
3252 ChainstateManager &chainman = *Assert(node.chainman);
3253 const Chainstate &chainstate =
3254 WITH_LOCK(::cs_main, return chainman.GetChainstateForIndexing());
3255 const CChain &index_chain = chainstate.m_chain;
3256
3257 for (auto index : node.indexes) {
3258 const IndexSummary &summary = index->GetSummary();
3259 if (summary.synced) {
3260 continue;
3261 }
3262
3263 // Get the last common block between the index best block and the active
3264 // chain
3265 LOCK(::cs_main);
3266 const CBlockIndex *pindex = chainman.m_blockman.LookupBlockIndex(
3267 BlockHash{summary.best_block_hash});
3268 if (!index_chain.Contains(pindex)) {
3269 pindex = index_chain.FindFork(pindex);
3270 }
3271
3272 if (!indexes_start_block || !pindex ||
3273 pindex->nHeight < indexes_start_block.value()->nHeight) {
3274 indexes_start_block = pindex;
3275 older_index_name = summary.name;
3276 if (!pindex) {
3277 // Starting from genesis so no need to look for earlier block.
3278 break;
3279 }
3280 }
3281 };
3282
3283 // Verify all blocks needed to sync to current tip are present.
3284 if (indexes_start_block) {
3285 LOCK(::cs_main);
3286 const CBlockIndex *start_block = *indexes_start_block;
3287 if (!start_block) {
3288 start_block = chainman.ActiveChain().Genesis();
3289 }
3290 if (!chainman.m_blockman.CheckBlockDataAvailability(
3291 *index_chain.Tip(), *Assert(start_block))) {
3292 return InitError(strprintf(
3293 Untranslated("%s best block of the index goes beyond pruned "
3294 "data. Please disable the index or reindex (which "
3295 "will download the whole blockchain again)"),
3296 older_index_name));
3297 }
3298 }
3299
3300 // Start threads
3301 for (auto index : node.indexes) {
3302 if (!index->StartBackgroundSync()) {
3303 return false;
3304 }
3305 }
3306 return true;
3307}
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:271
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:705
const char *const BITCOIN_SETTINGS_FILENAME
Definition: args.cpp:37
ArgsManager gArgs
Definition: args.cpp:39
const char *const BITCOIN_CONF_FILENAME
Definition: args.cpp:36
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:239
std::vector< bool > DecodeAsmap(fs::path path)
Read asmap from provided binary file.
Definition: asmap.cpp:295
static constexpr bool DEFAULT_PERSIST_AVAPEERS
Default for -persistavapeers.
Definition: avalanche.h:56
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:46
static constexpr bool DEFAULT_AVALANCHE_STAKING_PRECONSENSUS
Default for -avalanchestakingpreconsensus.
Definition: avalanche.h:62
static constexpr size_t AVALANCHE_DEFAULT_PEER_REPLACEMENT_COOLDOWN
Peer replacement cooldown time default value in seconds.
Definition: avalanche.h:27
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:53
static constexpr bool DEFAULT_AVALANCHE_PRECONSENSUS
Default for -avalanchepreconsensus.
Definition: avalanche.h:59
static constexpr Amount AVALANCHE_DEFAULT_MIN_QUORUM_STAKE
Default minimum cumulative stake of all known peers that constitutes a usable quorum.
Definition: avalanche.h:39
static constexpr size_t AVALANCHE_DEFAULT_CONFLICTING_PROOF_COOLDOWN
Conflicting proofs cooldown time default value in seconds.
Definition: avalanche.h:21
static constexpr bool DEFAULT_AVALANCHE_MINING_PRECONSENSUS
Default for -avalanchepreconsensusmining.
Definition: avalanche.h:65
static constexpr bool AVALANCHE_DEFAULT_ENABLED
Is avalanche enabled by default.
Definition: avalanche.h:15
static constexpr size_t AVALANCHE_DEFAULT_COOLDOWN
Avalanche default cooldown in milliseconds.
Definition: avalanche.h:33
static constexpr unsigned int DEFAULT_MISBEHAVING_BANTIME
Definition: banman.h:20
static constexpr std::chrono::minutes DUMP_BANS_INTERVAL
How often to dump banned addresses/subnets to disk.
Definition: banman.h:23
void RPCNotifyBlockChange(const CBlockIndex *pindex)
Callback for when block tip changed.
Definition: blockchain.cpp:256
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(std::function< std::unique_ptr< interfaces::Chain >()> make_chain, 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 ChainType chain)
Creates and returns a std::unique_ptr<CChainParams> of the chosen chain.
Definition: chainparams.cpp:33
const CChainParams & Params()
Return the currently selected parameters.
Definition: chainparams.cpp:21
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
std::unique_ptr< CBaseChainParams > CreateBaseChainParams(const ChainType chain)
Port numbers for incoming Tor connections (8334, 18334, 38334, 18445) have been chosen arbitrarily to...
void SetupChainParamsBaseOptions(ArgsManager &argsman)
Set the arguments for chainparams.
static constexpr bool DEFAULT_CHECKPOINTS_ENABLED
static constexpr auto DEFAULT_MAX_TIP_AGE
static constexpr int DEFAULT_STOPATHEIGHT
static constexpr bool DEFAULT_STORE_RECENT_HEADERS_TIME
std::string ChainTypeToString(ChainType chain)
Definition: chaintype.cpp:11
ChainType
Definition: chaintype.h:11
#define Assert(val)
Identity function.
Definition: check.h:84
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:140
std::list< SectionInfo > GetUnrecognizedSections() const
Log warnings for unrecognized section names in the config file.
Definition: args.cpp:164
@ NETWORK_ONLY
Definition: args.h:134
@ ALLOW_ANY
disable validation
Definition: args.h:114
@ DISALLOW_NEGATION
unimplemented, draft implementation in #16545
Definition: args.h:124
@ DISALLOW_ELISION
disallow -foo syntax that doesn't assign any value
Definition: args.h:126
@ DEBUG_ONLY
Definition: args.h:128
@ SENSITIVE
Definition: args.h:136
ChainType GetChainType() const
Looks for -regtest, -testnet and returns the appropriate BIP70 chain name.
Definition: args.cpp:761
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
Definition: args.cpp:361
fs::path GetDataDirNet() const
Get data directory path with appended network identifier.
Definition: args.h:239
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: args.cpp:371
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Definition: args.cpp:494
fs::path GetBlocksDirPath() const
Get blocks directory path.
Definition: args.cpp:299
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: args.cpp:462
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn't already have a value.
Definition: args.cpp:557
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: args.cpp:524
void AddHiddenArgs(const std::vector< std::string > &args)
Add many hidden arguments.
Definition: args.cpp:610
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
Definition: args.cpp:588
fs::path GetPathArg(std::string arg, const fs::path &default_value={}) const
Return path argument or default value.
Definition: args.cpp:285
static std::shared_ptr< LogRateLimiter > Create(SchedulerFunction &&scheduler_func, uint64_t max_bytes, std::chrono::seconds reset_window)
Definition: logging.cpp:367
void SetRateLimiting(std::shared_ptr< LogRateLimiter > limiter) EXCLUSIVE_LOCKS_REQUIRED(!m_cs)
Definition: logging.h:314
std::atomic< bool > m_reopen_file
Definition: logging.h:266
Definition: banman.h:59
void DumpBanlist()
Definition: banman.cpp:43
void Stop()
Stops the instance from staying in sync with blockchain updates.
Definition: base.cpp:418
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:404
BlockFilterIndex is used to store and retrieve block filters, hashes, and headers for a range of bloc...
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:160
BlockHash GetBlockHash() const
Definition: blockindex.h:130
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: blockindex.h:38
An in-memory indexed chain of blocks.
Definition: chain.h:138
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:154
CBlockIndex * Genesis() const
Returns the index entry for the genesis block of this chain, or nullptr if none.
Definition: chain.h:147
int Height() const
Return the maximal height in the chain.
Definition: chain.h:190
const CBlockIndex * FindFork(const CBlockIndex *pindex) const
Find the last common block between this chain and a block index entry.
Definition: chain.cpp:49
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:170
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:86
const CBlock & GenesisBlock() const
Definition: chainparams.h:112
bool DefaultConsistencyChecks() const
Default value for -checkmempool and -checkblockindex argument.
Definition: chainparams.h:114
const ChainTxData & TxData() const
Definition: chainparams.h:158
bool IsTestChain() const
If this chain is exclusively used for testing.
Definition: chainparams.h:118
uint16_t GetDefaultPort() const
Definition: chainparams.h:101
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.
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:573
std::string ToStringAddrPort() 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:739
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:838
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:1191
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:1468
SnapshotCompletionResult MaybeCompleteSnapshotValidation() 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:1442
std::thread m_thread_load
Definition: validation.h:1329
kernel::Notifications & GetNotifications() const
Definition: validation.h:1299
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
Definition: validation.h:1323
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1449
bool BackgroundSyncInProgress() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
The state of a background sync (for net processing)
Definition: validation.h:1456
std::function< void()> snapshot_download_completed
Function to restart active indexes; set dynamically to avoid a circular dependency on base/index....
Definition: validation.h:1280
const CChainParams & GetParams() const
Definition: validation.h:1284
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1443
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(std::vector< Chainstate * GetAll)()
Instantiate a new chainstate.
Definition: validation.h:1408
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:1332
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
Fast randomness source.
Definition: random.h:411
uint64_t rand64() noexcept
Generate a random 64-bit integer.
Definition: random.h:432
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:99
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)
Definition: netbase.h:67
bool IsValid() const
Definition: netbase.h:82
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:225
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
A base class defining functions for notifying about certain kernel events.
virtual void fatalError(const std::string &debug_message, const bilingual_str &user_message={})
The fatal error notification is sent to notify the user when an error occurs in kernel code that can'...
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
Definition: blockstorage.h:116
bool CheckBlockDataAvailability(const CBlockIndex &upper_block LIFETIMEBOUND, const CBlockIndex &lower_block LIFETIMEBOUND) EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex *GetFirstBlock(const CBlockIndex &upper_block LIFETIMEBOUND, std::function< bool(BlockStatus)> status_test, const CBlockIndex *lower_block=nullptr) const EXCLUSIVE_LOCKS_REQUIRED(boo m_have_pruned)
Check if all blocks in the [upper_block, lower_block] range have data available.
Definition: blockstorage.h:412
CBlockIndex * LookupBlockIndex(const BlockHash &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool IsPruneMode() const
Whether running in -prune mode.
Definition: blockstorage.h:350
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
int RaiseFileDescriptorLimit(int nMinFD)
This function tries to raise the file descriptor limit to the requested number.
Definition: fs_helpers.cpp:168
bool CheckDiskSpace(const fs::path &dir, uint64_t additional_bytes)
Definition: fs_helpers.cpp:97
void InterruptHTTPRPC()
Interrupt HTTP RPC subsystem.
Definition: httprpc.cpp:487
void StopHTTPRPC()
Stop HTTP RPC subsystem.
Definition: httprpc.cpp:491
bool StartHTTPRPC(HTTPRPCRequestProcessor &httpRPCRequestProcessor)
Start HTTP RPC subsystem.
Definition: httprpc.cpp:466
void StartREST(const std::any &context)
Start HTTP REST subsystem.
Definition: rest.cpp:828
void StopREST()
Stop HTTP REST subsystem.
Definition: rest.cpp:840
void InterruptREST()
Interrupt RPC REST subsystem.
Definition: rest.cpp:838
void InterruptHTTPServer()
Interrupt HTTP server threads.
Definition: httpserver.cpp:551
void StartHTTPServer()
Start HTTP server.
Definition: httpserver.cpp:540
void StopHTTPServer()
Stop HTTP server.
Definition: httpserver.cpp:562
bool InitHTTPServer(Config &config)
Initialize HTTP server.
Definition: httpserver.cpp:473
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:162
static bool CreatePidFile(const ArgsManager &args)
Definition: init.cpp:169
static const bool DEFAULT_PROXYRANDOMIZE
Definition: init.cpp:142
void Interrupt(NodeContext &node)
Interrupt threads.
Definition: init.cpp:209
void InitLogging(const ArgsManager &args)
Initialize global loggers.
Definition: init.cpp:1767
bool AppInitLockDataDirectory()
Lock bitcoin data directory.
Definition: init.cpp:2158
void SetupServerArgs(NodeContext &node)
Register all arguments with the ArgsManager.
Definition: init.cpp:433
static bool AppInitServers(Config &config, HTTPRPCRequestProcessor &httpRPCRequestProcessor, NodeContext &node)
Definition: init.cpp:1618
#define MIN_CORE_FILEDESCRIPTORS
Definition: init.cpp:152
static bool fHaveGenesis
Definition: init.cpp:1593
void Shutdown(NodeContext &node)
Definition: init.cpp:233
static void HandleSIGTERM(int)
Signal handlers are very limited in what they are allowed to do.
Definition: init.cpp:395
static GlobalMutex g_genesis_wait_mutex
Definition: init.cpp:1594
static void OnRPCStarted()
Definition: init.cpp:421
static constexpr bool DEFAULT_USEASHADDR
Definition: init.cpp:145
static void HandleSIGHUP(int)
Definition: init.cpp:399
bool AppInitBasicSetup(const ArgsManager &args, std::atomic< int > &exit_status)
Initialize bitcoin: Basic context setup.
Definition: init.cpp:1794
static fs::path GetPidFile(const ArgsManager &args)
Definition: init.cpp:164
static std::condition_variable g_genesis_wait_cv
Definition: init.cpp:1595
bool AppInitMain(Config &config, RPCServer &rpcServer, HTTPRPCRequestProcessor &httpRPCRequestProcessor, NodeContext &node, interfaces::BlockAndHeaderTipInfo *tip_info)
Bitcoin main initialization.
Definition: init.cpp:2180
static constexpr bool DEFAULT_CHRONIK
Definition: init.cpp:144
bool StartIndexBackgroundSync(NodeContext &node)
Validates requirements to run the indexes and spawns each index initial sync thread.
Definition: init.cpp:3245
bool AppInitInterfaces(NodeContext &node)
Initialize node and wallet interface pointers.
Definition: init.cpp:2170
static const char * DEFAULT_ASMAP_FILENAME
Definition: init.cpp:155
void InitParameterInteraction(ArgsManager &args)
Parameter interaction: change current parameters depending on various rules.
Definition: init.cpp:1643
static void BlockNotifyGenesisWait(const CBlockIndex *pBlockIndex)
Definition: init.cpp:1597
static void OnRPCStopped()
Definition: init.cpp:426
static bool LockDataDirectory(bool probeOnly)
Definition: init.cpp:2123
static void registerSignalHandler(int signal, void(*handler)(int))
Definition: init.cpp:411
bool AppInitParameterInteraction(Config &config, const ArgsManager &args)
Initialization: parameter interaction.
Definition: init.cpp:1836
static const bool DEFAULT_REST_ENABLE
Definition: init.cpp:143
static boost::signals2::connection rpc_notify_block_change_connection
Definition: init.cpp:420
static void new_handler_terminate()
Definition: init.cpp:1783
bool AppInitSanityChecks(const kernel::Context &kernel)
Initialization sanity checks.
Definition: init.cpp:2142
static const std::string HEADERS_TIME_FILE_NAME
Definition: init.cpp:157
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
static constexpr size_t DEFAULT_DB_CACHE_BATCH
Default LevelDB write batch size.
Definition: caches.h:16
BCLog::Logger & LogInstance()
Definition: logging.cpp:28
#define LogWarning(...)
Definition: logging.h:416
#define LogPrint(category,...)
Definition: logging.h:452
#define LogInfo(...)
Definition: logging.h:413
#define LogPrintf(...)
Definition: logging.h:424
void StopMapPort()
Definition: mapport.cpp:191
void InterruptMapPort()
Definition: mapport.cpp:185
void StartMapPort(bool enable)
Definition: mapport.cpp:176
static constexpr bool DEFAULT_NATPMP
Definition: mapport.h:8
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
constexpr auto RATELIMIT_WINDOW
Definition: logging.h:120
constexpr bool DEFAULT_LOGRATELIMIT
Definition: logging.h:121
constexpr uint64_t RATELIMIT_MAX_BYTES
Definition: logging.h:118
@ RPC
Definition: logging.h:76
void OnStarted(std::function< void()> slot)
Definition: server.cpp:115
void OnStopped(std::function< void()> slot)
Definition: server.cpp:119
static constexpr Amount PROOF_DUST_THRESHOLD
Minimum amount per utxo.
Definition: proof.h:38
bilingual_str AmountErrMsg(const std::string &optname, const std::string &strValue)
Definition: messages.cpp:73
bilingual_str ResolveErrMsg(const std::string &optname, const std::string &strBind)
Definition: messages.cpp:58
bilingual_str InvalidPortErrMsg(const std::string &optname, const std::string &invalid_value)
Definition: messages.cpp:63
static auto quoted(const std::string &s)
Definition: fs.h:112
static bool exists(const path &p)
Definition: fs.h:107
static std::string PathToString(const path &path)
Convert path object to byte string.
Definition: fs.h:147
static path PathFromString(const std::string &string)
Convert byte string to path object.
Definition: fs.h:170
std::string get_filesystem_error_message(const fs::filesystem_error &e)
Definition: fs.cpp:133
void AddLoggingArgs(ArgsManager &argsman)
Definition: common.cpp:24
void SetLoggingCategories(const ArgsManager &args)
Definition: common.cpp:179
bool StartLogging(const ArgsManager &args)
Definition: common.cpp:207
void SetLoggingLevel(const ArgsManager &args)
Definition: common.cpp:149
void SetLoggingOptions(const ArgsManager &args)
Definition: common.cpp:126
void LogPackageVersion()
Definition: common.cpp:254
std::unique_ptr< Chain > MakeChain(node::NodeContext &node, const CChainParams &params)
Return implementation of Chain interface.
Definition: interfaces.cpp:830
Definition: init.h:28
static constexpr bool DEFAULT_STOPAFTERBLOCKIMPORT
bool DumpMempool(const CTxMemPool &pool, const fs::path &dump_path, FopenFn mockable_fopen_function, bool skip_file_commit)
util::Result< void > SanityChecks(const Context &)
Ensure a usable environment with all necessary library support.
Definition: checks.cpp:13
Definition: messages.h:12
@ 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:26
fs::path MempoolPath(const ArgsManager &argsman)
bool ShouldPersistMempool(const ArgsManager &argsman)
ChainstateLoadResult LoadChainstate(ChainstateManager &chainman, const CacheSizes &cache_sizes, const ChainstateLoadOptions &options)
Definition: chainstate.cpp:171
ChainstateLoadResult VerifyLoadedChainstate(ChainstateManager &chainman, const ChainstateLoadOptions &options)
Definition: chainstate.cpp:275
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 ImportBlocks(ChainstateManager &chainman, avalanche::Processor *const avalanche, std::vector< fs::path > vImportFiles)
void ApplyArgsManOptions(const ArgsManager &args, const Config &config, BlockFitter::Options &options)
Apply options from ArgsManager to BlockFitter options.
Definition: blockfitter.cpp:40
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
LockResult LockDirectory(const fs::path &directory, const std::string lockfile_name, bool probe_only)
Definition: fs_helpers.cpp:56
bilingual_str ErrorString(const Result< T > &result)
Definition: result.h:90
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:105
void TraceThread(std::string_view thread_name, std::function< void()> thread_func)
A wrapper for do-something-once thread functions.
Definition: thread.cpp:14
void ReplaceAll(std::string &in_out, const std::string &search, const std::string &substitute)
Definition: string.cpp:11
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:140
bool fDiscover
Definition: net.cpp:128
bool fListen
Definition: net.cpp:129
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
Definition: net.cpp:320
bool AddLocal(const CService &addr, int nScore)
Definition: net.cpp:281
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:2461
bool IsReachable(enum Network net)
Definition: net.cpp:328
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
Definition: net.h:95
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
Definition: net.h:71
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
Definition: net.h:78
static const size_t DEFAULT_MAXSENDBUFFER
Definition: net.h:109
static const int NUM_FDS_MESSAGE_CAPTURE
Number of file descriptors required for message capture.
Definition: net.h:103
static const bool DEFAULT_BLOCKSONLY
Default for blocks only.
Definition: net.h:99
static const bool DEFAULT_FORCEDNSSEED
Definition: net.h:105
static constexpr uint64_t DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
Definition: net.h:97
static const size_t DEFAULT_MAXRECEIVEBUFFER
Definition: net.h:108
static const int DEFAULT_MAX_AVALANCHE_OUTBOUND_CONNECTIONS
Maximum number of avalanche enabled outgoing connections by default.
Definition: net.h:85
static const bool DEFAULT_FIXEDSEEDS
Definition: net.h:107
static const int MAX_FEELER_CONNECTIONS
Maximum number of feeler connections.
Definition: net.h:87
static const bool DEFAULT_LISTEN
-listen default
Definition: net.h:89
static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT
-peertimeout default
Definition: net.h:101
static const bool DEFAULT_DNSSEED
Definition: net.h:106
static const int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS
Maximum number of automatic outgoing nodes over which we'll relay everything (blocks,...
Definition: net.h:76
@ LOCAL_MANUAL
Definition: net.h:169
static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
Definition: net.h:80
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:37
@ NET_I2P
I2P.
Definition: netaddress.h:52
@ NET_MAX
Dummy value to indicate the number of NET_* constants.
Definition: netaddress.h:62
@ NET_ONION
TOR (v2 or v3)
Definition: netaddress.h:49
@ NET_IPV6
IPv6.
Definition: netaddress.h:46
@ NET_IPV4
IPv4.
Definition: netaddress.h:43
@ NET_UNROUTABLE
Addresses from these networks are not publicly routable on the global Internet.
Definition: netaddress.h:40
bool SetNameProxy(const Proxy &addrProxy)
Set the name proxy to use for all connections to nodes specified by a hostname.
Definition: netbase.cpp:819
enum Network ParseNetwork(const std::string &net_in)
Definition: netbase.cpp:100
bool SetProxy(enum Network net, const Proxy &addrProxy)
Definition: netbase.cpp:799
std::vector< CService > Lookup(const std::string &name, uint16_t portDefault, bool fAllowLookup, unsigned int nMaxSolutions, DNSLookupFn dns_lookup_function)
Resolve a service string to its corresponding service.
Definition: netbase.cpp:224
bool fNameLookup
Definition: netbase.cpp:48
int nConnectTimeout
Definition: netbase.cpp:47
bool IsUnixSocketPath(const std::string &name)
Check if a string is a valid UNIX domain socket path.
Definition: netbase.cpp:269
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:919
std::vector< std::string > GetNetworkNames(bool append_unroutable)
Return a vector of publicly routable Network names; optionally append NET_UNROUTABLE.
Definition: netbase.cpp:145
ConnectionDirection
Definition: netbase.h:37
static const int DEFAULT_NAME_LOOKUP
-dns default
Definition: netbase.h:30
const std::string ADDR_PREFIX_UNIX
Prefix for unix domain socket addresses (which are local filesystem paths)
Definition: netbase.h:35
static const int DEFAULT_CONNECT_TIMEOUT
-timeout default
Definition: netbase.h:28
static constexpr size_t MIN_DB_CACHE
min. -dbcache (bytes)
Definition: caches.h:16
static constexpr size_t DEFAULT_DB_CACHE
-dbcache default (bytes)
Definition: caches.h:18
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 size_t DEFAULT_AVALANCHE_MAX_ELEMENT_POLL
Maximum item that can be polled at once.
Definition: processor.h:55
static constexpr std::chrono::milliseconds AVALANCHE_DEFAULT_QUERY_TIMEOUT
How long before we consider that a query timed out.
Definition: processor.h:74
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:33
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:700
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:813
bool(* handler)(Config &config, const std::any &context, HTTPRequest *req, const std::string &strReq)
Definition: rest.cpp:814
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:35
static constexpr bool DEFAULT_RPC_DOC_CHECK
Definition: util.h:49
static constexpr bool DEFAULT_ENABLE_RTT
Default for -enablertt.
Definition: rtt.h:22
static constexpr size_t DEFAULT_SCRIPT_EXECUTION_CACHE_BYTES
Definition: scriptcache.h:102
void SetRPCWarmupFinished()
Mark warmup as done.
Definition: server.cpp:396
void StartRPC()
Definition: server.cpp:351
void StopRPC()
Definition: server.cpp:368
void InterruptRPC()
Definition: server.cpp:357
void SetRPCWarmupStatus(const std::string &newStatus)
Set the RPC warmup status.
Definition: server.cpp:391
CRPCTable tableRPC
Definition: server.cpp:683
void RpcInterruptionPoint()
Throw JSONRPCError if RPC is not running.
Definition: server.cpp:385
bool ShutdownRequested()
Returns true if a shutdown is requested, false otherwise.
Definition: shutdown.cpp:29
void StartShutdown()
Request shutdown of the application.
Definition: shutdown.cpp:16
void AbortShutdown()
Clear shutdown flag.
Definition: shutdown.cpp:25
static constexpr size_t DEFAULT_SIGNATURE_CACHE_BYTES
Definition: sigcache.h:26
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:28
Definition: amount.h:21
static constexpr Amount zero() noexcept
Definition: amount.h:34
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
int m_max_outbound_block_relay
Definition: net.h:847
unsigned int nReceiveFloodSize
Definition: net.h:855
int m_max_outbound_full_relay
Definition: net.h:846
std::vector< NetWhitebindPermissions > vWhiteBinds
Definition: net.h:861
uint64_t nMaxOutboundLimit
Definition: net.h:856
CClientUIInterface * uiInterface
Definition: net.h:851
std::vector< NetWhitelistPermissions > vWhitelistedRangeIncoming
Definition: net.h:859
int m_max_avalanche_outbound
Definition: net.h:848
std::vector< CService > onion_binds
Definition: net.h:863
int nMaxFeeler
Definition: net.h:850
std::vector< std::string > m_specified_outgoing
Definition: net.h:868
bool whitelist_relay
Definition: net.h:872
int nMaxConnections
Definition: net.h:845
ServiceFlags nLocalServices
Definition: net.h:844
std::vector< std::string > m_added_nodes
Definition: net.h:869
int64_t m_peer_connect_timeout
Definition: net.h:857
std::vector< CService > vBinds
Definition: net.h:862
unsigned int nSendBufferMaxSize
Definition: net.h:854
bool m_i2p_accept_incoming
Definition: net.h:870
std::vector< std::string > vSeedNodes
Definition: net.h:858
BanMan * m_banman
Definition: net.h:853
bool m_use_addrman_outgoing
Definition: net.h:867
std::vector< NetEventsInterface * > m_msgproc
Definition: net.h:852
bool whitelist_forcerelay
Definition: net.h:871
bool bind_on_any
True if the user did not specify -bind= or -whitebind= and thus we should bind on 0....
Definition: net.h:866
std::vector< NetWhitelistPermissions > vWhitelistedRangeOutgoing
Definition: net.h:860
int nMaxAddnode
Definition: net.h:849
static const Currency & get()
Definition: amount.cpp:18
std::string ticker
Definition: amount.h:155
std::string name
Definition: base.h:21
bool synced
Definition: base.h:22
BlockHash best_block_hash
Definition: base.h:24
Bilingual messages:
Definition: translation.h:17
bool empty() const
Definition: translation.h:27
std::string translated
Definition: translation.h:19
std::string original
Definition: translation.h:18
Block and header tip information.
Definition: node.h:50
An options struct for ChainstateManager, more ergonomically referred to as ChainstateManager::Options...
Context struct holding the kernel library's logically global state, and passed to external libbitcoin...
Definition: context.h:20
Options struct containing options for constructing a CTxMemPool.
int check_ratio
The ratio used to determine how often sanity checks will run.
std::function< void()> coins_error_cb
Definition: chainstate.h:39
std::function< bool()> check_interrupt
Definition: chainstate.h:38
NodeContext struct containing references to chain state and connection state.
Definition: context.h:48
#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:20
bool SetupNetworking()
Definition: system.cpp:101
int GetNumCores()
Return the number of cores available on the current system.
Definition: system.cpp:114
static int count
int64_t GetTimeMillis()
Returns the system time (not mockable)
Definition: time.cpp:76
void SetMockTime(int64_t nMockTimeIn)
DEPRECATED Use SetMockTime with chrono type.
Definition: time.cpp:64
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:890
const std::string DEFAULT_TOR_CONTROL
Default control port.
Definition: torcontrol.cpp:41
void InterruptTorControl()
Definition: torcontrol.cpp:872
void StartTorControl(CService onion_service_target)
Definition: torcontrol.cpp:853
void StopTorControl()
Definition: torcontrol.cpp:882
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:40
std::unique_ptr< TxIndex > g_txindex
The global transaction index, used in GetTransaction. May be null.
Definition: txindex.cpp:17
static constexpr bool DEFAULT_TXINDEX
Definition: txindex.h:15
CClientUIInterface uiInterface
void InitWarning(const bilingual_str &str)
Show warning message.
bool InitError(const bilingual_str &str)
Show error message.
bool ParseUInt16(std::string_view str, uint16_t *out)
Convert decimal string to unsigned 16-bit integer with strict parse error feedback.
bool SplitHostPort(std::string_view in, uint16_t &portOut, std::string &hostOut)
Splits socket address string into host string and port value.
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:118
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:99
assert(!tx.IsCoinBase())
static constexpr int DEFAULT_CHECKLEVEL
Definition: validation.h:101
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:115
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:99
static const int MAX_SCRIPTCHECK_THREADS
Maximum number of dedicated script-checking threads allowed.
Definition: validation.h:89
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition: validation.h:118
static const int DEFAULT_SCRIPTCHECK_THREADS
-par default (number of script-checking threads, 0 = auto)
Definition: validation.h:91
static const signed int DEFAULT_CHECKBLOCKS
Definition: validation.h:100
static const bool DEFAULT_PEERBLOOMFILTERS
Definition: validation.h:93
CMainSignals & GetMainSignals()
void UnregisterAllValidationInterfaces()
Unregister all subscribers.
void UnregisterValidationInterface(CValidationInterface *callbacks)
Unregister subscriber.
void RegisterValidationInterface(CValidationInterface *callbacks)
Register subscriber.
void SyncWithValidationInterfaceQueue()
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...
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