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 "Automatic broadcast and rebroadcast of any transactions "
523 "from inbound peers is disabled, unless the 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 connecting from the "
973 "given 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. Can be specified "
976 "multiple times.",
978 argsman.AddArg(
979 "-maxuploadtarget=<n>",
980 strprintf("Tries to keep outbound traffic under the given target (in "
981 "MiB per 24h). Limit does not apply to peers with 'download' "
982 "permission. 0 = no limit (default: %d)",
985
987
988#if ENABLE_ZMQ
989 argsman.AddArg("-zmqpubhashblock=<address>",
990 "Enable publish hash block in <address>",
992 argsman.AddArg("-zmqpubhashtx=<address>",
993 "Enable publish hash transaction in <address>",
995 argsman.AddArg("-zmqpubrawblock=<address>",
996 "Enable publish raw block in <address>",
998 argsman.AddArg("-zmqpubrawtx=<address>",
999 "Enable publish raw transaction in <address>",
1001 argsman.AddArg("-zmqpubsequence=<address>",
1002 "Enable publish hash block and tx sequence in <address>",
1004 argsman.AddArg(
1005 "-zmqpubhashblockhwm=<n>",
1006 strprintf("Set publish hash block outbound message high water "
1007 "mark (default: %d)",
1010 argsman.AddArg(
1011 "-zmqpubhashtxhwm=<n>",
1012 strprintf("Set publish hash transaction outbound message high "
1013 "water mark (default: %d)",
1015 false, OptionsCategory::ZMQ);
1016 argsman.AddArg(
1017 "-zmqpubrawblockhwm=<n>",
1018 strprintf("Set publish raw block outbound message high water "
1019 "mark (default: %d)",
1022 argsman.AddArg(
1023 "-zmqpubrawtxhwm=<n>",
1024 strprintf("Set publish raw transaction outbound message high "
1025 "water mark (default: %d)",
1028 argsman.AddArg("-zmqpubsequencehwm=<n>",
1029 strprintf("Set publish hash sequence message high water mark"
1030 " (default: %d)",
1033#else
1034 hidden_args.emplace_back("-zmqpubhashblock=<address>");
1035 hidden_args.emplace_back("-zmqpubhashtx=<address>");
1036 hidden_args.emplace_back("-zmqpubrawblock=<address>");
1037 hidden_args.emplace_back("-zmqpubrawtx=<address>");
1038 hidden_args.emplace_back("-zmqpubsequence=<n>");
1039 hidden_args.emplace_back("-zmqpubhashblockhwm=<n>");
1040 hidden_args.emplace_back("-zmqpubhashtxhwm=<n>");
1041 hidden_args.emplace_back("-zmqpubrawblockhwm=<n>");
1042 hidden_args.emplace_back("-zmqpubrawtxhwm=<n>");
1043 hidden_args.emplace_back("-zmqpubsequencehwm=<n>");
1044#endif
1045
1046 argsman.AddArg(
1047 "-checkblocks=<n>",
1048 strprintf("How many blocks to check at startup (default: %u, 0 = all)",
1052 argsman.AddArg("-checklevel=<n>",
1053 strprintf("How thorough the block verification of "
1054 "-checkblocks is: %s (0-4, default: %u)",
1058 argsman.AddArg("-checkblockindex",
1059 strprintf("Do a consistency check for the block tree, "
1060 "chainstate, and other validation data structures "
1061 "occasionally. (default: %u, regtest: %u)",
1062 defaultChainParams->DefaultConsistencyChecks(),
1063 regtestChainParams->DefaultConsistencyChecks()),
1066 argsman.AddArg("-checkaddrman=<n>",
1067 strprintf("Run addrman consistency checks every <n> "
1068 "operations. Use 0 to disable. (default: %u)",
1072 argsman.AddArg(
1073 "-checkmempool=<n>",
1074 strprintf("Run mempool consistency checks every <n> transactions. Use "
1075 "0 to disable. (default: %u, regtest: %u)",
1076 defaultChainParams->DefaultConsistencyChecks(),
1077 regtestChainParams->DefaultConsistencyChecks()),
1080 argsman.AddArg("-checkpoints",
1081 strprintf("Only accept block chain matching built-in "
1082 "checkpoints (default: %d)",
1086 argsman.AddArg("-deprecatedrpc=<method>",
1087 "Allows deprecated RPC method(s) to be used",
1090 argsman.AddArg(
1091 "-stopafterblockimport",
1092 strprintf("Stop running after importing blocks from disk (default: %d)",
1093 DEFAULT_STOPAFTERBLOCKIMPORT),
1096 argsman.AddArg("-stopatheight",
1097 strprintf("Stop running after reaching the given height in "
1098 "the main chain (default: %u)",
1102 argsman.AddArg("-addrmantest", "Allows to test address relay on localhost",
1105 argsman.AddArg("-capturemessages", "Capture all P2P messages to disk",
1108 argsman.AddArg("-mocktime=<n>",
1109 "Replace actual time with " + UNIX_EPOCH_TIME +
1110 " (default: 0)",
1113 argsman.AddArg(
1114 "-maxsigcachesize=<n>",
1115 strprintf("Limit size of signature cache to <n> MiB (default: %u)",
1119 argsman.AddArg(
1120 "-maxscriptcachesize=<n>",
1121 strprintf("Limit size of script cache to <n> MiB (default: %u)",
1125 argsman.AddArg("-maxtipage=<n>",
1126 strprintf("Maximum tip age in seconds to consider node in "
1127 "initial block download (default: %u)",
1131
1132 argsman.AddArg("-uacomment=<cmt>",
1133 "Append comment to the user agent string",
1135 argsman.AddArg("-uaclientname=<clientname>", "Set user agent client name",
1137 argsman.AddArg("-uaclientversion=<clientversion>",
1138 "Set user agent client version", ArgsManager::ALLOW_ANY,
1140
1142
1143 argsman.AddArg(
1144 "-acceptnonstdtxn",
1145 strprintf(
1146 "Relay and mine \"non-standard\" transactions (%sdefault: %u)",
1147 "testnet/regtest only; ", defaultChainParams->RequireStandard()),
1150 argsman.AddArg("-excessiveblocksize=<n>",
1151 strprintf("Do not accept blocks larger than this limit, in "
1152 "bytes (default: %d)",
1156 const auto &ticker = Currency::get().ticker;
1157 argsman.AddArg(
1158 "-dustrelayfee=<amt>",
1159 strprintf("Fee rate (in %s/kB) used to define dust, the value of an "
1160 "output such that it will cost about 1/3 of its value in "
1161 "fees at this fee rate to spend it. (default: %s)",
1165
1166 argsman.AddArg(
1167 "-bytespersigcheck",
1168 strprintf("Equivalent bytes per sigCheck in transactions for relay and "
1169 "mining (default: %u).",
1172 argsman.AddArg(
1173 "-bytespersigop",
1174 strprintf("DEPRECATED: Equivalent bytes per sigCheck in transactions "
1175 "for relay and mining (default: %u). This has been "
1176 "deprecated since v0.26.8 and will be removed in the future, "
1177 "please use -bytespersigcheck instead.",
1180 argsman.AddArg(
1181 "-datacarrier",
1182 strprintf("Relay and mine data carrier transactions (default: %d)",
1185 argsman.AddArg(
1186 "-datacarriersize",
1187 strprintf("Maximum size of data in data carrier transactions "
1188 "we relay and mine (default: %u)",
1191 argsman.AddArg(
1192 "-minrelaytxfee=<amt>",
1193 strprintf("Fees (in %s/kB) smaller than this are rejected for "
1194 "relaying, mining and transaction creation (default: %s)",
1197 argsman.AddArg(
1198 "-whitelistrelay",
1199 strprintf("Add 'relay' permission to whitelisted inbound peers "
1200 "with default permissions. This will accept relayed "
1201 "transactions even when not relaying transactions "
1202 "(default: %d)",
1205 argsman.AddArg(
1206 "-whitelistforcerelay",
1207 strprintf("Add 'forcerelay' permission to whitelisted inbound peers"
1208 " with default permissions. This will relay transactions "
1209 "even if the transactions were already in the mempool "
1210 "(default: %d)",
1213
1214 argsman.AddArg("-blockmaxsize=<n>",
1215 strprintf("Set maximum block size in bytes (default: %d)",
1218 argsman.AddArg(
1219 "-blockmintxfee=<amt>",
1220 strprintf("Set lowest fee rate (in %s/kB) for transactions to "
1221 "be included in block creation. (default: %s)",
1224
1225 argsman.AddArg("-blockversion=<n>",
1226 "Override block version to test forking scenarios",
1229
1230 argsman.AddArg("-server", "Accept command line and JSON-RPC commands",
1232 argsman.AddArg("-rest",
1233 strprintf("Accept public REST requests (default: %d)",
1236 argsman.AddArg(
1237 "-rpcbind=<addr>[:port]",
1238 "Bind to given address to listen for JSON-RPC connections. Do not "
1239 "expose the RPC server to untrusted networks such as the public "
1240 "internet! This option is ignored unless -rpcallowip is also passed. "
1241 "Port is optional and overrides -rpcport. Use [host]:port notation "
1242 "for IPv6. This option can be specified multiple times (default: "
1243 "127.0.0.1 and ::1 i.e., localhost)",
1247 argsman.AddArg(
1248 "-rpcdoccheck",
1249 strprintf("Throw a non-fatal error at runtime if the documentation for "
1250 "an RPC is incorrect (default: %u)",
1253 argsman.AddArg(
1254 "-rpccookiefile=<loc>",
1255 "Location of the auth cookie. Relative paths will be prefixed "
1256 "by a net-specific datadir location. (default: data dir)",
1258 argsman.AddArg("-rpcuser=<user>", "Username for JSON-RPC connections",
1261 argsman.AddArg("-rpcpassword=<pw>", "Password for JSON-RPC connections",
1264 argsman.AddArg(
1265 "-rpcwhitelist=<whitelist>",
1266 "Set a whitelist to filter incoming RPC calls for a specific user. The "
1267 "field <whitelist> comes in the format: <USERNAME>:<rpc 1>,<rpc "
1268 "2>,...,<rpc n>. If multiple whitelists are set for a given user, they "
1269 "are set-intersected. See -rpcwhitelistdefault documentation for "
1270 "information on default whitelist behavior.",
1272 argsman.AddArg(
1273 "-rpcwhitelistdefault",
1274 "Sets default behavior for rpc whitelisting. Unless "
1275 "rpcwhitelistdefault is set to 0, if any -rpcwhitelist is set, the rpc "
1276 "server acts as if all rpc users are subject to "
1277 "empty-unless-otherwise-specified whitelists. If rpcwhitelistdefault "
1278 "is set to 1 and no -rpcwhitelist is set, rpc server acts as if all "
1279 "rpc users are subject to empty whitelists.",
1281 argsman.AddArg(
1282 "-rpcauth=<userpw>",
1283 "Username and HMAC-SHA-256 hashed password for JSON-RPC connections. "
1284 "The field <userpw> comes in the format: <USERNAME>:<SALT>$<HASH>. A "
1285 "canonical python script is included in share/rpcauth. The client then "
1286 "connects normally using the rpcuser=<USERNAME>/rpcpassword=<PASSWORD> "
1287 "pair of arguments. This option can be specified multiple times",
1289 argsman.AddArg("-rpcport=<port>",
1290 strprintf("Listen for JSON-RPC connections on <port> "
1291 "(default: %u, testnet: %u, regtest: %u)",
1292 defaultBaseParams->RPCPort(),
1293 testnetBaseParams->RPCPort(),
1294 regtestBaseParams->RPCPort()),
1297 argsman.AddArg(
1298 "-rpcallowip=<ip>",
1299 "Allow JSON-RPC connections from specified source. Valid for "
1300 "<ip> are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. "
1301 "1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24). "
1302 "This option can be specified multiple times",
1304 argsman.AddArg(
1305 "-rpcthreads=<n>",
1306 strprintf(
1307 "Set the number of threads to service RPC calls (default: %d)",
1310 argsman.AddArg(
1311 "-rpccorsdomain=value",
1312 "Domain from which to accept cross origin requests (browser enforced)",
1314
1315 argsman.AddArg("-rpcworkqueue=<n>",
1316 strprintf("Set the depth of the work queue to service RPC "
1317 "calls (default: %d)",
1321 argsman.AddArg("-rpcservertimeout=<n>",
1322 strprintf("Timeout during HTTP requests (default: %d)",
1326
1327#if HAVE_DECL_FORK
1328 argsman.AddArg("-daemon",
1329 strprintf("Run in the background as a daemon and accept "
1330 "commands (default: %d)",
1333 argsman.AddArg("-daemonwait",
1334 strprintf("Wait for initialization to be finished before "
1335 "exiting. This implies -daemon (default: %d)",
1338#else
1339 hidden_args.emplace_back("-daemon");
1340 hidden_args.emplace_back("-daemonwait");
1341#endif
1342
1343 // Avalanche options.
1344 argsman.AddArg("-avalanche",
1345 strprintf("Enable the avalanche feature (default: %u)",
1348 argsman.AddArg(
1349 "-avalanchestakingrewards",
1350 strprintf("Enable the avalanche staking rewards feature (default: %u, "
1351 "testnet: %u, regtest: %u)",
1352 defaultChainParams->GetConsensus().enableStakingRewards,
1353 testnetChainParams->GetConsensus().enableStakingRewards,
1354 regtestChainParams->GetConsensus().enableStakingRewards),
1356 argsman.AddArg("-avalancheconflictingproofcooldown",
1357 strprintf("Mandatory cooldown before a proof conflicting "
1358 "with an already registered one can be considered "
1359 "in seconds (default: %u)",
1362 argsman.AddArg("-avalanchepeerreplacementcooldown",
1363 strprintf("Mandatory cooldown before a peer can be replaced "
1364 "in seconds (default: %u)",
1367 argsman.AddArg(
1368 "-avaminquorumstake",
1369 strprintf(
1370 "Minimum amount of known stake for a usable quorum (default: %s)",
1373 argsman.AddArg(
1374 "-avaminquorumconnectedstakeratio",
1375 strprintf("Minimum proportion of known stake we"
1376 " need nodes for to have a usable quorum (default: %s)",
1379 argsman.AddArg(
1380 "-avaminavaproofsnodecount",
1381 strprintf("Minimum number of node that needs to send us an avaproofs"
1382 " message before we consider we have a usable quorum"
1383 " (default: %s)",
1386 argsman.AddArg(
1387 "-avastalevotethreshold",
1388 strprintf("Number of avalanche votes before a voted item goes stale "
1389 "when voting confidence is low (default: %u)",
1392 argsman.AddArg(
1393 "-avastalevotefactor",
1394 strprintf(
1395 "Factor affecting the number of avalanche votes before a voted "
1396 "item goes stale when voting confidence is high (default: %u)",
1399 argsman.AddArg("-avacooldown",
1400 strprintf("Mandatory cooldown between two avapoll in "
1401 "milliseconds (default: %u)",
1404 argsman.AddArg(
1405 "-avatimeout",
1406 strprintf("Avalanche query timeout in milliseconds (default: %u)",
1409 argsman.AddArg(
1410 "-avadelegation",
1411 "Avalanche proof delegation to the master key used by this node "
1412 "(default: none). Should be used in conjunction with -avaproof and "
1413 "-avamasterkey",
1415 argsman.AddArg("-avaproof",
1416 "Avalanche proof to be used by this node (default: none)",
1418 argsman.AddArg(
1419 "-avaproofstakeutxoconfirmations",
1420 strprintf(
1421 "Minimum number of confirmations before a stake utxo is mature"
1422 " enough to be included into a proof. Utxos in the mempool are not "
1423 "accepted (i.e this value must be greater than 0) (default: %s)",
1426 argsman.AddArg("-avaproofstakeutxodustthreshold",
1427 strprintf("Minimum value each stake utxo must have to be "
1428 "considered valid (default: %s)",
1431 argsman.AddArg("-avamasterkey",
1432 "Master key associated with the proof. If a proof is "
1433 "required, this is mandatory.",
1436 argsman.AddArg("-avasessionkey", "Avalanche session key (default: random)",
1439 argsman.AddArg("-enablertt",
1440 strprintf("Whether to enforce Real Time Targeting via "
1441 "Avalanche, default (%u)",
1444 argsman.AddArg(
1445 "-maxavalancheoutbound",
1446 strprintf(
1447 "Set the maximum number of avalanche outbound peers to connect to. "
1448 "Note that this option takes precedence over the -maxconnections "
1449 "option (default: %u).",
1452 argsman.AddArg(
1453 "-persistavapeers",
1454 strprintf("Whether to save the avalanche peers upon shutdown and load "
1455 "them upon startup (default: %u).",
1458
1459 hidden_args.emplace_back("-avalanchepreconsensus");
1460 hidden_args.emplace_back("-avalanchestakingpreconsensus");
1461
1462 // Add the hidden options
1463 argsman.AddHiddenArgs(hidden_args);
1464}
1465
1466static bool fHaveGenesis = false;
1468static std::condition_variable g_genesis_wait_cv;
1469
1471 if (pBlockIndex != nullptr) {
1472 {
1474 fHaveGenesis = true;
1475 }
1476 g_genesis_wait_cv.notify_all();
1477 }
1478}
1479
1480#if HAVE_SYSTEM
1481static void StartupNotify(const ArgsManager &args) {
1482 std::string cmd = args.GetArg("-startupnotify", "");
1483 if (!cmd.empty()) {
1484 std::thread t(runCommand, cmd);
1485 // thread runs free
1486 t.detach();
1487 }
1488}
1489#endif
1490
1491static bool AppInitServers(Config &config,
1493 NodeContext &node) {
1494 const ArgsManager &args = *Assert(node.args);
1497 if (!InitHTTPServer(config)) {
1498 return false;
1499 }
1500
1501 StartRPC();
1502 node.rpc_interruption_point = RpcInterruptionPoint;
1503
1505 return false;
1506 }
1507 if (args.GetBoolArg("-rest", DEFAULT_REST_ENABLE)) {
1508 StartREST(&node);
1509 }
1510
1512 return true;
1513}
1514
1515// Parameter interaction based on rules
1517 // when specifying an explicit binding address, you want to listen on it
1518 // even when -connect or -proxy is specified.
1519 if (args.IsArgSet("-bind")) {
1520 if (args.SoftSetBoolArg("-listen", true)) {
1521 LogPrintf(
1522 "%s: parameter interaction: -bind set -> setting -listen=1\n",
1523 __func__);
1524 }
1525 }
1526 if (args.IsArgSet("-whitebind")) {
1527 if (args.SoftSetBoolArg("-listen", true)) {
1528 LogPrintf("%s: parameter interaction: -whitebind set -> setting "
1529 "-listen=1\n",
1530 __func__);
1531 }
1532 }
1533
1534 if (args.IsArgSet("-connect")) {
1535 // when only connecting to trusted nodes, do not seed via DNS, or listen
1536 // by default.
1537 if (args.SoftSetBoolArg("-dnsseed", false)) {
1538 LogPrintf("%s: parameter interaction: -connect set -> setting "
1539 "-dnsseed=0\n",
1540 __func__);
1541 }
1542 if (args.SoftSetBoolArg("-listen", false)) {
1543 LogPrintf("%s: parameter interaction: -connect set -> setting "
1544 "-listen=0\n",
1545 __func__);
1546 }
1547 }
1548
1549 if (args.IsArgSet("-proxy")) {
1550 // to protect privacy, do not listen by default if a default proxy
1551 // server is specified.
1552 if (args.SoftSetBoolArg("-listen", false)) {
1553 LogPrintf(
1554 "%s: parameter interaction: -proxy set -> setting -listen=0\n",
1555 __func__);
1556 }
1557 // to protect privacy, do not map ports when a proxy is set. The user
1558 // may still specify -listen=1 to listen locally, so don't rely on this
1559 // happening through -listen below.
1560 if (args.SoftSetBoolArg("-upnp", false)) {
1561 LogPrintf(
1562 "%s: parameter interaction: -proxy set -> setting -upnp=0\n",
1563 __func__);
1564 }
1565 if (args.SoftSetBoolArg("-natpmp", false)) {
1566 LogPrintf(
1567 "%s: parameter interaction: -proxy set -> setting -natpmp=0\n",
1568 __func__);
1569 }
1570 // to protect privacy, do not discover addresses by default
1571 if (args.SoftSetBoolArg("-discover", false)) {
1572 LogPrintf("%s: parameter interaction: -proxy set -> setting "
1573 "-discover=0\n",
1574 __func__);
1575 }
1576 }
1577
1578 if (!args.GetBoolArg("-listen", DEFAULT_LISTEN)) {
1579 // do not map ports or try to retrieve public IP when not listening
1580 // (pointless)
1581 if (args.SoftSetBoolArg("-upnp", false)) {
1582 LogPrintf(
1583 "%s: parameter interaction: -listen=0 -> setting -upnp=0\n",
1584 __func__);
1585 }
1586 if (args.SoftSetBoolArg("-natpmp", false)) {
1587 LogPrintf(
1588 "%s: parameter interaction: -listen=0 -> setting -natpmp=0\n",
1589 __func__);
1590 }
1591 if (args.SoftSetBoolArg("-discover", false)) {
1592 LogPrintf(
1593 "%s: parameter interaction: -listen=0 -> setting -discover=0\n",
1594 __func__);
1595 }
1596 if (args.SoftSetBoolArg("-listenonion", false)) {
1597 LogPrintf("%s: parameter interaction: -listen=0 -> setting "
1598 "-listenonion=0\n",
1599 __func__);
1600 }
1601 if (args.SoftSetBoolArg("-i2pacceptincoming", false)) {
1602 LogPrintf("%s: parameter interaction: -listen=0 -> setting "
1603 "-i2pacceptincoming=0\n",
1604 __func__);
1605 }
1606 }
1607
1608 if (args.IsArgSet("-externalip")) {
1609 // if an explicit public IP is specified, do not try to find others
1610 if (args.SoftSetBoolArg("-discover", false)) {
1611 LogPrintf("%s: parameter interaction: -externalip set -> setting "
1612 "-discover=0\n",
1613 __func__);
1614 }
1615 }
1616
1617 // disable whitelistrelay in blocksonly mode
1618 if (args.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)) {
1619 if (args.SoftSetBoolArg("-whitelistrelay", false)) {
1620 LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting "
1621 "-whitelistrelay=0\n",
1622 __func__);
1623 }
1624 }
1625
1626 // Forcing relay from whitelisted hosts implies we will accept relays from
1627 // them in the first place.
1628 if (args.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
1629 if (args.SoftSetBoolArg("-whitelistrelay", true)) {
1630 LogPrintf("%s: parameter interaction: -whitelistforcerelay=1 -> "
1631 "setting -whitelistrelay=1\n",
1632 __func__);
1633 }
1634 }
1635
1636 // If avalanche is set, soft set all the feature flags accordingly.
1637 if (args.IsArgSet("-avalanche")) {
1638 const bool fAvalanche =
1639 args.GetBoolArg("-avalanche", AVALANCHE_DEFAULT_ENABLED);
1640 args.SoftSetBoolArg("-automaticunparking", !fAvalanche);
1641 }
1642}
1643
1650void InitLogging(const ArgsManager &args) {
1653}
1654
1655namespace { // Variables internal to initialization process only
1656
1657int nMaxConnections;
1659int nFD;
1662std::set<BlockFilterType> g_enabled_filter_types;
1663
1664} // namespace
1665
1667 // Rather than throwing std::bad-alloc if allocation fails, terminate
1668 // immediately to (try to) avoid chain corruption. Since LogPrintf may
1669 // itself allocate memory, set the handler directly to terminate first.
1670 std::set_new_handler(std::terminate);
1671 LogPrintf("Error: Out of memory. Terminating.\n");
1672
1673 // The log was successful, terminate now.
1674 std::terminate();
1675};
1676
1678// Step 1: setup
1679#ifdef _MSC_VER
1680 // Turn off Microsoft heap dump noise
1683 OPEN_EXISTING, 0, 0));
1684 // Disable confusing "helpful" text message on abort, Ctrl-C
1686#endif
1687#ifdef WIN32
1688 // Enable Data Execution Prevention (DEP)
1690#endif
1691 if (!InitShutdownState()) {
1692 return InitError(
1693 Untranslated("Initializing wait-for-shutdown state failed."));
1694 }
1695
1696 if (!SetupNetworking()) {
1697 return InitError(Untranslated("Initializing networking failed"));
1698 }
1699
1700#ifndef WIN32
1701 if (!args.GetBoolArg("-sysperms", false)) {
1702 umask(077);
1703 }
1704
1705 // Clean shutdown on SIGTERM
1708
1709 // Reopen debug.log on SIGHUP
1711
1712 // Ignore SIGPIPE, otherwise it will bring the daemon down if the client
1713 // closes unexpectedly
1715#else
1717#endif
1718
1719 std::set_new_handler(new_handler_terminate);
1720
1721 return true;
1722}
1723
1725 const CChainParams &chainparams = config.GetChainParams();
1726 // Step 2: parameter interactions
1727
1728 // also see: InitParameterInteraction()
1729
1730 // Error if network-specific options (-addnode, -connect, etc) are
1731 // specified in default section of config file, but not overridden
1732 // on the command line or in this network's section of the config file.
1733 std::string network = args.GetChainName();
1735 for (const auto &arg : args.GetUnsuitableSectionOnlyArgs()) {
1736 errors += strprintf(_("Config setting for %s only applied on %s "
1737 "network when in [%s] section.") +
1738 Untranslated("\n"),
1739 arg, network, network);
1740 }
1741
1742 if (!errors.empty()) {
1743 return InitError(errors);
1744 }
1745
1746 // Warn if unrecognized section name are present in the config file.
1748 for (const auto &section : args.GetUnrecognizedSections()) {
1749 warnings += strprintf(Untranslated("%s:%i ") +
1750 _("Section [%s] is not recognized.") +
1751 Untranslated("\n"),
1752 section.m_file, section.m_line, section.m_name);
1753 }
1754
1755 if (!warnings.empty()) {
1757 }
1758
1759 if (!fs::is_directory(args.GetBlocksDirPath())) {
1760 return InitError(
1761 strprintf(_("Specified blocks directory \"%s\" does not exist."),
1762 args.GetArg("-blocksdir", "")));
1763 }
1764
1765 // parse and validate enabled filter types
1766 std::string blockfilterindex_value =
1767 args.GetArg("-blockfilterindex", DEFAULT_BLOCKFILTERINDEX);
1768 if (blockfilterindex_value == "" || blockfilterindex_value == "1") {
1770 } else if (blockfilterindex_value != "0") {
1771 const std::vector<std::string> names =
1772 args.GetArgs("-blockfilterindex");
1773 for (const auto &name : names) {
1776 return InitError(
1777 strprintf(_("Unknown -blockfilterindex value %s."), name));
1778 }
1780 }
1781 }
1782
1783 // Signal NODE_COMPACT_FILTERS if peerblockfilters and basic filters index
1784 // are both enabled.
1785 if (args.GetBoolArg("-peerblockfilters", DEFAULT_PEERBLOCKFILTERS)) {
1787 return InitError(
1788 _("Cannot set -peerblockfilters without -blockfilterindex."));
1789 }
1790
1791 nLocalServices = ServiceFlags(nLocalServices | NODE_COMPACT_FILTERS);
1792 }
1793
1794 // if using block pruning, then disallow txindex, coinstatsindex and chronik
1795 if (args.GetIntArg("-prune", 0)) {
1796 if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
1797 return InitError(_("Prune mode is incompatible with -txindex."));
1798 }
1799 if (args.GetBoolArg("-coinstatsindex", DEFAULT_COINSTATSINDEX)) {
1800 return InitError(
1801 _("Prune mode is incompatible with -coinstatsindex."));
1802 }
1803 if (args.GetBoolArg("-chronik", DEFAULT_CHRONIK)) {
1804 return InitError(_("Prune mode is incompatible with -chronik."));
1805 }
1806 }
1807
1808 // -bind and -whitebind can't be set when not listening
1809 size_t nUserBind =
1810 args.GetArgs("-bind").size() + args.GetArgs("-whitebind").size();
1811 if (nUserBind != 0 && !args.GetBoolArg("-listen", DEFAULT_LISTEN)) {
1812 return InitError(Untranslated(
1813 "Cannot set -bind or -whitebind together with -listen=0"));
1814 }
1815
1816 // Make sure enough file descriptors are available
1817 int nBind = std::max(nUserBind, size_t(1));
1819 args.GetIntArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
1820 nMaxConnections = std::max(nUserMaxConnections, 0);
1821
1822 // -maxavalancheoutbound takes precedence over -maxconnections
1823 const int maxAvalancheOutbound = args.GetIntArg(
1824 "-maxavalancheoutbound", DEFAULT_MAX_AVALANCHE_OUTBOUND_CONNECTIONS);
1825 const bool fAvalanche =
1826 args.GetBoolArg("-avalanche", AVALANCHE_DEFAULT_ENABLED);
1827 if (fAvalanche && maxAvalancheOutbound > nMaxConnections) {
1828 nMaxConnections = std::max(maxAvalancheOutbound, nMaxConnections);
1829 // Indicate the value set by the user
1830 LogPrintf("Increasing -maxconnections from %d to %d to comply with "
1831 "-maxavalancheoutbound\n",
1832 nUserMaxConnections, nMaxConnections);
1833 }
1834
1835 // Trim requested connection counts, to fit into system limitations
1836 // <int> in std::min<int>(...) to work around FreeBSD compilation issue
1837 // described in #2695
1839 nMaxConnections + nBind + MIN_CORE_FILEDESCRIPTORS +
1841#ifdef USE_POLL
1842 int fd_max = nFD;
1843#else
1844 int fd_max = FD_SETSIZE;
1845#endif
1846 nMaxConnections = std::max(
1847 std::min<int>(nMaxConnections,
1850 0);
1852 return InitError(_("Not enough file descriptors available."));
1853 }
1854 nMaxConnections =
1856 nMaxConnections);
1857
1858 if (nMaxConnections < nUserMaxConnections) {
1859 // Not categorizing as "Warning" because this is the normal behavior for
1860 // platforms using the select() interface for which FD_SETSIZE is
1861 // usually 1024.
1862 LogPrintf("Reducing -maxconnections from %d to %d, because of system "
1863 "limitations.\n",
1864 nUserMaxConnections, nMaxConnections);
1865 }
1866
1867 // Step 3: parameter-to-internal-flags
1869
1870 // Configure excessive block size.
1872 args.GetIntArg("-excessiveblocksize", DEFAULT_MAX_BLOCK_SIZE);
1873 if (nProposedExcessiveBlockSize <= 0 ||
1875 return InitError(
1876 _("Excessive block size must be > 1,000,000 bytes (1MB)"));
1877 }
1878
1879 // Check blockmaxsize does not exceed maximum accepted block size.
1881 args.GetIntArg("-blockmaxsize", DEFAULT_MAX_GENERATED_BLOCK_SIZE);
1883 return InitError(_("Max generated block size must be greater than 0"));
1884 }
1886 return InitError(_("Max generated block size (blockmaxsize) cannot "
1887 "exceed the excessive block size "
1888 "(excessiveblocksize)"));
1889 }
1890
1892 if (nConnectTimeout <= 0) {
1894 }
1895
1897 args.GetIntArg("-peertimeout", DEFAULT_PEER_CONNECT_TIMEOUT);
1898 if (peer_connect_timeout <= 0) {
1899 return InitError(Untranslated(
1900 "peertimeout cannot be configured with a negative value."));
1901 }
1902
1903 // Sanity check argument for min fee for including tx in block
1904 // TODO: Harmonize which arguments need sanity checking and where that
1905 // happens.
1906 if (args.IsArgSet("-blockmintxfee")) {
1907 Amount n = Amount::zero();
1908 if (!ParseMoney(args.GetArg("-blockmintxfee", ""), n)) {
1909 return InitError(AmountErrMsg("blockmintxfee",
1910 args.GetArg("-blockmintxfee", "")));
1911 }
1912 }
1913
1915 args.IsArgSet("-bytespersigcheck")
1916 ? args.GetIntArg("-bytespersigcheck", nBytesPerSigCheck)
1917 : args.GetIntArg("-bytespersigop", nBytesPerSigCheck);
1918
1920 return false;
1921 }
1922
1923 // Option to startup with mocktime set (used for regression testing):
1924 SetMockTime(args.GetIntArg("-mocktime", 0)); // SetMockTime(0) is a no-op
1925
1926 if (args.GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS)) {
1927 nLocalServices = ServiceFlags(nLocalServices | NODE_BLOOM);
1928 }
1929
1930 if (args.IsArgSet("-proxy") && args.GetArg("-proxy", "").empty()) {
1931 return InitError(_(
1932 "No proxy server specified. Use -proxy=<ip> or -proxy=<ip:port>."));
1933 }
1934
1935 // Avalanche parameters
1937 args.GetIntArg("-avaproofstakeutxoconfirmations",
1939
1940 if (!chainparams.IsTestChain() &&
1943 return InitError(_("Avalanche stake UTXO minimum confirmations can "
1944 "only be set on test chains."));
1945 }
1946
1947 if (stakeUtxoMinConfirmations <= 0) {
1948 return InitError(_("Avalanche stake UTXO minimum confirmations must be "
1949 "a positive integer."));
1950 }
1951
1952 if (args.IsArgSet("-avaproofstakeutxodustthreshold")) {
1953 Amount amount = Amount::zero();
1954 auto parsed = ParseMoney(
1955 args.GetArg("-avaproofstakeutxodustthreshold", ""), amount);
1956 if (!parsed || Amount::zero() == amount) {
1957 return InitError(AmountErrMsg(
1958 "avaproofstakeutxodustthreshold",
1959 args.GetArg("-avaproofstakeutxodustthreshold", "")));
1960 }
1961
1962 if (!chainparams.IsTestChain() &&
1964 return InitError(_("Avalanche stake UTXO dust threshold can "
1965 "only be set on test chains."));
1966 }
1967 }
1968
1969 // This is a staking node
1970 if (fAvalanche && args.IsArgSet("-avaproof")) {
1971 if (!args.GetBoolArg("-listen", true)) {
1972 return InitError(_("Running a staking node requires accepting "
1973 "inbound connections. Please enable -listen."));
1974 }
1975 if (args.IsArgSet("-proxy")) {
1976 return InitError(_("Running a staking node behind a proxy is not "
1977 "supported. Please disable -proxy."));
1978 }
1979 if (args.IsArgSet("-i2psam")) {
1980 return InitError(_("Running a staking node behind I2P is not "
1981 "supported. Please disable -i2psam."));
1982 }
1983 if (args.IsArgSet("-onlynet")) {
1984 return InitError(
1985 _("Restricting the outbound network is not supported when "
1986 "running a staking node. Please disable -onlynet."));
1987 }
1988 }
1989
1990 // Also report errors from parsing before daemonization
1991 {
1992 KernelNotifications notifications{};
1994 .config = config,
1995 .datadir = args.GetDataDirNet(),
1996 .notifications = notifications,
1997 };
1998 if (const auto error{ApplyArgsManOptions(args, chainman_opts_dummy)}) {
1999 return InitError(*error);
2000 }
2002 .chainparams = chainman_opts_dummy.config.GetChainParams(),
2003 .blocks_dir = args.GetBlocksDirPath(),
2004 };
2005 if (const auto error{ApplyArgsManOptions(args, blockman_opts_dummy)}) {
2006 return InitError(*error);
2007 }
2008 }
2009
2010 return true;
2011}
2012
2013static bool LockDataDirectory(bool probeOnly) {
2014 // Make sure only a single Bitcoin process is using the data directory.
2015 fs::path datadir = gArgs.GetDataDirNet();
2016 if (!DirIsWritable(datadir)) {
2017 return InitError(strprintf(
2018 _("Cannot write to data directory '%s'; check permissions."),
2019 fs::PathToString(datadir)));
2020 }
2021 if (!LockDirectory(datadir, ".lock", probeOnly)) {
2022 return InitError(strprintf(_("Cannot obtain a lock on data directory "
2023 "%s. %s is probably already running."),
2024 fs::PathToString(datadir), PACKAGE_NAME));
2025 }
2026 return true;
2027}
2028
2030 // Step 4: sanity checks
2031
2033
2034 // Sanity check
2035 if (!init::SanityChecks()) {
2036 return InitError(strprintf(
2037 _("Initialization sanity check failed. %s is shutting down."),
2038 PACKAGE_NAME));
2039 }
2040
2041 // Probe the data directory lock to give an early error message, if possible
2042 // We cannot hold the data directory lock here, as the forking for daemon()
2043 // hasn't yet happened, and a fork will cause weird behavior to it.
2044 return LockDataDirectory(true);
2045}
2046
2048 // After daemonization get the data directory lock again and hold on to it
2049 // until exit. This creates a slight window for a race condition to happen,
2050 // however this condition is harmless: it will at most make us exit without
2051 // printing a message to console.
2052 if (!LockDataDirectory(false)) {
2053 // Detailed error printed inside LockDataDirectory
2054 return false;
2055 }
2056 return true;
2057}
2058
2061 // Create client interfaces for wallets that are supposed to be loaded
2062 // according to -wallet and -disablewallet options. This only constructs
2063 // the interfaces, it doesn't load wallet data. Wallets actually get loaded
2064 // when load() and start() interface methods are called below.
2066 return true;
2067}
2068
2069bool AppInitMain(Config &config, RPCServer &rpcServer,
2073 // Step 4a: application initialization
2074 const ArgsManager &args = *Assert(node.args);
2075 const CChainParams &chainparams = config.GetChainParams();
2076
2077 if (!CreatePidFile(args)) {
2078 // Detailed error printed inside CreatePidFile().
2079 return false;
2080 }
2081 if (!init::StartLogging(args)) {
2082 // Detailed error printed inside StartLogging().
2083 return false;
2084 }
2085
2086 LogPrintf("Using at most %i automatic connections (%i file descriptors "
2087 "available)\n",
2088 nMaxConnections, nFD);
2089
2090 // Warn about relative -datadir path.
2091 if (args.IsArgSet("-datadir") &&
2092 !args.GetPathArg("-datadir").is_absolute()) {
2093 LogPrintf("Warning: relative datadir option '%s' specified, which will "
2094 "be interpreted relative to the current working directory "
2095 "'%s'. This is fragile, because if bitcoin is started in the "
2096 "future from a different location, it will be unable to "
2097 "locate the current data files. There could also be data "
2098 "loss if bitcoin is started while in a temporary "
2099 "directory.\n",
2100 args.GetArg("-datadir", ""),
2101 fs::PathToString(fs::current_path()));
2102 }
2103
2106
2107 if (!InitSignatureCache(validation_cache_sizes.signature_cache_bytes)) {
2108 return InitError(strprintf(
2109 _("Unable to allocate memory for -maxsigcachesize: '%s' MiB"),
2110 args.GetIntArg("-maxsigcachesize",
2112 }
2114 validation_cache_sizes.script_execution_cache_bytes)) {
2115 return InitError(strprintf(
2116 _("Unable to allocate memory for -maxscriptcachesize: '%s' MiB"),
2117 args.GetIntArg("-maxscriptcachesize",
2119 }
2120
2122 if (script_threads <= 0) {
2123 // -par=0 means autodetect (number of cores - 1 script threads)
2124 // -par=-n means "leave n cores free" (number of cores - n - 1 script
2125 // threads)
2127 }
2128
2129 // Subtract 1 because the main thread counts towards the par threads
2130 script_threads = std::max(script_threads - 1, 0);
2131
2132 // Number of script-checking threads <= MAX_SCRIPTCHECK_THREADS
2134
2135 LogPrintf("Script verification uses %d additional threads\n",
2137 if (script_threads >= 1) {
2139 }
2140
2141 assert(!node.scheduler);
2142 node.scheduler = std::make_unique<CScheduler>();
2143
2144 // Start the lightweight task scheduler thread
2145 node.scheduler->m_service_thread =
2146 std::thread(&util::TraceThread, "scheduler",
2147 [&] { node.scheduler->serviceQueue(); });
2148
2149 // Gather some entropy once per minute.
2150 node.scheduler->scheduleEvery(
2151 [] {
2153 return true;
2154 },
2155 std::chrono::minutes{1});
2156
2158
2163 RegisterAllRPCCommands(config, rpcServer, tableRPC);
2164 for (const auto &client : node.chain_clients) {
2165 client->registerRpcs();
2166 }
2167#if ENABLE_ZMQ
2169#endif
2170
2177 if (args.GetBoolArg("-server", false)) {
2178 uiInterface.InitMessage_connect(SetRPCWarmupStatus);
2180 return InitError(
2181 _("Unable to start HTTP server. See debug log for details."));
2182 }
2183 }
2184
2185 // Step 5: verify wallet database integrity
2186 for (const auto &client : node.chain_clients) {
2187 if (!client->verify()) {
2188 return false;
2189 }
2190 }
2191
2192 // Step 6: network initialization
2193
2194 // Note that we absolutely cannot open any actual connections
2195 // until the very end ("start node") as the UTXO/block state
2196 // is not yet setup and may end up being set up twice if we
2197 // need to reindex later.
2198
2199 fListen = args.GetBoolArg("-listen", DEFAULT_LISTEN);
2200 fDiscover = args.GetBoolArg("-discover", true);
2201
2202 {
2203 // Initialize addrman
2204 assert(!node.addrman);
2205
2206 // Read asmap file if configured
2207 std::vector<bool> asmap;
2208 if (args.IsArgSet("-asmap")) {
2210 args.GetPathArg("-asmap", DEFAULT_ASMAP_FILENAME);
2211 if (!asmap_path.is_absolute()) {
2213 }
2214 if (!fs::exists(asmap_path)) {
2215 InitError(strprintf(_("Could not find asmap file %s"),
2217 return false;
2218 }
2220 if (asmap.size() == 0) {
2221 InitError(strprintf(_("Could not parse asmap file %s"),
2223 return false;
2224 }
2225 const uint256 asmap_version = (HashWriter{} << asmap).GetHash();
2226 LogPrintf("Using asmap version %s for IP bucketing\n",
2227 asmap_version.ToString());
2228 } else {
2229 LogPrintf("Using /16 prefix for IP bucketing\n");
2230 }
2231
2232 uiInterface.InitMessage(_("Loading P2P addresses...").translated);
2233 auto addrman{LoadAddrman(chainparams, asmap, args)};
2234 if (!addrman) {
2235 return InitError(util::ErrorString(addrman));
2236 }
2237 node.addrman = std::move(*addrman);
2238 }
2239
2240 assert(!node.banman);
2241 node.banman = std::make_unique<BanMan>(
2242 args.GetDataDirNet() / "banlist.dat", config.GetChainParams(),
2244 assert(!node.connman);
2245 node.connman = std::make_unique<CConnman>(
2246 config, GetRand<uint64_t>(), GetRand<uint64_t>(), *node.addrman,
2247 args.GetBoolArg("-networkactive", true));
2248
2249 // sanitize comments per BIP-0014, format user agent and check total size
2250 std::vector<std::string> uacomments;
2251 for (const std::string &cmt : args.GetArgs("-uacomment")) {
2253 return InitError(strprintf(
2254 _("User Agent comment (%s) contains unsafe characters."), cmt));
2255 }
2256 uacomments.push_back(cmt);
2257 }
2258 const std::string client_name = args.GetArg("-uaclientname", CLIENT_NAME);
2259 const std::string client_version =
2260 args.GetArg("-uaclientversion", FormatVersion(CLIENT_VERSION));
2262 return InitError(strprintf(
2263 _("-uaclientname (%s) contains invalid characters."), client_name));
2264 }
2265 if (client_version !=
2267 return InitError(
2268 strprintf(_("-uaclientversion (%s) contains invalid characters."),
2270 }
2271 const std::string strSubVersion =
2273 if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
2274 return InitError(strprintf(
2275 _("Total length of network version string (%i) exceeds maximum "
2276 "length (%i). Reduce the number or size of uacomments."),
2278 }
2279
2280 if (args.IsArgSet("-onlynet")) {
2281 std::set<enum Network> nets;
2282 for (const std::string &snet : args.GetArgs("-onlynet")) {
2283 enum Network net = ParseNetwork(snet);
2284 if (net == NET_UNROUTABLE) {
2285 return InitError(strprintf(
2286 _("Unknown network specified in -onlynet: '%s'"), snet));
2287 }
2288 nets.insert(net);
2289 }
2290 for (int n = 0; n < NET_MAX; n++) {
2291 enum Network net = (enum Network)n;
2292 if (!nets.count(net)) {
2293 SetReachable(net, false);
2294 }
2295 }
2296 }
2297
2298 // Check for host lookup allowed before parsing any network related
2299 // parameters
2301
2302 bool proxyRandomize =
2303 args.GetBoolArg("-proxyrandomize", DEFAULT_PROXYRANDOMIZE);
2304 // -proxy sets a proxy for all outgoing network traffic
2305 // -noproxy (or -proxy=0) as well as the empty string can be used to not set
2306 // a proxy, this is the default
2307 std::string proxyArg = args.GetArg("-proxy", "");
2308 SetReachable(NET_ONION, false);
2309 if (proxyArg != "" && proxyArg != "0") {
2311 if (!Lookup(proxyArg, proxyAddr, 9050, fNameLookup)) {
2312 return InitError(strprintf(
2313 _("Invalid -proxy address or hostname: '%s'"), proxyArg));
2314 }
2315
2317 if (!addrProxy.IsValid()) {
2318 return InitError(strprintf(
2319 _("Invalid -proxy address or hostname: '%s'"), proxyArg));
2320 }
2321
2326 // by default, -proxy sets onion as reachable, unless -noonion later
2327 SetReachable(NET_ONION, true);
2328 }
2329
2330 // -onion can be used to set only a proxy for .onion, or override normal
2331 // proxy for .onion addresses.
2332 // -noonion (or -onion=0) disables connecting to .onion entirely. An empty
2333 // string is used to not override the onion proxy (in which case it defaults
2334 // to -proxy set above, or none)
2335 std::string onionArg = args.GetArg("-onion", "");
2336 if (onionArg != "") {
2337 if (onionArg == "0") {
2338 // Handle -noonion/-onion=0
2339 SetReachable(NET_ONION, false);
2340 } else {
2342 if (!Lookup(onionArg, onionProxy, 9050, fNameLookup)) {
2343 return InitError(strprintf(
2344 _("Invalid -onion address or hostname: '%s'"), onionArg));
2345 }
2347 if (!addrOnion.IsValid()) {
2348 return InitError(strprintf(
2349 _("Invalid -onion address or hostname: '%s'"), onionArg));
2350 }
2352 SetReachable(NET_ONION, true);
2353 }
2354 }
2355
2356 for (const std::string &strAddr : args.GetArgs("-externalip")) {
2357 CService addrLocal;
2358 if (Lookup(strAddr, addrLocal, GetListenPort(), fNameLookup) &&
2359 addrLocal.IsValid()) {
2360 AddLocal(addrLocal, LOCAL_MANUAL);
2361 } else {
2362 return InitError(ResolveErrMsg("externalip", strAddr));
2363 }
2364 }
2365
2366#if ENABLE_ZMQ
2368 [&chainman = node.chainman](CBlock &block, const CBlockIndex &index) {
2369 assert(chainman);
2370 return chainman->m_blockman.ReadBlockFromDisk(block, index);
2371 });
2372
2375 }
2376#endif
2377
2378 // Step 7: load block chain
2379
2380 node.notifications = std::make_unique<KernelNotifications>();
2381 fReindex = args.GetBoolArg("-reindex", false);
2382 bool fReindexChainState = args.GetBoolArg("-reindex-chainstate", false);
2383
2385 .config = config,
2386 .datadir = args.GetDataDirNet(),
2387 .adjusted_time_callback = GetAdjustedTime,
2388 .notifications = *node.notifications,
2389 };
2390 // no error can happen, already checked in AppInitParameterInteraction
2392
2393 if (chainman_opts.checkpoints_enabled) {
2394 LogPrintf("Checkpoints will be verified.\n");
2395 } else {
2396 LogPrintf("Skipping checkpoint verification.\n");
2397 }
2398
2400 .chainparams = chainman_opts.config.GetChainParams(),
2401 .blocks_dir = args.GetBlocksDirPath(),
2402 };
2403 // no error can happen, already checked in AppInitParameterInteraction
2405
2406 // cache size calculations
2408 CalculateCacheSizes(args, g_enabled_filter_types.size());
2409
2410 LogPrintf("Cache configuration:\n");
2411 LogPrintf("* Using %.1f MiB for block index database\n",
2412 cache_sizes.block_tree_db * (1.0 / 1024 / 1024));
2413 if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
2414 LogPrintf("* Using %.1f MiB for transaction index database\n",
2415 cache_sizes.tx_index * (1.0 / 1024 / 1024));
2416 }
2418 LogPrintf("* Using %.1f MiB for %s block filter index database\n",
2419 cache_sizes.filter_index * (1.0 / 1024 / 1024),
2421 }
2422 LogPrintf("* Using %.1f MiB for chain state database\n",
2423 cache_sizes.coins_db * (1.0 / 1024 / 1024));
2424
2425 assert(!node.mempool);
2426 assert(!node.chainman);
2427
2429 .check_ratio = chainparams.DefaultConsistencyChecks() ? 1 : 0,
2430 };
2431 if (const auto err{ApplyArgsManOptions(args, chainparams, mempool_opts)}) {
2432 return InitError(*err);
2433 }
2434 mempool_opts.check_ratio =
2435 std::clamp<int>(mempool_opts.check_ratio, 0, 1'000'000);
2436
2437 // FIXME: this legacy limit comes from the DEFAULT_DESCENDANT_SIZE_LIMIT
2438 // (101) that was enforced before the wellington activation. While it's
2439 // still a good idea to have some minimum mempool size, using this value as
2440 // a threshold is no longer relevant.
2441 int64_t nMempoolSizeMin = 101 * 1000 * 40;
2442 if (mempool_opts.max_size_bytes < 0 ||
2443 (!chainparams.IsTestChain() &&
2444 mempool_opts.max_size_bytes < nMempoolSizeMin)) {
2445 return InitError(strprintf(_("-maxmempool must be at least %d MB"),
2446 std::ceil(nMempoolSizeMin / 1000000.0)));
2447 }
2448 LogPrintf("* Using %.1f MiB for in-memory UTXO set (plus up to %.1f MiB of "
2449 "unused mempool space)\n",
2450 cache_sizes.coins * (1.0 / 1024 / 1024),
2451 mempool_opts.max_size_bytes * (1.0 / 1024 / 1024));
2452
2453 for (bool fLoaded = false; !fLoaded && !ShutdownRequested();) {
2454 node.mempool = std::make_unique<CTxMemPool>(mempool_opts);
2455
2456 node.chainman =
2457 std::make_unique<ChainstateManager>(chainman_opts, blockman_opts);
2458 ChainstateManager &chainman = *node.chainman;
2459
2461 options.mempool = Assert(node.mempool.get());
2462 options.reindex = node::fReindex;
2464 options.prune = chainman.m_blockman.IsPruneMode();
2465 options.check_blocks =
2466 args.GetIntArg("-checkblocks", DEFAULT_CHECKBLOCKS);
2467 options.check_level = args.GetIntArg("-checklevel", DEFAULT_CHECKLEVEL);
2469 args.IsArgSet("-checkblocks") || args.IsArgSet("-checklevel");
2471 options.coins_error_cb = [] {
2472 uiInterface.ThreadSafeMessageBox(
2473 _("Error reading from database, shutting down."), "",
2475 };
2476
2477 uiInterface.InitMessage(_("Loading block index...").translated);
2478
2480 auto catch_exceptions = [](auto &&f) {
2481 try {
2482 return f();
2483 } catch (const std::exception &e) {
2484 LogPrintf("%s\n", e.what());
2485 return std::make_tuple(node::ChainstateLoadStatus::FAILURE,
2486 _("Error opening block database"));
2487 }
2488 };
2489 auto [status, error] = catch_exceptions(
2490 [&] { return LoadChainstate(chainman, cache_sizes, options); });
2492 uiInterface.InitMessage(_("Verifying blocks...").translated);
2493 if (chainman.m_blockman.m_have_pruned &&
2494 options.check_blocks > MIN_BLOCKS_TO_KEEP) {
2495 LogPrintf("Prune: pruned datadir may not have more than %d "
2496 "blocks; only checking available blocks\n",
2498 }
2499 std::tie(status, error) = catch_exceptions(
2500 [&] { return VerifyLoadedChainstate(chainman, options); });
2502 WITH_LOCK(cs_main, return node.chainman->LoadRecentHeadersTime(
2503 node.chainman->m_options.datadir /
2505 fLoaded = true;
2506 LogPrintf(" block index %15dms\n",
2508 }
2509 }
2510
2513 status ==
2515 return InitError(error);
2516 }
2517
2518 if (!fLoaded && !ShutdownRequested()) {
2519 // first suggest a reindex
2520 if (!options.reindex) {
2521 bool fRet = uiInterface.ThreadSafeQuestion(
2522 error + Untranslated(".\n\n") +
2523 _("Do you want to rebuild the block database now?"),
2524 error.original + ".\nPlease restart with -reindex or "
2525 "-reindex-chainstate to recover.",
2526 "",
2529 if (fRet) {
2530 fReindex = true;
2531 AbortShutdown();
2532 } else {
2533 LogPrintf("Aborted block database rebuild. Exiting.\n");
2534 return false;
2535 }
2536 } else {
2537 return InitError(error);
2538 }
2539 }
2540 }
2541
2542 // As LoadBlockIndex can take several minutes, it's possible the user
2543 // requested to kill the GUI during the last operation. If so, exit.
2544 // As the program has not fully started yet, Shutdown() is possibly
2545 // overkill.
2546 if (ShutdownRequested()) {
2547 LogPrintf("Shutdown requested. Exiting.\n");
2548 return false;
2549 }
2550
2551 ChainstateManager &chainman = *Assert(node.chainman);
2552
2553 if (args.GetBoolArg("-avalanche", AVALANCHE_DEFAULT_ENABLED)) {
2554 // Initialize Avalanche.
2557 args, *node.chain, node.connman.get(), chainman, node.mempool.get(),
2558 *node.scheduler, avalancheError);
2559 if (!node.avalanche) {
2561 return false;
2562 }
2563
2564 if (node.avalanche->isAvalancheServiceAvailable()) {
2565 nLocalServices = ServiceFlags(nLocalServices | NODE_AVALANCHE);
2566 }
2567 }
2568
2571
2572 assert(!node.peerman);
2573 node.peerman = PeerManager::make(*node.connman, *node.addrman,
2574 node.banman.get(), chainman, *node.mempool,
2575 node.avalanche.get(), peerman_opts);
2576 RegisterValidationInterface(node.peerman.get());
2577
2578 // Encoded addresses using cashaddr instead of base58.
2579 // We do this by default to avoid confusion with BTC addresses.
2580 config.SetCashAddrEncoding(args.GetBoolArg("-usecashaddr", true));
2581
2582 // Step 8: load indexers
2583 if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
2584 auto result{
2586 chainman.m_blockman.m_block_tree_db)))};
2587 if (!result) {
2588 return InitError(util::ErrorString(result));
2589 }
2590
2591 g_txindex =
2592 std::make_unique<TxIndex>(cache_sizes.tx_index, false, fReindex);
2593 if (!g_txindex->Start(chainman.ActiveChainstate())) {
2594 return false;
2595 }
2596 }
2597
2598 for (const auto &filter_type : g_enabled_filter_types) {
2599 InitBlockFilterIndex(filter_type, cache_sizes.filter_index, false,
2600 fReindex);
2602 ->Start(chainman.ActiveChainstate())) {
2603 return false;
2604 }
2605 }
2606
2607 if (args.GetBoolArg("-coinstatsindex", DEFAULT_COINSTATSINDEX)) {
2608 g_coin_stats_index = std::make_unique<CoinStatsIndex>(
2609 /* cache size */ 0, false, fReindex);
2610 if (!g_coin_stats_index->Start(chainman.ActiveChainstate())) {
2611 return false;
2612 }
2613 }
2614
2615#if ENABLE_CHRONIK
2616 if (args.GetBoolArg("-chronik", DEFAULT_CHRONIK)) {
2617 const bool fReindexChronik =
2618 fReindex || args.GetBoolArg("-chronikreindex", false);
2619 if (!chronik::Start(args, config, node, fReindexChronik)) {
2620 return false;
2621 }
2622 }
2623#endif
2624
2625 // Step 9: load wallet
2626 for (const auto &client : node.chain_clients) {
2627 if (!client->load()) {
2628 return false;
2629 }
2630 }
2631
2632 // Step 10: data directory maintenance
2633
2634 // if pruning, unset the service bit and perform the initial blockstore
2635 // prune after any wallet rescanning has taken place.
2636 if (chainman.m_blockman.IsPruneMode()) {
2637 LogPrintf("Unsetting NODE_NETWORK on prune mode\n");
2638 nLocalServices = ServiceFlags(nLocalServices & ~NODE_NETWORK);
2639 if (!fReindex) {
2640 LOCK(cs_main);
2641 for (Chainstate *chainstate : chainman.GetAll()) {
2642 uiInterface.InitMessage(_("Pruning blockstore...").translated);
2643 chainstate->PruneAndFlush();
2644 }
2645 }
2646 }
2647
2648 // Step 11: import blocks
2649 if (!CheckDiskSpace(args.GetDataDirNet())) {
2650 InitError(
2651 strprintf(_("Error: Disk space is low for %s"),
2653 return false;
2654 }
2655 if (!CheckDiskSpace(args.GetBlocksDirPath())) {
2656 InitError(
2657 strprintf(_("Error: Disk space is low for %s"),
2659 return false;
2660 }
2661
2662 // Either install a handler to notify us when genesis activates, or set
2663 // fHaveGenesis directly.
2664 // No locking, as this happens before any background thread is started.
2665 boost::signals2::connection block_notify_genesis_wait_connection;
2666 if (WITH_LOCK(chainman.GetMutex(),
2667 return chainman.ActiveChain().Tip() == nullptr)) {
2669 uiInterface.NotifyBlockTip_connect(
2670 std::bind(BlockNotifyGenesisWait, std::placeholders::_2));
2671 } else {
2672 fHaveGenesis = true;
2673 }
2674
2675#if defined(HAVE_SYSTEM)
2676 const std::string block_notify = args.GetArg("-blocknotify", "");
2677 if (!block_notify.empty()) {
2678 uiInterface.NotifyBlockTip_connect([block_notify](
2680 const CBlockIndex *pBlockIndex) {
2682 return;
2683 }
2684 std::string command = block_notify;
2685 ReplaceAll(command, "%s", pBlockIndex->GetBlockHash().GetHex());
2686 std::thread t(runCommand, command);
2687 // thread runs free
2688 t.detach();
2689 });
2690 }
2691#endif
2692
2693 std::vector<fs::path> vImportFiles;
2694 for (const std::string &strFile : args.GetArgs("-loadblock")) {
2695 vImportFiles.push_back(fs::PathFromString(strFile));
2696 }
2697
2698 avalanche::Processor *const avalanche = node.avalanche.get();
2699 chainman.m_load_block =
2700 std::thread(&util::TraceThread, "loadblk", [=, &chainman, &args] {
2701 ThreadImport(chainman, avalanche, vImportFiles,
2702 ShouldPersistMempool(args) ? MempoolPath(args)
2703 : fs::path{});
2704 });
2705
2706 // Wait for genesis block to be processed
2707 {
2709 // We previously could hang here if StartShutdown() is called prior to
2710 // ThreadImport getting started, so instead we just wait on a timer to
2711 // check ShutdownRequested() regularly.
2712 while (!fHaveGenesis && !ShutdownRequested()) {
2713 g_genesis_wait_cv.wait_for(lock, std::chrono::milliseconds(500));
2714 }
2716 }
2717
2718 if (ShutdownRequested()) {
2719 return false;
2720 }
2721
2722 // Step 12: start node
2723
2725
2727 {
2728 LOCK(cs_main);
2729 LogPrintf("block tree size = %u\n", chainman.BlockIndex().size());
2730 chain_active_height = chainman.ActiveChain().Height();
2731 if (tip_info) {
2732 tip_info->block_height = chain_active_height;
2733 tip_info->block_time =
2734 chainman.ActiveChain().Tip()
2735 ? chainman.ActiveChain().Tip()->GetBlockTime()
2736 : chainman.GetParams().GenesisBlock().GetBlockTime();
2737 tip_info->verification_progress = GuessVerificationProgress(
2738 chainman.GetParams().TxData(), chainman.ActiveChain().Tip());
2739 }
2740 if (tip_info && chainman.m_best_header) {
2741 tip_info->header_height = chainman.m_best_header->nHeight;
2742 tip_info->header_time = chainman.m_best_header->GetBlockTime();
2743 }
2744 }
2745 LogPrintf("nBestHeight = %d\n", chain_active_height);
2746 if (node.peerman) {
2747 node.peerman->SetBestHeight(chain_active_height);
2748 }
2749
2750 // Map ports with UPnP or NAT-PMP.
2751 StartMapPort(args.GetBoolArg("-upnp", DEFAULT_UPNP),
2752 args.GetBoolArg("-natpmp", DEFAULT_NATPMP));
2753
2755 connOptions.nLocalServices = nLocalServices;
2756 connOptions.nMaxConnections = nMaxConnections;
2757 connOptions.m_max_avalanche_outbound =
2758 node.avalanche
2759 ? args.GetIntArg("-maxavalancheoutbound",
2761 : 0;
2762 connOptions.m_max_outbound_full_relay = std::min(
2764 connOptions.nMaxConnections - connOptions.m_max_avalanche_outbound);
2765 connOptions.m_max_outbound_block_relay = std::min(
2767 connOptions.nMaxConnections - connOptions.m_max_avalanche_outbound -
2768 connOptions.m_max_outbound_full_relay);
2771 connOptions.uiInterface = &uiInterface;
2772 connOptions.m_banman = node.banman.get();
2773 connOptions.m_msgproc.push_back(node.peerman.get());
2774 if (node.avalanche) {
2775 connOptions.m_msgproc.push_back(node.avalanche.get());
2776 }
2777 connOptions.nSendBufferMaxSize =
2778 1000 * args.GetIntArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER);
2779 connOptions.nReceiveFloodSize =
2780 1000 * args.GetIntArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER);
2781 connOptions.m_added_nodes = args.GetArgs("-addnode");
2782
2783 connOptions.nMaxOutboundLimit =
2784 1024 * 1024 *
2785 args.GetIntArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET);
2786 connOptions.m_peer_connect_timeout = peer_connect_timeout;
2787
2788 // Port to bind to if `-bind=addr` is provided without a `:port` suffix.
2789 const uint16_t default_bind_port = static_cast<uint16_t>(
2790 args.GetIntArg("-port", config.GetChainParams().GetDefaultPort()));
2791
2792 const auto BadPortWarning = [](const char *prefix, uint16_t port) {
2793 return strprintf(_("%s request to listen on port %u. This port is "
2794 "considered \"bad\" and "
2795 "thus it is unlikely that any Bitcoin ABC peers "
2796 "connect to it. See "
2797 "doc/p2p-bad-ports.md for details and a full list."),
2798 prefix, port);
2799 };
2800
2801 for (const std::string &bind_arg : args.GetArgs("-bind")) {
2803 const size_t index = bind_arg.rfind('=');
2804 if (index == std::string::npos) {
2806 /*fAllowLookup=*/false)) {
2807 connOptions.vBinds.push_back(bind_addr);
2808 if (IsBadPort(bind_addr.GetPort())) {
2809 InitWarning(BadPortWarning("-bind", bind_addr.GetPort()));
2810 }
2811 continue;
2812 }
2813 } else {
2814 const std::string network_type = bind_arg.substr(index + 1);
2815 if (network_type == "onion") {
2816 const std::string truncated_bind_arg =
2817 bind_arg.substr(0, index);
2819 BaseParams().OnionServiceTargetPort(), false)) {
2820 connOptions.onion_binds.push_back(bind_addr);
2821 continue;
2822 }
2823 }
2824 }
2825 return InitError(ResolveErrMsg("bind", bind_arg));
2826 }
2827
2828 for (const std::string &strBind : args.GetArgs("-whitebind")) {
2832 return InitError(error);
2833 }
2834 connOptions.vWhiteBinds.push_back(whitebind);
2835 }
2836
2837 // If the user did not specify -bind= or -whitebind= then we bind
2838 // on any address - 0.0.0.0 (IPv4) and :: (IPv6).
2839 connOptions.bind_on_any =
2840 args.GetArgs("-bind").empty() && args.GetArgs("-whitebind").empty();
2841
2842 // Emit a warning if a bad port is given to -port= but only if -bind and
2843 // -whitebind are not given, because if they are, then -port= is ignored.
2844 if (connOptions.bind_on_any && args.IsArgSet("-port")) {
2845 const uint16_t port_arg = args.GetIntArg("-port", 0);
2846 if (IsBadPort(port_arg)) {
2848 }
2849 }
2850
2852 if (!connOptions.onion_binds.empty()) {
2853 onion_service_target = connOptions.onion_binds.front();
2854 } else {
2856 connOptions.onion_binds.push_back(onion_service_target);
2857 }
2858
2859 if (args.GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION)) {
2860 if (connOptions.onion_binds.size() > 1) {
2862 _("More than one onion bind address is provided. Using %s "
2863 "for the automatically created Tor onion service."),
2864 onion_service_target.ToStringIPPort()));
2865 }
2867 }
2868
2869 if (connOptions.bind_on_any) {
2870 // Only add all IP addresses of the machine if we would be listening on
2871 // any address - 0.0.0.0 (IPv4) and :: (IPv6).
2872 Discover();
2873 }
2874
2875 for (const auto &net : args.GetArgs("-whitelist")) {
2879 return InitError(error);
2880 }
2881 connOptions.vWhitelistedRange.push_back(subnet);
2882 }
2883
2884 connOptions.vSeedNodes = args.GetArgs("-seednode");
2885
2886 // Initiate outbound connections unless connect=0
2887 connOptions.m_use_addrman_outgoing = !args.IsArgSet("-connect");
2888 if (!connOptions.m_use_addrman_outgoing) {
2889 const auto connect = args.GetArgs("-connect");
2890 if (connect.size() != 1 || connect[0] != "0") {
2891 connOptions.m_specified_outgoing = connect;
2892 }
2893 }
2894
2895 const std::string &i2psam_arg = args.GetArg("-i2psam", "");
2896 if (!i2psam_arg.empty()) {
2897 CService addr;
2898 if (!Lookup(i2psam_arg, addr, 7656, fNameLookup) || !addr.IsValid()) {
2899 return InitError(strprintf(
2900 _("Invalid -i2psam address or hostname: '%s'"), i2psam_arg));
2901 }
2902 SetReachable(NET_I2P, true);
2903 SetProxy(NET_I2P, proxyType{addr});
2904 } else {
2905 SetReachable(NET_I2P, false);
2906 }
2907
2908 connOptions.m_i2p_accept_incoming =
2909 args.GetBoolArg("-i2pacceptincoming", true);
2910
2911 if (!node.connman->Start(*node.scheduler, connOptions)) {
2912 return false;
2913 }
2914
2915 // Step 13: finished
2916
2917 // At this point, the RPC is "started", but still in warmup, which means it
2918 // cannot yet be called. Before we make it callable, we need to make sure
2919 // that the RPC's view of the best block is valid and consistent with
2920 // ChainstateManager's active tip.
2921 //
2922 // If we do not do this, RPC's view of the best block will be height=0 and
2923 // hash=0x0. This will lead to erroroneous responses for things like
2924 // waitforblockheight.
2926 WITH_LOCK(chainman.GetMutex(), return chainman.ActiveTip()));
2928
2929 uiInterface.InitMessage(_("Done loading").translated);
2930
2931 for (const auto &client : node.chain_clients) {
2932 client->start(*node.scheduler);
2933 }
2934
2935 BanMan *banman = node.banman.get();
2936 node.scheduler->scheduleEvery(
2937 [banman] {
2938 banman->DumpBanlist();
2939 return true;
2940 },
2942
2943 // Start Avalanche's event loop.
2944 if (node.avalanche) {
2945 node.avalanche->startEventLoop(*node.scheduler);
2946 }
2947
2948 if (node.peerman) {
2949 node.peerman->StartScheduledTasks(*node.scheduler);
2950 }
2951
2952#if HAVE_SYSTEM
2953 StartupNotify(args);
2954#endif
2955
2956 return true;
2957}
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:693
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, 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:471
void StopHTTPRPC()
Stop HTTP RPC subsystem.
Definition httprpc.cpp:475
bool StartHTTPRPC(HTTPRPCRequestProcessor &httpRPCRequestProcessor)
Start HTTP RPC subsystem.
Definition httprpc.cpp:450
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:1650
bool AppInitLockDataDirectory()
Lock bitcoin data directory.
Definition init.cpp:2047
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:1491
#define MIN_CORE_FILEDESCRIPTORS
Definition init.cpp:144
static bool fHaveGenesis
Definition init.cpp:1466
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:1467
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:1468
bool AppInitMain(Config &config, RPCServer &rpcServer, HTTPRPCRequestProcessor &httpRPCRequestProcessor, NodeContext &node, interfaces::BlockAndHeaderTipInfo *tip_info)
Bitcoin main initialization.
Definition init.cpp:2069
static constexpr bool DEFAULT_CHRONIK
Definition init.cpp:137
bool AppInitBasicSetup(const ArgsManager &args)
Initialize bitcoin: Basic context setup.
Definition init.cpp:1677
bool AppInitSanityChecks()
Initialization sanity checks: ecc init, sanity checks, dir lock.
Definition init.cpp:2029
bool AppInitInterfaces(NodeContext &node)
Initialize node and wallet interface pointers.
Definition init.cpp:2059
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:1516
static void BlockNotifyGenesisWait(const CBlockIndex *pBlockIndex)
Definition init.cpp:1470
static void OnRPCStopped()
Definition init.cpp:418
static bool LockDataDirectory(bool probeOnly)
Definition init.cpp:2013
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:1724
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:1666
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:2789
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS
The maximum number of peer connections to maintain.
Definition net.h:93
static const unsigned int MAX_SUBVERSION_LENGTH
Maximum length of the user agent string in version message.
Definition net.h:69
static const int MAX_ADDNODE_CONNECTIONS
Maximum number of addnode outgoing nodes.
Definition net.h:76
static const size_t DEFAULT_MAXSENDBUFFER
Definition net.h:107
static const int NUM_FDS_MESSAGE_CAPTURE
Number of file descriptors required for message capture.
Definition net.h:101
static const bool DEFAULT_BLOCKSONLY
Default for blocks only.
Definition net.h:97
static const bool DEFAULT_WHITELISTFORCERELAY
Default for -whitelistforcerelay.
Definition net.h:57
static const bool DEFAULT_FORCEDNSSEED
Definition net.h:103
static const bool DEFAULT_WHITELISTRELAY
Default for -whitelistrelay.
Definition net.h:55
static constexpr uint64_t DEFAULT_MAX_UPLOAD_TARGET
The default for -maxuploadtarget.
Definition net.h:95
static const size_t DEFAULT_MAXRECEIVEBUFFER
Definition net.h:106
static const int DEFAULT_MAX_AVALANCHE_OUTBOUND_CONNECTIONS
Maximum number of avalanche enabled outgoing connections by default.
Definition net.h:83
static const bool DEFAULT_FIXEDSEEDS
Definition net.h:105
static const int MAX_FEELER_CONNECTIONS
Maximum number of feeler connections.
Definition net.h:85
static const bool DEFAULT_LISTEN
-listen default
Definition net.h:87
static const int64_t DEFAULT_PEER_CONNECT_TIMEOUT
-peertimeout default
Definition net.h:99
static const bool DEFAULT_DNSSEED
Definition net.h:104
static const int MAX_OUTBOUND_FULL_RELAY_CONNECTIONS
Maximum number of automatic outgoing nodes over which we'll relay everything (blocks,...
Definition net.h:74
@ LOCAL_MANUAL
Definition net.h:242
static const int MAX_BLOCK_RELAY_ONLY_CONNECTIONS
Maximum number of block-relay-only outgoing connections.
Definition net.h:78
const std::vector< std::string > NET_PERMISSIONS_DOC
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:91
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:222
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:730
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:859
bool SetProxy(enum Network net, const proxyType &addrProxy)
Definition netbase.cpp:710
std::vector< std::string > GetNetworkNames(bool append_unroutable)
Return a vector of publicly routable Network names; optionally append NET_UNROUTABLE.
Definition netbase.cpp:136
static const int DEFAULT_NAME_LOOKUP
-dns default
Definition netbase.h:29
static const int DEFAULT_CONNECT_TIMEOUT
-timeout default
Definition netbase.h:27
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
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
@ 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:53
static constexpr Amount zero() noexcept
Definition amount.h:32
ServiceFlags nLocalServices
Definition net.h:853
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:49
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.
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:96
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:110
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:94
static const int MAX_SCRIPTCHECK_THREADS
Maximum number of dedicated script-checking threads allowed.
Definition validation.h:82
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition validation.h:113
static const int DEFAULT_SCRIPTCHECK_THREADS
-par default (number of script-checking threads, 0 = auto)
Definition validation.h:84
static const signed int DEFAULT_CHECKBLOCKS
Definition validation.h:95
static const bool DEFAULT_PEERBLOOMFILTERS
Definition validation.h:86
static const int DEFAULT_STOPATHEIGHT
Default for -stopatheight.
Definition validation.h:89
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