Bitcoin ABC 0.34.2
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 <logging.h>
44#include <mapport.h>
45#include <mempool_args.h>
46#include <net.h>
47#include <net_permissions.h>
48#include <net_processing.h>
49#include <netbase.h>
51#include <node/blockstorage.h>
52#include <node/caches.h>
53#include <node/chainstate.h>
55#include <node/context.h>
58#include <node/miner.h>
59#include <node/peerman_args.h>
60#include <node/ui_interface.h>
61#include <policy/block/rtt.h>
62#include <policy/policy.h>
63#include <policy/settings.h>
64#include <rpc/blockchain.h>
65#include <rpc/register.h>
66#include <rpc/server.h>
67#include <rpc/util.h>
68#include <scheduler.h>
69#include <script/scriptcache.h>
70#include <script/sigcache.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
139using util::Join;
140using util::ReplaceAll;
141
142static const bool DEFAULT_PROXYRANDOMIZE = true;
143static const bool DEFAULT_REST_ENABLE = false;
144static constexpr bool DEFAULT_STOPAFTERBLOCKIMPORT{false};
145static constexpr bool DEFAULT_CHRONIK = false;
146static constexpr bool DEFAULT_USEASHADDR = true;
147
148#ifdef WIN32
149// Win32 LevelDB doesn't use filedescriptors, and the ones used for accessing
150// block files don't count towards the fd_set size limit anyway.
151#define MIN_CORE_FILEDESCRIPTORS 0
152#else
153#define MIN_CORE_FILEDESCRIPTORS 150
154#endif
155
156static const char *DEFAULT_ASMAP_FILENAME = "ip_asn.map";
157
158static const std::string HEADERS_TIME_FILE_NAME{"headerstime.dat"};
159
163static const char *BITCOIN_PID_FILENAME = "bitcoind.pid";
164
165static fs::path GetPidFile(const ArgsManager &args) {
166 return AbsPathForConfigVal(args,
167 args.GetPathArg("-pid", BITCOIN_PID_FILENAME));
168}
169
170[[nodiscard]] static bool CreatePidFile(const ArgsManager &args) {
171 std::ofstream file{GetPidFile(args)};
172 if (file) {
173#ifdef WIN32
174 tfm::format(file, "%d\n", GetCurrentProcessId());
175#else
176 tfm::format(file, "%d\n", getpid());
177#endif
178 return true;
179 } else {
180 return InitError(strprintf(_("Unable to create the PID file '%s': %s"),
182 SysErrorString(errno)));
183 }
184}
185
187//
188// Shutdown
189//
190
191//
192// Thread management and startup/shutdown:
193//
194// The network-processing threads are all part of a thread group created by
195// AppInit() or the Qt main() function.
196//
197// A clean exit happens when StartShutdown() or the SIGTERM signal handler sets
198// fRequestShutdown, which makes main thread's WaitForShutdown() interrupts the
199// thread group.
200// And then, WaitForShutdown() makes all other on-going threads in the thread
201// group join the main thread.
202// Shutdown() is then called to clean up database connections, and stop other
203// threads that should only be stopped after the main network-processing threads
204// have exited.
205//
206// Shutdown for Qt is very similar, only it uses a QTimer to detect
207// ShutdownRequested() getting set, and then does the normal Qt shutdown thing.
208//
209
210#if HAVE_SYSTEM
211static void ShutdownNotify(const ArgsManager &args) {
212 std::vector<std::thread> threads;
213 for (const auto &cmd : args.GetArgs("-shutdownnotify")) {
214 threads.emplace_back(runCommand, cmd);
215 }
216 for (auto &t : threads) {
217 t.join();
218 }
219}
220#endif
221
223#if HAVE_SYSTEM
224 ShutdownNotify(*node.args);
225#endif
228 InterruptRPC();
232 if (node.avalanche) {
233 // Avalanche needs to be stopped before we interrupt the thread group as
234 // the scheduler will stop working then.
235 node.avalanche->stopEventLoop();
236 }
237 if (node.connman) {
238 node.connman->Interrupt();
239 }
240 if (g_txindex) {
241 g_txindex->Interrupt();
242 }
243 ForEachBlockFilterIndex([](BlockFilterIndex &index) { index.Interrupt(); });
244 if (g_coin_stats_index) {
245 g_coin_stats_index->Interrupt();
246 }
247}
248
250 static Mutex g_shutdown_mutex;
251 TRY_LOCK(g_shutdown_mutex, lock_shutdown);
252 if (!lock_shutdown) {
253 return;
254 }
255 LogPrintf("%s: In progress...\n", __func__);
256 Assert(node.args);
257
262 util::ThreadRename("shutoff");
263 if (node.mempool) {
264 node.mempool->AddTransactionsUpdated(1);
265 }
266
267 StopHTTPRPC();
268 StopREST();
269 StopRPC();
271
272#if ENABLE_CHRONIK
273 // Chronik serves its own HTTP and Electrum interfaces, whose handlers reach
274 // into peerman (to broadcast txs), the mempool and the chainstate. Stop
275 // serving requests together with the other interfaces, while all of these
276 // are still alive. The Chronik indexer keeps running until chronik::Stop()
277 // below, so it doesn't miss any validation interface event.
278 if (node.args->GetBoolArg("-chronik", DEFAULT_CHRONIK)) {
280 }
281#endif
282
283 for (const auto &client : node.chain_clients) {
284 client->flush();
285 }
286 StopMapPort();
287
288 // Because avalanche and the network depend on each other, it is important
289 // to shut them down in this order:
290 // 1. Stop avalanche event loop.
291 // 2. Shutdown network processing.
292 // 3. Destroy avalanche::Processor.
293 // 4. Destroy CConnman
294 if (node.avalanche) {
295 node.avalanche->stopEventLoop();
296 }
297
298 // Because these depend on each-other, we make sure that neither can be
299 // using the other before destroying them.
300 if (node.peerman && node.validation_signals) {
301 node.validation_signals->UnregisterValidationInterface(
302 node.peerman.get());
303 }
304 if (node.connman) {
305 node.connman->Stop();
306 }
307
309
310 if (node.background_init_thread.joinable()) {
311 node.background_init_thread.join();
312 }
313 // After everything has been shut down, but before things get flushed,
314 // stop the scheduler. After this point, SyncWithValidationInterfaceQueue()
315 // should not be called anymore as this would prevent the shutdown from
316 // completing.
317 if (node.scheduler) {
318 node.scheduler->stop();
319 }
320
321 // After the threads that potentially access these pointers have been
322 // stopped, destruct and reset all to nullptr.
323 node.peerman.reset();
324
325 // Destroy various global instances
326 node.avalanche.reset();
327 node.connman.reset();
328 node.banman.reset();
329 node.addrman.reset();
330
331 if (node.mempool && node.mempool->GetLoadTried() &&
332 ShouldPersistMempool(*node.args)) {
333 DumpMempool(*node.mempool, MempoolPath(*node.args));
334 }
335
336 // FlushStateToDisk generates a ChainStateFlushed callback, which we should
337 // avoid missing
338 if (node.chainman) {
339 LOCK(cs_main);
340 for (Chainstate *chainstate : node.chainman->GetAll()) {
341 if (chainstate->CanFlushToDisk()) {
342 chainstate->ForceFlushStateToDisk();
343 }
344 }
345 }
346
347 // After there are no more peers/RPC left to give us new data which may
348 // generate CValidationInterface callbacks, flush them...
349 if (node.validation_signals) {
350 node.validation_signals->FlushBackgroundCallbacks();
351 }
352
353 // Stop and delete all indexes only after flushing background callbacks. The
354 // scheduler is stopped and the queue is flushed at this point, so no
355 // validation interface callback can be running anymore and the indexes can
356 // safely be released.
357#if ENABLE_CHRONIK
358 if (node.args->GetBoolArg("-chronik", DEFAULT_CHRONIK)) {
359 chronik::Stop();
360 }
361#endif
362 if (g_txindex) {
363 g_txindex->Stop();
364 g_txindex.reset();
365 }
366 if (g_coin_stats_index) {
367 g_coin_stats_index->Stop();
368 g_coin_stats_index.reset();
369 }
370 ForEachBlockFilterIndex([](BlockFilterIndex &index) { index.Stop(); });
372
373 // Any future callbacks will be dropped. This should absolutely be safe - if
374 // missing a callback results in an unrecoverable situation, unclean
375 // shutdown would too. The only reason to do the above flushes is to let the
376 // wallet catch up with our current chain to avoid any strange pruning edge
377 // cases and make next startup faster by avoiding rescan.
378
379 if (node.chainman) {
380 LOCK(cs_main);
381 for (Chainstate *chainstate : node.chainman->GetAll()) {
382 if (chainstate->CanFlushToDisk()) {
383 chainstate->ForceFlushStateToDisk();
384 chainstate->ResetCoinsViews();
385 }
386 }
387
388 node.chainman->DumpRecentHeadersTime(node.chainman->m_options.datadir /
390 }
391 for (const auto &client : node.chain_clients) {
392 client->stop();
393 }
394
395#if ENABLE_ZMQ
397 if (node.validation_signals) {
398 node.validation_signals->UnregisterValidationInterface(
400 }
402 }
403#endif
404
405 node.chain_clients.clear();
406 if (node.validation_signals) {
407 node.validation_signals->UnregisterAllValidationInterfaces();
408 }
409 node.kernel.reset();
410 node.mempool.reset();
411 node.chainman.reset();
412 node.validation_signals.reset();
413 node.scheduler.reset();
414
415 try {
416 if (!fs::remove(GetPidFile(*node.args))) {
417 LogPrintf("%s: Unable to remove PID file: File does not exist\n",
418 __func__);
419 }
420 } catch (const fs::filesystem_error &e) {
421 LogWarning("%s: Unable to remove PID file: %s\n", __func__,
422 e.code().message());
423 }
424
425 LogPrintf("%s: done\n", __func__);
426}
427
433#ifndef WIN32
434static void HandleSIGTERM(int) {
436}
437
438static void HandleSIGHUP(int) {
439 LogInstance().m_reopen_file = true;
440}
441#else
442static BOOL WINAPI consoleCtrlHandler(DWORD dwCtrlType) {
444 Sleep(INFINITE);
445 return true;
446}
447#endif
448
449#ifndef WIN32
450static void registerSignalHandler(int signal, void (*handler)(int)) {
451 struct sigaction sa;
452 sa.sa_handler = handler;
453 sigemptyset(&sa.sa_mask);
454 sa.sa_flags = 0;
455 sigaction(signal, &sa, nullptr);
456}
457#endif
458
459static boost::signals2::connection rpc_notify_block_change_connection;
460static void OnRPCStarted() {
461 rpc_notify_block_change_connection = uiInterface.NotifyBlockTip_connect(
462 std::bind(RPCNotifyBlockChange, std::placeholders::_2));
463}
464
465static void OnRPCStopped() {
467 RPCNotifyBlockChange(nullptr);
468 g_best_block_cv.notify_all();
469 LogDebug(BCLog::RPC, "RPC stopped.\n");
470}
471
473 assert(!node.args);
474 node.args = &gArgs;
475 ArgsManager &argsman = *node.args;
476
477 SetupHelpOptions(argsman);
479 // server-only for now
480 argsman.AddArg("-help-debug",
481 "Print help message with debugging options and exit", false,
483
484 init::AddLoggingArgs(argsman);
485
486 const auto defaultBaseParams = CreateBaseChainParams(ChainType::MAIN);
487 const auto testnetBaseParams = CreateBaseChainParams(ChainType::TESTNET);
488 const auto regtestBaseParams = CreateBaseChainParams(ChainType::REGTEST);
489 const auto defaultChainParams = CreateChainParams(argsman, ChainType::MAIN);
490 const auto testnetChainParams =
492 const auto regtestChainParams =
494
495 // Hidden Options
496 std::vector<std::string> hidden_args = {
497 "-dbcrashratio",
498 "-forcecompactdb",
499 "-maxaddrtosend",
500 "-parkdeepreorg",
501 "-automaticunparking",
502 "-replayprotectionactivationtime",
503 "-enableminerfund",
504 "-chronikallowpause",
505 "-chronikcors",
506 // GUI args. These will be overwritten by SetupUIArgs for the GUI
507 "-allowselfsignedrootcertificates",
508 "-choosedatadir",
509 "-lang=<lang>",
510 "-min",
511 "-resetguisettings",
512 "-rootcertificates=<file>",
513 "-splash",
514 "-uiplatform",
515 // TODO remove after the November 2026 upgrade
516 "-mengeractivationtime",
517 };
518
519 // Set all of the args and their help
520 // When adding new options to the categories, please keep and ensure
521 // alphabetical ordering. Do not translate _(...) -help-debug options, Many
522 // technical terms, and only a very small audience, so is unnecessary stress
523 // to translators.
524 argsman.AddArg("-version", "Print version and exit", ArgsManager::ALLOW_ANY,
526#if defined(HAVE_SYSTEM)
527 argsman.AddArg(
528 "-alertnotify=<cmd>",
529 "Execute command when a relevant alert is received or we see "
530 "a really long fork (%s in cmd is replaced by message)",
532#endif
533 argsman.AddArg(
534 "-assumevalid=<hex>",
535 strprintf(
536 "If this block is in the chain assume that it and its ancestors "
537 "are valid and potentially skip their script verification (0 to "
538 "verify all, default: %s, testnet: %s)",
539 defaultChainParams->GetConsensus().defaultAssumeValid.GetHex(),
540 testnetChainParams->GetConsensus().defaultAssumeValid.GetHex()),
542 argsman.AddArg("-blocksdir=<dir>",
543 "Specify directory to hold blocks subdirectory for *.dat "
544 "files (default: <datadir>)",
546 argsman.AddArg("-fastprune",
547 "Use smaller block files and lower minimum prune height for "
548 "testing purposes",
551#if defined(HAVE_SYSTEM)
552 argsman.AddArg("-blocknotify=<cmd>",
553 "Execute command when the best block changes (%s in cmd is "
554 "replaced by block hash)",
556#endif
557 argsman.AddArg("-blockreconstructionextratxn=<n>",
558 strprintf("Extra transactions to keep in memory for compact "
559 "block reconstructions (default: %u)",
562 argsman.AddArg(
563 "-blocksonly",
564 strprintf("Whether to reject transactions from network peers. "
565 "Disables automatic broadcast and rebroadcast of "
566 "transactions, unless the source peer has the "
567 "'forcerelay' permission. RPC transactions are"
568 " not affected. (default: %u)",
571 argsman.AddArg("-coinstatsindex",
572 strprintf("Maintain coinstats index used by the "
573 "gettxoutsetinfo RPC (default: %u)",
576 argsman.AddArg(
577 "-conf=<file>",
578 strprintf("Specify path to read-only configuration file. Relative "
579 "paths will be prefixed by datadir location. (default: %s)",
582 argsman.AddArg("-datadir=<dir>", "Specify data directory",
584 argsman.AddArg(
585 "-dbbatchsize",
586 strprintf("Maximum database write batch size in bytes (default: %u)",
590 argsman.AddArg("-dbcache=<n>",
591 strprintf("Maximum database cache size <n> MiB (minimum %d, "
592 "default: %d). Make sure you have enough RAM. In "
593 "addition, unused memory allocated to the mempool "
594 "is shared with this cache (see -maxmempool).",
595 MIN_DB_CACHE >> 20, DEFAULT_DB_CACHE >> 20),
597 argsman.AddArg(
598 "-includeconf=<file>",
599 "Specify additional configuration file, relative to the -datadir path "
600 "(only useable from configuration file, not command line)",
602 argsman.AddArg("-allowignoredconf",
603 strprintf("For backwards compatibility, treat an unused %s "
604 "file in the datadir as a warning, not an error.",
607 argsman.AddArg("-loadblock=<file>",
608 "Imports blocks from external file on startup",
610 argsman.AddArg("-maxmempool=<n>",
611 strprintf("Keep the transaction memory pool below <n> "
612 "megabytes (default: %u)",
615 argsman.AddArg("-maxorphantx=<n>",
616 strprintf("Keep at most <n> unconnectable transactions in "
617 "memory (default: %u)",
620 argsman.AddArg("-mempoolexpiry=<n>",
621 strprintf("Do not keep transactions in the mempool longer "
622 "than <n> hours (default: %u)",
625 argsman.AddArg(
626 "-minimumchainwork=<hex>",
627 strprintf(
628 "Minimum work assumed to exist on a valid chain in hex "
629 "(default: %s, testnet: %s)",
630 defaultChainParams->GetConsensus().nMinimumChainWork.GetHex(),
631 testnetChainParams->GetConsensus().nMinimumChainWork.GetHex()),
634 argsman.AddArg(
635 "-par=<n>",
636 strprintf("Set the number of script verification threads (0 = auto, "
637 "up to %d, <0 = leave that many cores free, default: %d)",
640 argsman.AddArg("-persistmempool",
641 strprintf("Whether to save the mempool on shutdown and load "
642 "on restart (default: %u)",
645 argsman.AddArg(
646 "-persistrecentheaderstime",
647 strprintf(
648 "Whether the node stores the recent headers reception time to a "
649 "file and load it upon startup. This is intended for mining nodes "
650 "to overestimate the real time target upon restart (default: %u)",
653 argsman.AddArg(
654 "-pid=<file>",
655 strprintf("Specify pid file. Relative paths will be prefixed "
656 "by a net-specific datadir location. (default: %s)",
659 argsman.AddArg(
660 "-prune=<n>",
661 strprintf("Reduce storage requirements by enabling pruning (deleting) "
662 "of old blocks. This allows the pruneblockchain RPC to be "
663 "called to delete specific blocks and enables automatic "
664 "pruning of old blocks if a target size in MiB is provided. "
665 "This mode is incompatible with -txindex and -rescan. "
666 "Warning: Reverting this setting requires re-downloading the "
667 "entire blockchain. (default: 0 = disable pruning blocks, "
668 "1 = allow manual pruning via RPC, >=%u = automatically "
669 "prune block files to stay under the specified target size "
670 "in MiB)",
671 MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024),
673 argsman.AddArg(
674 "-reindex-chainstate",
675 "Rebuild chain state from the currently indexed blocks. When "
676 "in pruning mode or if blocks on disk might be corrupted, use "
677 "full -reindex instead.",
679 argsman.AddArg(
680 "-reindex",
681 "Rebuild chain state and block index from the blk*.dat files on disk."
682 " This will also rebuild active optional indexes.",
684 argsman.AddArg(
685 "-settings=<file>",
686 strprintf(
687 "Specify path to dynamic settings data file. Can be disabled with "
688 "-nosettings. File is written at runtime and not meant to be "
689 "edited by users (use %s instead for custom settings). Relative "
690 "paths will be prefixed by datadir location. (default: %s)",
693#if HAVE_SYSTEM
694 argsman.AddArg("-startupnotify=<cmd>", "Execute command on startup.",
696 argsman.AddArg(
697 "-shutdownnotify=<cmd>",
698 "Execute command immediately before beginning shutdown. The need for "
699 "shutdown may be urgent, so be careful not to delay it long (if the "
700 "command doesn't require interaction with the server, consider having "
701 "it fork into the background).",
703#endif
704#ifndef WIN32
705 argsman.AddArg(
706 "-sysperms",
707 "Create new files with system default permissions, instead of umask "
708 "077 (only effective with disabled wallet functionality)",
710#else
711 hidden_args.emplace_back("-sysperms");
712#endif
713 argsman.AddArg("-txindex",
714 strprintf("Maintain a full transaction index, used by the "
715 "getrawtransaction rpc call (default: %d)",
718#if ENABLE_CHRONIK
719 argsman.AddArg(
720 "-chronik",
721 strprintf("Enable the Chronik indexer, which can be read via a "
722 "dedicated HTTP/Protobuf interface (default: %d)",
725 argsman.AddArg(
726 "-chronikbind=<addr>[:port]",
727 strprintf(
728 "Bind the Chronik indexer to the given address to listen for "
729 "HTTP/Protobuf connections to access the index. Unlike the "
730 "JSON-RPC, it's ok to have this publicly exposed on the internet. "
731 "This option can be specified multiple times (default: %s; default "
732 "port: %u, testnet: %u, regtest: %u)",
733 Join(chronik::DEFAULT_BINDS, ", "),
734 defaultBaseParams->ChronikPort(), testnetBaseParams->ChronikPort(),
735 regtestBaseParams->ChronikPort()),
739 argsman.AddArg("-chroniktokenindex",
740 "Enable token indexing in Chronik (default: 1)",
742 argsman.AddArg("-chroniklokadidindex",
743 "Enable LOKAD ID indexing in Chronik (default: 1)",
745 argsman.AddArg("-chronikreindex",
746 "Reindex the Chronik indexer from genesis, but leave the "
747 "other indexes untouched",
749 argsman.AddArg(
750 "-chroniktxnumcachebuckets",
751 strprintf(
752 "Tuning param of the TxNumCache, specifies how many buckets "
753 "to use on the belt. Caution against setting this too high, "
754 "it may slow down indexing. Set to 0 to disable. (default: %d)",
755 chronik::DEFAULT_TX_NUM_CACHE_BUCKETS),
758 argsman.AddArg(
759 "-chroniktxnumcachebucketsize",
760 strprintf(
761 "Tuning param of the TxNumCache, specifies the size of each bucket "
762 "on the belt. Unlike the number of buckets, this may be increased "
763 "without much danger of slowing the indexer down. The total cache "
764 "size will be `num_buckets * bucket_size * 40B`, so by default the "
765 "cache will require %dkB of memory. (default: %d)",
766 chronik::DEFAULT_TX_NUM_CACHE_BUCKETS *
767 chronik::DEFAULT_TX_NUM_CACHE_BUCKET_SIZE * 40 / 1000,
768 chronik::DEFAULT_TX_NUM_CACHE_BUCKET_SIZE),
771 argsman.AddArg("-chronikperfstats",
772 "Output some performance statistics (e.g. num cache hits, "
773 "seconds spent) into a <datadir>/perf folder. (default: 0)",
775 argsman.AddArg("-chronikscripthashindex",
776 "Enable the scripthash index for the Chronik indexer "
777 "(default: 1 if chronikelectrumbind is set, 0 otherwise) ",
779 argsman.AddArg(
780 "-chronikelectrumbind=<addr>[:port][:t|s|w|y]",
781 strprintf(
782 "Bind the Chronik Electrum interface to the given "
783 "address:port:protocol. If not set, the Electrum interface will "
784 "not start. This option can be specified multiple times. The "
785 "protocol is selected by a single letter, where 't' means TCP, 's' "
786 "means TLS, 'w' means WS and 'y' means WSS. If TLS and/or WSS is "
787 "selected, the certificate chain and private key must both be "
788 "passed (see -chronikelectrumcert and -chronikelectrumprivkey "
789 "(default: disabled; default port: %u, testnet: %u, regtest: %u; "
790 "default protocol: TLS)",
791 defaultBaseParams->ChronikElectrumPort(),
792 testnetBaseParams->ChronikElectrumPort(),
793 regtestBaseParams->ChronikElectrumPort()),
797 argsman.AddArg(
798 "-chronikelectrumcert",
799 "Path to the certificate file to be used by the Chronik Electrum "
800 "server when the TLS protocol is selected. The file should contain "
801 "the whole certificate chain (typically a .pem file). If used the "
802 "-chronikelectrumprivkey must be set as well.",
806 argsman.AddArg(
807 "-chronikelectrumprivkey",
808 "Path to the private key file to be used by the Chronik Electrum "
809 "server when the TLS protocol is selected. If used the "
810 "-chronikelectrumcert must be set as well.",
814 argsman.AddArg(
815 "-chronikelectrumurl",
816 "The URL to advertise to the Electrum peers. This needs to be set to "
817 "the server public URL to instruct the other Electrum peers that they "
818 "don't have to drop the connection. See the 'hosts' key in "
819 "https://electrum-cash-protocol.readthedocs.io/en/latest/"
820 "protocol-methods.html#server.features (default: 127.0.0.1).",
824 argsman.AddArg(
825 "-chronikelectrummaxhistory",
826 strprintf("Largest tx history we are willing to serve. (default: %u)",
827 chronik::DEFAULT_ELECTRUM_MAX_HISTORY),
830 argsman.AddArg(
831 "-chronikelectrumdonationaddress",
832 strprintf(
833 "The server donation address. No checks are done on the server "
834 "side to ensure this is a valid eCash address, it is just relayed "
835 "to clients verbatim as a text string (%u characters maximum).",
836 chronik::MAX_LENGTH_DONATION_ADDRESS),
839 argsman.AddArg(
840 "-chronikelectrumpeersvalidationinterval",
841 strprintf(
842 "The peers submitted via the Chronik Electrum server.add_peer "
843 "endpoint are periodically checked for validity and are only "
844 "returned after they passed the validation. This option controls "
845 "the interval duration between successive peers validation "
846 "processes in seconds (default: %u). Setting this value to 0 "
847 "disables the peer validation completely.",
848 std::chrono::duration_cast<std::chrono::seconds>(
849 chronik::DEFAULT_ELECTRUM_PEER_VALIDATION_INTERVAL)
850 .count()),
853 argsman.AddArg(
854 "-chronikelectrumidletimeout",
855 strprintf(
856 "Drop Chronik Electrum clients that send no data for this many "
857 "seconds (default: %u). Set to 0 to disable. Healthy Electrum ABC "
858 "clients send server.ping every 5 minutes, so the default keeps "
859 "them connected while reclaiming silent or abandoned sessions.",
860 std::chrono::duration_cast<std::chrono::seconds>(
861 chronik::DEFAULT_ELECTRUM_IDLE_TIMEOUT)
862 .count()),
865 argsman.AddArg(
866 "-chronikmaxsubs",
867 strprintf(
868 "Maximum number of simultaneous Chronik subscriptions (WebSocket "
869 "and Electrum) across all clients (default: %u).",
870 chronik::DEFAULT_MAX_SUBS),
873 argsman.AddArg(
874 "-chronikmaxsubsperip",
875 strprintf(
876 "Maximum number of simultaneous Chronik subscriptions (WebSocket "
877 "and Electrum) per client IP address (default: %u).",
878 chronik::DEFAULT_MAX_SUBS_PER_IP),
881 argsman.AddArg(
882 "-chroniksubsmaxscriptsize",
883 strprintf("Maximum script size in bytes for Chronik WebSocket script "
884 "subscriptions (default: %u).",
885 chronik::DEFAULT_SUBSCRIPTION_MAX_SCRIPT_SIZE),
888 argsman.AddArg(
889 "-chroniksubsmaxpluginsize",
890 strprintf("Maximum plugin group size in bytes for Chronik WebSocket "
891 "plugin subscriptions (default: %u).",
892 chronik::DEFAULT_SUBSCRIPTION_MAX_PLUGIN_SIZE),
895#endif
896 argsman.AddArg(
897 "-blockfilterindex=<type>",
898 strprintf("Maintain an index of compact filters by block "
899 "(default: %s, values: %s).",
901 " If <type> is not supplied or if <type> = 1, indexes for "
902 "all known types are enabled.",
904 argsman.AddArg(
905 "-usecashaddr",
906 strprintf("Use Cash Address for destination encoding instead of legacy "
907 "base58 addresses (default: %d)",
910
911 argsman.AddArg(
912 "-addnode=<ip>",
913 "Add a node to connect to and attempt to keep the connection "
914 "open (see the `addnode` RPC command help for more info)",
917 argsman.AddArg("-asmap=<file>",
918 strprintf("Specify asn mapping used for bucketing of the "
919 "peers (default: %s). Relative paths will be "
920 "prefixed by the net-specific datadir location.",
923 argsman.AddArg("-bantime=<n>",
924 strprintf("Default duration (in seconds) of manually "
925 "configured bans (default: %u)",
928 argsman.AddArg(
929 "-bind=<addr>[:<port>][=onion]",
930 strprintf("Bind to given address and always listen on it (default: "
931 "0.0.0.0). Use [host]:port notation for IPv6. Append =onion "
932 "to tag any incoming connections to that address and port as "
933 "incoming Tor connections (default: 127.0.0.1:%u=onion, "
934 "testnet: 127.0.0.1:%u=onion, regtest: 127.0.0.1:%u=onion)",
935 defaultBaseParams->OnionServiceTargetPort(),
936 testnetBaseParams->OnionServiceTargetPort(),
937 regtestBaseParams->OnionServiceTargetPort()),
940 argsman.AddArg(
941 "-connect=<ip>",
942 "Connect only to the specified node(s); -noconnect disables automatic "
943 "connections (the rules for this peer are the same as for -addnode)",
946 argsman.AddArg(
947 "-discover",
948 "Discover own IP addresses (default: 1 when listening and no "
949 "-externalip or -proxy)",
951 argsman.AddArg("-dns",
952 strprintf("Allow DNS lookups for -addnode, -seednode and "
953 "-connect (default: %d)",
956 argsman.AddArg(
957 "-dnsseed",
958 strprintf(
959 "Query for peer addresses via DNS lookup, if low on addresses "
960 "(default: %u unless -connect used)",
963 argsman.AddArg("-externalip=<ip>", "Specify your own public address",
965 argsman.AddArg(
966 "-fixedseeds",
967 strprintf(
968 "Allow fixed seeds if DNS seeds don't provide peers (default: %u)",
971 argsman.AddArg(
972 "-forcednsseed",
973 strprintf(
974 "Always query for peer addresses via DNS lookup (default: %d)",
977 argsman.AddArg("-overridednsseed",
978 "If set, only use the specified DNS seed when "
979 "querying for peer addresses via DNS lookup.",
981 argsman.AddArg(
982 "-listen",
983 "Accept connections from outside (default: 1 if no -proxy or -connect)",
985 argsman.AddArg(
986 "-listenonion",
987 strprintf("Automatically create Tor onion service (default: %d)",
990 argsman.AddArg(
991 "-maxconnections=<n>",
992 strprintf("Maintain at most <n> connections to peers. The effective "
993 "limit depends on system limitations and might be lower than "
994 "the specified value (default: %u)",
997 argsman.AddArg("-maxreceivebuffer=<n>",
998 strprintf("Maximum per-connection receive buffer, <n>*1000 "
999 "bytes (default: %u)",
1002 argsman.AddArg(
1003 "-maxsendbuffer=<n>",
1004 strprintf(
1005 "Maximum per-connection send buffer, <n>*1000 bytes (default: %u)",
1008 argsman.AddArg(
1009 "-maxtimeadjustment",
1010 strprintf("Maximum allowed median peer time offset adjustment. Local "
1011 "perspective of time may be influenced by peers forward or "
1012 "backward by this amount. (default: %u seconds)",
1015#if HAVE_SOCKADDR_UN
1016 argsman.AddArg("-onion=<ip:port|path>",
1017 "Use separate SOCKS5 proxy to reach peers via Tor onion "
1018 "services, set -noonion to disable (default: -proxy). May "
1019 "be a local file path prefixed with 'unix:'.",
1021#else
1022 argsman.AddArg(
1023 "-onion=<ip:port>",
1024 strprintf("Use separate SOCKS5 proxy to reach peers via Tor "
1025 "onion services, set -noonion to disable (default: %s)",
1026 "-proxy"),
1028#endif
1029 argsman.AddArg("-i2psam=<ip:port>",
1030 "I2P SAM proxy to reach I2P peers and accept I2P "
1031 "connections (default: none)",
1033 argsman.AddArg(
1034 "-i2pacceptincoming",
1035 "If set and -i2psam is also set then incoming I2P connections are "
1036 "accepted via the SAM proxy. If this is not set but -i2psam is set "
1037 "then only outgoing connections will be made to the I2P network. "
1038 "Ignored if -i2psam is not set. Listening for incoming I2P connections "
1039 "is done through the SAM proxy, not by binding to a local address and "
1040 "port (default: 1)",
1042
1043 argsman.AddArg(
1044 "-onlynet=<net>",
1045 "Make outgoing connections only through network <net> (" +
1046 Join(GetNetworkNames(), ", ") +
1047 "). Incoming connections are not affected by this option. This "
1048 "option can be specified multiple times to allow multiple "
1049 "networks.",
1051 argsman.AddArg("-peerbloomfilters",
1052 strprintf("Support filtering of blocks and transaction with "
1053 "bloom filters (default: %d)",
1056 argsman.AddArg(
1057 "-peerblockfilters",
1058 strprintf(
1059 "Serve compact block filters to peers per BIP 157 (default: %u)",
1062 argsman.AddArg("-permitbaremultisig",
1063 strprintf("Relay non-P2SH multisig (default: %d)",
1066 // TODO: remove the sentence "Nodes not using ... incoming connections."
1067 // once the changes from https://github.com/bitcoin/bitcoin/pull/23542 have
1068 // become widespread.
1069 argsman.AddArg("-port=<port>",
1070 strprintf("Listen for connections on <port>. Nodes not "
1071 "using the default ports (default: %u, "
1072 "testnet: %u, regtest: %u) are unlikely to get "
1073 "incoming connections. Not relevant for I2P (see "
1074 "doc/i2p.md).",
1075 defaultChainParams->GetDefaultPort(),
1076 testnetChainParams->GetDefaultPort(),
1077 regtestChainParams->GetDefaultPort()),
1080#if HAVE_SOCKADDR_UN
1081 argsman.AddArg("-proxy=<ip:port|path>",
1082 "Connect through SOCKS5 proxy, set -noproxy to disable "
1083 "(default: disabled). May be a local file path prefixed "
1084 "with 'unix:' if the proxy supports it.",
1087#else
1088 argsman.AddArg("-proxy=<ip:port>",
1089 "Connect through SOCKS5 proxy, set -noproxy to disable "
1090 "(default: disabled)",
1093#endif
1094 argsman.AddArg(
1095 "-proxyrandomize",
1096 strprintf("Randomize credentials for every proxy connection. "
1097 "This enables Tor stream isolation (default: %d)",
1100 argsman.AddArg(
1101 "-seednode=<ip>",
1102 "Connect to a node to retrieve peer addresses, and disconnect",
1104 argsman.AddArg(
1105 "-networkactive",
1106 "Enable all P2P network activity (default: 1). Can be changed "
1107 "by the setnetworkactive RPC command",
1109 argsman.AddArg("-timeout=<n>",
1110 strprintf("Specify connection timeout in milliseconds "
1111 "(minimum: 1, default: %d)",
1114 argsman.AddArg(
1115 "-peertimeout=<n>",
1116 strprintf("Specify p2p connection timeout in seconds. This option "
1117 "determines the amount of time a peer may be inactive before "
1118 "the connection to it is dropped. (minimum: 1, default: %d)",
1121 argsman.AddArg(
1122 "-torcontrol=<ip>:<port>",
1123 strprintf(
1124 "Tor control port to use if onion listening enabled (default: %s)",
1127 argsman.AddArg("-torpassword=<pass>",
1128 "Tor control port password (default: empty)",
1131 // UPnP support was dropped. We keep `-upnp` as a hidden arg to display a
1132 // more user friendly error when set. TODO: remove (here and below) for
1133 // 0.34.0.
1134 argsman.AddArg("-upnp", "", ArgsManager::ALLOW_ANY,
1136 argsman.AddArg(
1137 "-natpmp",
1138 strprintf("Use PCP or NAT-PMP to map the listening port (default: %u)",
1141 argsman.AddArg(
1142 "-whitebind=<[permissions@]addr>",
1143 "Bind to the given address and add permission flags to the peers "
1144 "connecting to it."
1145 "Use [host]:port notation for IPv6. Allowed permissions: " +
1146 Join(NET_PERMISSIONS_DOC, ", ") +
1147 ". "
1148 "Specify multiple permissions separated by commas (default: "
1149 "download,noban,mempool,relay). Can be specified multiple times.",
1151
1152 argsman.AddArg("-whitelist=<[permissions@]IP address or network>",
1153 "Add permission flags to the peers using the given "
1154 "IP address (e.g. 1.2.3.4) or CIDR-notated network "
1155 "(e.g. 1.2.3.0/24). "
1156 "Uses the same permissions as -whitebind. "
1157 "Additional flags \"in\" and \"out\" control whether "
1158 "permissions apply to incoming connections and/or manual "
1159 "(default: incoming only). "
1160 "Can be specified multiple times.",
1162 argsman.AddArg(
1163 "-maxuploadtarget=<n>",
1164 strprintf("Tries to keep outbound traffic under the given target (in "
1165 "MiB per 24h). Limit does not apply to peers with 'download' "
1166 "permission. 0 = no limit (default: %d)",
1169
1171
1172#if ENABLE_ZMQ
1173 argsman.AddArg("-zmqpubhashblock=<address>",
1174 "Enable publish hash block in <address>",
1176 argsman.AddArg("-zmqpubhashtx=<address>",
1177 "Enable publish hash transaction in <address>",
1179 argsman.AddArg("-zmqpubrawblock=<address>",
1180 "Enable publish raw block in <address>",
1182 argsman.AddArg("-zmqpubrawtx=<address>",
1183 "Enable publish raw transaction in <address>",
1185 argsman.AddArg("-zmqpubsequence=<address>",
1186 "Enable publish hash block and tx sequence in <address>",
1188 argsman.AddArg(
1189 "-zmqpubhashblockhwm=<n>",
1190 strprintf("Set publish hash block outbound message high water "
1191 "mark (default: %d)",
1194 argsman.AddArg(
1195 "-zmqpubhashtxhwm=<n>",
1196 strprintf("Set publish hash transaction outbound message high "
1197 "water mark (default: %d)",
1199 false, OptionsCategory::ZMQ);
1200 argsman.AddArg(
1201 "-zmqpubrawblockhwm=<n>",
1202 strprintf("Set publish raw block outbound message high water "
1203 "mark (default: %d)",
1206 argsman.AddArg(
1207 "-zmqpubrawtxhwm=<n>",
1208 strprintf("Set publish raw transaction outbound message high "
1209 "water mark (default: %d)",
1212 argsman.AddArg("-zmqpubsequencehwm=<n>",
1213 strprintf("Set publish hash sequence message high water mark"
1214 " (default: %d)",
1217#else
1218 hidden_args.emplace_back("-zmqpubhashblock=<address>");
1219 hidden_args.emplace_back("-zmqpubhashtx=<address>");
1220 hidden_args.emplace_back("-zmqpubrawblock=<address>");
1221 hidden_args.emplace_back("-zmqpubrawtx=<address>");
1222 hidden_args.emplace_back("-zmqpubsequence=<n>");
1223 hidden_args.emplace_back("-zmqpubhashblockhwm=<n>");
1224 hidden_args.emplace_back("-zmqpubhashtxhwm=<n>");
1225 hidden_args.emplace_back("-zmqpubrawblockhwm=<n>");
1226 hidden_args.emplace_back("-zmqpubrawtxhwm=<n>");
1227 hidden_args.emplace_back("-zmqpubsequencehwm=<n>");
1228#endif
1229
1230 argsman.AddArg(
1231 "-checkblocks=<n>",
1232 strprintf("How many blocks to check at startup (default: %u, 0 = all)",
1236 argsman.AddArg("-checklevel=<n>",
1237 strprintf("How thorough the block verification of "
1238 "-checkblocks is: %s (0-4, default: %u)",
1242 argsman.AddArg("-checkblockindex",
1243 strprintf("Do a consistency check for the block tree, "
1244 "chainstate, and other validation data structures "
1245 " every <n> operations. Use 0 to disable. "
1246 "(default: %u, regtest: %u)",
1247 defaultChainParams->DefaultConsistencyChecks(),
1248 regtestChainParams->DefaultConsistencyChecks()),
1251 argsman.AddArg("-checkaddrman=<n>",
1252 strprintf("Run addrman consistency checks every <n> "
1253 "operations. Use 0 to disable. (default: %u)",
1257 argsman.AddArg(
1258 "-checkmempool=<n>",
1259 strprintf("Run mempool consistency checks every <n> transactions. Use "
1260 "0 to disable. (default: %u, regtest: %u)",
1261 defaultChainParams->DefaultConsistencyChecks(),
1262 regtestChainParams->DefaultConsistencyChecks()),
1265 argsman.AddArg("-checkpoints",
1266 strprintf("Only accept block chain matching built-in "
1267 "checkpoints (default: %d)",
1271 argsman.AddArg("-deprecatedrpc=<method>",
1272 "Allows deprecated RPC method(s) to be used",
1275 argsman.AddArg(
1276 "-stopafterblockimport",
1277 strprintf("Stop running after importing blocks from disk (default: %d)",
1281 argsman.AddArg("-stopatheight",
1282 strprintf("Stop running after reaching the given height in "
1283 "the main chain (default: %u)",
1287 argsman.AddArg("-addrmantest", "Allows to test address relay on localhost",
1290 argsman.AddArg("-capturemessages", "Capture all P2P messages to disk",
1293 argsman.AddArg("-mocktime=<n>",
1294 "Replace actual time with " + UNIX_EPOCH_TIME +
1295 " (default: 0)",
1298 argsman.AddArg(
1299 "-maxsigcachesize=<n>",
1300 strprintf("Limit size of signature cache to <n> MiB (default: %u)",
1304 argsman.AddArg(
1305 "-maxscriptcachesize=<n>",
1306 strprintf("Limit size of script cache to <n> MiB (default: %u)",
1310 argsman.AddArg("-maxtipage=<n>",
1311 strprintf("Maximum tip age in seconds to consider node in "
1312 "initial block download (default: %u)",
1313 Ticks<std::chrono::seconds>(DEFAULT_MAX_TIP_AGE)),
1316
1317 argsman.AddArg("-uacomment=<cmt>",
1318 "Append comment to the user agent string",
1320 argsman.AddArg("-uaclientname=<clientname>", "Set user agent client name",
1322 argsman.AddArg("-uaclientversion=<clientversion>",
1323 "Set user agent client version", ArgsManager::ALLOW_ANY,
1325
1327
1328 argsman.AddArg(
1329 "-acceptnonstdtxn",
1330 strprintf(
1331 "Relay and mine \"non-standard\" transactions (%sdefault: %u)",
1332 "testnet/regtest only; ", defaultChainParams->RequireStandard()),
1335 argsman.AddArg("-excessiveblocksize=<n>",
1336 strprintf("Do not accept blocks larger than this limit, in "
1337 "bytes (default: %d)",
1341 const auto ticker = Currency::getTicker();
1342 argsman.AddArg(
1343 "-dustrelayfee=<amt>",
1344 strprintf("Fee rate (in %s/kB) used to define dust, the value of an "
1345 "output such that it will cost more than its value in "
1346 "fees at this fee rate to spend it. (default: %s)",
1350
1351 argsman.AddArg(
1352 "-bytespersigcheck",
1353 strprintf("Equivalent bytes per sigCheck in transactions for relay and "
1354 "mining (default: %u).",
1357 argsman.AddArg(
1358 "-bytespersigop",
1359 strprintf("DEPRECATED: Equivalent bytes per sigCheck in transactions "
1360 "for relay and mining (default: %u). This has been "
1361 "deprecated since v0.26.8 and will be removed in the future, "
1362 "please use -bytespersigcheck instead.",
1365 argsman.AddArg(
1366 "-datacarrier",
1367 strprintf("Relay and mine data carrier transactions (default: %d)",
1370 argsman.AddArg(
1371 "-datacarriersize",
1372 strprintf("Maximum size of data in data carrier transactions "
1373 "we relay and mine (default: %u)",
1376 argsman.AddArg(
1377 "-minrelaytxfee=<amt>",
1378 strprintf("Fees (in %s/kB) smaller than this are rejected for "
1379 "relaying, mining and transaction creation (default: %s)",
1382 argsman.AddArg(
1383 "-whitelistrelay",
1384 strprintf("Add 'relay' permission to whitelisted peers "
1385 "with default permissions. This will accept relayed "
1386 "transactions even when not relaying transactions "
1387 "(default: %d)",
1390 argsman.AddArg(
1391 "-whitelistforcerelay",
1392 strprintf("Add 'forcerelay' permission to whitelisted peers "
1393 "with default permissions. This will relay transactions "
1394 "even if the transactions were already in the mempool "
1395 "(default: %d)",
1398
1399 argsman.AddArg("-blockmaxsize=<n>",
1400 strprintf("Set maximum block size in bytes (default: %d)",
1403 argsman.AddArg(
1404 "-blockmintxfee=<amt>",
1405 strprintf("Set lowest fee rate (in %s/kB) for transactions to "
1406 "be included in block creation. (default: %s)",
1409 argsman.AddArg("-simplegbt",
1410 "Use a simplified getblocktemplate output (default: 0)",
1412
1413 argsman.AddArg("-blockversion=<n>",
1414 "Override block version to test forking scenarios",
1417
1418 argsman.AddArg("-server", "Accept command line and JSON-RPC commands",
1420 argsman.AddArg("-rest",
1421 strprintf("Accept public REST requests (default: %d)",
1424 argsman.AddArg(
1425 "-rpcbind=<addr>[:port]",
1426 "Bind to given address to listen for JSON-RPC connections. Do not "
1427 "expose the RPC server to untrusted networks such as the public "
1428 "internet! This option is ignored unless -rpcallowip is also passed. "
1429 "Port is optional and overrides -rpcport. Use [host]:port notation "
1430 "for IPv6. This option can be specified multiple times (default: "
1431 "127.0.0.1 and ::1 i.e., localhost)",
1435 argsman.AddArg(
1436 "-rpcdoccheck",
1437 strprintf("Throw a non-fatal error at runtime if the documentation for "
1438 "an RPC is incorrect (default: %u)",
1441 argsman.AddArg(
1442 "-rpccookiefile=<loc>",
1443 "Location of the auth cookie. Relative paths will be prefixed "
1444 "by a net-specific datadir location. (default: data dir)",
1446 argsman.AddArg("-rpcuser=<user>", "Username for JSON-RPC connections",
1449 argsman.AddArg("-rpcpassword=<pw>", "Password for JSON-RPC connections",
1452 argsman.AddArg(
1453 "-rpcwhitelist=<whitelist>",
1454 "Set a whitelist to filter incoming RPC calls for a specific user. The "
1455 "field <whitelist> comes in the format: <USERNAME>:<rpc 1>,<rpc "
1456 "2>,...,<rpc n>. If multiple whitelists are set for a given user, they "
1457 "are set-intersected. See -rpcwhitelistdefault documentation for "
1458 "information on default whitelist behavior.",
1460 argsman.AddArg(
1461 "-rpcwhitelistdefault",
1462 "Sets default behavior for rpc whitelisting. Unless "
1463 "rpcwhitelistdefault is set to 0, if any -rpcwhitelist is set, the rpc "
1464 "server acts as if all rpc users are subject to "
1465 "empty-unless-otherwise-specified whitelists. If rpcwhitelistdefault "
1466 "is set to 1 and no -rpcwhitelist is set, rpc server acts as if all "
1467 "rpc users are subject to empty whitelists.",
1469 argsman.AddArg(
1470 "-rpcauth=<userpw>",
1471 "Username and HMAC-SHA-256 hashed password for JSON-RPC connections. "
1472 "The field <userpw> comes in the format: <USERNAME>:<SALT>$<HASH>. A "
1473 "canonical python script is included in share/rpcauth. The client then "
1474 "connects normally using the rpcuser=<USERNAME>/rpcpassword=<PASSWORD> "
1475 "pair of arguments. This option can be specified multiple times",
1477 argsman.AddArg("-rpcport=<port>",
1478 strprintf("Listen for JSON-RPC connections on <port> "
1479 "(default: %u, testnet: %u, regtest: %u)",
1480 defaultBaseParams->RPCPort(),
1481 testnetBaseParams->RPCPort(),
1482 regtestBaseParams->RPCPort()),
1485 argsman.AddArg(
1486 "-rpcallowip=<ip>",
1487 "Allow JSON-RPC connections from specified source. Valid for "
1488 "<ip> are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. "
1489 "1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24). "
1490 "This option can be specified multiple times",
1492 argsman.AddArg(
1493 "-rpcthreads=<n>",
1494 strprintf(
1495 "Set the number of threads to service RPC calls (default: %d)",
1498 argsman.AddArg(
1499 "-rpccorsdomain=value",
1500 "Domain from which to accept cross origin requests (browser enforced)",
1502
1503 argsman.AddArg("-rpcworkqueue=<n>",
1504 strprintf("Set the depth of the work queue to service RPC "
1505 "calls (default: %d)",
1509 argsman.AddArg("-rpcservertimeout=<n>",
1510 strprintf("Timeout during HTTP requests (default: %d)",
1514
1515#if HAVE_DECL_FORK
1516 argsman.AddArg("-daemon",
1517 strprintf("Run in the background as a daemon and accept "
1518 "commands (default: %d)",
1521 argsman.AddArg("-daemonwait",
1522 strprintf("Wait for initialization to be finished before "
1523 "exiting. This implies -daemon (default: %d)",
1526#else
1527 hidden_args.emplace_back("-daemon");
1528 hidden_args.emplace_back("-daemonwait");
1529#endif
1530
1531 // Avalanche options.
1532 argsman.AddArg("-avalanche",
1533 strprintf("Enable the avalanche feature (default: %u)",
1536 argsman.AddArg(
1537 "-avalanchestakingrewards",
1538 strprintf("Enable the avalanche staking rewards feature (default: %u, "
1539 "testnet: %u, regtest: %u)",
1540 defaultChainParams->GetConsensus().enableStakingRewards,
1541 testnetChainParams->GetConsensus().enableStakingRewards,
1542 regtestChainParams->GetConsensus().enableStakingRewards),
1544 argsman.AddArg("-avalanchestakingpreconsensus",
1545 strprintf("Enable the avalanche staking rewards "
1546 "preconsensus feature (default: %u)",
1549 argsman.AddArg(
1550 "-avalanchepreconsensus",
1551 strprintf("Enable the avalanche preconsensus feature (default: %u)",
1554 argsman.AddArg("-avalanchepreconsensusmining",
1555 strprintf("Enable mining only the avalanche finalized "
1556 "transactions (default: %u)",
1559 argsman.AddArg("-avalancheconflictingproofcooldown",
1560 strprintf("Mandatory cooldown before a proof conflicting "
1561 "with an already registered one can be considered "
1562 "in seconds (default: %u)",
1566 argsman.AddArg("-avalanchepeerreplacementcooldown",
1567 strprintf("Mandatory cooldown before a peer can be replaced "
1568 "in seconds (default: %u)",
1572 argsman.AddArg(
1573 "-avaminquorumstake",
1574 strprintf(
1575 "Minimum amount of known stake for a usable quorum (default: %s)",
1578 argsman.AddArg(
1579 "-avaminquorumconnectedstakeratio",
1580 strprintf("Minimum proportion of known stake we"
1581 " need nodes for to have a usable quorum (default: %s). "
1582 "This parameter is parsed with a maximum precision of "
1583 "0.000001.",
1587 argsman.AddArg(
1588 "-avaminavaproofsnodecount",
1589 strprintf("Minimum number of node that needs to send us an avaproofs"
1590 " message before we consider we have a usable quorum"
1591 " (default: %s)",
1595 argsman.AddArg(
1596 "-avastalevotethreshold",
1597 strprintf("Number of avalanche votes before a voted item goes stale "
1598 "when voting confidence is low (default: %u)",
1602 argsman.AddArg(
1603 "-avastalevotefactor",
1604 strprintf(
1605 "Factor affecting the number of avalanche votes before a voted "
1606 "item goes stale when voting confidence is high (default: %u)",
1610 argsman.AddArg("-avacooldown",
1611 strprintf("Mandatory cooldown between two avapoll in "
1612 "milliseconds (default: %u)",
1615 argsman.AddArg(
1616 "-avatimeout",
1617 strprintf("Avalanche query timeout in milliseconds (default: %u)",
1620 argsman.AddArg(
1621 "-avamaxelementpoll",
1622 strprintf("Maximum number of elements to include and accept in an "
1623 "avapoll (default: %u)",
1626 argsman.AddArg(
1627 "-avadelegation",
1628 "Avalanche proof delegation to the master key used by this node "
1629 "(default: none). Should be used in conjunction with -avaproof and "
1630 "-avamasterkey",
1632 argsman.AddArg("-avaproof",
1633 "Avalanche proof to be used by this node (default: none)",
1635 argsman.AddArg(
1636 "-avaproofstakeutxoconfirmations",
1637 strprintf(
1638 "Minimum number of confirmations before a stake utxo is mature"
1639 " enough to be included into a proof. Utxos in the mempool are not "
1640 "accepted (i.e this value must be greater than 0) (default: %s)",
1644 argsman.AddArg("-avaproofstakeutxodustthreshold",
1645 strprintf("Minimum value each stake utxo must have to be "
1646 "considered valid (default: %s)",
1649 argsman.AddArg("-avamasterkey",
1650 "Master key associated with the proof. If a proof is "
1651 "required, this is mandatory.",
1654 argsman.AddArg("-avasessionkey", "Avalanche session key (default: random)",
1657 argsman.AddArg("-enablertt",
1658 strprintf("Whether to enforce Real Time Targeting via "
1659 "Avalanche, default (%u)",
1662 argsman.AddArg(
1663 "-maxavalancheoutbound",
1664 strprintf(
1665 "Set the maximum number of avalanche outbound peers to connect to. "
1666 "Note that this option takes precedence over the -maxconnections "
1667 "option (default: %u).",
1671 argsman.AddArg(
1672 "-persistavapeers",
1673 strprintf("Whether to save the avalanche peers upon shutdown and load "
1674 "them upon startup (default: %u).",
1677
1678 // Add the hidden options
1679 argsman.AddHiddenArgs(hidden_args);
1680}
1681
1682static bool fHaveGenesis = false;
1684static std::condition_variable g_genesis_wait_cv;
1685
1686static void BlockNotifyGenesisWait(const CBlockIndex *pBlockIndex) {
1687 if (pBlockIndex != nullptr) {
1688 {
1690 fHaveGenesis = true;
1691 }
1692 g_genesis_wait_cv.notify_all();
1693 }
1694}
1695
1696#if HAVE_SYSTEM
1697static void StartupNotify(const ArgsManager &args) {
1698 std::string cmd = args.GetArg("-startupnotify", "");
1699 if (!cmd.empty()) {
1700 std::thread t(runCommand, cmd);
1701 // thread runs free
1702 t.detach();
1703 }
1704}
1705#endif
1706
1707static bool AppInitServers(Config &config,
1708 HTTPRPCRequestProcessor &httpRPCRequestProcessor,
1709 NodeContext &node) {
1710 const ArgsManager &args = *Assert(node.args);
1713 if (!InitHTTPServer(config)) {
1714 return false;
1715 }
1716
1717 StartRPC();
1718 node.rpc_interruption_point = RpcInterruptionPoint;
1719
1720 if (!StartHTTPRPC(httpRPCRequestProcessor)) {
1721 return false;
1722 }
1723 if (args.GetBoolArg("-rest", DEFAULT_REST_ENABLE)) {
1724 StartREST(&node);
1725 }
1726
1728 return true;
1729}
1730
1731// Parameter interaction based on rules
1733 // when specifying an explicit binding address, you want to listen on it
1734 // even when -connect or -proxy is specified.
1735 if (args.IsArgSet("-bind")) {
1736 if (args.SoftSetBoolArg("-listen", true)) {
1737 LogPrintf(
1738 "%s: parameter interaction: -bind set -> setting -listen=1\n",
1739 __func__);
1740 }
1741 }
1742 if (args.IsArgSet("-whitebind")) {
1743 if (args.SoftSetBoolArg("-listen", true)) {
1744 LogPrintf("%s: parameter interaction: -whitebind set -> setting "
1745 "-listen=1\n",
1746 __func__);
1747 }
1748 }
1749
1750 if (args.IsArgSet("-connect")) {
1751 // when only connecting to trusted nodes, do not seed via DNS, or listen
1752 // by default.
1753 if (args.SoftSetBoolArg("-dnsseed", false)) {
1754 LogPrintf("%s: parameter interaction: -connect set -> setting "
1755 "-dnsseed=0\n",
1756 __func__);
1757 }
1758 if (args.SoftSetBoolArg("-listen", false)) {
1759 LogPrintf("%s: parameter interaction: -connect set -> setting "
1760 "-listen=0\n",
1761 __func__);
1762 }
1763 }
1764
1765 if (args.IsArgSet("-proxy")) {
1766 // to protect privacy, do not listen by default if a default proxy
1767 // server is specified.
1768 if (args.SoftSetBoolArg("-listen", false)) {
1769 LogPrintf(
1770 "%s: parameter interaction: -proxy set -> setting -listen=0\n",
1771 __func__);
1772 }
1773 // to protect privacy, do not map ports when a proxy is set. The user
1774 // may still specify -listen=1 to listen locally, so don't rely on this
1775 // happening through -listen below.
1776 if (args.SoftSetBoolArg("-natpmp", false)) {
1777 LogPrintf(
1778 "%s: parameter interaction: -proxy set -> setting -natpmp=0\n",
1779 __func__);
1780 }
1781 // to protect privacy, do not discover addresses by default
1782 if (args.SoftSetBoolArg("-discover", false)) {
1783 LogPrintf("%s: parameter interaction: -proxy set -> setting "
1784 "-discover=0\n",
1785 __func__);
1786 }
1787 }
1788
1789 if (!args.GetBoolArg("-listen", DEFAULT_LISTEN)) {
1790 // do not map ports or try to retrieve public IP when not listening
1791 // (pointless)
1792 if (args.SoftSetBoolArg("-natpmp", false)) {
1793 LogPrintf(
1794 "%s: parameter interaction: -listen=0 -> setting -natpmp=0\n",
1795 __func__);
1796 }
1797 if (args.SoftSetBoolArg("-discover", false)) {
1798 LogPrintf(
1799 "%s: parameter interaction: -listen=0 -> setting -discover=0\n",
1800 __func__);
1801 }
1802 if (args.SoftSetBoolArg("-listenonion", false)) {
1803 LogPrintf("%s: parameter interaction: -listen=0 -> setting "
1804 "-listenonion=0\n",
1805 __func__);
1806 }
1807 if (args.SoftSetBoolArg("-i2pacceptincoming", false)) {
1808 LogPrintf("%s: parameter interaction: -listen=0 -> setting "
1809 "-i2pacceptincoming=0\n",
1810 __func__);
1811 }
1812 }
1813
1814 if (args.IsArgSet("-externalip")) {
1815 // if an explicit public IP is specified, do not try to find others
1816 if (args.SoftSetBoolArg("-discover", false)) {
1817 LogPrintf("%s: parameter interaction: -externalip set -> setting "
1818 "-discover=0\n",
1819 __func__);
1820 }
1821 }
1822
1823 // disable whitelistrelay in blocksonly mode
1824 if (args.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)) {
1825 if (args.SoftSetBoolArg("-whitelistrelay", false)) {
1826 LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting "
1827 "-whitelistrelay=0\n",
1828 __func__);
1829 }
1830 }
1831
1832 // Forcing relay from whitelisted hosts implies we will accept relays from
1833 // them in the first place.
1834 if (args.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
1835 if (args.SoftSetBoolArg("-whitelistrelay", true)) {
1836 LogPrintf("%s: parameter interaction: -whitelistforcerelay=1 -> "
1837 "setting -whitelistrelay=1\n",
1838 __func__);
1839 }
1840 }
1841
1842 // If avalanche is set, soft set all the feature flags accordingly.
1843 if (args.IsArgSet("-avalanche")) {
1844 const bool fAvalanche =
1845 args.GetBoolArg("-avalanche", AVALANCHE_DEFAULT_ENABLED);
1846 args.SoftSetBoolArg("-automaticunparking", !fAvalanche);
1847 }
1848}
1849
1856void InitLogging(const ArgsManager &args) {
1859}
1860
1861namespace { // Variables internal to initialization process only
1862
1863int nMaxConnections;
1864int nUserMaxConnections;
1865int nFD;
1867int64_t peer_connect_timeout;
1868std::set<BlockFilterType> g_enabled_filter_types;
1869
1870} // namespace
1871
1872[[noreturn]] static void new_handler_terminate() {
1873 // Rather than throwing std::bad-alloc if allocation fails, terminate
1874 // immediately to (try to) avoid chain corruption. Since LogPrintf may
1875 // itself allocate memory, set the handler directly to terminate first.
1876 std::set_new_handler(std::terminate);
1877 LogPrintf("Error: Out of memory. Terminating.\n");
1878
1879 // The log was successful, terminate now.
1880 std::terminate();
1881};
1882
1883bool AppInitBasicSetup(const ArgsManager &args, std::atomic<int> &exit_status) {
1884// Step 1: setup
1885#ifdef _MSC_VER
1886 // Turn off Microsoft heap dump noise
1887 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
1888 _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, nullptr,
1889 OPEN_EXISTING, 0, 0));
1890 // Disable confusing "helpful" text message on abort, Ctrl-C
1891 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
1892#endif
1893#ifdef WIN32
1894 // Enable Data Execution Prevention (DEP)
1895 SetProcessDEPPolicy(PROCESS_DEP_ENABLE);
1896#endif
1897 if (!SetupNetworking()) {
1898 return InitError(Untranslated("Initializing networking failed"));
1899 }
1900
1901#ifndef WIN32
1902 if (!args.GetBoolArg("-sysperms", false)) {
1903 umask(077);
1904 }
1905
1906 // Clean shutdown on SIGTERM
1909
1910 // Reopen debug.log on SIGHUP
1912
1913 // Ignore SIGPIPE, otherwise it will bring the daemon down if the client
1914 // closes unexpectedly
1915 signal(SIGPIPE, SIG_IGN);
1916#else
1917 SetConsoleCtrlHandler(consoleCtrlHandler, true);
1918#endif
1919
1920 std::set_new_handler(new_handler_terminate);
1921
1922 return true;
1923}
1924
1926 const CChainParams &chainparams = config.GetChainParams();
1927 // Step 2: parameter interactions
1928
1929 // also see: InitParameterInteraction()
1930
1931 // Error if network-specific options (-addnode, -connect, etc) are
1932 // specified in default section of config file, but not overridden
1933 // on the command line or in this chain's section of the config file.
1934 ChainType chain = args.GetChainType();
1935 bilingual_str errors;
1936 for (const auto &arg : args.GetUnsuitableSectionOnlyArgs()) {
1937 errors +=
1938 strprintf(_("Config setting for %s only applied on %s "
1939 "network when in [%s] section.") +
1940 Untranslated("\n"),
1941 arg, ChainTypeToString(chain), ChainTypeToString(chain));
1942 }
1943
1944 if (!errors.empty()) {
1945 return InitError(errors);
1946 }
1947
1948 // Warn if unrecognized section name are present in the config file.
1949 bilingual_str warnings;
1950 for (const auto &section : args.GetUnrecognizedSections()) {
1951 warnings += strprintf(Untranslated("%s:%i ") +
1952 _("Section [%s] is not recognized.") +
1953 Untranslated("\n"),
1954 section.m_file, section.m_line, section.m_name);
1955 }
1956
1957 if (!warnings.empty()) {
1958 InitWarning(warnings);
1959 }
1960
1961 if (!fs::is_directory(args.GetBlocksDirPath())) {
1962 return InitError(
1963 strprintf(_("Specified blocks directory \"%s\" does not exist."),
1964 args.GetArg("-blocksdir", "")));
1965 }
1966
1967 // parse and validate enabled filter types
1968 std::string blockfilterindex_value =
1969 args.GetArg("-blockfilterindex", DEFAULT_BLOCKFILTERINDEX);
1970 if (blockfilterindex_value == "" || blockfilterindex_value == "1") {
1971 g_enabled_filter_types = AllBlockFilterTypes();
1972 } else if (blockfilterindex_value != "0") {
1973 const std::vector<std::string> names =
1974 args.GetArgs("-blockfilterindex");
1975 for (const auto &name : names) {
1976 BlockFilterType filter_type;
1977 if (!BlockFilterTypeByName(name, filter_type)) {
1978 return InitError(
1979 strprintf(_("Unknown -blockfilterindex value %s."), name));
1980 }
1981 g_enabled_filter_types.insert(filter_type);
1982 }
1983 }
1984
1985 // Signal NODE_COMPACT_FILTERS if peerblockfilters and basic filters index
1986 // are both enabled.
1987 if (args.GetBoolArg("-peerblockfilters", DEFAULT_PEERBLOCKFILTERS)) {
1988 if (g_enabled_filter_types.count(BlockFilterType::BASIC) != 1) {
1989 return InitError(
1990 _("Cannot set -peerblockfilters without -blockfilterindex."));
1991 }
1992
1993 nLocalServices = ServiceFlags(nLocalServices | NODE_COMPACT_FILTERS);
1994 }
1995
1996 if (args.GetIntArg("-prune", 0)) {
1997 if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
1998 return InitError(_("Prune mode is incompatible with -txindex."));
1999 }
2000 if (args.GetBoolArg("-reindex-chainstate", false)) {
2001 return InitError(
2002 _("Prune mode is incompatible with -reindex-chainstate. Use "
2003 "full -reindex instead."));
2004 }
2005 if (args.GetBoolArg("-chronik", DEFAULT_CHRONIK)) {
2006 return InitError(_("Prune mode is incompatible with -chronik."));
2007 }
2008 }
2009
2010 // -bind and -whitebind can't be set when not listening
2011 size_t nUserBind =
2012 args.GetArgs("-bind").size() + args.GetArgs("-whitebind").size();
2013 if (nUserBind != 0 && !args.GetBoolArg("-listen", DEFAULT_LISTEN)) {
2014 return InitError(Untranslated(
2015 "Cannot set -bind or -whitebind together with -listen=0"));
2016 }
2017
2018 // Make sure enough file descriptors are available
2019 int nBind = std::max(nUserBind, size_t(1));
2020 nUserMaxConnections =
2021 args.GetIntArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
2022 nMaxConnections = std::max(nUserMaxConnections, 0);
2023
2024 // -maxavalancheoutbound takes precedence over -maxconnections
2025 const int maxAvalancheOutbound = args.GetIntArg(
2026 "-maxavalancheoutbound", DEFAULT_MAX_AVALANCHE_OUTBOUND_CONNECTIONS);
2027 const bool fAvalanche =
2028 args.GetBoolArg("-avalanche", AVALANCHE_DEFAULT_ENABLED);
2029 if (fAvalanche && maxAvalancheOutbound > nMaxConnections) {
2030 nMaxConnections = std::max(maxAvalancheOutbound, nMaxConnections);
2031 // Indicate the value set by the user
2032 LogPrintf("Increasing -maxconnections from %d to %d to comply with "
2033 "-maxavalancheoutbound\n",
2034 nUserMaxConnections, nMaxConnections);
2035 }
2036
2037 // Trim requested connection counts, to fit into system limitations
2038 // <int> in std::min<int>(...) to work around FreeBSD compilation issue
2039 // described in #2695
2041 nMaxConnections + nBind + MIN_CORE_FILEDESCRIPTORS +
2043#ifdef USE_POLL
2044 int fd_max = nFD;
2045#else
2046 int fd_max = FD_SETSIZE;
2047#endif
2048 nMaxConnections = std::max(
2049 std::min<int>(nMaxConnections,
2050 fd_max - nBind - MIN_CORE_FILEDESCRIPTORS -
2052 0);
2053 if (nFD < MIN_CORE_FILEDESCRIPTORS) {
2054 return InitError(_("Not enough file descriptors available."));
2055 }
2056 nMaxConnections =
2058 nMaxConnections);
2059
2060 if (nMaxConnections < nUserMaxConnections) {
2061 // Not categorizing as "Warning" because this is the normal behavior for
2062 // platforms using the select() interface for which FD_SETSIZE is
2063 // usually 1024.
2064 LogPrintf("Reducing -maxconnections from %d to %d, because of system "
2065 "limitations.\n",
2066 nUserMaxConnections, nMaxConnections);
2067 }
2068
2069 // Step 3: parameter-to-internal-flags
2072
2073 // Configure excessive block size.
2074 const int64_t nProposedExcessiveBlockSize =
2075 args.GetIntArg("-excessiveblocksize", DEFAULT_MAX_BLOCK_SIZE);
2076 if (nProposedExcessiveBlockSize <= 0 ||
2077 !config.SetMaxBlockSize(nProposedExcessiveBlockSize)) {
2078 return InitError(
2079 _("Excessive block size must be > 1,000,000 bytes (1MB)"));
2080 }
2081
2082 // Check blockmaxsize does not exceed maximum accepted block size.
2083 const int64_t nProposedMaxGeneratedBlockSize =
2084 args.GetIntArg("-blockmaxsize", DEFAULT_MAX_GENERATED_BLOCK_SIZE);
2085 if (nProposedMaxGeneratedBlockSize <= 0) {
2086 return InitError(_("Max generated block size must be greater than 0"));
2087 }
2088 if (uint64_t(nProposedMaxGeneratedBlockSize) > config.GetMaxBlockSize()) {
2089 return InitError(_("Max generated block size (blockmaxsize) cannot "
2090 "exceed the excessive block size "
2091 "(excessiveblocksize)"));
2092 }
2093
2095 if (nConnectTimeout <= 0) {
2097 }
2098
2099 peer_connect_timeout =
2100 args.GetIntArg("-peertimeout", DEFAULT_PEER_CONNECT_TIMEOUT);
2101 if (peer_connect_timeout <= 0) {
2102 return InitError(Untranslated(
2103 "peertimeout cannot be configured with a negative value."));
2104 }
2105
2106 // Sanity check argument for min fee for including tx in block
2107 // TODO: Harmonize which arguments need sanity checking and where that
2108 // happens.
2109 if (args.IsArgSet("-blockmintxfee")) {
2110 Amount n = Amount::zero();
2111 if (!ParseMoney(args.GetArg("-blockmintxfee", ""), n)) {
2112 return InitError(AmountErrMsg("blockmintxfee",
2113 args.GetArg("-blockmintxfee", "")));
2114 }
2115 }
2116
2118 args.IsArgSet("-bytespersigcheck")
2119 ? args.GetIntArg("-bytespersigcheck", nBytesPerSigCheck)
2120 : args.GetIntArg("-bytespersigop", nBytesPerSigCheck);
2121
2123 return false;
2124 }
2125
2126 // Option to startup with mocktime set (used for regression testing):
2127 SetMockTime(args.GetIntArg("-mocktime", 0)); // SetMockTime(0) is a no-op
2128
2129 if (args.GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS)) {
2130 nLocalServices = ServiceFlags(nLocalServices | NODE_BLOOM);
2131 }
2132
2133 // Avalanche parameters
2134 const int64_t stakeUtxoMinConfirmations =
2135 args.GetIntArg("-avaproofstakeutxoconfirmations",
2137
2138 if (!chainparams.IsTestChain() &&
2139 stakeUtxoMinConfirmations !=
2141 return InitError(_("Avalanche stake UTXO minimum confirmations can "
2142 "only be set on test chains."));
2143 }
2144
2145 if (stakeUtxoMinConfirmations <= 0) {
2146 return InitError(_("Avalanche stake UTXO minimum confirmations must be "
2147 "a positive integer."));
2148 }
2149
2150 if (args.IsArgSet("-avaproofstakeutxodustthreshold")) {
2151 Amount amount = Amount::zero();
2152 auto parsed = ParseMoney(
2153 args.GetArg("-avaproofstakeutxodustthreshold", ""), amount);
2154 if (!parsed || Amount::zero() == amount) {
2155 return InitError(AmountErrMsg(
2156 "avaproofstakeutxodustthreshold",
2157 args.GetArg("-avaproofstakeutxodustthreshold", "")));
2158 }
2159
2160 if (!chainparams.IsTestChain() &&
2162 return InitError(_("Avalanche stake UTXO dust threshold can "
2163 "only be set on test chains."));
2164 }
2165 }
2166
2167 // This is a staking node
2168 if (fAvalanche && args.IsArgSet("-avaproof")) {
2169 if (!args.GetBoolArg("-listen", true)) {
2170 return InitError(_("Running a staking node requires accepting "
2171 "inbound connections. Please enable -listen."));
2172 }
2173 if (args.IsArgSet("-proxy")) {
2174 return InitError(_("Running a staking node behind a proxy is not "
2175 "supported. Please disable -proxy."));
2176 }
2177 if (args.IsArgSet("-i2psam")) {
2178 return InitError(_("Running a staking node behind I2P is not "
2179 "supported. Please disable -i2psam."));
2180 }
2181 if (args.IsArgSet("-onlynet")) {
2182 return InitError(
2183 _("Restricting the outbound network is not supported when "
2184 "running a staking node. Please disable -onlynet."));
2185 }
2186 if (args.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)) {
2187 return InitError(
2188 _("Running a staking node in -blocksonly mode is not "
2189 "supported. Please disable -blocksonly."));
2190 }
2191 }
2192
2193 // Also report errors from parsing before daemonization
2194 {
2195 kernel::Notifications notifications{};
2196 ChainstateManager::Options chainman_opts_dummy{
2197 .config = config,
2198 .datadir = args.GetDataDirNet(),
2199 .notifications = notifications,
2200 };
2201 if (const auto error{ApplyArgsManOptions(args, chainman_opts_dummy)}) {
2202 return InitError(*error);
2203 }
2204 BlockManager::Options blockman_opts_dummy{
2205 .chainparams = chainman_opts_dummy.config.GetChainParams(),
2206 .blocks_dir = args.GetBlocksDirPath(),
2207 .notifications = chainman_opts_dummy.notifications,
2208 };
2209 if (const auto error{ApplyArgsManOptions(args, blockman_opts_dummy)}) {
2210 return InitError(*error);
2211 }
2212 }
2213
2214 return true;
2215}
2216
2217static bool LockDataDirectory(bool probeOnly) {
2218 // Make sure only a single Bitcoin process is using the data directory.
2219 const fs::path &datadir = gArgs.GetDataDirNet();
2220 switch (util::LockDirectory(datadir, ".lock", probeOnly)) {
2222 return InitError(
2223 strprintf(_("Cannot obtain a lock on data directory %s. %s is "
2224 "probably already running."),
2225 fs::PathToString(datadir), PACKAGE_NAME));
2227 return true;
2229 return InitError(strprintf(
2230 _("Cannot write to data directory '%s'; check permissions."),
2231 fs::PathToString(datadir)));
2232 } // no default case, so the compiler can warn about missing cases
2233 assert(false);
2234}
2235
2237 // Step 4: sanity checks
2238 auto result{kernel::SanityChecks(kernel)};
2239 if (!result) {
2241 return InitError(strprintf(
2242 _("Initialization sanity check failed. %s is shutting down."),
2243 PACKAGE_NAME));
2244 }
2245
2246 // Probe the data directory lock to give an early error message, if possible
2247 // We cannot hold the data directory lock here, as the forking for daemon()
2248 // hasn't yet happened, and a fork will cause weird behavior to it.
2249 return LockDataDirectory(true);
2250}
2251
2253 // After daemonization get the data directory lock again and hold on to it
2254 // until exit. This creates a slight window for a race condition to happen,
2255 // however this condition is harmless: it will at most make us exit without
2256 // printing a message to console.
2257 if (!LockDataDirectory(false)) {
2258 // Detailed error printed inside LockDataDirectory
2259 return false;
2260 }
2261 return true;
2262}
2263
2266 // Create client interfaces for wallets that are supposed to be loaded
2267 // according to -wallet and -disablewallet options. This only constructs
2268 // the interfaces, it doesn't load wallet data. Wallets actually get loaded
2269 // when load() and start() interface methods are called below.
2271 return true;
2272}
2273
2274bool AppInitMain(Config &config, RPCServer &rpcServer,
2275 HTTPRPCRequestProcessor &httpRPCRequestProcessor,
2278 // Step 4a: application initialization
2279 const ArgsManager &args = *Assert(node.args);
2280 const CChainParams &chainparams = config.GetChainParams();
2281
2282 if (!CreatePidFile(args)) {
2283 // Detailed error printed inside CreatePidFile().
2284 return false;
2285 }
2286 if (!init::StartLogging(args)) {
2287 // Detailed error printed inside StartLogging().
2288 return false;
2289 }
2290
2291 LogPrintf("Using at most %i automatic connections (%i file descriptors "
2292 "available)\n",
2293 nMaxConnections, nFD);
2294
2295 // Warn about relative -datadir path.
2296 if (args.IsArgSet("-datadir") &&
2297 !args.GetPathArg("-datadir").is_absolute()) {
2298 LogPrintf("Warning: relative datadir option '%s' specified, which will "
2299 "be interpreted relative to the current working directory "
2300 "'%s'. This is fragile, because if bitcoin is started in the "
2301 "future from a different location, it will be unable to "
2302 "locate the current data files. There could also be data "
2303 "loss if bitcoin is started while in a temporary "
2304 "directory.\n",
2305 args.GetArg("-datadir", ""),
2306 fs::PathToString(fs::current_path()));
2307 }
2308
2309 assert(!node.scheduler);
2310 node.scheduler = std::make_unique<CScheduler>();
2311 auto &scheduler = *node.scheduler;
2312
2313 // Start the lightweight task scheduler thread
2314 scheduler.m_service_thread =
2315 std::thread(&util::TraceThread, "scheduler",
2316 [&] { node.scheduler->serviceQueue(); });
2317
2318 // Gather some entropy once per minute.
2319 scheduler.scheduleEvery(
2320 [] {
2322 return true;
2323 },
2324 std::chrono::minutes{1});
2325
2326 if (args.GetBoolArg("-logratelimit", BCLog::DEFAULT_LOGRATELIMIT)) {
2328 [&scheduler](auto func, auto window) {
2329 scheduler.scheduleEvery(std::move(func), window);
2330 },
2332 } else {
2333 LogInfo("Log rate limiting disabled\n");
2334 }
2335
2336 // Check disk space every 5 minutes to avoid db corruption.
2337 scheduler.scheduleEvery(
2338 [&args] {
2339 constexpr uint64_t min_disk_space = 250_MiB;
2340 if (!CheckDiskSpace(args.GetBlocksDirPath(), min_disk_space)) {
2341 LogPrintf("Shutting down due to lack of disk space!\n");
2342 StartShutdown();
2343 }
2344 return true;
2345 },
2346 std::chrono::minutes{5});
2347
2348 assert(!node.validation_signals);
2349 node.validation_signals = std::make_unique<ValidationSignals>(
2350 std::make_unique<SerialTaskRunner>(scheduler));
2351 auto &validation_signals = *node.validation_signals;
2352
2357 RegisterAllRPCCommands(config, rpcServer, tableRPC);
2358 for (const auto &client : node.chain_clients) {
2359 client->registerRpcs();
2360 }
2361#if ENABLE_ZMQ
2363#endif
2364
2371 if (args.GetBoolArg("-server", false)) {
2372 uiInterface.InitMessage_connect(SetRPCWarmupStatus);
2373 if (!AppInitServers(config, httpRPCRequestProcessor, node)) {
2374 return InitError(
2375 _("Unable to start HTTP server. See debug log for details."));
2376 }
2377 }
2378
2379 // Step 5: verify wallet database integrity
2380 for (const auto &client : node.chain_clients) {
2381 if (!client->verify()) {
2382 return false;
2383 }
2384 }
2385
2386 // Step 6: network initialization
2387
2388 // Note that we absolutely cannot open any actual connections
2389 // until the very end ("start node") as the UTXO/block state
2390 // is not yet setup and may end up being set up twice if we
2391 // need to reindex later.
2392
2393 fListen = args.GetBoolArg("-listen", DEFAULT_LISTEN);
2394 fDiscover = args.GetBoolArg("-discover", true);
2395
2396 {
2397 // Initialize addrman
2398 assert(!node.addrman);
2399
2400 // Read asmap file if configured
2401 std::vector<bool> asmap;
2402 if (args.IsArgSet("-asmap")) {
2403 fs::path asmap_path =
2404 args.GetPathArg("-asmap", DEFAULT_ASMAP_FILENAME);
2405 if (!asmap_path.is_absolute()) {
2406 asmap_path = args.GetDataDirNet() / asmap_path;
2407 }
2408 if (!fs::exists(asmap_path)) {
2409 InitError(strprintf(_("Could not find asmap file %s"),
2410 fs::quoted(fs::PathToString(asmap_path))));
2411 return false;
2412 }
2413 asmap = DecodeAsmap(asmap_path);
2414 if (asmap.size() == 0) {
2415 InitError(strprintf(_("Could not parse asmap file %s"),
2416 fs::quoted(fs::PathToString(asmap_path))));
2417 return false;
2418 }
2419 const uint256 asmap_version = (HashWriter{} << asmap).GetHash();
2420 LogPrintf("Using asmap version %s for IP bucketing\n",
2421 asmap_version.ToString());
2422 } else {
2423 LogPrintf("Using /16 prefix for IP bucketing\n");
2424 }
2425
2426 uiInterface.InitMessage(_("Loading P2P addresses...").translated);
2427 auto addrman{LoadAddrman(chainparams, asmap, args)};
2428 if (!addrman) {
2429 return InitError(util::ErrorString(addrman));
2430 }
2431 node.addrman = std::move(*addrman);
2432 }
2433
2435 assert(!node.banman);
2436 node.banman = std::make_unique<BanMan>(
2437 args.GetDataDirNet() / "banlist", config.GetChainParams(), &uiInterface,
2438 args.GetIntArg("-bantime", DEFAULT_MISBEHAVING_BANTIME));
2439 assert(!node.connman);
2440 node.connman = std::make_unique<CConnman>(
2441 config, rng.rand64(), rng.rand64(), *node.addrman,
2442 args.GetBoolArg("-networkactive", true));
2443
2444 // Check port numbers
2445 for (const std::string port_option : {
2446 "-port",
2447 "-rpcport",
2448 }) {
2449 if (args.IsArgSet(port_option)) {
2450 const std::string port = args.GetArg(port_option, "");
2451 uint16_t n;
2452 if (!ParseUInt16(port, &n) || n == 0) {
2453 return InitError(InvalidPortErrMsg(port_option, port));
2454 }
2455 }
2456 }
2457
2458 for ([[maybe_unused]] const auto &[arg, supports_unix_socket] :
2459 std::vector<std::pair<std::string, bool>>{
2460 // arg name UNIX socket support
2461 {"-i2psam", false},
2462 {"-onion", true},
2463 {"-proxy", true},
2464 {"-rpcbind", false},
2465 {"-torcontrol", false},
2466 {"-whitebind", false},
2467 {"-zmqpubhashblock", true},
2468 {"-zmqpubhashtx", true},
2469 {"-zmqpubrawblock", true},
2470 {"-zmqpubrawtx", true},
2471 {"-zmqpubsequence", true},
2472 }) {
2473 for (const std::string &socket_addr : args.GetArgs(arg)) {
2474 std::string host_out;
2475 uint16_t port_out{0};
2476 if (!SplitHostPort(socket_addr, port_out, host_out)) {
2477#if HAVE_SOCKADDR_UN
2478 // Allow unix domain sockets for some options e.g.
2479 // unix:/some/file/path
2480 if (!supports_unix_socket ||
2481 socket_addr.find(ADDR_PREFIX_UNIX) != 0) {
2482 return InitError(InvalidPortErrMsg(arg, socket_addr));
2483 }
2484#else
2485 return InitError(InvalidPortErrMsg(arg, socket_addr));
2486#endif
2487 }
2488 }
2489 }
2490
2491 for (const std::string &socket_addr : args.GetArgs("-bind")) {
2492 std::string host_out;
2493 uint16_t port_out{0};
2494 std::string bind_socket_addr =
2495 socket_addr.substr(0, socket_addr.rfind('='));
2496 if (!SplitHostPort(bind_socket_addr, port_out, host_out)) {
2497 return InitError(InvalidPortErrMsg("-bind", socket_addr));
2498 }
2499 }
2500
2501 // sanitize comments per BIP-0014, format user agent and check total size
2502 std::vector<std::string> uacomments;
2503 for (const std::string &cmt : args.GetArgs("-uacomment")) {
2504 if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT)) {
2505 return InitError(strprintf(
2506 _("User Agent comment (%s) contains unsafe characters."), cmt));
2507 }
2508 uacomments.push_back(cmt);
2509 }
2510 const std::string client_name = args.GetArg("-uaclientname", CLIENT_NAME);
2511 const std::string client_version =
2512 args.GetArg("-uaclientversion", FormatVersion(CLIENT_VERSION));
2513 if (client_name != SanitizeString(client_name, SAFE_CHARS_UA_COMMENT)) {
2514 return InitError(strprintf(
2515 _("-uaclientname (%s) contains invalid characters."), client_name));
2516 }
2517 if (client_version !=
2518 SanitizeString(client_version, SAFE_CHARS_UA_COMMENT)) {
2519 return InitError(
2520 strprintf(_("-uaclientversion (%s) contains invalid characters."),
2521 client_version));
2522 }
2523 const std::string strSubVersion =
2524 FormatUserAgent(client_name, client_version, uacomments);
2525 if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
2526 return InitError(strprintf(
2527 _("Total length of network version string (%i) exceeds maximum "
2528 "length (%i). Reduce the number or size of uacomments."),
2529 strSubVersion.size(), MAX_SUBVERSION_LENGTH));
2530 }
2531
2532 if (args.IsArgSet("-onlynet")) {
2533 std::set<enum Network> nets;
2534 for (const std::string &snet : args.GetArgs("-onlynet")) {
2535 enum Network net = ParseNetwork(snet);
2536 if (net == NET_UNROUTABLE) {
2537 return InitError(strprintf(
2538 _("Unknown network specified in -onlynet: '%s'"), snet));
2539 }
2540 nets.insert(net);
2541 }
2542 for (int n = 0; n < NET_MAX; n++) {
2543 enum Network net = (enum Network)n;
2544 assert(IsReachable(net));
2545 if (!nets.count(net)) {
2546 SetReachable(net, false);
2547 }
2548 }
2549 }
2550
2551 // Check for host lookup allowed before parsing any network related
2552 // parameters
2554
2555 Proxy onion_proxy;
2556
2557 bool proxyRandomize =
2558 args.GetBoolArg("-proxyrandomize", DEFAULT_PROXYRANDOMIZE);
2559 // -proxy sets a proxy for all outgoing network traffic
2560 // -noproxy (or -proxy=0) as well as the empty string can be used to not set
2561 // a proxy, this is the default
2562 std::string proxyArg = args.GetArg("-proxy", "");
2563 if (proxyArg != "" && proxyArg != "0") {
2564 Proxy addrProxy;
2565 if (IsUnixSocketPath(proxyArg)) {
2566 addrProxy = Proxy(proxyArg, proxyRandomize);
2567 } else {
2568 const std::optional<CService> proxyAddr{
2569 Lookup(proxyArg, 9050, fNameLookup)};
2570 if (!proxyAddr.has_value()) {
2571 return InitError(strprintf(
2572 _("Invalid -proxy address or hostname: '%s'"), proxyArg));
2573 }
2574
2575 addrProxy = Proxy(proxyAddr.value(), proxyRandomize);
2576 }
2577
2578 if (!addrProxy.IsValid()) {
2579 return InitError(strprintf(
2580 _("Invalid -proxy address or hostname: '%s'"), proxyArg));
2581 }
2582
2583 SetProxy(NET_IPV4, addrProxy);
2584 SetProxy(NET_IPV6, addrProxy);
2585 SetNameProxy(addrProxy);
2586 onion_proxy = addrProxy;
2587 }
2588
2589 const bool onlynet_used_with_onion{args.IsArgSet("-onlynet") &&
2591
2592 // -onion can be used to set only a proxy for .onion, or override normal
2593 // proxy for .onion addresses.
2594 // -noonion (or -onion=0) disables connecting to .onion entirely. An empty
2595 // string is used to not override the onion proxy (in which case it defaults
2596 // to -proxy set above, or none)
2597 std::string onionArg = args.GetArg("-onion", "");
2598 if (onionArg != "") {
2599 if (onionArg == "0") {
2600 // Handle -noonion/-onion=0
2601 onion_proxy = Proxy{};
2602 if (onlynet_used_with_onion) {
2603 return InitError(_("Outbound connections restricted to Tor "
2604 "(-onlynet=onion) but the proxy for "
2605 "reaching the Tor network is explicitly "
2606 "forbidden: -onion=0"));
2607 }
2608 } else {
2609 if (IsUnixSocketPath(onionArg)) {
2610 onion_proxy = Proxy(onionArg, proxyRandomize);
2611 } else {
2612 const std::optional<CService> addr{
2613 Lookup(onionArg, 9050, fNameLookup)};
2614 if (!addr.has_value() || !addr->IsValid()) {
2615 return InitError(
2616 strprintf(_("Invalid -onion address or hostname: '%s'"),
2617 onionArg));
2618 }
2619
2620 onion_proxy = Proxy(addr.value(), proxyRandomize);
2621 }
2622 }
2623 }
2624
2625 if (onion_proxy.IsValid()) {
2626 SetProxy(NET_ONION, onion_proxy);
2627 } else {
2628 // If -listenonion is set, then we will (try to) connect to the Tor
2629 // control port later from the torcontrol thread and may retrieve the
2630 // onion proxy from there.
2631 const bool listenonion_disabled{
2632 !args.GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION)};
2633 if (onlynet_used_with_onion && listenonion_disabled) {
2634 return InitError(_("Outbound connections restricted to Tor "
2635 "(-onlynet=onion) but the proxy for "
2636 "reaching the Tor network is not provided: none "
2637 "of -proxy, -onion or "
2638 "-listenonion is given"));
2639 }
2640 SetReachable(NET_ONION, false);
2641 }
2642
2643 for (const std::string &strAddr : args.GetArgs("-externalip")) {
2644 const std::optional<CService> addrLocal{
2645 Lookup(strAddr, GetListenPort(), fNameLookup)};
2646 if (addrLocal.has_value() && addrLocal->IsValid()) {
2647 AddLocal(addrLocal.value(), LOCAL_MANUAL);
2648 } else {
2649 return InitError(ResolveErrMsg("externalip", strAddr));
2650 }
2651 }
2652
2653#if ENABLE_ZMQ
2655 [&chainman = node.chainman](CBlock &block, const CBlockIndex &index) {
2656 assert(chainman);
2657 return chainman->m_blockman.ReadBlock(block, index);
2658 });
2659
2661 validation_signals.RegisterValidationInterface(
2663 }
2664#endif
2665
2666 // Step 7: load block chain
2667
2668 node.notifications =
2669 std::make_unique<KernelNotifications>(node.exit_status);
2670 ReadNotificationArgs(args, *node.notifications);
2671 ChainstateManager::Options chainman_opts{
2672 .config = config,
2673 .datadir = args.GetDataDirNet(),
2674 .adjusted_time_callback = GetAdjustedTime,
2675 .notifications = *node.notifications,
2676 .signals = &validation_signals,
2677 };
2678 // no error can happen, already checked in AppInitParameterInteraction
2679 Assert(!ApplyArgsManOptions(args, chainman_opts));
2680
2681 if (chainman_opts.checkpoints_enabled) {
2682 LogPrintf("Checkpoints will be verified.\n");
2683 } else {
2684 LogPrintf("Skipping checkpoint verification.\n");
2685 }
2686
2687 BlockManager::Options blockman_opts{
2688 .chainparams = chainman_opts.config.GetChainParams(),
2689 .blocks_dir = args.GetBlocksDirPath(),
2690 .notifications = chainman_opts.notifications,
2691 };
2692 // no error can happen, already checked in AppInitParameterInteraction
2693 Assert(!ApplyArgsManOptions(args, blockman_opts));
2694
2695 // cache size calculations
2696 const auto [index_cache_sizes, kernel_cache_sizes] =
2697 CalculateCacheSizes(args, g_enabled_filter_types.size());
2698
2699 LogInfo("Cache configuration:\n");
2700 LogInfo("* Using %.1f MiB for block index database\n",
2701 kernel_cache_sizes.block_tree_db * (1.0 / 1024 / 1024));
2702 if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
2703 LogInfo("* Using %.1f MiB for transaction index database\n",
2704 index_cache_sizes.tx_index * (1.0 / 1024 / 1024));
2705 }
2706 for (BlockFilterType filter_type : g_enabled_filter_types) {
2707 LogInfo("* Using %.1f MiB for %s block filter index database\n",
2708 index_cache_sizes.filter_index * (1.0 / 1024 / 1024),
2709 BlockFilterTypeName(filter_type));
2710 }
2711 LogInfo("* Using %.1f MiB for chain state database\n",
2712 kernel_cache_sizes.coins_db * (1.0 / 1024 / 1024));
2713
2714 assert(!node.mempool);
2715 assert(!node.chainman);
2716
2717 CTxMemPool::Options mempool_opts{
2718 .check_ratio = chainparams.DefaultConsistencyChecks() ? 1 : 0,
2719 .signals = &validation_signals,
2720 };
2721 if (const auto err{ApplyArgsManOptions(args, chainparams, mempool_opts)}) {
2722 return InitError(*err);
2723 }
2724 mempool_opts.check_ratio =
2725 std::clamp<int>(mempool_opts.check_ratio, 0, 1'000'000);
2726
2727 // FIXME: this legacy limit comes from the DEFAULT_DESCENDANT_SIZE_LIMIT
2728 // (101) that was enforced before the wellington activation. While it's
2729 // still a good idea to have some minimum mempool size, using this value as
2730 // a threshold is no longer relevant.
2731 int64_t nMempoolSizeMin = 101 * 1000 * 40;
2732 if (mempool_opts.max_size_bytes < 0 ||
2733 (!chainparams.IsTestChain() &&
2734 mempool_opts.max_size_bytes < nMempoolSizeMin)) {
2735 return InitError(strprintf(_("-maxmempool must be at least %d MB"),
2736 std::ceil(nMempoolSizeMin / 1000000.0)));
2737 }
2738 LogInfo("* Using %.1f MiB for in-memory UTXO set (plus up to %.1f MiB of "
2739 "unused mempool space)\n",
2740 kernel_cache_sizes.coins * (1.0 / 1024 / 1024),
2741 mempool_opts.max_size_bytes * (1.0 / 1024 / 1024));
2742
2743 bool do_reindex{args.GetBoolArg("-reindex", false)};
2744 const bool do_reindex_chainstate{
2745 args.GetBoolArg("-reindex-chainstate", false)};
2746
2747 for (bool fLoaded = false; !fLoaded && !ShutdownRequested();) {
2748 node.mempool = std::make_unique<CTxMemPool>(config, mempool_opts);
2749
2750 node.chainman = std::make_unique<ChainstateManager>(
2751 node.kernel->interrupt, chainman_opts, blockman_opts);
2752 ChainstateManager &chainman = *node.chainman;
2753
2754 // This is defined and set here instead of inline in validation.h to
2755 // avoid a hard dependency between validation and index/base, since the
2756 // latter is not in libbitcoinkernel.
2757 chainman.snapshot_download_completed = [&node]() {
2758 if (!node.chainman->m_blockman.IsPruneMode()) {
2759 LogPrintf("[snapshot] re-enabling NODE_NETWORK services\n");
2760 node.connman->AddLocalServices(NODE_NETWORK);
2761 }
2762
2763 LogPrintf("[snapshot] restarting indexes\n");
2764
2765 // Drain the validation interface queue to ensure that the old
2766 // indexes don't have any pending work.
2767 Assert(node.validation_signals)->SyncWithValidationInterfaceQueue();
2768
2769 for (auto *index : node.indexes) {
2770 index->Interrupt();
2771 index->Stop();
2772 if (!(index->Init() && index->StartBackgroundSync())) {
2773 LogPrintf("[snapshot] WARNING failed to restart index %s "
2774 "on snapshot chain\n",
2775 index->GetName());
2776 }
2777 }
2778 };
2779
2781 options.mempool = Assert(node.mempool.get());
2782 options.wipe_block_tree_db = do_reindex;
2783 options.wipe_chainstate_db = do_reindex || do_reindex_chainstate;
2784 options.prune = chainman.m_blockman.IsPruneMode();
2785 options.check_blocks =
2786 args.GetIntArg("-checkblocks", DEFAULT_CHECKBLOCKS);
2787 options.check_level = args.GetIntArg("-checklevel", DEFAULT_CHECKLEVEL);
2789 args.IsArgSet("-checkblocks") || args.IsArgSet("-checklevel");
2791 options.coins_error_cb = [] {
2792 uiInterface.ThreadSafeMessageBox(
2793 _("Error reading from database, shutting down."), "",
2795 };
2796
2797 uiInterface.InitMessage(_("Loading block index...").translated);
2798
2799 const int64_t load_block_index_start_time = GetTimeMillis();
2800 auto catch_exceptions = [](auto &&f) {
2801 try {
2802 return f();
2803 } catch (const std::exception &e) {
2804 LogPrintf("%s\n", e.what());
2805 return std::make_tuple(node::ChainstateLoadStatus::FAILURE,
2806 _("Error opening block database"));
2807 }
2808 };
2809 auto [status, error] =
2810 catch_exceptions([&, &kernel_cache_sizes_ = kernel_cache_sizes] {
2811 return LoadChainstate(chainman, kernel_cache_sizes_, options);
2812 });
2814 uiInterface.InitMessage(_("Verifying blocks...").translated);
2815 if (chainman.m_blockman.m_have_pruned &&
2816 options.check_blocks > MIN_BLOCKS_TO_KEEP) {
2817 LogWarning("pruned datadir may not have more than %d "
2818 "blocks; only checking available blocks\n",
2820 }
2821 std::tie(status, error) = catch_exceptions(
2822 [&] { return VerifyLoadedChainstate(chainman, options); });
2824 WITH_LOCK(cs_main, return node.chainman->LoadRecentHeadersTime(
2825 node.chainman->m_options.datadir /
2827 fLoaded = true;
2828 LogPrintf(" block index %15dms\n",
2829 GetTimeMillis() - load_block_index_start_time);
2830 }
2831 }
2832
2835 status ==
2837 return InitError(error);
2838 }
2839
2840 if (!fLoaded && !ShutdownRequested()) {
2841 // first suggest a reindex
2842 if (!do_reindex) {
2843 bool fRet = uiInterface.ThreadSafeQuestion(
2844 error + Untranslated(".\n\n") +
2845 _("Do you want to rebuild the block database now?"),
2846 error.original + ".\nPlease restart with -reindex or "
2847 "-reindex-chainstate to recover.",
2848 "",
2851 if (fRet) {
2852 do_reindex = true;
2853 AbortShutdown();
2854 } else {
2855 LogPrintf("Aborted block database rebuild. Exiting.\n");
2856 return false;
2857 }
2858 } else {
2859 return InitError(error);
2860 }
2861 }
2862 }
2863
2864 // As LoadBlockIndex can take several minutes, it's possible the user
2865 // requested to kill the GUI during the last operation. If so, exit.
2866 // As the program has not fully started yet, Shutdown() is possibly
2867 // overkill.
2868 if (ShutdownRequested()) {
2869 LogPrintf("Shutdown requested. Exiting.\n");
2870 return false;
2871 }
2872
2873 ChainstateManager &chainman = *Assert(node.chainman);
2874
2875 if (args.GetBoolArg("-avalanche", AVALANCHE_DEFAULT_ENABLED)) {
2876 // Initialize Avalanche.
2877 bilingual_str avalancheError;
2879 args, *node.chain, node.connman.get(), chainman, node.mempool.get(),
2880 scheduler, avalancheError);
2881 if (!node.avalanche) {
2882 InitError(avalancheError);
2883 return false;
2884 }
2885
2886 if (node.avalanche->isAvalancheServiceAvailable()) {
2887 nLocalServices = ServiceFlags(nLocalServices | NODE_AVALANCHE);
2888 }
2889 }
2890
2891 PeerManager::Options peerman_opts{};
2892 ApplyArgsManOptions(args, peerman_opts);
2893
2894 assert(!node.peerman);
2895 node.peerman = PeerManager::make(*node.connman, *node.addrman,
2896 node.banman.get(), chainman, *node.mempool,
2897 node.avalanche.get(), peerman_opts);
2898 validation_signals.RegisterValidationInterface(node.peerman.get());
2899
2900 // Encoded addresses using cashaddr instead of base58.
2901 // We do this by default to avoid confusion with BTC addresses.
2902 config.SetCashAddrEncoding(
2903 args.GetBoolArg("-usecashaddr", DEFAULT_USEASHADDR));
2904
2905 // Step 8: load indexers
2906
2907 if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
2908 auto result{
2910 chainman.m_blockman.m_block_tree_db)))};
2911 if (!result) {
2912 return InitError(util::ErrorString(result));
2913 }
2914
2915 g_txindex = std::make_unique<TxIndex>(
2916 interfaces::MakeChain(node, Params()), index_cache_sizes.tx_index,
2917 false, do_reindex);
2918 node.indexes.emplace_back(g_txindex.get());
2919 }
2920
2921 for (const auto &filter_type : g_enabled_filter_types) {
2923 [&] { return interfaces::MakeChain(node, Params()); }, filter_type,
2924 index_cache_sizes.filter_index, false, do_reindex);
2925 node.indexes.emplace_back(GetBlockFilterIndex(filter_type));
2926 }
2927
2928 if (args.GetBoolArg("-coinstatsindex", DEFAULT_COINSTATSINDEX)) {
2929 g_coin_stats_index = std::make_unique<CoinStatsIndex>(
2930 interfaces::MakeChain(node, Params()), /* cache size */ 0, false,
2931 do_reindex);
2932 node.indexes.emplace_back(g_coin_stats_index.get());
2933 }
2934
2935 // Init indexes
2936 for (auto index : node.indexes) {
2937 if (!index->Init()) {
2938 return false;
2939 }
2940 }
2941
2942 const bool background_sync_in_progress{WITH_LOCK(
2943 chainman.GetMutex(), return chainman.BackgroundSyncInProgress())};
2944#if ENABLE_CHRONIK
2945 if (args.GetBoolArg("-chronik", DEFAULT_CHRONIK)) {
2946 if (background_sync_in_progress) {
2947 return InitError(
2948 _("Assumeutxo is incompatible with -chronik. Wait for "
2949 "background sync to complete before enabling Chronik."));
2950 }
2951
2952 const bool fReindexChronik =
2953 do_reindex || args.GetBoolArg("-chronikreindex", false);
2954 if (!chronik::Start(args, config, node, fReindexChronik)) {
2955 return false;
2956 }
2957 }
2958#endif
2959
2960 // Step 9: load wallet
2961 for (const auto &client : node.chain_clients) {
2962 if (!client->load()) {
2963 return false;
2964 }
2965 }
2966
2967 // Step 10: data directory maintenance
2968
2969 // if pruning, perform the initial blockstore prune
2970 // after any wallet rescanning has taken place.
2971 if (chainman.m_blockman.IsPruneMode()) {
2972 if (chainman.m_blockman.m_blockfiles_indexed) {
2973 LOCK(cs_main);
2974 for (Chainstate *chainstate : chainman.GetAll()) {
2975 uiInterface.InitMessage(_("Pruning blockstore...").translated);
2976 chainstate->PruneAndFlush();
2977 }
2978 }
2979 } else {
2980 // Prior to setting NODE_NETWORK, check if we can provide historical
2981 // blocks.
2982 if (!background_sync_in_progress) {
2983 LogPrintf("Setting NODE_NETWORK on non-prune mode\n");
2984 nLocalServices = ServiceFlags(nLocalServices | NODE_NETWORK);
2985 } else {
2986 LogPrintf("Running node in NODE_NETWORK_LIMITED mode until "
2987 "snapshot background sync completes\n");
2988 }
2989 }
2990
2991 // Step 11: import blocks
2992 if (!CheckDiskSpace(args.GetDataDirNet())) {
2993 InitError(
2994 strprintf(_("Error: Disk space is low for %s"),
2996 return false;
2997 }
2998 if (!CheckDiskSpace(args.GetBlocksDirPath())) {
2999 InitError(
3000 strprintf(_("Error: Disk space is low for %s"),
3002 return false;
3003 }
3004
3005 // Either install a handler to notify us when genesis activates, or set
3006 // fHaveGenesis directly.
3007 // No locking, as this happens before any background thread is started.
3008 boost::signals2::connection block_notify_genesis_wait_connection;
3009 if (WITH_LOCK(chainman.GetMutex(),
3010 return chainman.ActiveChain().Tip() == nullptr)) {
3011 block_notify_genesis_wait_connection =
3012 uiInterface.NotifyBlockTip_connect(
3013 std::bind(BlockNotifyGenesisWait, std::placeholders::_2));
3014 } else {
3015 fHaveGenesis = true;
3016 }
3017
3018#if defined(HAVE_SYSTEM)
3019 const std::string block_notify = args.GetArg("-blocknotify", "");
3020 if (!block_notify.empty()) {
3021 uiInterface.NotifyBlockTip_connect([block_notify](
3022 SynchronizationState sync_state,
3023 const CBlockIndex *pBlockIndex) {
3024 if (sync_state != SynchronizationState::POST_INIT || !pBlockIndex) {
3025 return;
3026 }
3027 std::string command = block_notify;
3028 ReplaceAll(command, "%s", pBlockIndex->GetBlockHash().GetHex());
3029 std::thread t(runCommand, command);
3030 // thread runs free
3031 t.detach();
3032 });
3033 }
3034#endif
3035
3036 std::vector<fs::path> vImportFiles;
3037 for (const std::string &strFile : args.GetArgs("-loadblock")) {
3038 vImportFiles.push_back(fs::PathFromString(strFile));
3039 }
3040
3041 avalanche::Processor *const avalanche = node.avalanche.get();
3042 node.background_init_thread = std::thread(
3043 &util::TraceThread, "initload", [=, &chainman, &args, &node] {
3044 // Import blocks
3045 ImportBlocks(chainman, avalanche, vImportFiles);
3046 if (args.GetBoolArg("-stopafterblockimport",
3048 LogPrintf("Stopping after block import\n");
3049 StartShutdown();
3050 return;
3051 }
3052 // Start indexes initial sync
3054 bilingual_str err_str =
3055 _("Failed to start indexes, shutting down..");
3056 chainman.GetNotifications().fatalError(err_str.original,
3057 err_str);
3058 return;
3059 }
3060 // Load mempool from disk
3061 if (auto *pool{chainman.ActiveChainstate().GetMempool()}) {
3062 LoadMempool(*pool,
3063 ShouldPersistMempool(args) ? MempoolPath(args)
3064 : fs::path{},
3065 chainman.ActiveChainstate(), {});
3066 pool->SetLoadTried(!chainman.m_interrupt);
3067 }
3068 });
3069
3070 // Wait for genesis block to be processed
3071 {
3073 // We previously could hang here if StartShutdown() is called prior to
3074 // ImportBlocks getting started, so instead we just wait on a timer to
3075 // check ShutdownRequested() regularly.
3076 while (!fHaveGenesis && !ShutdownRequested()) {
3077 g_genesis_wait_cv.wait_for(lock, std::chrono::milliseconds(500));
3078 }
3079 block_notify_genesis_wait_connection.disconnect();
3080 }
3081
3082 if (ShutdownRequested()) {
3083 return false;
3084 }
3085
3086 // Step 12: start node
3087
3088 int chain_active_height;
3089
3091 {
3092 LOCK(cs_main);
3093 LogPrintf("block tree size = %u\n", chainman.BlockIndex().size());
3094 chain_active_height = chainman.ActiveChain().Height();
3095 if (tip_info) {
3096 tip_info->block_height = chain_active_height;
3097 tip_info->block_time =
3098 chainman.ActiveChain().Tip()
3099 ? chainman.ActiveChain().Tip()->GetBlockTime()
3100 : chainman.GetParams().GenesisBlock().GetBlockTime();
3102 chainman.GetParams().TxData(), chainman.ActiveChain().Tip());
3103 }
3104 if (tip_info && chainman.m_best_header) {
3105 tip_info->header_height = chainman.m_best_header->nHeight;
3106 tip_info->header_time = chainman.m_best_header->GetBlockTime();
3107 }
3108 }
3109 LogPrintf("nBestHeight = %d\n", chain_active_height);
3110 if (node.peerman) {
3111 node.peerman->SetBestHeight(chain_active_height);
3112 }
3113
3114 // Map ports with NAT-PMP
3115 StartMapPort(args.GetBoolArg("-natpmp", DEFAULT_NATPMP));
3116
3117 CConnman::Options connOptions;
3118 connOptions.nLocalServices = nLocalServices;
3119 connOptions.nMaxConnections = nMaxConnections;
3120 connOptions.m_max_avalanche_outbound =
3121 node.avalanche
3122 ? args.GetIntArg("-maxavalancheoutbound",
3124 : 0;
3125 connOptions.m_max_outbound_full_relay = std::min(
3127 connOptions.nMaxConnections - connOptions.m_max_avalanche_outbound);
3128 connOptions.m_max_outbound_block_relay = std::min(
3130 connOptions.nMaxConnections - connOptions.m_max_avalanche_outbound -
3131 connOptions.m_max_outbound_full_relay);
3133 connOptions.nMaxFeeler = MAX_FEELER_CONNECTIONS;
3134 connOptions.uiInterface = &uiInterface;
3135 connOptions.m_banman = node.banman.get();
3136 connOptions.m_msgproc.push_back(node.peerman.get());
3137 if (node.avalanche) {
3138 connOptions.m_msgproc.push_back(node.avalanche.get());
3139 }
3140 connOptions.nSendBufferMaxSize =
3141 1000 * args.GetIntArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER);
3142 connOptions.nReceiveFloodSize =
3143 1000 * args.GetIntArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER);
3144 connOptions.m_added_nodes = args.GetArgs("-addnode");
3145
3146 connOptions.nMaxOutboundLimit =
3147 1024 * 1024 *
3148 args.GetIntArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET);
3149 connOptions.m_peer_connect_timeout = peer_connect_timeout;
3150 connOptions.whitelist_forcerelay =
3151 args.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY);
3152 connOptions.whitelist_relay =
3153 args.GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY);
3154
3155 // Port to bind to if `-bind=addr` is provided without a `:port` suffix.
3156 const uint16_t default_bind_port = static_cast<uint16_t>(
3157 args.GetIntArg("-port", config.GetChainParams().GetDefaultPort()));
3158
3159 const auto BadPortWarning = [](const char *prefix, uint16_t port) {
3160 return strprintf(_("%s request to listen on port %u. This port is "
3161 "considered \"bad\" and "
3162 "thus it is unlikely that any Bitcoin ABC peers "
3163 "connect to it. See "
3164 "doc/p2p-bad-ports.md for details and a full list."),
3165 prefix, port);
3166 };
3167
3168 for (const std::string &bind_arg : args.GetArgs("-bind")) {
3169 std::optional<CService> bind_addr;
3170 const size_t index = bind_arg.rfind('=');
3171 if (index == std::string::npos) {
3172 bind_addr =
3173 Lookup(bind_arg, default_bind_port, /*fAllowLookup=*/false);
3174 if (bind_addr.has_value()) {
3175 connOptions.vBinds.push_back(bind_addr.value());
3176 if (IsBadPort(bind_addr.value().GetPort())) {
3178 BadPortWarning("-bind", bind_addr.value().GetPort()));
3179 }
3180 continue;
3181 }
3182 } else {
3183 const std::string network_type = bind_arg.substr(index + 1);
3184 if (network_type == "onion") {
3185 const std::string truncated_bind_arg =
3186 bind_arg.substr(0, index);
3187 bind_addr =
3188 Lookup(truncated_bind_arg,
3189 BaseParams().OnionServiceTargetPort(), false);
3190 if (bind_addr.has_value()) {
3191 connOptions.onion_binds.push_back(bind_addr.value());
3192 continue;
3193 }
3194 }
3195 }
3196 return InitError(ResolveErrMsg("bind", bind_arg));
3197 }
3198
3199 for (const std::string &strBind : args.GetArgs("-whitebind")) {
3200 NetWhitebindPermissions whitebind;
3201 bilingual_str error;
3202 if (!NetWhitebindPermissions::TryParse(strBind, whitebind, error)) {
3203 return InitError(error);
3204 }
3205 connOptions.vWhiteBinds.push_back(whitebind);
3206 }
3207
3208 // If the user did not specify -bind= or -whitebind= then we bind
3209 // on any address - 0.0.0.0 (IPv4) and :: (IPv6).
3210 connOptions.bind_on_any =
3211 args.GetArgs("-bind").empty() && args.GetArgs("-whitebind").empty();
3212
3213 // Emit a warning if a bad port is given to -port= but only if -bind and
3214 // -whitebind are not given, because if they are, then -port= is ignored.
3215 if (connOptions.bind_on_any && args.IsArgSet("-port")) {
3216 const uint16_t port_arg = args.GetIntArg("-port", 0);
3217 if (IsBadPort(port_arg)) {
3218 InitWarning(BadPortWarning("-port", port_arg));
3219 }
3220 }
3221
3222 CService onion_service_target;
3223 if (!connOptions.onion_binds.empty()) {
3224 onion_service_target = connOptions.onion_binds.front();
3225 } else if (!connOptions.vBinds.empty()) {
3226 onion_service_target = connOptions.vBinds.front();
3227 } else {
3228 onion_service_target = DefaultOnionServiceTarget();
3229 connOptions.onion_binds.push_back(onion_service_target);
3230 }
3231
3232 if (args.GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION)) {
3233 if (connOptions.onion_binds.size() > 1) {
3235 _("More than one onion bind address is provided. Using %s "
3236 "for the automatically created Tor onion service."),
3237 onion_service_target.ToStringAddrPort()));
3238 }
3239 StartTorControl(onion_service_target);
3240 }
3241
3242 if (connOptions.bind_on_any) {
3243 // Only add all IP addresses of the machine if we would be listening on
3244 // any address - 0.0.0.0 (IPv4) and :: (IPv6).
3245 Discover();
3246 }
3247
3248 for (const auto &net : args.GetArgs("-whitelist")) {
3250 ConnectionDirection connection_direction;
3251 bilingual_str error;
3252 if (!NetWhitelistPermissions::TryParse(net, subnet,
3253 connection_direction, error)) {
3254 return InitError(error);
3255 }
3256 if (connection_direction & ConnectionDirection::In) {
3257 connOptions.vWhitelistedRangeIncoming.push_back(subnet);
3258 }
3259 if (connection_direction & ConnectionDirection::Out) {
3260 connOptions.vWhitelistedRangeOutgoing.push_back(subnet);
3261 }
3262 }
3263
3264 connOptions.vSeedNodes = args.GetArgs("-seednode");
3265
3266 // Initiate outbound connections unless connect=0
3267 connOptions.m_use_addrman_outgoing = !args.IsArgSet("-connect");
3268 if (!connOptions.m_use_addrman_outgoing) {
3269 const auto connect = args.GetArgs("-connect");
3270 if (connect.size() != 1 || connect[0] != "0") {
3271 connOptions.m_specified_outgoing = connect;
3272 }
3273 }
3274
3275 const std::string &i2psam_arg = args.GetArg("-i2psam", "");
3276 if (!i2psam_arg.empty()) {
3277 const std::optional<CService> addr{
3278 Lookup(i2psam_arg, 7656, fNameLookup)};
3279 if (!addr.has_value() || !addr->IsValid()) {
3280 return InitError(strprintf(
3281 _("Invalid -i2psam address or hostname: '%s'"), i2psam_arg));
3282 }
3283 SetProxy(NET_I2P, Proxy{addr.value()});
3284 } else {
3285 SetReachable(NET_I2P, false);
3286 }
3287
3288 connOptions.m_i2p_accept_incoming =
3289 args.GetBoolArg("-i2pacceptincoming", true);
3290
3291 if (!node.connman->Start(scheduler, connOptions)) {
3292 return false;
3293 }
3294
3295 // Step 13: finished
3296
3297 // At this point, the RPC is "started", but still in warmup, which means it
3298 // cannot yet be called. Before we make it callable, we need to make sure
3299 // that the RPC's view of the best block is valid and consistent with
3300 // ChainstateManager's active tip.
3301 //
3302 // If we do not do this, RPC's view of the best block will be height=0 and
3303 // hash=0x0. This will lead to erroroneous responses for things like
3304 // waitforblockheight.
3306 WITH_LOCK(chainman.GetMutex(), return chainman.ActiveTip()));
3308
3309 uiInterface.InitMessage(_("Done loading").translated);
3310
3311 for (const auto &client : node.chain_clients) {
3312 client->start(scheduler);
3313 }
3314
3315 BanMan *banman = node.banman.get();
3316 scheduler.scheduleEvery(
3317 [banman] {
3318 banman->DumpBanlist();
3319 return true;
3320 },
3322
3323 // Start Avalanche's event loop.
3324 if (node.avalanche) {
3325 node.avalanche->startEventLoop(scheduler);
3326 }
3327
3328 if (node.peerman) {
3329 node.peerman->StartScheduledTasks(scheduler);
3330 }
3331
3332#if HAVE_SYSTEM
3333 StartupNotify(args);
3334#endif
3335
3336 return true;
3337}
3338
3340 // Find the oldest block among all indexes.
3341 // This block is used to verify that we have the required blocks' data
3342 // stored on disk, starting from that point up to the current tip.
3343 // indexes_start_block='nullptr' means "start from height 0".
3344 std::optional<const CBlockIndex *> indexes_start_block;
3345 std::string older_index_name;
3346 ChainstateManager &chainman = *Assert(node.chainman);
3347 const Chainstate &chainstate =
3348 WITH_LOCK(::cs_main, return chainman.GetChainstateForIndexing());
3349 const CChain &index_chain = chainstate.m_chain;
3350
3351 for (auto index : node.indexes) {
3352 const IndexSummary &summary = index->GetSummary();
3353 if (summary.synced) {
3354 continue;
3355 }
3356
3357 // Get the last common block between the index best block and the active
3358 // chain
3359 LOCK(::cs_main);
3360 const CBlockIndex *pindex = chainman.m_blockman.LookupBlockIndex(
3361 BlockHash{summary.best_block_hash});
3362 if (!index_chain.Contains(pindex)) {
3363 pindex = index_chain.FindFork(pindex);
3364 }
3365
3366 if (!indexes_start_block || !pindex ||
3367 pindex->nHeight < indexes_start_block.value()->nHeight) {
3368 indexes_start_block = pindex;
3369 older_index_name = summary.name;
3370 if (!pindex) {
3371 // Starting from genesis so no need to look for earlier block.
3372 break;
3373 }
3374 }
3375 };
3376
3377 // Verify all blocks needed to sync to current tip are present.
3378 if (indexes_start_block) {
3379 LOCK(::cs_main);
3380 const CBlockIndex *start_block = *indexes_start_block;
3381 if (!start_block) {
3382 start_block = chainman.ActiveChain().Genesis();
3383 }
3384 if (!chainman.m_blockman.CheckBlockDataAvailability(
3385 *index_chain.Tip(), *Assert(start_block))) {
3386 return InitError(strprintf(
3387 Untranslated("%s best block of the index goes beyond pruned "
3388 "data. Please disable the index or reindex (which "
3389 "will download the whole blockchain again)"),
3390 older_index_name));
3391 }
3392 }
3393
3394 // Start threads
3395 for (auto index : node.indexes) {
3396 if (!index->StartBackgroundSync()) {
3397 return false;
3398 }
3399 }
3400 return true;
3401}
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 int DEFAULT_SCRIPTCHECK_THREADS
-par default (number of script-checking threads, 0 = auto)
static constexpr bool DEFAULT_CHECKPOINTS_ENABLED
static constexpr auto DEFAULT_MAX_TIP_AGE
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:87
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:417
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:403
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:159
BlockHash GetBlockHash() const
Definition: blockindex.h:129
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
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:727
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:826
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:1176
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:1472
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:1446
kernel::Notifications & GetNotifications() const
Definition: validation.h:1305
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
Definition: validation.h:1328
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1453
bool BackgroundSyncInProgress() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
The state of a background sync (for net processing)
Definition: validation.h:1460
const util::SignalInterrupt & m_interrupt
Definition: validation.h:1332
std::function< void()> snapshot_download_completed
Function to restart active indexes; set dynamically to avoid a circular dependency on base/index....
Definition: validation.h:1288
const CChainParams & GetParams() const
Definition: validation.h:1292
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1447
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(std::vector< Chainstate * GetAll)()
Instantiate a new chainstate.
Definition: validation.h:1412
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:1336
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:226
std::string ToString() const
Definition: uint256.h:117
std::string GetHex() const
Definition: uint256.cpp:10
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:114
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:416
std::atomic_bool m_blockfiles_indexed
Whether all blockfiles have been added to the block tree database.
Definition: blockstorage.h:268
CBlockIndex * LookupBlockIndex(const BlockHash &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool IsPruneMode() const
Whether running in -prune mode.
Definition: blockstorage.h:356
256-bit opaque blob.
Definition: uint256.h:199
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:1095
void StopREST()
Stop HTTP REST subsystem.
Definition: rest.cpp:1107
void InterruptREST()
Interrupt RPC REST subsystem.
Definition: rest.cpp:1105
void InterruptHTTPServer()
Interrupt HTTP server threads.
Definition: httpserver.cpp:548
void StartHTTPServer()
Start HTTP server.
Definition: httpserver.cpp:536
void StopHTTPServer()
Stop HTTP server.
Definition: httpserver.cpp:559
bool InitHTTPServer(Config &config)
Initialize HTTP server.
Definition: httpserver.cpp:469
static const int DEFAULT_HTTP_SERVER_TIMEOUT
Definition: httpserver.h:15
static const int DEFAULT_HTTP_WORKQUEUE
Definition: httpserver.h:14
static const int DEFAULT_HTTP_THREADS
Definition: httpserver.h:13
Common init functions shared by bitcoin-node, bitcoin-wallet, etc.
static const char * BITCOIN_PID_FILENAME
The PID file facilities.
Definition: init.cpp:163
static bool CreatePidFile(const ArgsManager &args)
Definition: init.cpp:170
static const bool DEFAULT_PROXYRANDOMIZE
Definition: init.cpp:142
void Interrupt(NodeContext &node)
Interrupt threads.
Definition: init.cpp:222
void InitLogging(const ArgsManager &args)
Initialize global loggers.
Definition: init.cpp:1856
bool AppInitLockDataDirectory()
Lock bitcoin data directory.
Definition: init.cpp:2252
void SetupServerArgs(NodeContext &node)
Register all arguments with the ArgsManager.
Definition: init.cpp:472
static bool AppInitServers(Config &config, HTTPRPCRequestProcessor &httpRPCRequestProcessor, NodeContext &node)
Definition: init.cpp:1707
#define MIN_CORE_FILEDESCRIPTORS
Definition: init.cpp:153
static bool fHaveGenesis
Definition: init.cpp:1682
void Shutdown(NodeContext &node)
Definition: init.cpp:249
static void HandleSIGTERM(int)
Signal handlers are very limited in what they are allowed to do.
Definition: init.cpp:434
static GlobalMutex g_genesis_wait_mutex
Definition: init.cpp:1683
static void OnRPCStarted()
Definition: init.cpp:460
static constexpr bool DEFAULT_USEASHADDR
Definition: init.cpp:146
static void HandleSIGHUP(int)
Definition: init.cpp:438
bool AppInitBasicSetup(const ArgsManager &args, std::atomic< int > &exit_status)
Initialize bitcoin: Basic context setup.
Definition: init.cpp:1883
static fs::path GetPidFile(const ArgsManager &args)
Definition: init.cpp:165
static std::condition_variable g_genesis_wait_cv
Definition: init.cpp:1684
bool AppInitMain(Config &config, RPCServer &rpcServer, HTTPRPCRequestProcessor &httpRPCRequestProcessor, NodeContext &node, interfaces::BlockAndHeaderTipInfo *tip_info)
Bitcoin main initialization.
Definition: init.cpp:2274
static constexpr bool DEFAULT_CHRONIK
Definition: init.cpp:145
bool StartIndexBackgroundSync(NodeContext &node)
Validates requirements to run the indexes and spawns each index initial sync thread.
Definition: init.cpp:3339
bool AppInitInterfaces(NodeContext &node)
Initialize node and wallet interface pointers.
Definition: init.cpp:2264
static constexpr bool DEFAULT_STOPAFTERBLOCKIMPORT
Definition: init.cpp:144
static const char * DEFAULT_ASMAP_FILENAME
Definition: init.cpp:156
void InitParameterInteraction(ArgsManager &args)
Parameter interaction: change current parameters depending on various rules.
Definition: init.cpp:1732
static void BlockNotifyGenesisWait(const CBlockIndex *pBlockIndex)
Definition: init.cpp:1686
static void OnRPCStopped()
Definition: init.cpp:465
static bool LockDataDirectory(bool probeOnly)
Definition: init.cpp:2217
static void registerSignalHandler(int signal, void(*handler)(int))
Definition: init.cpp:450
bool AppInitParameterInteraction(Config &config, const ArgsManager &args)
Initialization: parameter interaction.
Definition: init.cpp:1925
static const bool DEFAULT_REST_ENABLE
Definition: init.cpp:143
static boost::signals2::connection rpc_notify_block_change_connection
Definition: init.cpp:459
static void new_handler_terminate()
Definition: init.cpp:1872
bool AppInitSanityChecks(const kernel::Context &kernel)
Initialization sanity checks.
Definition: init.cpp:2236
static const std::string HEADERS_TIME_FILE_NAME
Definition: init.cpp:158
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 LogInfo(...)
Definition: logging.h:413
#define LogDebug(category,...)
Definition: logging.h:446
#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:41
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
void AddLoggingArgs(ArgsManager &argsman)
Definition: common.cpp:27
void SetLoggingCategories(const ArgsManager &args)
Definition: common.cpp:182
bool StartLogging(const ArgsManager &args)
Definition: common.cpp:210
void SetLoggingLevel(const ArgsManager &args)
Definition: common.cpp:152
void SetLoggingOptions(const ArgsManager &args)
Definition: common.cpp:129
void LogPackageVersion()
Definition: common.cpp:257
std::unique_ptr< Chain > MakeChain(node::NodeContext &node, const CChainParams &params)
Return implementation of Chain interface.
Definition: interfaces.cpp:837
Definition: init.h:28
bool LoadMempool(CTxMemPool &pool, const fs::path &load_path, Chainstate &active_chainstate, ImportMempoolOptions &&opts)
Import the file and attempt to add its contents to the mempool.
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)
void ReadNotificationArgs(const ArgsManager &args, KernelNotifications &notifications)
ChainstateLoadResult LoadChainstate(ChainstateManager &chainman, const CacheSizes &cache_sizes, const ChainstateLoadOptions &options)
Definition: chainstate.cpp:172
ChainstateLoadResult VerifyLoadedChainstate(ChainstateManager &chainman, const ChainstateLoadOptions &options)
Definition: chainstate.cpp:276
static constexpr bool DEFAULT_PERSIST_MEMPOOL
Default for -persistmempool, indicating whether the node should attempt to automatically load the mem...
static constexpr int DEFAULT_STOPATHEIGHT
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:1113
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:109
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, std::string_view search, std::string_view substitute)
Replace every non-overlapping occurrence of search with substitute, treating both literally; the repl...
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:27
static constexpr unsigned int MAX_OP_RETURN_RELAY
Default setting for nMaxDatacarrierBytes.
Definition: policy.h:77
static constexpr Amount DUST_RELAY_TX_FEE(3000 *SATOSHI)
Min feerate for defining dust.
static constexpr bool DEFAULT_PERMIT_BAREMULTISIG
Default for -permitbaremultisig.
Definition: policy.h:58
static constexpr bool DEFAULT_ACCEPT_DATACARRIER
Default for -datacarrier.
Definition: policy.h:72
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:56
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:1078
bool(* handler)(Config &config, const std::any &context, HTTPRequest *req, const std::string &strReq)
Definition: rest.cpp:1079
const char * name
Definition: rest.cpp:46
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:36
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
@ SAFE_CHARS_UA_COMMENT
BIP-0014 subset.
Definition: strencodings.h:28
Definition: amount.h:23
static constexpr Amount zero() noexcept
Definition: amount.h:36
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
int m_max_outbound_block_relay
Definition: net.h:844
unsigned int nReceiveFloodSize
Definition: net.h:852
int m_max_outbound_full_relay
Definition: net.h:843
std::vector< NetWhitebindPermissions > vWhiteBinds
Definition: net.h:858
uint64_t nMaxOutboundLimit
Definition: net.h:853
CClientUIInterface * uiInterface
Definition: net.h:848
std::vector< NetWhitelistPermissions > vWhitelistedRangeIncoming
Definition: net.h:856
int m_max_avalanche_outbound
Definition: net.h:845
std::vector< CService > onion_binds
Definition: net.h:860
int nMaxFeeler
Definition: net.h:847
std::vector< std::string > m_specified_outgoing
Definition: net.h:865
bool whitelist_relay
Definition: net.h:869
int nMaxConnections
Definition: net.h:842
ServiceFlags nLocalServices
Definition: net.h:841
std::vector< std::string > m_added_nodes
Definition: net.h:866
int64_t m_peer_connect_timeout
Definition: net.h:854
std::vector< CService > vBinds
Definition: net.h:859
unsigned int nSendBufferMaxSize
Definition: net.h:851
bool m_i2p_accept_incoming
Definition: net.h:867
std::vector< std::string > vSeedNodes
Definition: net.h:855
BanMan * m_banman
Definition: net.h:850
bool m_use_addrman_outgoing
Definition: net.h:864
std::vector< NetEventsInterface * > m_msgproc
Definition: net.h:849
bool whitelist_forcerelay
Definition: net.h:868
bool bind_on_any
True if the user did not specify -bind= or -whitebind= and thus we should bind on 0....
Definition: net.h:863
std::vector< NetWhitelistPermissions > vWhitelistedRangeOutgoing
Definition: net.h:857
int nMaxAddnode
Definition: net.h:846
static std::string getTicker()
Definition: amount.h:163
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:44
std::function< bool()> check_interrupt
Definition: chainstate.h:43
NodeContext struct containing references to chain state and connection state.
Definition: context.h:50
#define WAIT_LOCK(cs, name)
Definition: sync.h:304
#define LOCK(cs)
Definition: sync.h:295
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:343
#define TRY_LOCK(cs, name)
Definition: sync.h:303
std::string SysErrorString(int err)
Return system error string from errno value.
Definition: syserror.cpp:20
bool SetupNetworking()
Definition: system.cpp:101
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:1203
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.
std::condition_variable g_best_block_cv
Definition: validation.cpp:114
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...
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument 'checklevel'.
Definition: validation.cpp:95
assert(!tx.IsCoinBase())
static constexpr int MAX_SCRIPTCHECK_THREADS
Maximum number of dedicated script-checking threads allowed.
Definition: validation.h:109
static constexpr int DEFAULT_CHECKLEVEL
Definition: validation.h:92
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:106
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:90
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition: validation.h:112
static const signed int DEFAULT_CHECKBLOCKS
Definition: validation.h:91
static const bool DEFAULT_PEERBLOOMFILTERS
Definition: validation.h:84
static constexpr uint32_t AVALANCHE_VOTE_STALE_FACTOR
Scaling factor applied to confidence to determine staleness threshold.
Definition: voterecord.h:36
static constexpr uint32_t AVALANCHE_VOTE_STALE_THRESHOLD
Number of votes before a record may be considered as stale.
Definition: voterecord.h:23
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