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