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